From 7cdf5548645aee0fe6f4ca6fb8fe87f6ce728b06 Mon Sep 17 00:00:00 2001 From: alpharush <0xalpharush@protonmail.com> Date: Thu, 12 Nov 2026 17:35:31 -0600 Subject: [PATCH 1/3] feat(refinement): certify solar output to bytecode --- .github/workflows/refinement.yml | 107 + .gitignore | 1 + SolidCore.lean | 3 + SolidCore/Refinement.lean | 34 + SolidCore/Refinement/Abi.lean | 111 + SolidCore/Refinement/Axioms/Audit.lean | 83 + SolidCore/Refinement/Axioms/C4.lean | 23 + .../Refinement/Axioms/CounterGeneric.lean | 12 + SolidCore/Refinement/Axioms/Main.lean | 94 + SolidCore/Refinement/Axioms/MulX.lean | 20 + SolidCore/Refinement/Axioms/W4.lean | 15 + SolidCore/Refinement/Bytecode/B1.lean | 20 + SolidCore/Refinement/Bytecode/B2.lean | 20 + SolidCore/Refinement/Bytecode/B3.lean | 20 + SolidCore/Refinement/Bytecode/B4.lean | 20 + SolidCore/Refinement/Bytecode/B5.lean | 20 + SolidCore/Refinement/Bytecode/B6.lean | 20 + SolidCore/Refinement/Bytecode/B7.lean | 20 + SolidCore/Refinement/Bytecode/C1.lean | 20 + SolidCore/Refinement/Bytecode/C10.lean | 20 + SolidCore/Refinement/Bytecode/C11.lean | 20 + SolidCore/Refinement/Bytecode/C2.lean | 20 + SolidCore/Refinement/Bytecode/C3.lean | 20 + SolidCore/Refinement/Bytecode/C4.lean | 20 + SolidCore/Refinement/Bytecode/C5.lean | 20 + SolidCore/Refinement/Bytecode/C6.lean | 20 + SolidCore/Refinement/Bytecode/C7.lean | 20 + SolidCore/Refinement/Bytecode/C8.lean | 20 + SolidCore/Refinement/Bytecode/C9.lean | 20 + SolidCore/Refinement/Bytecode/D1.lean | 20 + SolidCore/Refinement/Bytecode/D2.lean | 20 + SolidCore/Refinement/Bytecode/D3.lean | 20 + SolidCore/Refinement/Bytecode/D4.lean | 20 + SolidCore/Refinement/Bytecode/W1.lean | 20 + SolidCore/Refinement/Bytecode/W2.lean | 20 + SolidCore/Refinement/Bytecode/W3.lean | 20 + SolidCore/Refinement/Bytecode/W4.lean | 20 + SolidCore/Refinement/Bytecode/W5.lean | 24 + SolidCore/Refinement/C1/Refinement.lean | 260 ++ SolidCore/Refinement/C1/Spec.lean | 46 + SolidCore/Refinement/C1/Target.lean | 370 +++ SolidCore/Refinement/Check.lean | 200 ++ SolidCore/Refinement/Compose.lean | 58 + SolidCore/Refinement/ComposeSeq.lean | 533 ++++ SolidCore/Refinement/Dirty.lean | 22 + SolidCore/Refinement/Dirty/Source.lean | 479 +++ SolidCore/Refinement/Dyn.lean | 24 + SolidCore/Refinement/Dyn/Abi.lean | 161 + SolidCore/Refinement/Dyn/Evm.lean | 225 ++ SolidCore/Refinement/Dyn/Refines.lean | 44 + SolidCore/Refinement/Dyn/Source.lean | 457 +++ SolidCore/Refinement/Evm/Calldata.lean | 226 ++ SolidCore/Refinement/Evm/Lemmas.lean | 127 + SolidCore/Refinement/Evm/Symex.lean | 397 +++ SolidCore/Refinement/Evm/Wide.lean | 286 ++ SolidCore/Refinement/Evm/WideStorage.lean | 690 +++++ SolidCore/Refinement/Evm/WideStorageAt.lean | 41 + SolidCore/Refinement/Facts.lean | 31 + SolidCore/Refinement/Facts/B1.lean | 113 + SolidCore/Refinement/Facts/B2.lean | 52 + SolidCore/Refinement/Facts/B3.lean | 49 + SolidCore/Refinement/Facts/B4.lean | 142 + SolidCore/Refinement/Facts/B5.lean | 59 + SolidCore/Refinement/Facts/B6.lean | 193 ++ SolidCore/Refinement/Facts/B7.lean | 59 + SolidCore/Refinement/Facts/C1.lean | 103 + SolidCore/Refinement/Facts/C10.lean | 52 + SolidCore/Refinement/Facts/C11.lean | 51 + SolidCore/Refinement/Facts/C2.lean | 67 + SolidCore/Refinement/Facts/C3.lean | 154 + SolidCore/Refinement/Facts/C4.lean | 467 +++ SolidCore/Refinement/Facts/C5.lean | 103 + SolidCore/Refinement/Facts/C6.lean | 127 + SolidCore/Refinement/Facts/C7.lean | 169 ++ SolidCore/Refinement/Facts/C8.lean | 86 + SolidCore/Refinement/Facts/C9.lean | 407 +++ SolidCore/Refinement/Facts/Prelude.lean | 14 + SolidCore/Refinement/Facts/W1.lean | 31 + SolidCore/Refinement/Facts/W2.lean | 66 + SolidCore/Refinement/Facts/W3.lean | 53 + SolidCore/Refinement/Facts/W4.lean | 31 + SolidCore/Refinement/Generic/Event.lean | 148 + SolidCore/Refinement/Generic/Mir.lean | 390 +++ SolidCore/Refinement/Generic/MirRun.lean | 1194 ++++++++ SolidCore/Refinement/Generic/MulTest.lean | 314 ++ SolidCore/Refinement/Generic/Packed.lean | 107 + SolidCore/Refinement/Generic/Simp.lean | 724 +++++ SolidCore/Refinement/Generic/Source.lean | 774 +++++ SolidCore/Refinement/Generic/SourceCall.lean | 102 + SolidCore/Refinement/Generic/SourceRun.lean | 814 ++++++ SolidCore/Refinement/Generic/SourceStmt.lean | 1518 ++++++++++ SolidCore/Refinement/Generic/Stage.lean | 290 ++ SolidCore/Refinement/Generic/Tree.lean | 482 +++ SolidCore/Refinement/Generic/Value.lean | 285 ++ SolidCore/Refinement/Headline.lean | 101 + SolidCore/Refinement/Keccak/Agree.lean | 307 ++ SolidCore/Refinement/Keccak/TwoWords.lean | 53 + SolidCore/Refinement/Kernel.lean | 378 +++ SolidCore/Refinement/KernelCopies.lean | 28 + SolidCore/Refinement/KernelRfl.lean | 172 ++ SolidCore/Refinement/Seq/Check.lean | 277 ++ SolidCore/Refinement/Seq/Corpus.lean | 24 + SolidCore/Refinement/Seq/Explore.lean | 90 + SolidCore/Refinement/Sequence.lean | 138 + SolidCore/Refinement/Solar/Assemble.lean | 824 ++++++ SolidCore/Refinement/Solar/AssembleFast.lean | 286 ++ SolidCore/Refinement/Solar/AssembleSim.lean | 1832 ++++++++++++ SolidCore/Refinement/Solar/Bank/Assembly.lean | 104 + .../Refinement/Solar/Bank/Certified.lean | 217 ++ SolidCore/Refinement/Solar/Bank/Lowering.lean | 631 ++++ SolidCore/Refinement/Solar/Bank/Mutants.lean | 62 + SolidCore/Refinement/Solar/C4/Assembly.lean | 76 + SolidCore/Refinement/Solar/C4/Certified.lean | 185 ++ SolidCore/Refinement/Solar/C4/Lowering.lean | 1033 +++++++ .../Refinement/Solar/C4/LoweringGeneric.lean | 171 ++ .../Refinement/Solar/Counter/AnyStorage.lean | 509 ++++ .../Refinement/Solar/Counter/Assembly.lean | 219 ++ .../Refinement/Solar/Counter/AssemblyAt.lean | 171 ++ SolidCore/Refinement/Solar/Counter/Calls.lean | 323 +++ SolidCore/Refinement/Solar/Counter/Every.lean | 253 ++ .../Refinement/Solar/Counter/EverySeq.lean | 71 + .../Refinement/Solar/Counter/Lowering.lean | 263 ++ .../Refinement/Solar/Counter/LoweringAt.lean | 92 + .../Solar/Counter/LoweringGeneric.lean | 109 + .../Refinement/Solar/Counter/Milestone.lean | 175 ++ .../Refinement/Solar/Counter/NegativeAt.lean | 252 ++ .../Solar/Counter/NegativeValue.lean | 139 + .../Refinement/Solar/Counter/Sequence.lean | 121 + .../Refinement/Solar/Counter/Sequences.lean | 168 ++ .../Refinement/Solar/Counter/Source.lean | 62 + SolidCore/Refinement/Solar/Counter/Spec.lean | 381 +++ .../Refinement/Solar/Counter/SpecAt.lean | 201 ++ SolidCore/Refinement/Solar/Counter/Value.lean | 191 ++ .../Refinement/Solar/Events/Assembly.lean | 110 + .../Refinement/Solar/Events/Certified.lean | 137 + .../Refinement/Solar/Events/Lowering.lean | 296 ++ SolidCore/Refinement/Solar/Hex.lean | 50 + SolidCore/Refinement/Solar/Lowering.lean | 308 ++ .../Refinement/Solar/LoweringGeneric.lean | 117 + SolidCore/Refinement/Solar/Milestone.lean | 124 + SolidCore/Refinement/Solar/MulX/Assembly.lean | 84 + .../Refinement/Solar/MulX/Certified.lean | 152 + SolidCore/Refinement/Solar/MulX/Lowering.lean | 593 ++++ .../Solar/RequireModulo/Assembly.lean | 96 + .../Solar/RequireModulo/Bytecode.lean | 20 + .../Refinement/Solar/RequireModulo/Evm10.lean | 81 + SolidCore/Refinement/Solar/Sequences.lean | 77 + SolidCore/Refinement/Solar/W1.lean | 741 +++++ SolidCore/Refinement/Solar/W1Value.lean | 417 +++ SolidCore/Refinement/Solar/W4/Milestone.lean | 268 ++ SolidCore/Refinement/Solar/W4Lowering.lean | 114 + SolidCore/Refinement/Source/B1.lean | 72 + SolidCore/Refinement/Source/B2.lean | 57 + SolidCore/Refinement/Source/B3.lean | 52 + SolidCore/Refinement/Source/B4.lean | 58 + SolidCore/Refinement/Source/B5.lean | 62 + SolidCore/Refinement/Source/B6.lean | 64 + SolidCore/Refinement/Source/B7.lean | 72 + SolidCore/Refinement/Source/Bank.lean | 91 + SolidCore/Refinement/Source/C1.lean | 46 + SolidCore/Refinement/Source/C10.lean | 46 + SolidCore/Refinement/Source/C11.lean | 48 + SolidCore/Refinement/Source/C2.lean | 46 + SolidCore/Refinement/Source/C3.lean | 46 + SolidCore/Refinement/Source/C4.lean | 58 + SolidCore/Refinement/Source/C5.lean | 52 + SolidCore/Refinement/Source/C6.lean | 46 + SolidCore/Refinement/Source/C7.lean | 48 + SolidCore/Refinement/Source/C8.lean | 61 + SolidCore/Refinement/Source/C9.lean | 62 + SolidCore/Refinement/Source/D1.lean | 46 + SolidCore/Refinement/Source/D2.lean | 46 + SolidCore/Refinement/Source/D3.lean | 48 + SolidCore/Refinement/Source/D4.lean | 48 + SolidCore/Refinement/Source/Events.lean | 49 + SolidCore/Refinement/Source/MulX.lean | 74 + SolidCore/Refinement/Source/W1.lean | 46 + SolidCore/Refinement/Source/W2.lean | 46 + SolidCore/Refinement/Source/W3.lean | 46 + SolidCore/Refinement/Source/W4.lean | 52 + SolidCore/Refinement/Source/W5.lean | 46 + SolidCore/Refinement/Spec.lean | 71 + SolidCore/Refinement/Statement.lean | 191 ++ SolidCore/Refinement/Wide/Clean.lean | 79 + SolidCore/Refinement/Wide/Refines.lean | 196 ++ SolidCore/Refinement/Wide/Source.lean | 141 + SolidCore/Refinement/Wide/Tactic.lean | 486 ++++ SolidCore/Solidity/ABI.lean | 60 +- SolidCore/Solidity/AdoptionLaws.lean | 22 +- SolidCore/Solidity/Ast.lean | 127 +- SolidCore/Solidity/Interface/Expressions.lean | 195 +- SolidCore/Solidity/Interface/Foundation.lean | 21 +- SolidCore/Solidity/Interface/Statements.lean | 26 +- SolidCore/Solidity/Interpreter.lean | 8 +- SolidCore/Solidity/TypeCheck.lean | 2 +- SolidCore/Verify.lean | 10 + SolidCore/Verify/Abi.lean | 38 + SolidCore/Verify/Basic.lean | 189 ++ SolidCore/Verify/C1.lean | 222 ++ SolidCore/Verify/C4.lean | 458 +++ SolidCore/Verify/Finite.lean | 75 + SolidCore/Verify/Run.lean | 132 + SolidCore/Verify/Tactic.lean | 110 + SolidCore/Verify/W1.lean | 98 + SolidCore/Verify/W4.lean | 173 ++ SolidCore/Verify/W5.lean | 173 ++ SolidCore/Witness/AddmodArgOrder.lean | 240 ++ .../Witness/BytesNShiftConversionWidth.lean | 224 ++ SolidCore/Witness/TupleStorageCopyOrder.lean | 320 ++ lake-manifest.json | 320 +- lakefile.lean | 96 +- lean-toolchain | 2 +- scripts/refinement/FACTS.md | 58 + scripts/refinement/axiom-audit.sh | 18 + scripts/refinement/axiom-closure.py | 116 + scripts/refinement/bank/bank.sol | 26 + scripts/refinement/c4.sh | 154 + scripts/refinement/c4/c4.sol | 3 + scripts/refinement/check-solar-w1.sh | 32 + scripts/refinement/check.sh | 17 + scripts/refinement/corpus/b1.sol | 8 + scripts/refinement/corpus/b2.sol | 11 + scripts/refinement/corpus/b3.sol | 9 + scripts/refinement/corpus/b4.sol | 9 + scripts/refinement/corpus/b5.sol | 14 + scripts/refinement/corpus/b6.sol | 15 + scripts/refinement/corpus/b7.sol | 15 + scripts/refinement/corpus/c1.sol | 8 + scripts/refinement/corpus/c10.sol | 3 + scripts/refinement/corpus/c11.sol | 4 + scripts/refinement/corpus/c2.sol | 3 + scripts/refinement/corpus/c3.sol | 3 + scripts/refinement/corpus/c4.sol | 4 + scripts/refinement/corpus/c5.sol | 3 + scripts/refinement/corpus/c6.sol | 3 + scripts/refinement/corpus/c7.sol | 3 + scripts/refinement/corpus/c8.sol | 3 + scripts/refinement/corpus/c9.sol | 3 + scripts/refinement/corpus/d1.sol | 3 + scripts/refinement/corpus/d2.sol | 3 + scripts/refinement/corpus/d3.sol | 3 + scripts/refinement/corpus/d4.sol | 3 + scripts/refinement/corpus/w1.sol | 8 + scripts/refinement/corpus/w2.sol | 7 + scripts/refinement/corpus/w3.sol | 7 + scripts/refinement/corpus/w4.sol | 9 + scripts/refinement/corpus/w5.sol | 8 + scripts/refinement/counter/counter.sol | 7 + scripts/refinement/counter/milestone.sh | 332 +++ scripts/refinement/events/events.sol | 7 + scripts/refinement/facts.sh | 254 ++ scripts/refinement/gen.sh | 173 ++ scripts/refinement/gen_proof.py | 1297 +++++++++ scripts/refinement/mulx/mul.sol | 9 + scripts/refinement/prove-rev | 1 + scripts/refinement/require-modulo.sh | 150 + scripts/refinement/routes | 3 + scripts/refinement/solar-rev | 1 + scripts/refinement/w5-milestone.sh | 307 ++ vendor/README.md | 21 + vendor/evm-interaction/EvmInteraction.lean | 15 + .../Simulation/Interaction.lean | 2579 +++++++++++++++++ .../EvmInteraction/Simulation/OpenWorld.lean | 618 ++++ .../EvmInteraction/Simulation/Outcome.lean | 105 + vendor/evm-interaction/lakefile.lean | 37 + vendor/evmyul/.gitignore | 2 + vendor/evmyul/Conform/Wheels.lean | 112 + vendor/evmyul/EvmYul/Data/Stack.lean | 86 + vendor/evmyul/EvmYul/EVM/Exception.lean | 153 + vendor/evmyul/EvmYul/EVM/GasConstants.lean | 47 + vendor/evmyul/EvmYul/FFI/ffi.lean | 94 + vendor/evmyul/EvmYul/MachineState.lean | 40 + vendor/evmyul/EvmYul/MachineStateOps.lean | 156 + vendor/evmyul/EvmYul/Maps/AccountMap.lean | 133 + vendor/evmyul/EvmYul/Maps/ByteMap.lean | 32 + vendor/evmyul/EvmYul/Maps/StorageMap.lean | 53 + vendor/evmyul/EvmYul/Operations.lean | 813 ++++++ vendor/evmyul/EvmYul/PerformIO.lean | 7 + vendor/evmyul/EvmYul/Pretty.lean | 44 + vendor/evmyul/EvmYul/SharedState.lean | 9 + .../evmyul/EvmYul/SpongeHash/Keccak256.lean | 214 ++ vendor/evmyul/EvmYul/State.lean | 41 + vendor/evmyul/EvmYul/State/Account.lean | 127 + vendor/evmyul/EvmYul/State/AccountOps.lean | 49 + vendor/evmyul/EvmYul/State/Block.lean | 357 +++ vendor/evmyul/EvmYul/State/BlockHeader.lean | 107 + vendor/evmyul/EvmYul/State/ExecutionEnv.lean | 49 + vendor/evmyul/EvmYul/State/Substate.lean | 87 + vendor/evmyul/EvmYul/State/SubstateOps.lean | 15 + vendor/evmyul/EvmYul/State/Transaction.lean | 183 ++ vendor/evmyul/EvmYul/State/TrieRoot.lean | 34 + vendor/evmyul/EvmYul/State/Withdrawal.lean | 65 + vendor/evmyul/EvmYul/StateOps.lean | 189 ++ vendor/evmyul/EvmYul/UInt256.lean | 532 ++++ vendor/evmyul/EvmYul/Wheels.lean | 413 +++ vendor/evmyul/EvmYul/Yul/Ast.lean | 113 + vendor/evmyul/lakefile.lean | 73 + vendor/evmyul/license.txt | 201 ++ vendor/loom/LICENSE | 191 ++ vendor/loom/Loom.lean | 1 + vendor/loom/Loom/MonadAlgebras/Defs.lean | 248 ++ .../Loom/MonadAlgebras/Instances/Basic.lean | 26 + vendor/loom/Loom/MonadAlgebras/WP/Basic.lean | 148 + vendor/loom/Loom/MonadUtil.lean | 40 + vendor/loom/Loom/SpecMonad.lean | 57 + vendor/loom/README.md | 39 + 306 files changed, 47809 insertions(+), 210 deletions(-) create mode 100644 .github/workflows/refinement.yml create mode 100644 SolidCore/Refinement.lean create mode 100644 SolidCore/Refinement/Abi.lean create mode 100644 SolidCore/Refinement/Axioms/Audit.lean create mode 100644 SolidCore/Refinement/Axioms/C4.lean create mode 100644 SolidCore/Refinement/Axioms/CounterGeneric.lean create mode 100644 SolidCore/Refinement/Axioms/Main.lean create mode 100644 SolidCore/Refinement/Axioms/MulX.lean create mode 100644 SolidCore/Refinement/Axioms/W4.lean create mode 100644 SolidCore/Refinement/Bytecode/B1.lean create mode 100644 SolidCore/Refinement/Bytecode/B2.lean create mode 100644 SolidCore/Refinement/Bytecode/B3.lean create mode 100644 SolidCore/Refinement/Bytecode/B4.lean create mode 100644 SolidCore/Refinement/Bytecode/B5.lean create mode 100644 SolidCore/Refinement/Bytecode/B6.lean create mode 100644 SolidCore/Refinement/Bytecode/B7.lean create mode 100644 SolidCore/Refinement/Bytecode/C1.lean create mode 100644 SolidCore/Refinement/Bytecode/C10.lean create mode 100644 SolidCore/Refinement/Bytecode/C11.lean create mode 100644 SolidCore/Refinement/Bytecode/C2.lean create mode 100644 SolidCore/Refinement/Bytecode/C3.lean create mode 100644 SolidCore/Refinement/Bytecode/C4.lean create mode 100644 SolidCore/Refinement/Bytecode/C5.lean create mode 100644 SolidCore/Refinement/Bytecode/C6.lean create mode 100644 SolidCore/Refinement/Bytecode/C7.lean create mode 100644 SolidCore/Refinement/Bytecode/C8.lean create mode 100644 SolidCore/Refinement/Bytecode/C9.lean create mode 100644 SolidCore/Refinement/Bytecode/D1.lean create mode 100644 SolidCore/Refinement/Bytecode/D2.lean create mode 100644 SolidCore/Refinement/Bytecode/D3.lean create mode 100644 SolidCore/Refinement/Bytecode/D4.lean create mode 100644 SolidCore/Refinement/Bytecode/W1.lean create mode 100644 SolidCore/Refinement/Bytecode/W2.lean create mode 100644 SolidCore/Refinement/Bytecode/W3.lean create mode 100644 SolidCore/Refinement/Bytecode/W4.lean create mode 100644 SolidCore/Refinement/Bytecode/W5.lean create mode 100644 SolidCore/Refinement/C1/Refinement.lean create mode 100644 SolidCore/Refinement/C1/Spec.lean create mode 100644 SolidCore/Refinement/C1/Target.lean create mode 100644 SolidCore/Refinement/Check.lean create mode 100644 SolidCore/Refinement/Compose.lean create mode 100644 SolidCore/Refinement/ComposeSeq.lean create mode 100644 SolidCore/Refinement/Dirty.lean create mode 100644 SolidCore/Refinement/Dirty/Source.lean create mode 100644 SolidCore/Refinement/Dyn.lean create mode 100644 SolidCore/Refinement/Dyn/Abi.lean create mode 100644 SolidCore/Refinement/Dyn/Evm.lean create mode 100644 SolidCore/Refinement/Dyn/Refines.lean create mode 100644 SolidCore/Refinement/Dyn/Source.lean create mode 100644 SolidCore/Refinement/Evm/Calldata.lean create mode 100644 SolidCore/Refinement/Evm/Lemmas.lean create mode 100644 SolidCore/Refinement/Evm/Symex.lean create mode 100644 SolidCore/Refinement/Evm/Wide.lean create mode 100644 SolidCore/Refinement/Evm/WideStorage.lean create mode 100644 SolidCore/Refinement/Evm/WideStorageAt.lean create mode 100644 SolidCore/Refinement/Facts.lean create mode 100644 SolidCore/Refinement/Facts/B1.lean create mode 100644 SolidCore/Refinement/Facts/B2.lean create mode 100644 SolidCore/Refinement/Facts/B3.lean create mode 100644 SolidCore/Refinement/Facts/B4.lean create mode 100644 SolidCore/Refinement/Facts/B5.lean create mode 100644 SolidCore/Refinement/Facts/B6.lean create mode 100644 SolidCore/Refinement/Facts/B7.lean create mode 100644 SolidCore/Refinement/Facts/C1.lean create mode 100644 SolidCore/Refinement/Facts/C10.lean create mode 100644 SolidCore/Refinement/Facts/C11.lean create mode 100644 SolidCore/Refinement/Facts/C2.lean create mode 100644 SolidCore/Refinement/Facts/C3.lean create mode 100644 SolidCore/Refinement/Facts/C4.lean create mode 100644 SolidCore/Refinement/Facts/C5.lean create mode 100644 SolidCore/Refinement/Facts/C6.lean create mode 100644 SolidCore/Refinement/Facts/C7.lean create mode 100644 SolidCore/Refinement/Facts/C8.lean create mode 100644 SolidCore/Refinement/Facts/C9.lean create mode 100644 SolidCore/Refinement/Facts/Prelude.lean create mode 100644 SolidCore/Refinement/Facts/W1.lean create mode 100644 SolidCore/Refinement/Facts/W2.lean create mode 100644 SolidCore/Refinement/Facts/W3.lean create mode 100644 SolidCore/Refinement/Facts/W4.lean create mode 100644 SolidCore/Refinement/Generic/Event.lean create mode 100644 SolidCore/Refinement/Generic/Mir.lean create mode 100644 SolidCore/Refinement/Generic/MirRun.lean create mode 100644 SolidCore/Refinement/Generic/MulTest.lean create mode 100644 SolidCore/Refinement/Generic/Packed.lean create mode 100644 SolidCore/Refinement/Generic/Simp.lean create mode 100644 SolidCore/Refinement/Generic/Source.lean create mode 100644 SolidCore/Refinement/Generic/SourceCall.lean create mode 100644 SolidCore/Refinement/Generic/SourceRun.lean create mode 100644 SolidCore/Refinement/Generic/SourceStmt.lean create mode 100644 SolidCore/Refinement/Generic/Stage.lean create mode 100644 SolidCore/Refinement/Generic/Tree.lean create mode 100644 SolidCore/Refinement/Generic/Value.lean create mode 100644 SolidCore/Refinement/Headline.lean create mode 100644 SolidCore/Refinement/Keccak/Agree.lean create mode 100644 SolidCore/Refinement/Keccak/TwoWords.lean create mode 100644 SolidCore/Refinement/Kernel.lean create mode 100644 SolidCore/Refinement/KernelCopies.lean create mode 100644 SolidCore/Refinement/KernelRfl.lean create mode 100644 SolidCore/Refinement/Seq/Check.lean create mode 100644 SolidCore/Refinement/Seq/Corpus.lean create mode 100644 SolidCore/Refinement/Seq/Explore.lean create mode 100644 SolidCore/Refinement/Sequence.lean create mode 100644 SolidCore/Refinement/Solar/Assemble.lean create mode 100644 SolidCore/Refinement/Solar/AssembleFast.lean create mode 100644 SolidCore/Refinement/Solar/AssembleSim.lean create mode 100644 SolidCore/Refinement/Solar/Bank/Assembly.lean create mode 100644 SolidCore/Refinement/Solar/Bank/Certified.lean create mode 100644 SolidCore/Refinement/Solar/Bank/Lowering.lean create mode 100644 SolidCore/Refinement/Solar/Bank/Mutants.lean create mode 100644 SolidCore/Refinement/Solar/C4/Assembly.lean create mode 100644 SolidCore/Refinement/Solar/C4/Certified.lean create mode 100644 SolidCore/Refinement/Solar/C4/Lowering.lean create mode 100644 SolidCore/Refinement/Solar/C4/LoweringGeneric.lean create mode 100644 SolidCore/Refinement/Solar/Counter/AnyStorage.lean create mode 100644 SolidCore/Refinement/Solar/Counter/Assembly.lean create mode 100644 SolidCore/Refinement/Solar/Counter/AssemblyAt.lean create mode 100644 SolidCore/Refinement/Solar/Counter/Calls.lean create mode 100644 SolidCore/Refinement/Solar/Counter/Every.lean create mode 100644 SolidCore/Refinement/Solar/Counter/EverySeq.lean create mode 100644 SolidCore/Refinement/Solar/Counter/Lowering.lean create mode 100644 SolidCore/Refinement/Solar/Counter/LoweringAt.lean create mode 100644 SolidCore/Refinement/Solar/Counter/LoweringGeneric.lean create mode 100644 SolidCore/Refinement/Solar/Counter/Milestone.lean create mode 100644 SolidCore/Refinement/Solar/Counter/NegativeAt.lean create mode 100644 SolidCore/Refinement/Solar/Counter/NegativeValue.lean create mode 100644 SolidCore/Refinement/Solar/Counter/Sequence.lean create mode 100644 SolidCore/Refinement/Solar/Counter/Sequences.lean create mode 100644 SolidCore/Refinement/Solar/Counter/Source.lean create mode 100644 SolidCore/Refinement/Solar/Counter/Spec.lean create mode 100644 SolidCore/Refinement/Solar/Counter/SpecAt.lean create mode 100644 SolidCore/Refinement/Solar/Counter/Value.lean create mode 100644 SolidCore/Refinement/Solar/Events/Assembly.lean create mode 100644 SolidCore/Refinement/Solar/Events/Certified.lean create mode 100644 SolidCore/Refinement/Solar/Events/Lowering.lean create mode 100644 SolidCore/Refinement/Solar/Hex.lean create mode 100644 SolidCore/Refinement/Solar/Lowering.lean create mode 100644 SolidCore/Refinement/Solar/LoweringGeneric.lean create mode 100644 SolidCore/Refinement/Solar/Milestone.lean create mode 100644 SolidCore/Refinement/Solar/MulX/Assembly.lean create mode 100644 SolidCore/Refinement/Solar/MulX/Certified.lean create mode 100644 SolidCore/Refinement/Solar/MulX/Lowering.lean create mode 100644 SolidCore/Refinement/Solar/RequireModulo/Assembly.lean create mode 100644 SolidCore/Refinement/Solar/RequireModulo/Bytecode.lean create mode 100644 SolidCore/Refinement/Solar/RequireModulo/Evm10.lean create mode 100644 SolidCore/Refinement/Solar/Sequences.lean create mode 100644 SolidCore/Refinement/Solar/W1.lean create mode 100644 SolidCore/Refinement/Solar/W1Value.lean create mode 100644 SolidCore/Refinement/Solar/W4/Milestone.lean create mode 100644 SolidCore/Refinement/Solar/W4Lowering.lean create mode 100644 SolidCore/Refinement/Source/B1.lean create mode 100644 SolidCore/Refinement/Source/B2.lean create mode 100644 SolidCore/Refinement/Source/B3.lean create mode 100644 SolidCore/Refinement/Source/B4.lean create mode 100644 SolidCore/Refinement/Source/B5.lean create mode 100644 SolidCore/Refinement/Source/B6.lean create mode 100644 SolidCore/Refinement/Source/B7.lean create mode 100644 SolidCore/Refinement/Source/Bank.lean create mode 100644 SolidCore/Refinement/Source/C1.lean create mode 100644 SolidCore/Refinement/Source/C10.lean create mode 100644 SolidCore/Refinement/Source/C11.lean create mode 100644 SolidCore/Refinement/Source/C2.lean create mode 100644 SolidCore/Refinement/Source/C3.lean create mode 100644 SolidCore/Refinement/Source/C4.lean create mode 100644 SolidCore/Refinement/Source/C5.lean create mode 100644 SolidCore/Refinement/Source/C6.lean create mode 100644 SolidCore/Refinement/Source/C7.lean create mode 100644 SolidCore/Refinement/Source/C8.lean create mode 100644 SolidCore/Refinement/Source/C9.lean create mode 100644 SolidCore/Refinement/Source/D1.lean create mode 100644 SolidCore/Refinement/Source/D2.lean create mode 100644 SolidCore/Refinement/Source/D3.lean create mode 100644 SolidCore/Refinement/Source/D4.lean create mode 100644 SolidCore/Refinement/Source/Events.lean create mode 100644 SolidCore/Refinement/Source/MulX.lean create mode 100644 SolidCore/Refinement/Source/W1.lean create mode 100644 SolidCore/Refinement/Source/W2.lean create mode 100644 SolidCore/Refinement/Source/W3.lean create mode 100644 SolidCore/Refinement/Source/W4.lean create mode 100644 SolidCore/Refinement/Source/W5.lean create mode 100644 SolidCore/Refinement/Spec.lean create mode 100644 SolidCore/Refinement/Statement.lean create mode 100644 SolidCore/Refinement/Wide/Clean.lean create mode 100644 SolidCore/Refinement/Wide/Refines.lean create mode 100644 SolidCore/Refinement/Wide/Source.lean create mode 100644 SolidCore/Refinement/Wide/Tactic.lean create mode 100644 SolidCore/Verify.lean create mode 100644 SolidCore/Verify/Abi.lean create mode 100644 SolidCore/Verify/Basic.lean create mode 100644 SolidCore/Verify/C1.lean create mode 100644 SolidCore/Verify/C4.lean create mode 100644 SolidCore/Verify/Finite.lean create mode 100644 SolidCore/Verify/Run.lean create mode 100644 SolidCore/Verify/Tactic.lean create mode 100644 SolidCore/Verify/W1.lean create mode 100644 SolidCore/Verify/W4.lean create mode 100644 SolidCore/Verify/W5.lean create mode 100644 SolidCore/Witness/AddmodArgOrder.lean create mode 100644 SolidCore/Witness/BytesNShiftConversionWidth.lean create mode 100644 SolidCore/Witness/TupleStorageCopyOrder.lean create mode 100644 scripts/refinement/FACTS.md create mode 100755 scripts/refinement/axiom-audit.sh create mode 100755 scripts/refinement/axiom-closure.py create mode 100644 scripts/refinement/bank/bank.sol create mode 100755 scripts/refinement/c4.sh create mode 100644 scripts/refinement/c4/c4.sol create mode 100755 scripts/refinement/check-solar-w1.sh create mode 100755 scripts/refinement/check.sh create mode 100644 scripts/refinement/corpus/b1.sol create mode 100644 scripts/refinement/corpus/b2.sol create mode 100644 scripts/refinement/corpus/b3.sol create mode 100644 scripts/refinement/corpus/b4.sol create mode 100644 scripts/refinement/corpus/b5.sol create mode 100644 scripts/refinement/corpus/b6.sol create mode 100644 scripts/refinement/corpus/b7.sol create mode 100644 scripts/refinement/corpus/c1.sol create mode 100644 scripts/refinement/corpus/c10.sol create mode 100644 scripts/refinement/corpus/c11.sol create mode 100644 scripts/refinement/corpus/c2.sol create mode 100644 scripts/refinement/corpus/c3.sol create mode 100644 scripts/refinement/corpus/c4.sol create mode 100644 scripts/refinement/corpus/c5.sol create mode 100644 scripts/refinement/corpus/c6.sol create mode 100644 scripts/refinement/corpus/c7.sol create mode 100644 scripts/refinement/corpus/c8.sol create mode 100644 scripts/refinement/corpus/c9.sol create mode 100644 scripts/refinement/corpus/d1.sol create mode 100644 scripts/refinement/corpus/d2.sol create mode 100644 scripts/refinement/corpus/d3.sol create mode 100644 scripts/refinement/corpus/d4.sol create mode 100644 scripts/refinement/corpus/w1.sol create mode 100644 scripts/refinement/corpus/w2.sol create mode 100644 scripts/refinement/corpus/w3.sol create mode 100644 scripts/refinement/corpus/w4.sol create mode 100644 scripts/refinement/corpus/w5.sol create mode 100644 scripts/refinement/counter/counter.sol create mode 100755 scripts/refinement/counter/milestone.sh create mode 100644 scripts/refinement/events/events.sol create mode 100755 scripts/refinement/facts.sh create mode 100755 scripts/refinement/gen.sh create mode 100755 scripts/refinement/gen_proof.py create mode 100644 scripts/refinement/mulx/mul.sol create mode 100644 scripts/refinement/prove-rev create mode 100755 scripts/refinement/require-modulo.sh create mode 100644 scripts/refinement/routes create mode 100644 scripts/refinement/solar-rev create mode 100755 scripts/refinement/w5-milestone.sh create mode 100644 vendor/README.md create mode 100644 vendor/evm-interaction/EvmInteraction.lean create mode 100644 vendor/evm-interaction/EvmInteraction/Simulation/Interaction.lean create mode 100644 vendor/evm-interaction/EvmInteraction/Simulation/OpenWorld.lean create mode 100644 vendor/evm-interaction/EvmInteraction/Simulation/Outcome.lean create mode 100644 vendor/evm-interaction/lakefile.lean create mode 100644 vendor/evmyul/.gitignore create mode 100644 vendor/evmyul/Conform/Wheels.lean create mode 100644 vendor/evmyul/EvmYul/Data/Stack.lean create mode 100644 vendor/evmyul/EvmYul/EVM/Exception.lean create mode 100644 vendor/evmyul/EvmYul/EVM/GasConstants.lean create mode 100644 vendor/evmyul/EvmYul/FFI/ffi.lean create mode 100644 vendor/evmyul/EvmYul/MachineState.lean create mode 100644 vendor/evmyul/EvmYul/MachineStateOps.lean create mode 100644 vendor/evmyul/EvmYul/Maps/AccountMap.lean create mode 100644 vendor/evmyul/EvmYul/Maps/ByteMap.lean create mode 100644 vendor/evmyul/EvmYul/Maps/StorageMap.lean create mode 100644 vendor/evmyul/EvmYul/Operations.lean create mode 100644 vendor/evmyul/EvmYul/PerformIO.lean create mode 100644 vendor/evmyul/EvmYul/Pretty.lean create mode 100644 vendor/evmyul/EvmYul/SharedState.lean create mode 100644 vendor/evmyul/EvmYul/SpongeHash/Keccak256.lean create mode 100644 vendor/evmyul/EvmYul/State.lean create mode 100644 vendor/evmyul/EvmYul/State/Account.lean create mode 100644 vendor/evmyul/EvmYul/State/AccountOps.lean create mode 100644 vendor/evmyul/EvmYul/State/Block.lean create mode 100644 vendor/evmyul/EvmYul/State/BlockHeader.lean create mode 100644 vendor/evmyul/EvmYul/State/ExecutionEnv.lean create mode 100644 vendor/evmyul/EvmYul/State/Substate.lean create mode 100644 vendor/evmyul/EvmYul/State/SubstateOps.lean create mode 100644 vendor/evmyul/EvmYul/State/Transaction.lean create mode 100644 vendor/evmyul/EvmYul/State/TrieRoot.lean create mode 100644 vendor/evmyul/EvmYul/State/Withdrawal.lean create mode 100644 vendor/evmyul/EvmYul/StateOps.lean create mode 100644 vendor/evmyul/EvmYul/UInt256.lean create mode 100644 vendor/evmyul/EvmYul/Wheels.lean create mode 100644 vendor/evmyul/EvmYul/Yul/Ast.lean create mode 100644 vendor/evmyul/lakefile.lean create mode 100644 vendor/evmyul/license.txt create mode 100644 vendor/loom/LICENSE create mode 100644 vendor/loom/Loom.lean create mode 100644 vendor/loom/Loom/MonadAlgebras/Defs.lean create mode 100644 vendor/loom/Loom/MonadAlgebras/Instances/Basic.lean create mode 100644 vendor/loom/Loom/MonadAlgebras/WP/Basic.lean create mode 100644 vendor/loom/Loom/MonadUtil.lean create mode 100644 vendor/loom/Loom/SpecMonad.lean create mode 100644 vendor/loom/README.md diff --git a/.github/workflows/refinement.yml b/.github/workflows/refinement.yml new file mode 100644 index 00000000..06f731d2 --- /dev/null +++ b/.github/workflows/refinement.yml @@ -0,0 +1,107 @@ +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 against solar + 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/refinement/gen.sh', 'scripts/refinement/prove-rev', 'scripts/refinement/facts.sh') }} + + - name: Cache Lake build + uses: actions/cache@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') }}- + + # The solar checkout the milestone checks clone next to this repository: its build and the + # Lean builds of solar-tv (W1Proofs, counter), keyed by the scripts that pin it. + - name: Cache the solar checkout's builds + uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 + with: + path: | + ../ck-pipeline/target + ../ck-pipeline/solar-tv/.lake + ../ck-pipeline/scripts/evm-rules/lean/.lake + key: refinement-solar-${{ hashFiles('lakefile.lean', 'scripts/refinement/w5-milestone.sh', 'scripts/refinement/counter/milestone.sh') }} + + # Clones solar at the pinned commit into the path lakefile.lean requires solar_tv from + # (../ck-pipeline), so it runs before check.sh. Mathlib comes from the Lake build cache + # above, else from its build cache (lake exe cache get). + - name: Check the w5 milestone + env: + SOLAR_REPO: https://github.com/paradigmxyz/solar.git + REQUIRE_SOLC: "1" + CARGO_BUILD_JOBS: "4" + # The runner has 16 GB: each Lean process is capped, and the statement lowering, + # which peaks at about 5.4 GB, builds alone on one thread under its own cap. + LEAN_NUM_THREADS: "2" + LEAN_MEMORY: "4500" + W5_LOWERING_MEMORY: "7000" + run: scripts/refinement/w5-milestone.sh + + # The storage counter's milestone, on the solar checkout the w5 check made. + - name: Check the counter milestone + env: + SOLAR_REPO: https://github.com/paradigmxyz/solar.git + REQUIRE_SOLC: "1" + CARGO_BUILD_JOBS: "4" + LEAN_NUM_THREADS: "2" + LEAN_MEMORY: "4500" + run: scripts/refinement/counter/milestone.sh + + # The generic assembly theorem on solar's RequireModuloCases, whose layout has a turned + # branch, fallthroughs and a backward jump, on the same solar checkout. + - name: Check RequireModuloCases' assembly + env: + SOLAR_REPO: https://github.com/paradigmxyz/solar.git + CARGO_BUILD_JOBS: "4" + LEAN_NUM_THREADS: "2" + LEAN_MEMORY: "4500" + run: scripts/refinement/require-modulo.sh + + # The generic assembly theorem on c4, two uint8 fields packed in one slot (BYTE, NOT and + # SHL), on the same solar checkout. + - name: Check c4's assembly + env: + SOLAR_REPO: https://github.com/paradigmxyz/solar.git + CARGO_BUILD_JOBS: "4" + LEAN_NUM_THREADS: "2" + LEAN_MEMORY: "4500" + run: scripts/refinement/c4.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..7172907b 100644 --- a/.gitignore +++ b/.gitignore @@ -13,3 +13,4 @@ tests/.foundry-suites/ __pycache__/ tests/forge-harness/*/out/ tests/forge-harness/*/cache/ +/.cache/ 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..c4be998d --- /dev/null +++ b/SolidCore/Refinement.lean @@ -0,0 +1,34 @@ +import SolidCore.Refinement.Statement +import SolidCore.Refinement.Corpus +import SolidCore.Refinement.Compose +import SolidCore.Refinement.Spec +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 + +/-! +# 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/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/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/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/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/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..dafd07a9 --- /dev/null +++ b/SolidCore/Refinement/Facts.lean @@ -0,0 +1,31 @@ +-- 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.W1 +import SolidCore.Refinement.Facts.W2 +import SolidCore.Refinement.Facts.W3 +import SolidCore.Refinement.Facts.W4 +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/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/Generic/Event.lean b/SolidCore/Refinement/Generic/Event.lean new file mode 100644 index 00000000..5c5c2213 --- /dev/null +++ b/SolidCore/Refinement/Generic/Event.lean @@ -0,0 +1,148 @@ +import SolidCore.Refinement.Generic.Source + +/-! +# 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` constant that fits in 160 bits (`evOk`; SolidCore reverts on an +address that does not, 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` constant that +fits in 160 bits. -/ +def evFieldOk (f : EventField) (w : WExpr) : Bool := + match f.ty, w with + | .uint256, _ => true + | .address, .lit n => decide (n < 2 ^ 160) + | _, _ => false + +/-- Whether every field is one the fragment logs, with its word. -/ +def evOk : List EventField → List WExpr → Bool + | [], [] => true + | f :: fs, w :: ws => evFieldOk f w && evOk 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) {f : EventField} {w : WExpr} (h : evFieldOk 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 n hty + simp only [decide_eq_true_eq] at h + have hn : n % wordSize < 2 ^ 160 := Nat.lt_of_le_of_lt (Nat.mod_le _ _) h + have hn' : n % wordSize < 1461501637330902918203684832716283019655932542976 := hn + rw [hty] + have hb : abiStaticBytes? Ty.address (.word ((WExpr.lit n).eval ρ)) = + some (wordToBytesBE wordBytes ((WExpr.lit n).eval ρ)) := by + simp [abiStaticBytes?, abiAddressFits, WExpr.eval, norm_mod, Nat.mod_mod, hn'] + exact ⟨hb, hb, rfl, rfl, rfl⟩ + · simp at h + +theorem encode_ok (ρ : Val) : ∀ (fs : List EventField) (ws : List WExpr), evOk 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 ρ fs ws h.2 + obtain ⟨hs, -, hh, -, -⟩ := evFieldOk_static ρ 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 : ∀ (fs : List EventField) (ws : List WExpr), evOk fs ws = true → + ∀ (ρ : Val) (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, ρ, off => by + simp only [evOk, Bool.and_eq_true] at h + obtain ⟨ih1, ih2⟩ := evData_ok fs ws h.2 ρ off + obtain ⟨-, hs, -, hd, hw⟩ := evFieldOk_static ρ 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) (fs : List EventField) (ws : List WExpr) (h : evOk 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 ρ (wordBytes * (evData fs ws).length) + simp [abiEncodeValues?, h1, h2, bind, Option.bind] + +end SolidCore.Refinement.Generic diff --git a/SolidCore/Refinement/Generic/Mir.lean b/SolidCore/Refinement/Generic/Mir.lean new file mode 100644 index 00000000..34750ee1 --- /dev/null +++ b/SolidCore/Refinement/Generic/Mir.lean @@ -0,0 +1,390 @@ +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`); 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; a call that binds or publishes further results (a callee returning several + words), a callee or an entry function that stores an entry heap (`Function.entryHeap`), and + `heap_floor` 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 + deriving DecidableEq, Repr + +/-- No environment read. -/ +def EnvFlags.off : EnvFlags := ⟨false, false⟩ + +/-- The caller and the hash of two words. -/ +def EnvFlags.all : EnvFlags := ⟨true, true⟩ + +/-- The caller only. -/ +def EnvFlags.callerOnly : EnvFlags := ⟨true, false⟩ + +/-- 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 }) + | .caller, [], st => if ev.caller = true then some (some (.w (.lit callerWord)), 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 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).lit? 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 + -- Outside the fragment (a cast, a low-bits mask, a select, a heap floor, 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 callee of an internal or tail call, when the module has it and it stores no entry heap +on entering it (`Function.entryHeap`, outside the fragment): then entering it keeps the state +(`Function.start`). -/ +def symCallee (m : Module) (callee : Nat) : Option Function := + match m.functions[callee]? with + | some g => if g.entryHeap.isNone then some g else none + | none => none + +/-- Whether the module's entry function stores no entry heap when the run starts +(`Module.startState`), so that the run starts in the call's initial state. -/ +def entryFree (m : Module) : Bool := + match m.functions[m.entry]? with + | some f => f.entryHeap.isNone + | none => true + +/-- 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' 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 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 := + if entryFree m then + symRun env (.w (.lit 0)) m sel n fuel [] (.enter m.entry 0 0) (fun _ => .w (.lit 0)) SState.initial [] + else none + +/-- 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 := + if entryFree m then + symRun env .paid m sel n fuel [] (.enter m.entry 0 0) (fun _ => .w (.lit 0)) SState.initial [] + else none + +end SolidCore.Refinement.Generic diff --git a/SolidCore/Refinement/Generic/MirRun.lean b/SolidCore/Refinement/Generic/MirRun.lean new file mode 100644 index 00000000..5f18e969 --- /dev/null +++ b/SolidCore/Refinement/Generic/MirRun.lean @@ -0,0 +1,1194 @@ +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 = callerWord + 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 ρ) (ev : EnvFlags) : EnvAsk ev o ρ := + ⟨fun _ => h.caller, 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 + +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 } + · -- 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, WExpr.eval, henv.caller hev] + exact (Nat.mod_eq_of_lt callerWord_lt).symm + · 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.eq_of_lit? hl] at hse + simp only [SV.Rel] at hwv + rw [hwv, ← hse] + rfl + 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 .. :: _, _, _, _, _, h, _, _, _, _ => by simp [symInsts] at h + | .low .. :: _, _, _, _, _, h, _, _, _, _ => by simp [symInsts] at h + | .select .. :: _, _, _, _, _, h, _, _, _, _ => by simp [symInsts] at h + | .call .. :: _, _, _, _, _, h, _, _, _, _ => by simp [symInsts] at h + | .heapFloor .. :: _, _, _, _, _, 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 ∧ ∀ s, g.start s = s := by + unfold symCallee at h + split at h + · rename_i g' hg + split at h + · rename_i hn + simp only [Option.some.injEq] at h + subst h + refine ⟨hg, fun s => ?_⟩ + unfold Function.start + cases he : g'.entryHeap with + | none => rfl + | some _ => simp [he] at hn + · simp at h + · simp at h + +theorem entryFree_start {m : Module} (h : entryFree m = true) (s : State) : m.startState s = s := by + unfold entryFree at h + unfold Module.startState + split + · rename_i f hf + simp only [hf] at h + unfold Function.start + cases he : f.entryHeap with + | none => rfl + | some _ => simp [he] at h + · rfl + +/-- 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 + obtain ⟨hg', hstart⟩ := 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, s, by simp only [segment, splitCall, execInsts, hg', hbp', hstart], hst, he3, + hs⟩ + | 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 + obtain ⟨hg', hstart⟩ := 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, s2, + by simp only [segment, hsp, hexec, hg', hbp', hstart], + ⟨rfl, rfl, rfl, rfl, rfl, rfl, rfl, he2, hst⟩, he3, hs2⟩ + | 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} (hfree : entryFree m = true) + (h : symRun ev cv m sel n fuel [] (.enter m.entry 0 0) (fun _ => .w (.lit 0)) 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) (fun _ hp => absurd hp List.not_mem_nil) + rw [← entryFree_start hfree (State.initial call)] at hk + 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 + split at h + · exact symRun_entry_sound hc.at o henv m ‹_› h + · simp at 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 + split at h + · exact symRun_entry_sound hc o henv m ‹_› h + · simp at 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..317494a5 --- /dev/null +++ b/SolidCore/Refinement/Generic/Simp.lean @@ -0,0 +1,724 @@ +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, 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) + +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 _ + | .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) + +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] + | .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, 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) + | 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 => 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..7428a2ef --- /dev/null +++ b/SolidCore/Refinement/Generic/Source.lean @@ -0,0 +1,774 @@ +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 + +/-- 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 + 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 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 ([], .lit callerWord) + | .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 => 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 => do + let o ← binOf op + 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) + | .storageRead .header x [] => + (fieldOf? fields x).map fun (k, off, bytes) => ([], readField (S.writes.read (.lit k)) off bytes) + | .storageRead .ref x [] => + (fieldOf? fields x).map fun (k, off, bytes) => ([], readField (S.writes.read (.lit k)) off bytes) + | .storageRead .element x [idx] => do + let k ← mapOf? fields x + let (gs, v) ← eraseExpr fields S idx + some (gs, S.writes.read (.hash v (.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 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 = callerWord + 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_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] + +/-- 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] + +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 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] + 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, 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, 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] at h + | some pl => + cases hr : eraseExpr fields S r with + | none => cases op <;> simp [eraseExpr, hl, hr, binOf] 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, 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] + split <;> simp_all [SolI.ofExcept, WExpr.eval, BinOp.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) + | 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, WExpr.eval, + hrel.sender, callerWord] + rfl + | storageRead m x idx => + cases m + case element => + match idx, h with + | [i], h => + simp only [eraseExpr, 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⟩ := 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 + all_goals + cases idx <;> simp only [eraseExpr, Option.map_eq_some_iff, Prod.mk.injEq] at h + all_goals first + | (simp at h; done) + | skip + all_goals + obtain ⟨⟨k, off, bytes⟩, hk, 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 + | _ => 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..671f0136 --- /dev/null +++ b/SolidCore/Refinement/Generic/SourceCall.lean @@ -0,0 +1,102 @@ +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` 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 with neither. +-/ + +namespace SolidCore.Refinement.Generic +open SolidCore.Solidity.Source + +/-- A binding of the fragment: a `uint256`, not a storage reference. -/ +def wordBinding (b : BindingDecl) : Bool := + (match b.ty with | .uint256 => 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 + +/-- 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 := [] } + +/-- 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) : Leaf → Option Tree + | .normal S => do + let ws ← fn.returns.mapM fun r => Scopes.get? S.scopes r.name + some (.halt true (ws.flatMap wordOBytes) S.writes S.logs) + | .returned S vs => + if vs = [] then do + let ws ← fn.returns.mapM fun r => Scopes.get? S.scopes r.name + some (.halt true (ws.flatMap wordOBytes) S.writes S.logs) + else if vs.length = fn.returns.length then + some (.halt true (vs.flatMap wordOBytes) S.writes S.logs) + else none + | .reverted none => some (.halt false [] [] []) + | .reverted (some c) => some (.halt false (panicBytes c) [] []) + +/-- The call's tree from its body's branch tree. -/ +def brTree (fn : FunctionDef) : Br → Option Tree + | .leaf l => leafTree fn l + | .ite c t e => do + let t' ← brTree fn t + let e' ← brTree fn 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`. -/ +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 fuel fn.body (initState fn) + let t ← brTree fn 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..e9cb4abd --- /dev/null +++ b/SolidCore/Refinement/Generic/SourceRun.lean @@ -0,0 +1,814 @@ +import SolidCore.Refinement.Generic.SourceCall +import SolidCore.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⟩).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 := ⟨core.storageFields, core.eventDecls, 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] + +theorem defaults_words (ρ : Val) (rs : List BindingDecl) + (hrs : ∀ r ∈ rs, r.ty = .uint256 ∧ 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))] + simp [BindingDecl.defaultBinding, h.1, h.2, Source.Ty.defaultValue, WExpr.eval] + +/-! ## 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) + (hl : ∀ x e, Scopes.get? S.scopes x = some e → rt.lookupLocal? x = some (.word (e.eval ρ))) : + ∀ (rs : List BindingDecl) (ws : List WExpr), (∀ r ∈ rs, r.ty = .uint256) → + 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 + have ih := collect_words ρ rt S hl rs ws' (fun q hq => hrs q (List.mem_cons_of_mem _ hq)) hws' + simp [collectReturnBindings.collect, hl _ _ he, deref_word, hrs r List.mem_cons_self, + coerce_word, ih, bind, Except.bind, pure, Except.pure] + +theorem coerce_words (ρ : Val) (rt : Runtime) : + ∀ (rs : List BindingDecl) (ws : List WExpr), (∀ r ∈ rs, r.ty = .uint256) → + ws.length = rs.length → + 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, hl => by + have ih := coerce_words ρ rt rs ws (fun q hq => hrs q (List.mem_cons_of_mem _ hq)) + (by simpa using hl) + simp only [List.map_cons] at ih ⊢ + simp [coerceReturnBindings.coerce, deref_word, hrs r List.mem_cons_self, coerce_word, ih, + bind, Except.bind, pure, Except.pure] + | [], _ :: _, _, hl | _ :: _, [], _, hl => by simp at hl + +/-! ## 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) : + ∀ (rs : List BindingDecl) (ws : List WExpr) (off : Nat), (∀ r ∈ rs, r.ty = .uint256) → + ws.length = rs.length → + 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, hl => by + have ih := encodeAux_words ρ rs ws off (fun q hq => hrs q (List.mem_cons_of_mem _ hq)) + (by simpa using hl) + have hty := hrs r List.mem_cons_self + simp only [List.map_cons, hty, ABI.encodeValuesAux?, ABI.Ty.isDynamicAbi, ABI.encodeStaticValue?, + ih, List.flatMap_cons, List.map_append, encodeWord_eval] + rfl + | [], _ :: _, _, _, hl | _ :: _, [], _, _, hl => by simp at hl + +theorem encode_words (ρ : Val) (rs : List BindingDecl) (ws : List WExpr) + (hrs : ∀ r ∈ rs, r.ty = .uint256) (hl : ws.length = rs.length) : + 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), (∀ r ∈ rs, r.ty = .uint256) → + ABI.Ty.listAbiHeadWords? (rs.map BindingDecl.ty) = some rs.length := by + intro rs hrs + induction rs with + | nil => rfl + | cons r rs ih => + simp [ABI.Ty.listAbiHeadWords?, hrs r List.mem_cons_self, ABI.Ty.abiHeadWords?, + ABI.Ty.isDynamicAbi, ABI.Ty.staticAbiHeadWords?, + ih (fun q hq => hrs q (List.mem_cons_of_mem _ hq)), Nat.add_comm] + simp [ABI.encodeValues?, hhw rs hrs, encodeAux_words ρ rs ws _ hrs hl, 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 + +/-! ## The call -/ + +theorem brTree_eval (fn : FunctionDef) (ρ : Val) : + ∀ (b : Br) (T : Tree), brTree fn b = some T → + ∃ T', leafTree fn (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 ρ e e' he + · exact brTree_eval fn ρ 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] + +/-- **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) : + b.ty = .uint256 ∧ 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 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) fuel fn.body (initState fn) = some b) {T : Tree} + (hT : brTree fn b = some T) (args : List Nat) + (hlen : args.length = fn.params.length) (hargs : ∀ a ∈ args, a < 2 ^ 256) + (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⟩).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, r.ty = .uint256 ∧ 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⟩ with hρ + have hρok : ρ.Ok := slotValue_store σ + 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 ρ (envOf c.core) 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] } + obtain ⟨r, hrun, hleaf⟩ := eval_stmt ρ (envOf c.core) 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 = (envOf c.core).tbl from rfl, hrun] + rfl + obtain ⟨T', hT', hTe⟩ := brTree_eval fn ρ b T hT + rw [hacc, if_pos rfl, hcall, ← hTe] + have hrl : ∀ l : List BindingDecl, (∀ x ∈ l, x.ty = .uint256 ∧ x.isStorageRef = false) → + ∀ x ∈ l, x.ty = .uint256 := fun l h x hx => (h x hx).1 + 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, Option.some.injEq] at hT' + obtain ⟨ws, hws, rfl⟩ := hT' + have hlen' : ws.length = fn.returns.length := by + exact length_of_mapM _ _ _ hws + simp only [FunctionDef.callBodyResult, FunctionDef.collectReturns, collectReturnBindings, + collect_words ρ rt S hleaf.expr.locals fn.returns ws (hrl _ hr) hws, untag_words, + encode_words ρ fn.returns ws (hrl _ hr) hlen', 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, + Option.some.injEq] at hT' + obtain ⟨ws, hws, rfl⟩ := hT' + have hlen' : ws.length = fn.returns.length := length_of_mapM _ _ _ hws + simp only [FunctionDef.callBodyResult, List.map_nil, List.isEmpty_nil, if_true, + FunctionDef.collectReturns, collectReturnBindings, + collect_words ρ rt S hst'.expr.locals fn.returns ws (hrl _ hr) hws, untag_words, + encode_words ρ fn.returns ws (hrl _ hr) hlen', 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 hlen' + 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 fn.returns vs (hrl _ hr) hlen', untag_words, + encode_words ρ fn.returns vs (hrl _ hr) hlen', 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 p <;> cases r <;> simp only [LeafRel] at hleaf + · subst hleaf + simp only [leafTree, Option.some.injEq] at hT' + subst hT' + simp [FunctionDef.callBodyResult, RevertData.untagFixedBytes, + ABI.Contract.encodeRevertData?, Source.observe, Tree.eval, Res.obs, hρ, + SolidCore.Refinement.Evm.Wide.callAt] + · subst hleaf + simp only [leafTree, Option.some.injEq] at hT' + subst hT' + simp [FunctionDef.callBodyResult, RevertData.untagFixedBytes, encode_panic ρ, + 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⟩).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⟩ 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 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..94882736 --- /dev/null +++ b/SolidCore/Refinement/Generic/SourceStmt.lean @@ -0,0 +1,1518 @@ +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 + +/-- How a statement of the fragment ends. -/ +inductive Leaf where + | normal (S : SymState) + | returned (S : SymState) (vals : List WExpr) + | reverted (panic : Option Nat) + 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 (some 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 (some 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. -/ +structure EraseEnv where + fields : List StorageField + events : List EventDecl + tbl : FunctionTable + +/-- 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 })) + +/-- 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 + +/-- 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` and panics. -/ +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 (some code))) + | .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 } + 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 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 + | _ => 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 = callerWord + 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 ρ) + +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] } + +/-- 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 none => r = .empty + | .reverted _ r, .reverted (some c) => r = .panic c + | _, _ => 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⟩ + +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) + {ws : List WExpr} (hok : evOk 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 ρ decl.fields ws hok + have hdata := encodeValues_ok ρ 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 }⟩ + · 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 } from { hrel1 with frames := rfl })⟩ + 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 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 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 } := + { 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 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 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 + 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..0caac7bb --- /dev/null +++ b/SolidCore/Refinement/Generic/Stage.lean @@ -0,0 +1,290 @@ +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`-word returns, checked +`+`, `-`, `*` with narrow cleanups, truncating casts such as `uint256(a)`, bitwise `&`, `|`, `^`, +comparisons, 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`), `if`, blocks, returns and reverts with `Panic`, 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 `=` 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⟩`. -/ +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⟩ + { 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⟩ := + ⟨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⟩ := + ⟨h.caller, 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. -/ +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 => decide (t1.canon = 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 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/Tree.lean b/SolidCore/Refinement/Generic/Tree.lean new file mode 100644 index 00000000..41bbf7d1 --- /dev/null +++ b/SolidCore/Refinement/Generic/Tree.lean @@ -0,0 +1,482 @@ +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 `=`, which the kernel decides. +-/ + +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) + 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 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 + +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 _ _ => + 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 + +/-- 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 + +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] + +/-- 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..406553ac --- /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⟩ + { 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..cfb4ea57 --- /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 SolidCore.Verify +import SolidCore.Verify.C4 +import SolidCore.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/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..fb7cb7d9 --- /dev/null +++ b/SolidCore/Refinement/Seq/Corpus.lean @@ -0,0 +1,24 @@ +-- Generated by scripts/refinement/gen_proof.py. Do not edit. + +import SolidCore.Refinement.Sequence +import SolidCore.Refinement.Corpus.B1.Seq +import SolidCore.Refinement.Corpus.B2.Seq +import SolidCore.Refinement.Corpus.B3.Seq +import SolidCore.Refinement.Corpus.B4.Seq +import SolidCore.Refinement.Corpus.B5.Seq +import SolidCore.Refinement.Corpus.B6.Seq +import SolidCore.Refinement.Corpus.B7.Seq +import SolidCore.Refinement.Corpus.C1.Seq +import SolidCore.Refinement.Corpus.C10.Seq +import SolidCore.Refinement.Corpus.C11.Seq +import SolidCore.Refinement.Corpus.C2.Seq +import SolidCore.Refinement.Corpus.C3.Seq +import SolidCore.Refinement.Corpus.C4.Seq +import SolidCore.Refinement.Corpus.C5.Seq +import SolidCore.Refinement.Corpus.C6.Seq +import SolidCore.Refinement.Corpus.C7.Seq +import SolidCore.Refinement.Corpus.C8.Seq +import SolidCore.Refinement.Corpus.C9.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/Assemble.lean b/SolidCore/Refinement/Solar/Assemble.lean new file mode 100644 index 00000000..d9b4338c --- /dev/null +++ b/SolidCore/Refinement/Solar/Assemble.lean @@ -0,0 +1,824 @@ +import SolidCore.Refinement.Evm.Wide +import SolarTV.Composition +import SolarTV.Stages.AssemblyCheck + +/-! +# 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 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 + 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. -/ +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 + | .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 => some (0x80 + i.val) | .swap i => some (0x90 + i.val) + | _ => 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 _ => [.op 0xfe] + | .effect .callvalue _ => [.op 0x34] + | .effect .calldataload _ => [.op 0x35] + | .effect .calldatasize _ => [.op 0x36] + | .effect .caller _ => [.op 0x33] + | .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 _ _ => [.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 | .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 => some (i.val + 1, 1) + | .swap i => some (i.val + 2, 0) + | _ => 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 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 + 1 ≤ h) && ok (h + 1) [] (tyAt ty i.val :: ty) (k - 1) + | .swap i => decide (1 ≤ k) && 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 + unfold decode at h + split at h + · cases h + · rename_i b hb + by_cases h0 : b = PUSH0 + · simp [h0] at h + · by_cases h1 : PUSH1 ≤ b ∧ b ≤ PUSH32 + · rw [if_neg h0, if_pos h1] at h + split at h <;> simp at h + · rw [if_neg h0, if_neg h1] at h + simp only [Option.some.injEq, Prod.mk.injEq, Instr.op.injEq] at h + exact ⟨by rw [hb, h.1], h.2.symm⟩ + +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 + 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 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 <;> 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 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 => + simp only [SolarTV.EVM.step, Option.map_eq_some_iff] at hstep + obtain ⟨x, hx, rfl⟩ := hstep + exact ⟨_, le_refl _, dup i hlt hcode hx hgas hlen⟩ + case swap i => + 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) hx hgas⟩ + +/-- 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 + +end SolidCore.Refinement.Solar.Assemble diff --git a/SolidCore/Refinement/Solar/AssembleFast.lean b/SolidCore/Refinement/Solar/AssembleFast.lean new file mode 100644 index 00000000..24acd54b --- /dev/null +++ b/SolidCore/Refinement/Solar/AssembleFast.lean @@ -0,0 +1,286 @@ +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 some (.op byte, pc + 1, tl) + +/-- `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 && labelAt 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 + · simp [h0, h1, htl] + +/-- A successful decode ends within the code. -/ +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 + unfold decode at h + split at h + · cases h + · rename_i byte hb + have hlt := (List.getElem?_eq_some_iff.1 hb).1 + split at h + · cases h + omega + · split at h + · split at h + · cases h + assumption + · cases h + · cases h + omega + +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] + 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 : labelAt offset pc item <;> + 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 + +/-- The walk steps from an instruction to the next opcode, as EthLib's scan does. -/ +theorem next_eq_nextOpcode {code : ByteArray} {pc next : Nat} {i : SolarTV.Assembly.Instr} + (h : decode (bytesOf code) pc = some (i, next)) : next = nextOpcode code pc ∧ pc < code.size := by + unfold decode at h + split at h + · cases h + · rename_i byte hb + have hlt := (List.getElem?_eq_some_iff.1 hb).1 + rw [length_bytesOf] at hlt + have hbyte : (byteAt code pc).toNat = byte := by + rw [byteAt_toNat, List.getD_eq_getElem?_getD, hb] + rfl + refine ⟨?_, hlt⟩ + rw [nextOpcode_eq_opLen, opLen_eq, hbyte] + unfold PUSH0 PUSH1 PUSH32 at h + split at h + · cases h + rename_i h0 + simp [h0] + · split at h + · split at h + · cases h + rename_i h0 h1 _ + simp only [h1, and_self, ↓reduceIte] + omega + · cases h + · cases h + rename_i h1 + simp only [h1, ↓reduceIte] + +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) + +/-- 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 ∧ labelAt offset pc item = 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 ⟨hnext, hpc⟩ := next_eq_nextOpcode hd + have hbpc := hb hpc + rcases List.mem_cons.1 hl with rfl | hl + · have hoff : offset l = pc := by simpa [labelAt] 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 + · refine walk_labels items next hw' (fun hn => ?_) l hl + rw [hnext] at hn ⊢ + exact boundary_next hbpc hn + · 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/AssembleSim.lean b/SolidCore/Refinement/Solar/AssembleSim.lean new file mode 100644 index 00000000..7b466576 --- /dev/null +++ b/SolidCore/Refinement/Solar/AssembleSim.lean @@ -0,0 +1,1832 @@ +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 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 + +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 + +/-- EthLib's logs are those of `ss0` and then one for each event of SolarTV's world. -/ +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 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 ⊢ + +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) + (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 ∧ ok h' [] 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 ⟨⟨hk, hi⟩, hok⟩ := hok + have hiS : i.val < S.length := by omega + have hiT : i.val < T.length := by omega + refine ⟨hk, _, rfl, h + 1, _, _, _, ?_, ?_, SR.dup hR hiS hiT, by simp; omega, by simp, 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 ⟨⟨hk, 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 ⟨hk, _, rfl, h, _, _, _, ?_, ?_, SR.swap hR hiS hiT, by simp; omega, by simp, 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 ⟨⟨hk, h1⟩, hok⟩ := hok + rcases S with _ | ⟨a, S⟩ + · simp at hh; omega + rcases T with _ | ⟨b, T⟩ + · simp at hL + refine ⟨hk, _, rfl, h - 1, _, _, _, rfl, rfl, (SR.uncons.1 hR).2, by simp at hh; omega, + by simp only [List.length_cons]; omega, 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 ⟨⟨⟨hk, 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 ⟨hk, byte, hbyte, (h + d).toNat, _, _, _, hstep, hstepT, + SR.cons (τ := some false) rfl (SR.drop need hR), ?_, ?_, 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⟩ + +/-- 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) + +/-! ## 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', hok⟩ := + stack_sim (ctx := context o call s) hne hok' hh 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' [] ty' S' T' (k - 1) s (pc + 1) M g1 st ss hok (by omega) + (List.nil_prefix) 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' + · 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], + 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 + +/-- 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}, 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 + +/-- 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/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..bf83b3f9 --- /dev/null +++ b/SolidCore/Refinement/Solar/Bank/Certified.lean @@ -0,0 +1,217 @@ +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), solar's version with the commit its manifest records (a8179dfc), 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 = [("solar-tv/milestone/bank/bank.sol", + "513398d47335b204a6b047493dd86e9c05066e950ba1300ba5d25850a5f8cb1f")] ∧ + Manifest.compiler = "0.8.38+commit.4a7d9ede.solar.0.3.0-dev" ∧ + Manifest.arguments = ["solar-tv/milestone/bank/bank.sol", "-Ogas", "--evm-version", "osaka", + "--emit=bin-runtime", "-Zemit-lean-stages=solar-tv/milestone/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, 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 = [("solar-tv/milestone/bank/bank.sol", + "513398d47335b204a6b047493dd86e9c05066e950ba1300ba5d25850a5f8cb1f")] ∧ + Manifest.compiler = "0.8.38+commit.4a7d9ede.solar.0.3.0-dev" ∧ + Manifest.arguments = ["solar-tv/milestone/bank/bank.sol", "-Ogas", "--evm-version", "osaka", + "--emit=bin-runtime", "-Zemit-lean-stages=solar-tv/milestone/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..2be635fb --- /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 +513398d47335b204a6b047493dd86e9c05066e950ba1300ba5d25850a5f8cb1f, 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..76a77f58 --- /dev/null +++ b/SolidCore/Refinement/Solar/C4/Certified.lean @@ -0,0 +1,185 @@ +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), solar's version with its commit 7817979b, 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 = [("solar-tv/milestone/c4/c4.sol", + "31c39cd4e9c5cba0f78aff3a986d69be40c5f68cdb36fbf05ad3d0a5e950e858")] ∧ + Manifest.compiler = "0.8.38+commit.a8179dfc.solar.0.3.0-dev" ∧ + Manifest.arguments = ["solar-tv/milestone/c4/c4.sol", "-Zcheck-analyses=false", + "--emit=bin-runtime", "-Zemit-lean-stages=solar-tv/milestone/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, 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..badaa9a4 --- /dev/null +++ b/SolidCore/Refinement/Solar/C4/Lowering.lean @@ -0,0 +1,1033 @@ +import SolidCore.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 + 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..762892ca --- /dev/null +++ b/SolidCore/Refinement/Solar/C4/LoweringGeneric.lean @@ -0,0 +1,171 @@ +import SolidCore.Refinement.Generic.Value +import SolidCore.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..afb66a0e --- /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⟩ + 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..30c57516 --- /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⟩ + 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..53b9f024 --- /dev/null +++ b/SolidCore/Refinement/Solar/Counter/Milestone.lean @@ -0,0 +1,175 @@ +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 for +compiler 1134e61f 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.compiler = "0.8.38+commit.1134e61f.solar.0.3.0-dev" ∧ + 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, 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..f237b55b --- /dev/null +++ b/SolidCore/Refinement/Solar/Counter/Spec.lean @@ -0,0 +1,381 @@ +import SolidCore.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; 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 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/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..a30e0d50 --- /dev/null +++ b/SolidCore/Refinement/Solar/Events/Certified.lean @@ -0,0 +1,137 @@ +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), solar's version with its commit 0a455fda, 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 = [("solar-tv/milestone/events/events.sol", + "8b951679cab695d07c193e56dd5d96d14a1c63976673c79a72c690f07c50b5b0")] ∧ + Manifest.compiler = "0.8.38+commit.0a455fda.solar.0.3.0-dev" ∧ + Manifest.arguments = ["solar-tv/milestone/events/events.sol", "-Ogas", "--evm-version", "osaka", + "--emit=bin-runtime", "-Zemit-lean-stages=solar-tv/milestone/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, 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..df4349aa --- /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 +8b951679cab695d07c193e56dd5d96d14a1c63976673c79a72c690f07c50b5b0, 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..cbc757ac --- /dev/null +++ b/SolidCore/Refinement/Solar/Lowering.lean @@ -0,0 +1,308 @@ +import SolidCore.Refinement.Solar.W1 +import SolidCore.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, ?_⟩ + · simp only [State.initial] + 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, ?_⟩ + · simp only [State.initial] + 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..93950497 --- /dev/null +++ b/SolidCore/Refinement/Solar/Milestone.lean @@ -0,0 +1,124 @@ +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.compiler = "0.8.38+commit.3ca8f483.solar.0.3.0-dev" ∧ + 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, 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..bd716e62 --- /dev/null +++ b/SolidCore/Refinement/Solar/MulX/Certified.lean @@ -0,0 +1,152 @@ +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), solar's version with its commit a8179dfc, 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 = [("solar-tv/milestone/mulx/mulx.sol", + "50ef03a3c5724105509c3ed40b7ee7d92ea43b5d48a67d0e6722b26806dd4980")] ∧ + Manifest.compiler = "0.8.38+commit.4a7d9ede.solar.0.3.0-dev" ∧ + Manifest.arguments = ["solar-tv/milestone/mulx/mulx.sol", "-Zcheck-analyses=false", + "--emit=bin-runtime", "-Zemit-lean-stages=solar-tv/milestone/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, 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..88be5cfe --- /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 +50ef03a3c5724105509c3ed40b7ee7d92ea43b5d48a67d0e6722b26806dd4980), + + 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/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/W1.lean b/SolidCore/Refinement/Solar/W1.lean new file mode 100644 index 00000000..c90b34d5 --- /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, ?_⟩ + · 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, Quot.sound] -/ +#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..1ef1f89a --- /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, ?_⟩ + · 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..1350aaef --- /dev/null +++ b/SolidCore/Refinement/Solar/W4/Milestone.lean @@ -0,0 +1,268 @@ +import SolidCore.Refinement.Solar.W4Lowering +import SolidCore.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/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/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/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/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/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..a7c60cea 100644 --- a/SolidCore/Solidity/Ast.lean +++ b/SolidCore/Solidity/Ast.lean @@ -95,7 +95,132 @@ 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. -/ +def Ty.reprListString (ts : List Ty) : String := + let s := Ty.reprFlatList ts + if s.length < 100 then s else toString (repr ts) def Ty.function (params returns : List Ty) (mutability : StateMutability) (visibility : Visibility) : Ty := diff --git a/SolidCore/Solidity/Interface/Expressions.lean b/SolidCore/Solidity/Interface/Expressions.lean index 718dca69..d500e257 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 @@ -2990,8 +3005,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 derived print, computed structurally when short so the kernel can evaluate it. + 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 @@ -7795,6 +7811,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 +8006,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 +8056,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 +8077,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 +8100,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 +8389,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 +8676,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..1177853d 100644 --- a/SolidCore/Solidity/Interface/Foundation.lean +++ b/SolidCore/Solidity/Interface/Foundation.lean @@ -4631,10 +4631,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 derived print, + -- computed structurally when short so the kernel can evaluate it. some (externalCallKindTypeEnvPrefix ++ contractName ++ ":" ++ signature ++ - "#" ++ toString (repr paramTys)) + "#" ++ Ty.reprListString paramTys) def ExternalCallKindEntry.toTypeEnvEntry? (entry : ExternalCallKindEntry) : Option (Option (Name × Ty)) := do @@ -7930,7 +7931,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..027e76ac 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 @@ -9855,7 +9879,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 diff --git a/SolidCore/Solidity/Interpreter.lean b/SolidCore/Solidity/Interpreter.lean index 7cbefcf2..c844a674 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 @@ -7654,9 +7654,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 +7672,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''') ← diff --git a/SolidCore/Solidity/TypeCheck.lean b/SolidCore/Solidity/TypeCheck.lean index 284aa998..4aee41d8 100644 --- a/SolidCore/Solidity/TypeCheck.lean +++ b/SolidCore/Solidity/TypeCheck.lean @@ -10185,7 +10185,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 diff --git a/SolidCore/Verify.lean b/SolidCore/Verify.lean new file mode 100644 index 00000000..02f4b06e --- /dev/null +++ b/SolidCore/Verify.lean @@ -0,0 +1,10 @@ +import SolidCore.Verify.Basic +import SolidCore.Verify.Abi +import SolidCore.Verify.Finite +import SolidCore.Verify.Run +import SolidCore.Verify.Tactic +import SolidCore.Verify.C1 +import SolidCore.Verify.W1 +import SolidCore.Verify.W4 +import SolidCore.Verify.C4 +import SolidCore.Verify.W5 diff --git a/SolidCore/Verify/Abi.lean b/SolidCore/Verify/Abi.lean new file mode 100644 index 00000000..388295c8 --- /dev/null +++ b/SolidCore/Verify/Abi.lean @@ -0,0 +1,38 @@ +import SolidCore.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/SolidCore/Verify/Basic.lean b/SolidCore/Verify/Basic.lean new file mode 100644 index 00000000..78d10502 --- /dev/null +++ b/SolidCore/Verify/Basic.lean @@ -0,0 +1,189 @@ +import Loom.MonadAlgebras.WP.Basic +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 + +/-! ## 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 + +end SolidCore.Verify + diff --git a/SolidCore/Verify/C1.lean b/SolidCore/Verify/C1.lean new file mode 100644 index 00000000..79afadda --- /dev/null +++ b/SolidCore/Verify/C1.lean @@ -0,0 +1,222 @@ +import SolidCore.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/SolidCore/Verify/C4.lean b/SolidCore/Verify/C4.lean new file mode 100644 index 00000000..977b5365 --- /dev/null +++ b/SolidCore/Verify/C4.lean @@ -0,0 +1,458 @@ +import SolidCore.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/SolidCore/Verify/Finite.lean b/SolidCore/Verify/Finite.lean new file mode 100644 index 00000000..b3e975b4 --- /dev/null +++ b/SolidCore/Verify/Finite.lean @@ -0,0 +1,75 @@ +import SolidCore.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/SolidCore/Verify/Run.lean b/SolidCore/Verify/Run.lean new file mode 100644 index 00000000..90fce1b6 --- /dev/null +++ b/SolidCore/Verify/Run.lean @@ -0,0 +1,132 @@ +import SolidCore.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/SolidCore/Verify/Tactic.lean b/SolidCore/Verify/Tactic.lean new file mode 100644 index 00000000..ce8e5f4e --- /dev/null +++ b/SolidCore/Verify/Tactic.lean @@ -0,0 +1,110 @@ +import SolidCore.Verify.Run +import SolidCore.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/SolidCore/Verify/W1.lean b/SolidCore/Verify/W1.lean new file mode 100644 index 00000000..876032a5 --- /dev/null +++ b/SolidCore/Verify/W1.lean @@ -0,0 +1,98 @@ +import SolidCore.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/SolidCore/Verify/W4.lean b/SolidCore/Verify/W4.lean new file mode 100644 index 00000000..e23082c5 --- /dev/null +++ b/SolidCore/Verify/W4.lean @@ -0,0 +1,173 @@ +import SolidCore.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/SolidCore/Verify/W5.lean b/SolidCore/Verify/W5.lean new file mode 100644 index 00000000..95775752 --- /dev/null +++ b/SolidCore/Verify/W5.lean @@ -0,0 +1,173 @@ +import SolidCore.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/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/lake-manifest.json b/lake-manifest.json index 085d68a3..a831f685 100644 --- a/lake-manifest.json +++ b/lake-manifest.json @@ -1,140 +1,180 @@ -{ - "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"}, + {"url": "https://github.com/paradigmxyz/solar.git", + "type": "git", + "subDir": "solar-tv", + "scope": "", + "rev": "2144dccb0984e6df238cc2e5e9d741e2e52e722d", + "name": "solar_tv", + "manifestFile": "lake-manifest.json", + "inputRev": "2144dccb0984e6df238cc2e5e9d741e2e52e722d", + "inherited": false, + "configFile": "lakefile.toml"}, + {"type": "path", + "scope": "", + "name": "«evm-interaction»", + "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"}, + {"type": "path", + "scope": "", + "name": "evm_rules", + "manifestFile": "lake-manifest.json", + "inherited": true, + "dir": ".lake/packages/solar_tv/solar-tv/../scripts/evm-rules/lean", + "copy": false, + "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": "«solidity-lean»", + "lakeDir": ".lake", + "fixedToolchain": false} diff --git a/lakefile.lean b/lakefile.lean index 5b4ab383..2ddbf64f 100644 --- a/lakefile.lean +++ b/lakefile.lean @@ -1,26 +1,53 @@ 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" + +-- solar's translation validation library: its contract semantics interface (SolarTV.Sem: +-- Call, Observable, Sem, Stage) is this library's, its lowered MIR and EVM IR semantics are +-- the languages of the w5 milestone's stages, and its W1Proofs library proves the backend +-- stages. A git dependency on solar at 2144dccb, whose solar-tv has the w1, w4, +-- counter, c4, mulx, bank and events milestones and the semantics of internal calls, casts and +-- selects. +require solar_tv from git + "https://github.com/paradigmxyz/solar.git" @ "2144dccb0984e6df238cc2e5e9d741e2e52e722d" / "solar-tv" + +-- 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 +55,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=7000 (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 +89,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 +123,29 @@ lean_exe precompileParity where lean_exe specHuntRunner where root := `SpecHuntRunner supportInterpreter := true + +/-- Loom's monad algebras and weakest preconditions, vendored with the changes Lean +4.35 needs; see vendor/loom/README.md. -/ +lean_lib Loom where + srcDir := "vendor/loom" + globs := #[.submodules `Loom] + +-- 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] 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/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..c51223bc --- /dev/null +++ b/scripts/refinement/axiom-audit.sh @@ -0,0 +1,18 @@ +#!/usr/bin/env bash +# The axiom pass: elaborates the five 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 +set -uo pipefail +cd "$(dirname "$0")/../.." +logs=() closures=() +for part in Main C4 MulX W4 CounterGeneric; 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.sh b/scripts/refinement/c4.sh new file mode 100755 index 00000000..9482b101 --- /dev/null +++ b/scripts/refinement/c4.sh @@ -0,0 +1,154 @@ +#!/usr/bin/env bash +# The generic assembly theorem on c4, two uint8 fields packed in one slot: the EVM IR to +# bytecode stage of scripts/refinement/c4/c4.sol's Main, which +# SolidCore/Refinement/Solar/C4/Assembly.lean proves from Assemble.stage_of_check, from any +# storage on every call with no value. solar's solar-tv/milestone/c4 proves the stages before it. +# +# scripts/refinement/c4.sh +# +# 1. Puts the solar checkout that lakefile.lean requires (the ..//solar-tv next to this repository, +# fetched from SOLAR_REPO when it is not a git checkout yet) at the pinned solar commit, with +# no uncommitted changes, as the milestone checks do. +# 2. Builds solar (cargo, CARGO_TARGET_DIR, default target in that checkout), or takes SOLAR, +# which must report the pinned commit. +# 3. Compiles c4.sol with solar's default options, -Zcheck-analyses=false (as release builds +# run) and -Zemit-lean-stages, and checks that the final EVM IR stage (Evm5.lean, after +# cfg-simplify-early) and the bytecode (Bytecode.lean) are the committed files byte for byte, +# and the bytecode is solar's --emit=bin-runtime output, the pinned 107 bytes. +# 4. Builds the module with lake under a cap per Lean process (LEAN_MEMORY, MB, default 4500) +# and prints the axioms of the stage, the check and the negative tests, failing on any axiom +# beyond propext, Classical.choice and Quot.sound. +# 5. Negative test: Assemble.stage_of_check, applied to the bytes this script gives it with the +# checker run by the kernel, proves the stage for solar's bytecode and fails for a one-byte +# mutant (SUB for the addition's ADD), where the checker evaluates to false. +set -euo pipefail + +root="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)" +cd "$root" + +# solar: branch ck-mulx, whose solar-tv has the c4 milestone. +solar_rev=37540a4715ffa6aa06e48e810e9aed57f74ef242 +sol=scripts/refinement/c4/c4.sol +contract=Main +# The runtime bytecode, 107 bytes. +bytecode=346055575f3560e01c806302067e6a036055576024361060ff60043511176055576004355f5460ff8116820160ff81116059579060ff1916179081601e1a1860081b9061ff00191617805f5560ff165f5260205ff35b5f5ffd5b6011602052634e487b715f526024601cfd + +tv_dir="$(sed -nE 's|^require solar_tv from "[.][.]" / "([^"]+)" / "solar-tv"$|\1|p' lakefile.lean)" +[[ -n "$tv_dir" ]] || { echo "error: lakefile.lean requires solar_tv from no ..//solar-tv" >&2; exit 1; } +tv="$(cd "$root/.." && pwd)/$tv_dir" +# The exported stages the proofs import. +lean_dir="$tv/milestone/c4/gen/Main" +export PATH="$HOME/.elan/bin:$PATH" +export LEAN_NUM_THREADS="${LEAN_NUM_THREADS:-2}" +memory="${LEAN_MEMORY:-4500}" +export CARGO_TARGET_DIR="${CARGO_TARGET_DIR:-$tv/target}" +work="$(mktemp -d)" +trap 'rm -rf "$work"' EXIT + +step() { printf '\n== %s\n' "$*"; } +die() { echo "error: $*" >&2; exit 1; } + +step "1. solar at $solar_rev" +if [[ ! -e "$tv/.git" ]]; then + repo="${SOLAR_REPO:?set SOLAR_REPO to a solar clone, bundle or URL with commit $solar_rev}" + mkdir -p "$tv" + git -C "$tv" init -q + git -C "$tv" fetch -q "$repo" '+refs/heads/*:refs/remotes/solar/*' + git -C "$tv" checkout -q --detach "$solar_rev" +fi +git -C "$tv" diff --quiet HEAD || die "$tv has uncommitted changes" +if [[ "$(git -C "$tv" rev-parse HEAD)" != "$solar_rev" ]]; then + git -C "$tv" checkout -q --detach "$solar_rev" +fi +echo "solar $solar_rev" + +step "2. build solar" +if [[ -n "${SOLAR-}" ]]; then + solar="$SOLAR" +else + (cd "$tv" && cargo build -j "${CARGO_BUILD_JOBS:-2}" --bin solar 2>&1 | tail -n 1) + solar="$CARGO_TARGET_DIR/debug/solar" +fi +"$solar" --version | grep -q "^Commit SHA: $solar_rev\$" || die "$solar is not solar $solar_rev" +"$solar" --version | head -n 1 + +step "3. regenerate the stages and compare them with the committed files" +runtime() { + 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(":" + sys.argv[1])))' "$contract" +} +emitted="$("$solar" "$sol" --emit=bin-runtime -Zcheck-analyses=false -Zemit-lean-stages="$work/gen" \ + 2>/dev/null | runtime)" || die "solar failed on $sol" +[[ "$emitted" == "$bytecode" ]] || die "solar's bytecode is not the pinned one: $emitted" +plain="$("$solar" "$sol" --emit=bin-runtime -Zcheck-analyses=false 2>/dev/null | runtime)" +[[ "$plain" == "$bytecode" ]] || die "-Zemit-lean-stages changed the bytecode: $plain" +last="$(ls "$work/gen/$contract" | sed -nE 's/^Evm([0-9]+)[.]lean$/\1/p' | sort -n | tail -n 1)" +[[ "$last" == 5 ]] || die "the last EVM IR stage is Evm$last.lean, not Evm5.lean" +for file in Evm5.lean Bytecode.lean; do + cmp -s "$work/gen/$contract/$file" "$lean_dir/$file" || { + diff "$work/gen/$contract/$file" "$lean_dir/$file" | head -n 40 >&2 + die "$lean_dir/$file is not solar's output" + } +done +grep -q "^ \"$bytecode\"\$" "$lean_dir/Bytecode.lean" || die "Bytecode.lean has other bytes" +echo "Evm5.lean and Bytecode.lean regenerate byte for byte; bytecode is solar's (107 bytes)" + +step "4. build and audit the axioms" +if [[ ! -f .lake/packages/mathlib/.lake/build/lib/lean/Mathlib.olean ]]; then + lake exe cache get > "$work/cache.log" 2>&1 || { tail -n 20 "$work/cache.log" >&2; die "lake exe cache get failed"; } +fi +if ! lake build -R -KleanMemory="$memory" SolidCore.Refinement.Solar.C4.Assembly \ + > "$work/build.log" 2>&1; then + grep -E '^error' -A8 "$work/build.log" | head -n 40 >&2 + die "lake build failed" +fi +tail -n 1 "$work/build.log" +cat > "$work/Audit.lean" <<'LEAN' +import SolidCore.Refinement.Solar.C4.Assembly +open SolidCore.Refinement.Solar +#print axioms Assemble.stage_of_check +#print axioms C4.check_ok +#print axioms C4.stage +#print axioms C4.mutated_bytes +#print axioms C4.mutantSub_check +#print axioms C4.mutantShl_check +LEAN +report="$(lake env lean -M "$memory" "$work/Audit.lean" 2>&1)" +echo "$report" +if grep -q "error" <<<"$report"; then die "the audit file does not check"; fi +bad="$(grep "depends on axioms" <<<"$report" | + sed -E 's/.*depends on axioms: \[(.*)\]/\1/' | tr ',' '\n' | tr -d ' ' | + grep -v -x -E 'propext|Classical\.choice|Quot\.sound' || true)" +[[ -z "$bad" ]] || die "axioms beyond propext, Classical.choice and Quot.sound: $bad" +[[ "$(grep -c "depends on axioms" <<<"$report")" -eq 6 ]] || die "a theorem is missing from the audit" + +step "5. negative: the generic assembly checker rejects a mutated bytecode" +# stage_of_check for the program and certificate on the bytes given, the check by the kernel. +generic_stage() { + cat > "$work/$1.lean" < h +#print axioms generic_stage +LEAN + # The mutant's case fails by design: its error is the output to check. + { lake env lean -M "$memory" "$work/$1.lean" 2>&1 || true; } | tr -s '[:space:]' ' ' +} +control="$(generic_stage control "$bytecode")" +[[ "$control" == *"depends on axioms: [propext, Classical.choice, Quot.sound]"* && "$control" != *error* ]] || + die "stage_of_check does not prove the stage for solar's bytecode: $control" +echo "control: stage_of_check proves the stage for solar's bytecode (propext, Classical.choice, Quot.sound)" +[[ "${bytecode:86:2}" == "01" ]] || die "offset 0x2b is not ADD" +edited="$(generic_stage mutant "${bytecode:0:86}03${bytecode:88}")" +grep -q -E 'error: Tactic `decide` proved that the proposition Assemble\.check SolarTV\.Export\.Main\.evm5 .* C4\.cert = true is false' <<<"$edited" || + die "the mutated bytecode did not fail the generic checker: $edited" +echo "rejected by a mismatch, as expected: the kernel evaluates Assemble.check on the mutant to false" + +printf '\nok: c4 assembly checked (solar %s)\n' "$solar_rev" 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/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/counter/milestone.sh b/scripts/refinement/counter/milestone.sh new file mode 100755 index 00000000..b34dc893 --- /dev/null +++ b/scripts/refinement/counter/milestone.sh @@ -0,0 +1,332 @@ +#!/usr/bin/env bash +# The counter milestone in one command: solar's bytecode for a storage counter (inc adds its +# argument to the uint256 in slot 0 with the overflow check) meets inc's specification verified +# on SolidCore with the Loom VC generator, with every stage of solar's pipeline proved in Lean. +# +# scripts/refinement/counter/milestone.sh +# +# 1. Puts the solar checkout that lakefile.lean requires (its solar_tv path, ../ck-pipeline +# next to this repository; fetched from SOLAR_REPO, a clone, bundle or URL whose branches +# hold the pinned commit, when it is not a git checkout yet, even if restored builds are +# there) at the pinned solar commit, with no uncommitted changes, and checks +# that its compiler sources are those of the commit the evidence's manifest names, except for +# the stage exporter (crates/codegen/src/lean_stages.rs), which only prints the stages as Lean. +# 2. Builds solar (cargo -j2, CARGO_TARGET_DIR, default target in that checkout). +# 3. Runs solar-tv/milestone/certify.sh on counter.sol: compiles Counter with -Ogas +# --evm-version osaka and -Zemit-lean-stages, checks the pinned bytecode and the manifest's +# hashes, regenerates every backend stage proof, builds them one module at a time under +# 4.5 GB, audits their axioms, runs solar-tv's negative tests (a bytecode mutation of the +# addition and edits of the stage outputs: the SSTORE's key (a wrong slot), the addition, +# the call value check and the overflow check dropped, each rejected by a mismatch, with +# unedited controls passing), and +# checks that every regenerated file is the committed evidence (except the compiler's build +# commit in the manifest). Then restores the manifest. +# 4. Binds the source: scripts/refinement/counter/counter.sol (which SolidCore parses) is +# solar-tv/milestone/counter/counter.sol (which solar's stages come from) byte for byte, +# solar compiles it to the pinned bytecode, the Lean literals and sha256s are solar's +# output, and, with solc 0.8.35 (SOLC, or cached or downloaded and checked; without one the +# check is skipped and reported unless REQUIRE_SOLC=1), SolidCore's source AST regenerates +# to the committed Counter/Source.lean. +# 5. Negative tests: one-byte mutations of the bytecode's ADD (x + d) and SSTORE (slot 0), the +# overflow check's PUSH1 0x41 JUMPI replaced by POP JUMPDEST JUMPDEST, and the call value +# check's jump target (offset 2) changed from 0x34 to the Panic(0x11) block's 0x41, fail the +# artifact check by a sha256 mismatch; in Lean, Counter.Milestone proves the assembly checker's walk +# rejects all three, Counter.Assembly and Counter.NegativeAt that the generic checker rejects +# all three, Counter.Lowering proves the source stage false for a lowering that subtracts +# instead of adding, and Counter.NegativeAt proves, from any storage, the assembly stage false +# for the third mutant and the source stage false for a lowering without the overflow check, +# each by a mismatch of observables (the overflow revert against a success), and +# Counter.NegativeValue proves the assembly stage on calls with value false for the fourth +# mutant, by a mismatch of observables (the empty revert against Panic(0x11)). +# 6. Fetches Mathlib's build cache when Mathlib is not built, builds the proof chain with lake, +# one Lean process at a time under a cap of LEAN_MEMORY MB (default 4500), and prints the +# axioms of the final theorems (certified, from the deployed storage, and certifiedAt, from +# any initial storage, where the overflow revert is reached; refinesSeq, every sequence of inc +# calls with the storage carried between calls; certifiedEvery, every call of inc and get with +# or without value, malformed call data and unknown selectors, from any storage, with +# certifiedValue, its calls with value; certifiedSeqEvery, every sequence of those calls), each +# stage (the assembly stages, stage and +# stageAt, from the generic theorem for every program the checker accepts, and directly as +# cross-checks, stage_run and stageAt_run) and the negative tests, failing on any axiom beyond +# propext, Classical.choice and Quot.sound. +# 7. Negative test of the generic assembly theorem: Assemble.stage_of_check, applied to the +# bytes this script gives it with the checker run by the kernel, proves the counter's +# assembly stage for solar's bytecode (only the three axioms) and fails for all four step 5 +# mutants, where the checker evaluates to false. +set -euo pipefail + +root="$(cd "$(dirname "${BASH_SOURCE[0]}")/../../.." && pwd)" +cd "$root" + +# solar: branch ck-pipeline, the generator of backend stage proofs and counter's evidence. +solar_rev=f19e9e46309c7cdb3a0f36668f7881d12bb8503a +# The commit whose compiler sources built the committed evidence (its manifest's compiler). +compiler_rev=1134e61fc7faa873d870d59a651839ce4c996cf8 +# The runtime bytecode, 83 bytes. +bytecode=346034575f3560e01c80636d4ce63c146038578063812600df03603457602436106034575f5460043581019081106041575f55005b5f5ffd5b5f545f5260205ff35b6011602052634e487b715f526024601cfd +bytecode_sha256=daed21b0c790bb2c08bcf999c9ebc6fea950c213ea0a799418552aa14c18f6ec +solc_version=0.8.35 +solc_sha256=fa8ac9a32d301ad023a36ee5a29f8e291fe3200c60244e43c142539e82a617f4 + +# lakefile.lean requires solar_tv from ..//solar-tv: the solar checkout is ../. +tv_dir="$(sed -nE 's|^require solar_tv from "[.][.]" / "([^"]+)" / "solar-tv"$|\1|p' lakefile.lean)" +[[ -n "$tv_dir" ]] || { echo "error: lakefile.lean requires solar_tv from no ..//solar-tv" >&2; exit 1; } +tv="$(cd "$root/.." && pwd)/$tv_dir" +export PATH="$HOME/.elan/bin:$PATH" +export LEAN_NUM_THREADS="${LEAN_NUM_THREADS:-2}" +# The cap of each Lean process, in MB. +memory="${LEAN_MEMORY:-4500}" +export CARGO_TARGET_DIR="${CARGO_TARGET_DIR:-$tv/target}" +sol=scripts/refinement/counter/counter.sol +lean_dir=SolidCore/Refinement/Solar/Counter +size=$((${#bytecode} / 2)) +logs="$(mktemp -d)" +trap 'rm -rf "$logs"' EXIT + +step() { printf '\n== %s\n' "$*"; } +die() { echo "error: $*" >&2; exit 1; } +sha_hex() { python3 -c 'import hashlib,sys; print(hashlib.sha256(bytes.fromhex(sys.argv[1])).hexdigest())' "$1"; } +bin_runtime() { + "$solar" "$1" -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(":Counter")))' +} +# Whether hex is the milestone's bytecode by its sha256: prints a mismatch and fails otherwise. +check_bytecode() { + local got + got="$(sha_hex "$1")" + if [[ "$got" != "$bytecode_sha256" ]]; then + echo "mismatch: sha256 $got, expected $bytecode_sha256" >&2 + return 1 + fi +} + +step "1. solar at $solar_rev" +if [[ ! -e "$tv/.git" ]]; then + # A new checkout, in a directory that may already hold restored builds (target, .lake). + repo="${SOLAR_REPO:?set SOLAR_REPO to a solar clone, bundle or URL with commit $solar_rev}" + mkdir -p "$tv" + git -C "$tv" init -q + git -C "$tv" fetch -q "$repo" '+refs/heads/*:refs/remotes/solar/*' + git -C "$tv" checkout -q --detach "$solar_rev" +fi +git -C "$tv" diff --quiet HEAD || die "$tv has uncommitted changes" +if [[ "$(git -C "$tv" rev-parse HEAD)" != "$solar_rev" ]]; then + git -C "$tv" checkout -q --detach "$solar_rev" +fi +exporter=crates/codegen/src/lean_stages.rs +git -C "$tv" diff --quiet "$compiler_rev" HEAD -- crates Cargo.toml Cargo.lock ":!$exporter" || + die "the compiler sources at $solar_rev differ from $compiler_rev's" +echo "solar $solar_rev; compiler sources identical to $compiler_rev except the exporter $exporter" + +step "2. build solar" +(cd "$tv" && cargo build -j "${CARGO_BUILD_JOBS:-2}" --bin solar 2>&1 | tail -n 1) +solar="$CARGO_TARGET_DIR/debug/solar" +"$solar" --version | head -n 1 + +step "3. certify solar's backend stages and compare them with the evidence" +manifest=solar-tv/milestone/counter/gen/Counter +restore() { git -C "$tv" checkout -q -- "$manifest/Manifest.lean" "$manifest/manifest.json"; } +if ! (cd "$tv" && CERTIFY_SKIP_BUILD=1 SOLAR="$solar" LEAN_MEMORY="$memory" \ + solar-tv/milestone/certify.sh solar-tv/milestone/counter/counter.sol Counter) > "$logs/certify.log" 2>&1; then + tail -n 30 "$logs/certify.log" >&2 + restore + die "certify.sh failed for counter" +fi +grep -E '^(==|ok|skip|counter|every|stages|bytecode)' "$logs/certify.log" +grep "depends on axioms" "$logs/certify.log" +for case in Evm5-sstore-key Evm5-no-overflow-check Evm5-no-callvalue-check; do + grep -q "^ok $case: " "$logs/certify.log" || die "the negative test $case did not reject its edit" +done +restore +git -C "$tv" diff --quiet HEAD || die "certify.sh left changes in $tv" +[[ -z "$(git -C "$tv" status --porcelain -- solar-tv/milestone/counter)" ]] || + die "certify.sh left files the evidence does not have" + +step "4. bind the source and the bytecode" +cmp -s "$sol" "$tv/solar-tv/milestone/counter/counter.sol" || + die "$sol and solar-tv/milestone/counter/counter.sol differ" +echo "$sol is solar-tv/milestone/counter/counter.sol byte for byte" +out="$(bin_runtime "$sol")" +[[ "$out" == "$bytecode" ]] || die "solar's bytecode is not the milestone's: $out" +check_bytecode "$out" +[[ "$(cat "$tv/solar-tv/milestone/counter/bytecode.hex")" == "$bytecode" ]] || + die "solar-tv's pinned bytecode.hex is not the milestone's" +manifest_sha="$(python3 -c 'import json,sys; print(json.load(open(sys.argv[1]))["bytecode_sha256"])' "$tv/$manifest/manifest.json")" +[[ "$manifest_sha" == "$bytecode_sha256" ]] || die "the manifest's sha256 is not the bytecode's" +grep -q "^def runtimeSha256 : String := \"$bytecode_sha256\"" "$lean_dir/Spec.lean" || + die "Spec.lean records another sha256" +grep -q "^ \"$bytecode\"\$" "$lean_dir/Spec.lean" || die "Spec.lean's runtimeHex has other bytes" +grep -q "^ 0x$bytecode\$" "$lean_dir/Spec.lean" || die "Spec.lean's runtimeNat has other bytes" +grep -q "^def runtimeSize : Nat := $size\$" "$lean_dir/Spec.lean" || + die "Spec.lean's runtimeSize is not the bytecode's length" +echo "bytecode sha256 $bytecode_sha256 ($size bytes): solar's output, Spec.lean's literals and the manifest's" +if [[ -z "${SOLC-}" ]]; then + cached="${XDG_CACHE_HOME:-$HOME/.cache}/solc/solc-$solc_version" + if [[ ! -x "$cached" ]]; then + mkdir -p "$(dirname "$cached")" + curl -fsSL -o "$cached.tmp" \ + "https://github.com/argotorg/solidity/releases/download/v$solc_version/solc-static-linux" || true + if [[ -s "$cached.tmp" ]] && echo "$solc_sha256 $cached.tmp" | sha256sum -c --quiet; then + chmod +x "$cached.tmp" + mv "$cached.tmp" "$cached" + else + rm -f "$cached.tmp" + fi + fi + if [[ -x "$cached" ]] && echo "$solc_sha256 $cached" | sha256sum -c --quiet; then SOLC="$cached"; fi +fi +if [[ -n "${SOLC-}" ]]; then + "$SOLC" --version | grep -q "Version: $solc_version+" || die "$SOLC is not solc $solc_version" + { + echo "-- Generated by scripts/refinement/counter/milestone.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 Counter --solc "$SOLC" \ + --namespace "SolidCore.Refinement.Source.Counter" --body-only | + sed "s|^def importedSourceName : String := .*$|def importedSourceName : String := \"$sol\"|" + } | diff -q - "$lean_dir/Source.lean" > /dev/null || + die "$lean_dir/Source.lean is not the source AST of $sol" + echo "SolidCore's source AST of counter.sol regenerates to $lean_dir/Source.lean" +elif [[ -n "${REQUIRE_SOLC-}" ]]; then + die "no solc $solc_version (set SOLC)" +else + echo "skipped: no solc $solc_version, so the source AST check did not run" +fi + +step "5. negative: mutated bytecode is rejected" +[[ "${bytecode:84:2}" == "01" ]] || die "offset 42 is not ADD" +[[ "${bytecode:100:2}" == "55" ]] || die "offset 50 is not SSTORE" +[[ "${bytecode:92:6}" == "604157" ]] || die "offsets 46 to 48 are not the overflow check's PUSH1 0x41 JUMPI" +no_check="${bytecode:0:92}505b5b${bytecode:98}" +grep -q "^ 0x$no_check\$" "$lean_dir/NegativeAt.lean" || die "NegativeAt.lean's mutantNoCheckNat is not the mutant" +[[ "${bytecode:0:8}" == "34603457" ]] || die "offsets 0 to 3 are not the call value check's CALLVALUE PUSH1 0x34 JUMPI" +value="${bytecode:0:4}41${bytecode:6}" +grep -q "^ 0x$value\$" "$lean_dir/NegativeValue.lean" || die "NegativeValue.lean's mutantValueNat is not the mutant" +for mutant in "${bytecode:0:84}03${bytecode:86}" "${bytecode:0:100}54${bytecode:102}" "$no_check" "$value"; do + if check_bytecode "$mutant"; then die "a mutated bytecode passed the check"; fi +done +echo "the four mutants (ADD to SUB at 42, SSTORE to SLOAD at 50, the overflow check's PUSH1 0x41" +echo "JUMPI at 46 to POP JUMPDEST JUMPDEST, the call value check's jump target 0x34 to 0x41 at 2)" +echo "rejected by a mismatch, as expected; in Lean," +echo "mutantAdd_no_walk, mutantStore_no_walk and mutantNoCheck_no_walk prove the assembly walk" +echo "rejects them, mutantAdd_check, mutantStore_check and mutantNoCheck_check that the generic" +echo "checker rejects them, lowering_rejects_bad proves the source stage false for a lowering with" +echo "SUB for ADD, and, from any storage, stageAt_rejects proves the assembly stage false for the" +echo "third mutant and loweringAt_rejects the source stage false for a lowering without" +echo "the overflow check, each by different observables on inc(1) from a full slot 0, and" +echo "assemblyValue_rejects the assembly stage on calls with value false for the fourth, by" +echo "different observables on get() with value 1 (the empty revert against Panic(0x11))" + +step "6. build the proof chain and audit its axioms" +if [[ ! -f .lake/packages/mathlib/.lake/build/lib/lean/Mathlib.olean ]]; then + lake exe cache get > "$logs/cache.log" 2>&1 || { tail -n 20 "$logs/cache.log" >&2; die "lake exe cache get failed"; } + echo "Mathlib from its build cache" +fi +if ! lake build -KleanMemory="$memory" SolidCore.Refinement.Solar.Counter.Milestone \ + SolidCore.Refinement.Solar.Counter.Sequences > "$logs/build.log" 2>&1; then + grep -E '^error' -A8 "$logs/build.log" | head -n 40 >&2 + die "lake build failed" +fi +tail -n 1 "$logs/build.log" +audit="$logs/Audit.lean" +cat > "$audit" <<'LEAN' +import SolidCore.Refinement.Solar.Counter.Sequences +import SolidCore.Refinement.Solar.Counter.Sequences +open SolidCore.Refinement.Solar.Counter +#check @certified +#check @certifiedAt +#print axioms certified +#print axioms certifiedAt +#print axioms satisfies +#print axioms satisfiesAt +#print axioms vcs +#print axioms shapeOk_eq_true +#print axioms lowering +#print axioms loweringAt +#print axioms SolarTV.Milestone.Counter.counter_mir_to_evmir +#print axioms stage +#print axioms stage_run +#print axioms stageAt +#print axioms stageAt_run +#print axioms stageAnyStorage +#print axioms check_ok +#print axioms SolidCore.Refinement.Solar.Assemble.stage_of_check +#print axioms target_run +#print axioms target_run_at +#print axioms lowering_rejects_bad +#print axioms mutantAdd_no_walk +#print axioms mutantStore_no_walk +#print axioms loweringAt_rejects +#print axioms mutantNoCheck_run_at +#print axioms stageAt_rejects +#print axioms mutantNoCheck_no_walk +#print axioms refinesSeq +#print axioms two_calls +#print axioms mutantAdd_check +#print axioms mutantStore_check +#print axioms mutantNoCheck_check +#check @certifiedEvery +#print axioms certifiedEvery +#print axioms certifiedSeqEvery +#print axioms satisfiesEvery +#print axioms source_run_every +#print axioms mir_run_every +#print axioms loweringEvery +#print axioms assemblyEvery +#print axioms certifiedValue +#print axioms target_run_value +#print axioms assemblyValue_rejects +#print axioms mutantValue_run +#print axioms mutantValue_check +#print axioms mutantValue_no_walk +#check @certifiedSeq +#check @total +#print axioms certifiedSeq +#print axioms total +LEAN +report="$(lake env lean -M "$memory" "$audit" 2>&1)" +echo "$report" +if grep -q "error" <<<"$report"; then die "the audit file does not check"; fi +bad="$(grep "depends on axioms" <<<"$report" | + sed -E 's/.*depends on axioms: \[(.*)\]/\1/' | tr ',' '\n' | tr -d ' ' | + grep -v -x -E 'propext|Classical\.choice|Quot\.sound' || true)" +[[ -z "$bad" ]] || die "axioms beyond propext, Classical.choice and Quot.sound: $bad" +[[ "$(grep -c "depends on axioms" <<<"$report")" -eq 45 ]] || die "a theorem is missing from the audit" + +step "7. negative: the generic assembly checker rejects the mutated bytecode" +# stage_of_check for the counter's program and certificate on the bytes given, the check by the +# kernel. +generic_stage() { + cat > "$logs/$1.lean" < Counter.scope_value h +#print axioms generic_stage +LEAN + # A mutant's case fails by design: its error is the output to check. + { lake env lean -M "$memory" "$logs/$1.lean" 2>&1 || true; } | tr -s '[:space:]' ' ' +} +control="$(generic_stage control "$bytecode")" +[[ "$control" == *"depends on axioms: [propext, Classical.choice, Quot.sound]"* && "$control" != *error* ]] || + die "stage_of_check does not prove the stage for solar's bytecode: $control" +echo "control: stage_of_check proves the stage for solar's bytecode (propext, Classical.choice, Quot.sound)" +for case in "add ${bytecode:0:84}03${bytecode:86}" "store ${bytecode:0:100}54${bytecode:102}" \ + "no_check $no_check" "value $value"; do + name="${case%% *}" + edited="$(generic_stage "mutant_$name" "${case#* }")" + grep -q -E 'error: Tactic `decide` proved that the proposition Assemble\.check SolarTV\.Export\.Counter\.evm5 .* Counter\.cert = true is false' <<<"$edited" || + die "the $name mutant did not fail the generic checker: $edited" + echo "$name mutant rejected by a mismatch, as expected: the kernel evaluates Assemble.check to false" +done + +printf '\nok: counter milestone checked (solar %s, bytecode sha256 %s)\n' "$solar_rev" "$bytecode_sha256" 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..0a9f7e31 --- /dev/null +++ b/scripts/refinement/gen.sh @@ -0,0 +1,173 @@ +#!/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, 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. +# +# 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" + "$SOLAR_BIN" ${solar_flags[@]+"${solar_flags[@]}"} --emit abi,hashes --no-warnings "$sol" > "$tmp/solar.json" + "$SOLC" --combined-json ast "$sol" > "$tmp/ast.json" + status=0 + python3 scripts/refinement/gen_proof.py "$name" "$module" "$tmp/solar.json" "$tmp/ast.json" \ + "$sol" || status=$? + if (( status == 0 )); then + proved+=("$module") + elif (( status != 3 )); then + exit "$status" + 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..e60137fd --- /dev/null +++ b/scripts/refinement/gen_proof.py @@ -0,0 +1,1297 @@ +#!/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 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 + + +# 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/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/require-modulo.sh b/scripts/refinement/require-modulo.sh new file mode 100755 index 00000000..283db396 --- /dev/null +++ b/scripts/refinement/require-modulo.sh @@ -0,0 +1,150 @@ +#!/usr/bin/env bash +# The generic assembly theorem on a layout with a turned branch, fallthroughs and a backward +# jump: solar's UI test require_modulo_chain.sol, whose EVM IR to bytecode stage +# SolidCore/Refinement/Solar/RequireModulo/Assembly.lean proves from Assemble.stage_of_check. +# +# scripts/refinement/require-modulo.sh +# +# 1. Puts the solar checkout that lakefile.lean requires (../ck-pipeline next to this repository, +# fetched from SOLAR_REPO when it is not a git checkout yet) at the pinned solar commit, with +# no uncommitted changes, as the milestone checks do. +# 2. Builds solar (cargo, CARGO_TARGET_DIR, default target in that checkout), or takes SOLAR, +# which must report the pinned commit. +# 3. Compiles the checkout's tests/ui/codegen/lowering/evm-ir/constructs/require_modulo_chain.sol +# with -Ogas --evm-version osaka and -Zemit-lean-stages, and checks that the last EVM IR stage +# (Evm10.lean, after block-layout) and the bytecode (Bytecode.lean) are the committed files +# byte for byte, and the bytecode is solar's --emit=bin-runtime output. +# 4. Builds the module with lake under a cap per Lean process (LEAN_MEMORY, MB, default 4500) +# and prints the axioms of the stage, the check and the negative tests, failing on any axiom +# beyond propext, Classical.choice and Quot.sound. +# 5. Negative test: Assemble.stage_of_check, applied to the bytes this script gives it with the +# checker run by the kernel, proves the stage for solar's bytecode and fails for a one-byte +# mutant (NOT for the ISZERO of the turned branch), where the checker evaluates to false. +set -euo pipefail + +root="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)" +cd "$root" + +# solar: branch ck-pipeline, the commit the milestone checks pin. +solar_rev=f19e9e46309c7cdb3a0f36668f7881d12bb8503a +test_sol=tests/ui/codegen/lowering/evm-ir/constructs/require_modulo_chain.sol +contract=RequireModuloCases +lean_dir=SolidCore/Refinement/Solar/RequireModulo +# The runtime bytecode, 103 bytes. +bytecode=34604a575f3560e01c80631ea7714403604a5760443610604a576024358015604e57600435818106604a576003820615603a5760018116604a575b9081019081106061575f5260205ff35b5f5ffd5b60125b602052634e487b715f526024601cfd5b6011605156 + +tv_dir="$(sed -nE 's|^require solar_tv from "[.][.]" / "([^"]+)" / "solar-tv"$|\1|p' lakefile.lean)" +[[ -n "$tv_dir" ]] || { echo "error: lakefile.lean requires solar_tv from no ..//solar-tv" >&2; exit 1; } +tv="$(cd "$root/.." && pwd)/$tv_dir" +export PATH="$HOME/.elan/bin:$PATH" +export LEAN_NUM_THREADS="${LEAN_NUM_THREADS:-2}" +memory="${LEAN_MEMORY:-4500}" +export CARGO_TARGET_DIR="${CARGO_TARGET_DIR:-$tv/target}" +work="$(mktemp -d)" +trap 'rm -rf "$work"' EXIT + +step() { printf '\n== %s\n' "$*"; } +die() { echo "error: $*" >&2; exit 1; } + +step "1. solar at $solar_rev" +if [[ ! -e "$tv/.git" ]]; then + repo="${SOLAR_REPO:?set SOLAR_REPO to a solar clone, bundle or URL with commit $solar_rev}" + mkdir -p "$tv" + git -C "$tv" init -q + git -C "$tv" fetch -q "$repo" '+refs/heads/*:refs/remotes/solar/*' + git -C "$tv" checkout -q --detach "$solar_rev" +fi +git -C "$tv" diff --quiet HEAD || die "$tv has uncommitted changes" +if [[ "$(git -C "$tv" rev-parse HEAD)" != "$solar_rev" ]]; then + git -C "$tv" checkout -q --detach "$solar_rev" +fi +echo "solar $solar_rev" + +step "2. build solar" +if [[ -n "${SOLAR-}" ]]; then + solar="$SOLAR" +else + (cd "$tv" && cargo build -j "${CARGO_BUILD_JOBS:-2}" --bin solar 2>&1 | tail -n 1) + solar="$CARGO_TARGET_DIR/debug/solar" +fi +"$solar" --version | grep -q "^Commit SHA: $solar_rev\$" || die "$solar is not solar $solar_rev" +"$solar" --version | head -n 1 + +step "3. regenerate the stages and compare them with the committed files" +(cd "$tv" && "$solar" "$test_sol" -Ogas --evm-version osaka --emit=bin-runtime \ + -Zemit-lean-stages="$work/gen" 2>/dev/null) > "$work/out.json" || die "solar failed on $test_sol" +emitted="$(python3 -c 'import json,sys; c=json.load(open(sys.argv[1]))["contracts"]; print(next(v["bin-runtime"] for k,v in c.items() if k.endswith(":" + sys.argv[2])))' "$work/out.json" "$contract")" +[[ "$emitted" == "$bytecode" ]] || die "solar's bytecode is not the pinned one: $emitted" +last="$(ls "$work/gen/$contract" | sed -nE 's/^Evm([0-9]+)[.]lean$/\1/p' | sort -n | tail -n 1)" +[[ "$last" == 10 ]] || die "the last EVM IR stage is Evm$last.lean, not Evm10.lean" +for file in Evm10.lean Bytecode.lean; do + cmp -s "$work/gen/$contract/$file" "$lean_dir/$file" || { + diff "$work/gen/$contract/$file" "$lean_dir/$file" | head -n 40 >&2 + die "$lean_dir/$file is not solar's output" + } +done +grep -q "^ \"$bytecode\"\$" "$lean_dir/Bytecode.lean" || die "Bytecode.lean has other bytes" +echo "Evm10.lean and Bytecode.lean regenerate byte for byte; bytecode is solar's (103 bytes)" + +step "4. build and audit the axioms" +if [[ ! -f .lake/packages/mathlib/.lake/build/lib/lean/Mathlib.olean ]]; then + lake exe cache get > "$work/cache.log" 2>&1 || { tail -n 20 "$work/cache.log" >&2; die "lake exe cache get failed"; } +fi +if ! lake build -R -KleanMemory="$memory" SolidCore.Refinement.Solar.RequireModulo.Assembly \ + > "$work/build.log" 2>&1; then + grep -E '^error' -A8 "$work/build.log" | head -n 40 >&2 + die "lake build failed" +fi +tail -n 1 "$work/build.log" +cat > "$work/Audit.lean" <<'LEAN' +import SolidCore.Refinement.Solar.RequireModulo.Assembly +open SolidCore.Refinement.Solar +#print axioms Assemble.stage_of_check +#print axioms RequireModulo.check_ok +#print axioms RequireModulo.stage +#print axioms RequireModulo.unturned_check +#print axioms RequireModulo.forward_check +#print axioms RequireModulo.mutated_bytes +#print axioms RequireModulo.mutantNot_check +#print axioms RequireModulo.mutantDiv_check +LEAN +report="$(lake env lean -M "$memory" "$work/Audit.lean" 2>&1)" +echo "$report" +if grep -q "error" <<<"$report"; then die "the audit file does not check"; fi +bad="$(grep "depends on axioms" <<<"$report" | + sed -E 's/.*depends on axioms: \[(.*)\]/\1/' | tr ',' '\n' | tr -d ' ' | + grep -v -x -E 'propext|Classical\.choice|Quot\.sound' || true)" +[[ -z "$bad" ]] || die "axioms beyond propext, Classical.choice and Quot.sound: $bad" +[[ "$(grep -c "depends on axioms" <<<"$report")" -eq 8 ]] || die "a theorem is missing from the audit" + +step "5. negative: the generic assembly checker rejects a mutated bytecode" +# stage_of_check for the program and certificate on the bytes given, the check by the kernel. +generic_stage() { + cat > "$work/$1.lean" < h +#print axioms generic_stage +LEAN + # The mutant's case fails by design: its error is the output to check. + { lake env lean -M "$memory" "$work/$1.lean" 2>&1 || true; } | tr -s '[:space:]' ' ' +} +control="$(generic_stage control "$bytecode")" +[[ "$control" == *"depends on axioms: [propext, Classical.choice, Quot.sound]"* && "$control" != *error* ]] || + die "stage_of_check does not prove the stage for solar's bytecode: $control" +echo "control: stage_of_check proves the stage for solar's bytecode (propext, Classical.choice, Quot.sound)" +[[ "${bytecode:94:2}" == "15" ]] || die "offset 47 is not ISZERO" +edited="$(generic_stage mutant "${bytecode:0:94}19${bytecode:96}")" +grep -q -E 'error: Tactic `decide` proved that the proposition Assemble\.check SolarTV\.Export\.RequireModuloCases\.evm10 .* RequireModulo\.cert = true is false' <<<"$edited" || + die "the mutated bytecode did not fail the generic checker: $edited" +echo "rejected by a mismatch, as expected: the kernel evaluates Assemble.check on the mutant to false" + +printf '\nok: RequireModuloCases assembly checked (solar %s)\n' "$solar_rev" 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/w5-milestone.sh b/scripts/refinement/w5-milestone.sh new file mode 100755 index 00000000..1fc8270a --- /dev/null +++ b/scripts/refinement/w5-milestone.sh @@ -0,0 +1,307 @@ +#!/usr/bin/env bash +# The w5 milestone in one command: solar's bytecode for w5 meets w5's verified specification, +# with every stage of solar's pipeline proved in Lean. +# +# scripts/refinement/w5-milestone.sh +# +# 1. Puts the solar checkout that lakefile.lean requires (its solar_tv path, ../ck-pipeline +# next to this repository; fetched from SOLAR_REPO, a clone, bundle or URL whose branches +# hold the pinned commit, when it is not a git checkout yet, even if restored builds are +# there) at the pinned solar commit, and checks that its compiler sources are those of the +# commit the evidence names, except for the stage exporter (crates/codegen/src/lean_stages.rs), +# which only prints the stages as Lean. +# 2. Builds solar (cargo, CARGO_TARGET_DIR, default target in that checkout). +# 3. Runs solar-tv/milestone/w1/gen.sh: compiles w1.sol with -Ogas --evm-version osaka and +# -Zemit-lean-stages, checks the bytecode and the manifest's hashes, and builds the stages. +# Then checks that every regenerated file is the committed evidence, byte for byte except +# for the compiler's build commit in its version, and restores the committed files. +# 4. Binds the source: w5.sol (which SolidCore parses) is w1.sol (which solar's stages come +# from) up to comments and whitespace, solar compiles both to the same bytecode, the Lean +# literals and sha256s are solar's output, and, with solc 0.8.35 (SOLC, checked to be that +# version; else the cached or downloaded release, checked by its sha256), the SolidCore +# source AST regenerates to the committed Source/W5.lean. Without network and SOLC, that +# one check is skipped and reported, unless REQUIRE_SOLC=1. +# 5. Negative tests: a one-byte mutation of the bytecode fails the artifact check, and +# solar-tv's negative.sh shows meaning-changing edits of the bytecode and of stage outputs +# fail their proofs with a mismatch (the assembly walk, or sym_exec on a path whose runs end +# differently), with unedited controls passing. +# 6. Fetches Mathlib's build cache when Mathlib is not built, builds the proof chain with lake +# under a cap per Lean process (LEAN_MEMORY, MB, default 4500), and prints the axioms of the +# final theorems (certified, certifiedAt from any initial storage, and certifiedValue on +# every call with a nonzero value, which f rejects because it is not payable), each stage, +# the generic assembly theorem and the negative tests (loweringValue_rejects: the source +# stage on the value scope is false for a lowering without the call value check), failing +# on any axiom beyond propext, Classical.choice and Quot.sound. One module needs more: the +# statement lowering's mutual block (SolidCore/Solidity/Interface/Statements.lean) peaks at +# about 5.4 GB in the kernel on one thread, so it builds first and alone, on one thread, +# under W5_LOWERING_MEMORY (MB, default 7000). +# 7. Negative test of the generic assembly theorem: Assemble.stage_of_check, applied to the +# bytes this script gives it with the checker run by the kernel, proves w1's assembly stage +# for solar's bytecode (only the three axioms) and fails for the step 5 mutant, where the +# checker evaluates to false. +# +# It needs git, cargo, python3, curl and elan (Lean 4.35.0 from lean-toolchain); a fresh +# directory works: clone this repository, set SOLAR_REPO, and run it. Each step's time is +# printed at the end. +set -euo pipefail + +root="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)" +cd "$root" + +# solar: branch ck-pipeline, the exporter, the backend stage proofs on Lean 4.35.0 and the +# generator of backend stage proofs (certify.sh), whose output w1's proofs are. +solar_rev=f19e9e46309c7cdb3a0f36668f7881d12bb8503a +# The commit whose compiler sources built the committed evidence (its manifest's compiler). +compiler_rev=7b1f8a1b4a98fd79903551f488da83432d919c5a +# The runtime bytecode, 68 bytes. +bytecode=34602e575f3560e01c806313d1aa2e03602e5760443610602e5760043560243581019081106032575f5260205ff35b5f5ffd5b6011602052634e487b715f526024601cfd +bytecode_sha256=24d2438e4d77b39b2530aac7af63774b10576eabc3c093d282620ab44403778b +solc_version=0.8.35 +solc_sha256=fa8ac9a32d301ad023a36ee5a29f8e291fe3200c60244e43c142539e82a617f4 + +# lakefile.lean requires solar_tv from ..//solar-tv: the solar checkout is ../. +tv_dir="$(sed -nE 's|^require solar_tv from "[.][.]" / "([^"]+)" / "solar-tv"$|\1|p' lakefile.lean)" +[[ -n "$tv_dir" ]] || { echo "error: lakefile.lean requires solar_tv from no ..//solar-tv" >&2; exit 1; } +tv="$(cd "$root/.." && pwd)/$tv_dir" +export PATH="$HOME/.elan/bin:$PATH" +export LEAN_NUM_THREADS="${LEAN_NUM_THREADS:-2}" +# The cap of each Lean process, in MB. +memory="${LEAN_MEMORY:-4500}" +export CARGO_TARGET_DIR="${CARGO_TARGET_DIR:-$tv/target}" +work="$(mktemp -d)" +trap 'rm -rf "$work"' EXIT +start=$SECONDS +last=$SECONDS +times=() +step_name= +step() { + if [[ -n "$step_name" ]]; then times+=("$step_name $((SECONDS - last))s"); fi + last=$SECONDS + step_name="${1%%.*}" + printf '\n== %s\n' "$*" +} +die() { echo "error: $*" >&2; exit 1; } +sha_hex() { python3 -c 'import hashlib,sys; print(hashlib.sha256(bytes.fromhex(sys.argv[1])).hexdigest())' "$1"; } +bin_runtime() { + "$solar" "$1" -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")))' +} +# Whether hex is the milestone's bytecode by its sha256: prints a mismatch and fails otherwise. +check_bytecode() { + local got + got="$(sha_hex "$1")" + if [[ "$got" != "$bytecode_sha256" ]]; then + echo "mismatch: sha256 $got, expected $bytecode_sha256" >&2 + return 1 + fi +} + +step "1. solar at $solar_rev" +if [[ ! -e "$tv/.git" ]]; then + # A new checkout, in a directory that may already hold restored builds (target, .lake). + repo="${SOLAR_REPO:?set SOLAR_REPO to a solar clone, bundle or URL with commit $solar_rev}" + mkdir -p "$tv" + git -C "$tv" init -q + git -C "$tv" fetch -q "$repo" '+refs/heads/*:refs/remotes/solar/*' + git -C "$tv" checkout -q --detach "$solar_rev" +fi +git -C "$tv" diff --quiet HEAD || die "$tv has uncommitted changes" +if [[ "$(git -C "$tv" rev-parse HEAD)" != "$solar_rev" ]]; then + git -C "$tv" checkout -q --detach "$solar_rev" +fi +exporter=crates/codegen/src/lean_stages.rs +git -C "$tv" diff --quiet "$compiler_rev" HEAD -- crates Cargo.toml Cargo.lock ":!$exporter" || + die "the compiler sources at $solar_rev differ from $compiler_rev's" +echo "solar $solar_rev; compiler sources identical to $compiler_rev except the exporter $exporter" + +step "2. build solar" +(cd "$tv" && cargo build -j "${CARGO_BUILD_JOBS:-2}" --bin solar 2>&1 | tail -n 1) +solar="$CARGO_TARGET_DIR/debug/solar" +"$solar" --version | head -n 1 + +step "3. regenerate solar's stages and compare them with the evidence" +gen=solar-tv/milestone/w1/gen +restore() { git -C "$tv" checkout -q -- "$gen"; git -C "$tv" clean -qfd -- "$gen"; } +trap 'restore; rm -rf "$work"' EXIT +W1_SKIP_BUILD=1 SOLAR="$solar" "$tv/solar-tv/milestone/w1/gen.sh" +[[ -z "$(git -C "$tv" ls-files --others --exclude-standard -- "$gen")" ]] || + die "gen.sh wrote files the evidence does not have" +norm() { sed -E 's/commit\.[0-9a-f]{8}/commit./g'; } +for file in $(git -C "$tv" ls-files -- "$gen"); do + if ! diff -q <(git -C "$tv" show "HEAD:$file" | norm) <(norm < "$tv/$file") > /dev/null; then + git -C "$tv" diff -- "$file" | head -n 40 >&2 + die "regenerated $file is not the committed evidence" + fi +done +echo "every file of $gen regenerates to the committed evidence (stages, bytecode, manifest)" +restore +trap 'rm -rf "$work"' EXIT + +step "4. bind the source and the bytecode" +w1="$tv/solar-tv/milestone/w1/w1.sol" +w5=scripts/refinement/corpus/w5.sol +strip_sol() { sed -E 's|//.*$||' "$1" | tr -s '[:space:]' ' ' | sed -E 's/ ?([{}();,]) ?/\1/g; s/^ //; s/ $//'; } +[[ "$(strip_sol "$w1")" == "$(strip_sol "$w5")" ]] || die "$w5 and w1.sol are different contracts" +echo "w5.sol and w1.sol are the same source up to comments and whitespace" +out1="$(bin_runtime "$w1")" +out5="$(bin_runtime "$w5")" +[[ "$out1" == "$bytecode" && "$out5" == "$bytecode" ]] || die "solar's bytecode is not the milestone's" +check_bytecode "$out1" +manifest_sha="$(python3 -c 'import json,sys; print(json.load(open(sys.argv[1]))["bytecode_sha256"])' "$tv/$gen/Main/manifest.json")" +[[ "$manifest_sha" == "$bytecode_sha256" ]] || die "the manifest's sha256 is not the bytecode's" +grep -q "def Main.runtimeSha256 : String := \"$bytecode_sha256\"" SolidCore/Refinement/Bytecode/W5.lean || + die "Bytecode/W5.lean records another sha256" +grep -q "^ 0x$bytecode\$" SolidCore/Refinement/Bytecode/W5.lean || die "Bytecode/W5.lean has other bytes" +scripts/refinement/check-solar-w1.sh "$solar" "$w1" | tail -n 1 +echo "bytecode sha256 $bytecode_sha256 (68 bytes)" +solc_skipped= +if [[ -n "${SOLC-}" ]]; then + "$SOLC" --version | grep -q "Version: $solc_version+" || + die "SOLC is $("$SOLC" --version | tail -n 1), not solc $solc_version" +else + SOLC="${XDG_CACHE_HOME:-$HOME/.cache}/solc/solc-$solc_version" + if [[ ! -x "$SOLC" ]]; then + mkdir -p "$(dirname "$SOLC")" + if curl -fsSL -o "$SOLC.tmp" \ + "https://github.com/argotorg/solidity/releases/download/v$solc_version/solc-static-linux"; then + chmod +x "$SOLC.tmp" + mv "$SOLC.tmp" "$SOLC" + else + rm -f "$SOLC.tmp" + [[ -z "${REQUIRE_SOLC-}" ]] || die "cannot download solc $solc_version; set SOLC" + solc_skipped=1 + fi + fi + if [[ -z "$solc_skipped" ]]; then + echo "$solc_sha256 $SOLC" | sha256sum -c --quiet || die "$SOLC is not the solc $solc_version release" + fi +fi +if [[ -n "$solc_skipped" ]]; then + echo "SKIPPED: no solc $solc_version (set SOLC or allow the download); the source AST is not regenerated" +else +# The generator's commands for one source, as scripts/refinement/gen.sh runs them. +{ + echo "-- Generated by scripts/refinement/gen.sh from $w5 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 "$w5" --contract Main --solc "$SOLC" \ + --namespace "SolidCore.Refinement.Source.W5" --body-only | + sed "s|^def importedSourceName : String := .*$|def importedSourceName : String := \"$w5\"|" +} | diff -q - SolidCore/Refinement/Source/W5.lean > /dev/null || + die "SolidCore/Refinement/Source/W5.lean is not the source AST of $w5" +echo "SolidCore's source AST of w5.sol regenerates to SolidCore/Refinement/Source/W5.lean" +fi + +step "5. negative: a mutated bytecode is rejected" +[[ "${bytecode:66:2}" == "01" ]] || die "offset 33 is not ADD" +mutant="${bytecode:0:66}03${bytecode:68}" # offset 33: ADD (01) to SUB (03) +if check_bytecode "$mutant"; then die "the mutated bytecode passed the check"; fi +echo "rejected by a mismatch, as expected; in Lean, mutant_not_stage proves the assembly stage" +echo "false for it, and lowering_rejects_bad the source stage false for a lowering with SUB for ADD" +(cd "$tv/solar-tv" && lake build W1Proofs > /dev/null 2>&1) || die "lake build W1Proofs failed in $tv/solar-tv" +LEAN_MEMORY="$memory" "$tv/solar-tv/milestone/w1/proofs/negative.sh" + +step "6. build the proof chain and audit its axioms" +if [[ ! -f .lake/packages/mathlib/.lake/build/lib/lean/Mathlib.olean ]]; then + lake exe cache get > "$work/cache.log" 2>&1 || { tail -n 20 "$work/cache.log" >&2; die "lake exe cache get failed"; } + echo "Mathlib from its build cache" +fi +log="${W5_BUILD_LOG:-$work/build.log}" +# Builds with lake, appending to the log, and fails with its errors. +build() { + if ! "$@" >> "$log" 2>&1; then + grep -E '^error' "$log" | head -n 20 >&2 + cp "$log" "${TMPDIR:-/tmp}/w5-milestone-build.log" + die "$* failed (${TMPDIR:-/tmp}/w5-milestone-build.log)" + fi +} +: > "$log" +# The statement lowering alone, after its imports, so that no other Lean process runs beside it. +# Lake keeps the configuration it last elaborated, -K options included: -R makes each cap apply. +build lake build -R -KleanMemory="$memory" SolidCore.Solidity.Interface.Expressions +build env LEAN_NUM_THREADS=1 lake build -R -KleanMemory="${W5_LOWERING_MEMORY:-7000}" \ + SolidCore.Solidity.Interface.Statements +build lake build -R -KleanMemory="$memory" W1Proofs SolidCore.Refinement.Solar.Milestone \ + SolidCore.Refinement.Solar.W1Value SolidCore.Refinement.Solar.Sequences +tail -n 1 "$log" +audit="$work/audit.lean" +cat > "$audit" <<'LEAN' +import SolidCore.Refinement.Solar.Milestone +import SolidCore.Refinement.Solar.W1Value +import SolidCore.Refinement.Solar.Sequences +import W1Proofs +open SolidCore.Refinement.Solar.W1 +#check @certified +#check @certifiedAt +#check @certifiedValue +#check @certifiedSeq +#print axioms certified +#print axioms certifiedAt +#print axioms certifiedSeq +#print axioms lowering +#print axioms loweringAt +#print axioms SolarTV.Milestone.W1.w1_mir_to_evmir +#print axioms stage +#print axioms stageAt +#print axioms stageAt_run +#print axioms SolidCore.Verify.W5.satisfies +#print axioms SolidCore.Verify.W5.satisfiesAt +#print axioms SolidCore.Refinement.Corpus.W5.shapeOk_eq_true +#print axioms lowering_rejects_bad +#print axioms mutant_not_stage +#print axioms mutant_no_walk +#print axioms certifiedValue +#print axioms satisfiesValue +#print axioms source_run_value +#print axioms loweringValue +#print axioms target_run_value +#print axioms assemblyValue +#print axioms loweringValue_rejects +#print axioms SolidCore.Refinement.Solar.Assemble.stage_of_check +#print axioms stage_run +#print axioms check_ok +#print axioms mutant_check +LEAN +report="$(lake env lean -M "$memory" "$audit" 2>&1)" +echo "$report" +if grep -q "error" <<<"$report"; then die "the audit file does not check"; fi +bad="$(grep "depends on axioms" <<<"$report" | + sed -E 's/.*depends on axioms: \[(.*)\]/\1/' | tr ',' '\n' | tr -d ' ' | + grep -v -x -E 'propext|Classical\.choice|Quot\.sound' || true)" +[[ -z "$bad" ]] || die "axioms beyond propext, Classical.choice and Quot.sound: $bad" +[[ "$(grep -c "depends on axioms" <<<"$report")" -eq 26 ]] || die "a theorem is missing from the audit" + +step "7. negative: the generic assembly checker rejects the mutated bytecode" +# stage_of_check for w1's program and certificate on the bytes given, the check by the kernel. +generic_stage() { + cat > "$work/$1.lean" < (W1.scope_facts h).1 +#print axioms generic_stage +LEAN + # The mutant's case fails by design: its error is the output to check. + { lake env lean -M "$memory" "$work/$1.lean" 2>&1 || true; } | tr -s '[:space:]' ' ' +} +control="$(generic_stage control "$bytecode")" +[[ "$control" == *"depends on axioms: [propext, Classical.choice, Quot.sound]"* && "$control" != *error* ]] || + die "stage_of_check does not prove the stage for solar's bytecode: $control" +echo "control: stage_of_check proves the stage for solar's bytecode (propext, Classical.choice, Quot.sound)" +edited="$(generic_stage mutant "$mutant")" +grep -q -E 'error: Tactic `decide` proved that the proposition Assemble\.check W1\.program .* W1\.cert = true is false' <<<"$edited" || + die "the mutated bytecode did not fail the generic checker: $edited" +echo "rejected by a mismatch, as expected: the kernel evaluates Assemble.check on the mutant to false" + +times+=("$step_name $((SECONDS - last))s") +echo "step times (step seconds): ${times[*]}; total $((SECONDS - start))s" +skipped="${solc_skipped:+ (source AST regeneration skipped: no solc)}" +printf '\nok: w5 milestone checked (solar %s, bytecode sha256 %s)%s\n' "$solar_rev" "$bytecode_sha256" "$skipped" 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/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.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. diff --git a/vendor/loom/LICENSE b/vendor/loom/LICENSE new file mode 100644 index 00000000..d5728852 --- /dev/null +++ b/vendor/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/vendor/loom/Loom.lean b/vendor/loom/Loom.lean new file mode 100644 index 00000000..ae15f6a1 --- /dev/null +++ b/vendor/loom/Loom.lean @@ -0,0 +1 @@ +import Loom.MonadAlgebras.WP.Basic diff --git a/vendor/loom/Loom/MonadAlgebras/Defs.lean b/vendor/loom/Loom/MonadAlgebras/Defs.lean new file mode 100644 index 00000000..cf5491a3 --- /dev/null +++ b/vendor/loom/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/vendor/loom/Loom/MonadAlgebras/Instances/Basic.lean b/vendor/loom/Loom/MonadAlgebras/Instances/Basic.lean new file mode 100644 index 00000000..a91536b9 --- /dev/null +++ b/vendor/loom/Loom/MonadAlgebras/Instances/Basic.lean @@ -0,0 +1,26 @@ +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 + +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 + +-- solidity-lean: Loom's DivM (the divergence monad) and its partial- and +-- total-correctness algebras are dropped; see vendor/loom/README.md. diff --git a/vendor/loom/Loom/MonadAlgebras/WP/Basic.lean b/vendor/loom/Loom/MonadAlgebras/WP/Basic.lean new file mode 100644 index 00000000..a4cc273a --- /dev/null +++ b/vendor/loom/Loom/MonadAlgebras/WP/Basic.lean @@ -0,0 +1,148 @@ +import Loom.MonadAlgebras.Defs + +import Loom.MonadAlgebras.Instances.Basic + +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 + + +-- solidity-lean: the loop, lifting, ExceptT, StateT, ReaderT and Gen sections of +-- this file are dropped with the transformer instances; see vendor/loom/README.md. diff --git a/vendor/loom/Loom/MonadUtil.lean b/vendor/loom/Loom/MonadUtil.lean new file mode 100644 index 00000000..23abfe44 --- /dev/null +++ b/vendor/loom/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/vendor/loom/Loom/SpecMonad.lean b/vendor/loom/Loom/SpecMonad.lean new file mode 100644 index 00000000..ac3d4a5d --- /dev/null +++ b/vendor/loom/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/vendor/loom/README.md b/vendor/loom/README.md new file mode 100644 index 00000000..e6c285fe --- /dev/null +++ b/vendor/loom/README.md @@ -0,0 +1,39 @@ +# Loom, vendored + +The parts of [Loom](https://github.com/verse-lab/loom) (verse-lab, Apache-2.0, see +`LICENSE`) that SolidCore's verification-condition generator (`SolidCore/Verify/`) builds on, +from commit `78928abc9054b31d0bea85985496490baae95244` (master, 2026-02-21), which targets Lean +4.24 and Mathlib v4.24. Ported to this repository's Lean 4.35 and Mathlib v4.35.0 and built as +the `Loom` library of the main package (`lean_lib Loom where srcDir := "vendor/loom"` in the +root lakefile), so it adds no package and no manifest entry. + +## 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. From fe8c2c0571b52d21785780d2c40ca7b1c6a7c7f5 Mon Sep 17 00:00:00 2001 From: alpharush <0xalpharush@protonmail.com> Date: Thu, 12 Nov 2026 17:36:07 -0600 Subject: [PATCH 2/3] feat(corpus): add generated refinement proofs --- SolidCore/Refinement/Corpus.lean | 31 ++ SolidCore/Refinement/Corpus/B1.lean | 65 ++++ SolidCore/Refinement/Corpus/B1/Defs.lean | 50 +++ SolidCore/Refinement/Corpus/B1/Dirty.lean | 31 ++ SolidCore/Refinement/Corpus/B1/Part0.lean | 9 + SolidCore/Refinement/Corpus/B1/Seq.lean | 54 ++++ SolidCore/Refinement/Corpus/B1/SeqDefs.lean | 59 ++++ SolidCore/Refinement/Corpus/B1/SeqPart0.lean | 9 + SolidCore/Refinement/Corpus/B1/SeqStates.lean | 22 ++ SolidCore/Refinement/Corpus/B2.lean | 65 ++++ SolidCore/Refinement/Corpus/B2/Defs.lean | 50 +++ SolidCore/Refinement/Corpus/B2/Dirty.lean | 31 ++ SolidCore/Refinement/Corpus/B2/Part0.lean | 9 + SolidCore/Refinement/Corpus/B2/Seq.lean | 54 ++++ SolidCore/Refinement/Corpus/B2/SeqDefs.lean | 59 ++++ SolidCore/Refinement/Corpus/B2/SeqPart0.lean | 9 + SolidCore/Refinement/Corpus/B2/SeqStates.lean | 23 ++ SolidCore/Refinement/Corpus/B3.lean | 65 ++++ SolidCore/Refinement/Corpus/B3/Defs.lean | 50 +++ SolidCore/Refinement/Corpus/B3/Dirty.lean | 31 ++ SolidCore/Refinement/Corpus/B3/Part0.lean | 9 + SolidCore/Refinement/Corpus/B3/Seq.lean | 54 ++++ SolidCore/Refinement/Corpus/B3/SeqDefs.lean | 59 ++++ SolidCore/Refinement/Corpus/B3/SeqPart0.lean | 9 + SolidCore/Refinement/Corpus/B3/SeqStates.lean | 21 ++ SolidCore/Refinement/Corpus/B4.lean | 65 ++++ SolidCore/Refinement/Corpus/B4/Defs.lean | 50 +++ SolidCore/Refinement/Corpus/B4/Dirty.lean | 31 ++ SolidCore/Refinement/Corpus/B4/Part0.lean | 9 + SolidCore/Refinement/Corpus/B4/Seq.lean | 54 ++++ SolidCore/Refinement/Corpus/B4/SeqDefs.lean | 59 ++++ SolidCore/Refinement/Corpus/B4/SeqPart0.lean | 9 + SolidCore/Refinement/Corpus/B4/SeqStates.lean | 21 ++ SolidCore/Refinement/Corpus/B5.lean | 65 ++++ SolidCore/Refinement/Corpus/B5/Defs.lean | 50 +++ SolidCore/Refinement/Corpus/B5/Dirty.lean | 31 ++ SolidCore/Refinement/Corpus/B5/Part0.lean | 9 + SolidCore/Refinement/Corpus/B5/Seq.lean | 54 ++++ SolidCore/Refinement/Corpus/B5/SeqDefs.lean | 59 ++++ SolidCore/Refinement/Corpus/B5/SeqPart0.lean | 9 + SolidCore/Refinement/Corpus/B5/SeqStates.lean | 22 ++ SolidCore/Refinement/Corpus/B6.lean | 65 ++++ SolidCore/Refinement/Corpus/B6/Defs.lean | 50 +++ SolidCore/Refinement/Corpus/B6/Dirty.lean | 31 ++ SolidCore/Refinement/Corpus/B6/Part0.lean | 9 + SolidCore/Refinement/Corpus/B6/Seq.lean | 54 ++++ SolidCore/Refinement/Corpus/B6/SeqDefs.lean | 59 ++++ SolidCore/Refinement/Corpus/B6/SeqPart0.lean | 9 + SolidCore/Refinement/Corpus/B6/SeqStates.lean | 22 ++ SolidCore/Refinement/Corpus/B7.lean | 65 ++++ SolidCore/Refinement/Corpus/B7/Defs.lean | 50 +++ SolidCore/Refinement/Corpus/B7/Dirty.lean | 31 ++ SolidCore/Refinement/Corpus/B7/Part0.lean | 9 + SolidCore/Refinement/Corpus/B7/Seq.lean | 54 ++++ SolidCore/Refinement/Corpus/B7/SeqDefs.lean | 59 ++++ SolidCore/Refinement/Corpus/B7/SeqPart0.lean | 9 + SolidCore/Refinement/Corpus/B7/SeqStates.lean | 22 ++ SolidCore/Refinement/Corpus/C1.lean | 238 +++++++++++++++ SolidCore/Refinement/Corpus/C1/Defs.lean | 50 +++ SolidCore/Refinement/Corpus/C1/Dirty.lean | 31 ++ SolidCore/Refinement/Corpus/C1/Seq.lean | 54 ++++ SolidCore/Refinement/Corpus/C1/SeqDefs.lean | 59 ++++ SolidCore/Refinement/Corpus/C1/SeqPart0.lean | 9 + SolidCore/Refinement/Corpus/C1/SeqStates.lean | 21 ++ SolidCore/Refinement/Corpus/C10.lean | 65 ++++ SolidCore/Refinement/Corpus/C10/Defs.lean | 50 +++ SolidCore/Refinement/Corpus/C10/Dirty.lean | 31 ++ SolidCore/Refinement/Corpus/C10/Part0.lean | 9 + SolidCore/Refinement/Corpus/C10/Seq.lean | 54 ++++ SolidCore/Refinement/Corpus/C10/SeqDefs.lean | 59 ++++ SolidCore/Refinement/Corpus/C10/SeqPart0.lean | 9 + .../Refinement/Corpus/C10/SeqStates.lean | 21 ++ SolidCore/Refinement/Corpus/C11.lean | 65 ++++ SolidCore/Refinement/Corpus/C11/Defs.lean | 50 +++ SolidCore/Refinement/Corpus/C11/Dirty.lean | 31 ++ SolidCore/Refinement/Corpus/C11/Part0.lean | 9 + SolidCore/Refinement/Corpus/C11/Seq.lean | 54 ++++ SolidCore/Refinement/Corpus/C11/SeqDefs.lean | 59 ++++ SolidCore/Refinement/Corpus/C11/SeqPart0.lean | 9 + .../Refinement/Corpus/C11/SeqStates.lean | 21 ++ SolidCore/Refinement/Corpus/C2.lean | 95 ++++++ SolidCore/Refinement/Corpus/C2/Defs.lean | 50 +++ SolidCore/Refinement/Corpus/C2/Dirty.lean | 31 ++ SolidCore/Refinement/Corpus/C2/Part0.lean | 9 + SolidCore/Refinement/Corpus/C2/Part1.lean | 9 + SolidCore/Refinement/Corpus/C2/Part10.lean | 9 + SolidCore/Refinement/Corpus/C2/Part11.lean | 9 + SolidCore/Refinement/Corpus/C2/Part12.lean | 9 + SolidCore/Refinement/Corpus/C2/Part13.lean | 9 + SolidCore/Refinement/Corpus/C2/Part14.lean | 9 + SolidCore/Refinement/Corpus/C2/Part15.lean | 9 + SolidCore/Refinement/Corpus/C2/Part2.lean | 9 + SolidCore/Refinement/Corpus/C2/Part3.lean | 9 + SolidCore/Refinement/Corpus/C2/Part4.lean | 9 + SolidCore/Refinement/Corpus/C2/Part5.lean | 9 + SolidCore/Refinement/Corpus/C2/Part6.lean | 9 + SolidCore/Refinement/Corpus/C2/Part7.lean | 9 + SolidCore/Refinement/Corpus/C2/Part8.lean | 9 + SolidCore/Refinement/Corpus/C2/Part9.lean | 9 + SolidCore/Refinement/Corpus/C2/Seq.lean | 84 +++++ SolidCore/Refinement/Corpus/C2/SeqDefs.lean | 59 ++++ SolidCore/Refinement/Corpus/C2/SeqPart0.lean | 9 + SolidCore/Refinement/Corpus/C2/SeqPart1.lean | 9 + SolidCore/Refinement/Corpus/C2/SeqPart10.lean | 9 + SolidCore/Refinement/Corpus/C2/SeqPart11.lean | 9 + SolidCore/Refinement/Corpus/C2/SeqPart12.lean | 9 + SolidCore/Refinement/Corpus/C2/SeqPart13.lean | 9 + SolidCore/Refinement/Corpus/C2/SeqPart14.lean | 9 + SolidCore/Refinement/Corpus/C2/SeqPart15.lean | 9 + SolidCore/Refinement/Corpus/C2/SeqPart2.lean | 9 + SolidCore/Refinement/Corpus/C2/SeqPart3.lean | 9 + SolidCore/Refinement/Corpus/C2/SeqPart4.lean | 9 + SolidCore/Refinement/Corpus/C2/SeqPart5.lean | 9 + SolidCore/Refinement/Corpus/C2/SeqPart6.lean | 9 + SolidCore/Refinement/Corpus/C2/SeqPart7.lean | 9 + SolidCore/Refinement/Corpus/C2/SeqPart8.lean | 9 + SolidCore/Refinement/Corpus/C2/SeqPart9.lean | 9 + SolidCore/Refinement/Corpus/C2/SeqStates.lean | 21 ++ SolidCore/Refinement/Corpus/C3.lean | 95 ++++++ SolidCore/Refinement/Corpus/C3/Defs.lean | 50 +++ SolidCore/Refinement/Corpus/C3/Dirty.lean | 31 ++ SolidCore/Refinement/Corpus/C3/Part0.lean | 9 + SolidCore/Refinement/Corpus/C3/Part1.lean | 9 + SolidCore/Refinement/Corpus/C3/Part10.lean | 9 + SolidCore/Refinement/Corpus/C3/Part11.lean | 9 + SolidCore/Refinement/Corpus/C3/Part12.lean | 9 + SolidCore/Refinement/Corpus/C3/Part13.lean | 9 + SolidCore/Refinement/Corpus/C3/Part14.lean | 9 + SolidCore/Refinement/Corpus/C3/Part15.lean | 9 + SolidCore/Refinement/Corpus/C3/Part2.lean | 9 + SolidCore/Refinement/Corpus/C3/Part3.lean | 9 + SolidCore/Refinement/Corpus/C3/Part4.lean | 9 + SolidCore/Refinement/Corpus/C3/Part5.lean | 9 + SolidCore/Refinement/Corpus/C3/Part6.lean | 9 + SolidCore/Refinement/Corpus/C3/Part7.lean | 9 + SolidCore/Refinement/Corpus/C3/Part8.lean | 9 + SolidCore/Refinement/Corpus/C3/Part9.lean | 9 + SolidCore/Refinement/Corpus/C3/Seq.lean | 84 +++++ SolidCore/Refinement/Corpus/C3/SeqDefs.lean | 59 ++++ SolidCore/Refinement/Corpus/C3/SeqPart0.lean | 9 + SolidCore/Refinement/Corpus/C3/SeqPart1.lean | 9 + SolidCore/Refinement/Corpus/C3/SeqPart10.lean | 9 + SolidCore/Refinement/Corpus/C3/SeqPart11.lean | 9 + SolidCore/Refinement/Corpus/C3/SeqPart12.lean | 9 + SolidCore/Refinement/Corpus/C3/SeqPart13.lean | 9 + SolidCore/Refinement/Corpus/C3/SeqPart14.lean | 9 + SolidCore/Refinement/Corpus/C3/SeqPart15.lean | 9 + SolidCore/Refinement/Corpus/C3/SeqPart2.lean | 9 + SolidCore/Refinement/Corpus/C3/SeqPart3.lean | 9 + SolidCore/Refinement/Corpus/C3/SeqPart4.lean | 9 + SolidCore/Refinement/Corpus/C3/SeqPart5.lean | 9 + SolidCore/Refinement/Corpus/C3/SeqPart6.lean | 9 + SolidCore/Refinement/Corpus/C3/SeqPart7.lean | 9 + SolidCore/Refinement/Corpus/C3/SeqPart8.lean | 9 + SolidCore/Refinement/Corpus/C3/SeqPart9.lean | 9 + SolidCore/Refinement/Corpus/C3/SeqStates.lean | 21 ++ SolidCore/Refinement/Corpus/C4.lean | 251 +++++++++++++++ SolidCore/Refinement/Corpus/C4/Defs.lean | 50 +++ SolidCore/Refinement/Corpus/C4/Dirty.lean | 31 ++ SolidCore/Refinement/Corpus/C4/Seq.lean | 87 ++++++ SolidCore/Refinement/Corpus/C4/SeqDefs.lean | 60 ++++ SolidCore/Refinement/Corpus/C4/SeqPart0.lean | 9 + SolidCore/Refinement/Corpus/C4/SeqPart1.lean | 9 + SolidCore/Refinement/Corpus/C4/SeqPart10.lean | 9 + SolidCore/Refinement/Corpus/C4/SeqPart11.lean | 9 + SolidCore/Refinement/Corpus/C4/SeqPart12.lean | 9 + SolidCore/Refinement/Corpus/C4/SeqPart13.lean | 9 + SolidCore/Refinement/Corpus/C4/SeqPart14.lean | 9 + SolidCore/Refinement/Corpus/C4/SeqPart15.lean | 9 + SolidCore/Refinement/Corpus/C4/SeqPart2.lean | 9 + SolidCore/Refinement/Corpus/C4/SeqPart3.lean | 9 + SolidCore/Refinement/Corpus/C4/SeqPart4.lean | 9 + SolidCore/Refinement/Corpus/C4/SeqPart5.lean | 9 + SolidCore/Refinement/Corpus/C4/SeqPart6.lean | 9 + SolidCore/Refinement/Corpus/C4/SeqPart7.lean | 9 + SolidCore/Refinement/Corpus/C4/SeqPart8.lean | 9 + SolidCore/Refinement/Corpus/C4/SeqPart9.lean | 9 + SolidCore/Refinement/Corpus/C4/SeqStates.lean | 276 +++++++++++++++++ SolidCore/Refinement/Corpus/C5.lean | 65 ++++ SolidCore/Refinement/Corpus/C5/Defs.lean | 50 +++ SolidCore/Refinement/Corpus/C5/Dirty.lean | 31 ++ SolidCore/Refinement/Corpus/C5/Part0.lean | 9 + SolidCore/Refinement/Corpus/C5/Seq.lean | 89 ++++++ SolidCore/Refinement/Corpus/C5/SeqDefs.lean | 60 ++++ SolidCore/Refinement/Corpus/C5/SeqPart0.lean | 9 + SolidCore/Refinement/Corpus/C5/SeqPart1.lean | 9 + SolidCore/Refinement/Corpus/C5/SeqPart10.lean | 9 + SolidCore/Refinement/Corpus/C5/SeqPart11.lean | 9 + SolidCore/Refinement/Corpus/C5/SeqPart12.lean | 9 + SolidCore/Refinement/Corpus/C5/SeqPart13.lean | 9 + SolidCore/Refinement/Corpus/C5/SeqPart14.lean | 9 + SolidCore/Refinement/Corpus/C5/SeqPart15.lean | 9 + SolidCore/Refinement/Corpus/C5/SeqPart16.lean | 9 + SolidCore/Refinement/Corpus/C5/SeqPart2.lean | 9 + SolidCore/Refinement/Corpus/C5/SeqPart3.lean | 9 + SolidCore/Refinement/Corpus/C5/SeqPart4.lean | 9 + SolidCore/Refinement/Corpus/C5/SeqPart5.lean | 9 + SolidCore/Refinement/Corpus/C5/SeqPart6.lean | 9 + SolidCore/Refinement/Corpus/C5/SeqPart7.lean | 9 + SolidCore/Refinement/Corpus/C5/SeqPart8.lean | 9 + SolidCore/Refinement/Corpus/C5/SeqPart9.lean | 9 + SolidCore/Refinement/Corpus/C5/SeqStates.lean | 277 +++++++++++++++++ SolidCore/Refinement/Corpus/C6.lean | 65 ++++ SolidCore/Refinement/Corpus/C6/Defs.lean | 50 +++ SolidCore/Refinement/Corpus/C6/Dirty.lean | 31 ++ SolidCore/Refinement/Corpus/C6/Part0.lean | 9 + SolidCore/Refinement/Corpus/C6/Seq.lean | 54 ++++ SolidCore/Refinement/Corpus/C6/SeqDefs.lean | 59 ++++ SolidCore/Refinement/Corpus/C6/SeqPart0.lean | 9 + SolidCore/Refinement/Corpus/C6/SeqStates.lean | 21 ++ SolidCore/Refinement/Corpus/C7.lean | 65 ++++ SolidCore/Refinement/Corpus/C7/Defs.lean | 50 +++ SolidCore/Refinement/Corpus/C7/Dirty.lean | 31 ++ SolidCore/Refinement/Corpus/C7/Part0.lean | 9 + SolidCore/Refinement/Corpus/C7/Seq.lean | 54 ++++ SolidCore/Refinement/Corpus/C7/SeqDefs.lean | 59 ++++ SolidCore/Refinement/Corpus/C7/SeqPart0.lean | 9 + SolidCore/Refinement/Corpus/C7/SeqStates.lean | 21 ++ SolidCore/Refinement/Corpus/C8.lean | 65 ++++ SolidCore/Refinement/Corpus/C8/Defs.lean | 50 +++ SolidCore/Refinement/Corpus/C8/Dirty.lean | 31 ++ SolidCore/Refinement/Corpus/C8/Part0.lean | 9 + SolidCore/Refinement/Corpus/C8/Seq.lean | 54 ++++ SolidCore/Refinement/Corpus/C8/SeqDefs.lean | 59 ++++ SolidCore/Refinement/Corpus/C8/SeqPart0.lean | 9 + SolidCore/Refinement/Corpus/C8/SeqStates.lean | 21 ++ SolidCore/Refinement/Corpus/C9.lean | 65 ++++ SolidCore/Refinement/Corpus/C9/Defs.lean | 50 +++ SolidCore/Refinement/Corpus/C9/Dirty.lean | 31 ++ SolidCore/Refinement/Corpus/C9/Part0.lean | 9 + SolidCore/Refinement/Corpus/C9/Seq.lean | 89 ++++++ SolidCore/Refinement/Corpus/C9/SeqDefs.lean | 60 ++++ SolidCore/Refinement/Corpus/C9/SeqPart0.lean | 9 + SolidCore/Refinement/Corpus/C9/SeqPart1.lean | 9 + SolidCore/Refinement/Corpus/C9/SeqPart10.lean | 9 + SolidCore/Refinement/Corpus/C9/SeqPart11.lean | 9 + SolidCore/Refinement/Corpus/C9/SeqPart12.lean | 9 + SolidCore/Refinement/Corpus/C9/SeqPart13.lean | 9 + SolidCore/Refinement/Corpus/C9/SeqPart14.lean | 9 + SolidCore/Refinement/Corpus/C9/SeqPart15.lean | 9 + SolidCore/Refinement/Corpus/C9/SeqPart16.lean | 9 + SolidCore/Refinement/Corpus/C9/SeqPart2.lean | 9 + SolidCore/Refinement/Corpus/C9/SeqPart3.lean | 9 + SolidCore/Refinement/Corpus/C9/SeqPart4.lean | 9 + SolidCore/Refinement/Corpus/C9/SeqPart5.lean | 9 + SolidCore/Refinement/Corpus/C9/SeqPart6.lean | 9 + SolidCore/Refinement/Corpus/C9/SeqPart7.lean | 9 + SolidCore/Refinement/Corpus/C9/SeqPart8.lean | 9 + SolidCore/Refinement/Corpus/C9/SeqPart9.lean | 9 + SolidCore/Refinement/Corpus/C9/SeqStates.lean | 277 +++++++++++++++++ SolidCore/Refinement/Corpus/D1.lean | 95 ++++++ SolidCore/Refinement/Corpus/D1/Defs.lean | 51 ++++ SolidCore/Refinement/Corpus/D1/Malformed.lean | 30 ++ SolidCore/Refinement/Corpus/D1/Part0.lean | 9 + SolidCore/Refinement/Corpus/D1/Part1.lean | 9 + SolidCore/Refinement/Corpus/D1/Part10.lean | 9 + SolidCore/Refinement/Corpus/D1/Part11.lean | 9 + SolidCore/Refinement/Corpus/D1/Part12.lean | 9 + SolidCore/Refinement/Corpus/D1/Part13.lean | 9 + SolidCore/Refinement/Corpus/D1/Part14.lean | 9 + SolidCore/Refinement/Corpus/D1/Part15.lean | 9 + SolidCore/Refinement/Corpus/D1/Part16.lean | 9 + SolidCore/Refinement/Corpus/D1/Part2.lean | 9 + SolidCore/Refinement/Corpus/D1/Part3.lean | 9 + SolidCore/Refinement/Corpus/D1/Part4.lean | 9 + SolidCore/Refinement/Corpus/D1/Part5.lean | 9 + SolidCore/Refinement/Corpus/D1/Part6.lean | 9 + SolidCore/Refinement/Corpus/D1/Part7.lean | 9 + SolidCore/Refinement/Corpus/D1/Part8.lean | 9 + SolidCore/Refinement/Corpus/D1/Part9.lean | 9 + SolidCore/Refinement/Corpus/D2.lean | 95 ++++++ SolidCore/Refinement/Corpus/D2/Defs.lean | 51 ++++ SolidCore/Refinement/Corpus/D2/Malformed.lean | 30 ++ SolidCore/Refinement/Corpus/D2/Part0.lean | 9 + SolidCore/Refinement/Corpus/D2/Part1.lean | 9 + SolidCore/Refinement/Corpus/D2/Part10.lean | 9 + SolidCore/Refinement/Corpus/D2/Part11.lean | 9 + SolidCore/Refinement/Corpus/D2/Part12.lean | 9 + SolidCore/Refinement/Corpus/D2/Part13.lean | 9 + SolidCore/Refinement/Corpus/D2/Part14.lean | 9 + SolidCore/Refinement/Corpus/D2/Part15.lean | 9 + SolidCore/Refinement/Corpus/D2/Part16.lean | 9 + SolidCore/Refinement/Corpus/D2/Part2.lean | 9 + SolidCore/Refinement/Corpus/D2/Part3.lean | 9 + SolidCore/Refinement/Corpus/D2/Part4.lean | 9 + SolidCore/Refinement/Corpus/D2/Part5.lean | 9 + SolidCore/Refinement/Corpus/D2/Part6.lean | 9 + SolidCore/Refinement/Corpus/D2/Part7.lean | 9 + SolidCore/Refinement/Corpus/D2/Part8.lean | 9 + SolidCore/Refinement/Corpus/D2/Part9.lean | 9 + SolidCore/Refinement/Corpus/D3.lean | 63 ++++ SolidCore/Refinement/Corpus/D3/Defs.lean | 51 ++++ SolidCore/Refinement/Corpus/D3/Malformed.lean | 30 ++ SolidCore/Refinement/Corpus/D3/Part0.lean | 9 + SolidCore/Refinement/Corpus/D4.lean | 63 ++++ SolidCore/Refinement/Corpus/D4/Defs.lean | 51 ++++ SolidCore/Refinement/Corpus/D4/Malformed.lean | 30 ++ SolidCore/Refinement/Corpus/D4/Part0.lean | 9 + SolidCore/Refinement/Corpus/W1.lean | 207 +++++++++++++ SolidCore/Refinement/Corpus/W2.lean | 286 ++++++++++++++++++ SolidCore/Refinement/Corpus/W3.lean | 198 ++++++++++++ SolidCore/Refinement/Corpus/W4.lean | 195 ++++++++++++ SolidCore/Refinement/Corpus/W5.lean | 229 ++++++++++++++ 303 files changed, 9777 insertions(+) create mode 100644 SolidCore/Refinement/Corpus.lean create mode 100644 SolidCore/Refinement/Corpus/B1.lean create mode 100644 SolidCore/Refinement/Corpus/B1/Defs.lean create mode 100644 SolidCore/Refinement/Corpus/B1/Dirty.lean create mode 100644 SolidCore/Refinement/Corpus/B1/Part0.lean create mode 100644 SolidCore/Refinement/Corpus/B1/Seq.lean create mode 100644 SolidCore/Refinement/Corpus/B1/SeqDefs.lean create mode 100644 SolidCore/Refinement/Corpus/B1/SeqPart0.lean create mode 100644 SolidCore/Refinement/Corpus/B1/SeqStates.lean create mode 100644 SolidCore/Refinement/Corpus/B2.lean create mode 100644 SolidCore/Refinement/Corpus/B2/Defs.lean create mode 100644 SolidCore/Refinement/Corpus/B2/Dirty.lean create mode 100644 SolidCore/Refinement/Corpus/B2/Part0.lean create mode 100644 SolidCore/Refinement/Corpus/B2/Seq.lean create mode 100644 SolidCore/Refinement/Corpus/B2/SeqDefs.lean create mode 100644 SolidCore/Refinement/Corpus/B2/SeqPart0.lean create mode 100644 SolidCore/Refinement/Corpus/B2/SeqStates.lean create mode 100644 SolidCore/Refinement/Corpus/B3.lean create mode 100644 SolidCore/Refinement/Corpus/B3/Defs.lean create mode 100644 SolidCore/Refinement/Corpus/B3/Dirty.lean create mode 100644 SolidCore/Refinement/Corpus/B3/Part0.lean create mode 100644 SolidCore/Refinement/Corpus/B3/Seq.lean create mode 100644 SolidCore/Refinement/Corpus/B3/SeqDefs.lean create mode 100644 SolidCore/Refinement/Corpus/B3/SeqPart0.lean create mode 100644 SolidCore/Refinement/Corpus/B3/SeqStates.lean create mode 100644 SolidCore/Refinement/Corpus/B4.lean create mode 100644 SolidCore/Refinement/Corpus/B4/Defs.lean create mode 100644 SolidCore/Refinement/Corpus/B4/Dirty.lean create mode 100644 SolidCore/Refinement/Corpus/B4/Part0.lean create mode 100644 SolidCore/Refinement/Corpus/B4/Seq.lean create mode 100644 SolidCore/Refinement/Corpus/B4/SeqDefs.lean create mode 100644 SolidCore/Refinement/Corpus/B4/SeqPart0.lean create mode 100644 SolidCore/Refinement/Corpus/B4/SeqStates.lean create mode 100644 SolidCore/Refinement/Corpus/B5.lean create mode 100644 SolidCore/Refinement/Corpus/B5/Defs.lean create mode 100644 SolidCore/Refinement/Corpus/B5/Dirty.lean create mode 100644 SolidCore/Refinement/Corpus/B5/Part0.lean create mode 100644 SolidCore/Refinement/Corpus/B5/Seq.lean create mode 100644 SolidCore/Refinement/Corpus/B5/SeqDefs.lean create mode 100644 SolidCore/Refinement/Corpus/B5/SeqPart0.lean create mode 100644 SolidCore/Refinement/Corpus/B5/SeqStates.lean create mode 100644 SolidCore/Refinement/Corpus/B6.lean create mode 100644 SolidCore/Refinement/Corpus/B6/Defs.lean create mode 100644 SolidCore/Refinement/Corpus/B6/Dirty.lean create mode 100644 SolidCore/Refinement/Corpus/B6/Part0.lean create mode 100644 SolidCore/Refinement/Corpus/B6/Seq.lean create mode 100644 SolidCore/Refinement/Corpus/B6/SeqDefs.lean create mode 100644 SolidCore/Refinement/Corpus/B6/SeqPart0.lean create mode 100644 SolidCore/Refinement/Corpus/B6/SeqStates.lean create mode 100644 SolidCore/Refinement/Corpus/B7.lean create mode 100644 SolidCore/Refinement/Corpus/B7/Defs.lean create mode 100644 SolidCore/Refinement/Corpus/B7/Dirty.lean create mode 100644 SolidCore/Refinement/Corpus/B7/Part0.lean create mode 100644 SolidCore/Refinement/Corpus/B7/Seq.lean create mode 100644 SolidCore/Refinement/Corpus/B7/SeqDefs.lean create mode 100644 SolidCore/Refinement/Corpus/B7/SeqPart0.lean create mode 100644 SolidCore/Refinement/Corpus/B7/SeqStates.lean create mode 100644 SolidCore/Refinement/Corpus/C1.lean create mode 100644 SolidCore/Refinement/Corpus/C1/Defs.lean create mode 100644 SolidCore/Refinement/Corpus/C1/Dirty.lean create mode 100644 SolidCore/Refinement/Corpus/C1/Seq.lean create mode 100644 SolidCore/Refinement/Corpus/C1/SeqDefs.lean create mode 100644 SolidCore/Refinement/Corpus/C1/SeqPart0.lean create mode 100644 SolidCore/Refinement/Corpus/C1/SeqStates.lean create mode 100644 SolidCore/Refinement/Corpus/C10.lean create mode 100644 SolidCore/Refinement/Corpus/C10/Defs.lean create mode 100644 SolidCore/Refinement/Corpus/C10/Dirty.lean create mode 100644 SolidCore/Refinement/Corpus/C10/Part0.lean create mode 100644 SolidCore/Refinement/Corpus/C10/Seq.lean create mode 100644 SolidCore/Refinement/Corpus/C10/SeqDefs.lean create mode 100644 SolidCore/Refinement/Corpus/C10/SeqPart0.lean create mode 100644 SolidCore/Refinement/Corpus/C10/SeqStates.lean create mode 100644 SolidCore/Refinement/Corpus/C11.lean create mode 100644 SolidCore/Refinement/Corpus/C11/Defs.lean create mode 100644 SolidCore/Refinement/Corpus/C11/Dirty.lean create mode 100644 SolidCore/Refinement/Corpus/C11/Part0.lean create mode 100644 SolidCore/Refinement/Corpus/C11/Seq.lean create mode 100644 SolidCore/Refinement/Corpus/C11/SeqDefs.lean create mode 100644 SolidCore/Refinement/Corpus/C11/SeqPart0.lean create mode 100644 SolidCore/Refinement/Corpus/C11/SeqStates.lean create mode 100644 SolidCore/Refinement/Corpus/C2.lean create mode 100644 SolidCore/Refinement/Corpus/C2/Defs.lean create mode 100644 SolidCore/Refinement/Corpus/C2/Dirty.lean create mode 100644 SolidCore/Refinement/Corpus/C2/Part0.lean create mode 100644 SolidCore/Refinement/Corpus/C2/Part1.lean create mode 100644 SolidCore/Refinement/Corpus/C2/Part10.lean create mode 100644 SolidCore/Refinement/Corpus/C2/Part11.lean create mode 100644 SolidCore/Refinement/Corpus/C2/Part12.lean create mode 100644 SolidCore/Refinement/Corpus/C2/Part13.lean create mode 100644 SolidCore/Refinement/Corpus/C2/Part14.lean create mode 100644 SolidCore/Refinement/Corpus/C2/Part15.lean create mode 100644 SolidCore/Refinement/Corpus/C2/Part2.lean create mode 100644 SolidCore/Refinement/Corpus/C2/Part3.lean create mode 100644 SolidCore/Refinement/Corpus/C2/Part4.lean create mode 100644 SolidCore/Refinement/Corpus/C2/Part5.lean create mode 100644 SolidCore/Refinement/Corpus/C2/Part6.lean create mode 100644 SolidCore/Refinement/Corpus/C2/Part7.lean create mode 100644 SolidCore/Refinement/Corpus/C2/Part8.lean create mode 100644 SolidCore/Refinement/Corpus/C2/Part9.lean create mode 100644 SolidCore/Refinement/Corpus/C2/Seq.lean create mode 100644 SolidCore/Refinement/Corpus/C2/SeqDefs.lean create mode 100644 SolidCore/Refinement/Corpus/C2/SeqPart0.lean create mode 100644 SolidCore/Refinement/Corpus/C2/SeqPart1.lean create mode 100644 SolidCore/Refinement/Corpus/C2/SeqPart10.lean create mode 100644 SolidCore/Refinement/Corpus/C2/SeqPart11.lean create mode 100644 SolidCore/Refinement/Corpus/C2/SeqPart12.lean create mode 100644 SolidCore/Refinement/Corpus/C2/SeqPart13.lean create mode 100644 SolidCore/Refinement/Corpus/C2/SeqPart14.lean create mode 100644 SolidCore/Refinement/Corpus/C2/SeqPart15.lean create mode 100644 SolidCore/Refinement/Corpus/C2/SeqPart2.lean create mode 100644 SolidCore/Refinement/Corpus/C2/SeqPart3.lean create mode 100644 SolidCore/Refinement/Corpus/C2/SeqPart4.lean create mode 100644 SolidCore/Refinement/Corpus/C2/SeqPart5.lean create mode 100644 SolidCore/Refinement/Corpus/C2/SeqPart6.lean create mode 100644 SolidCore/Refinement/Corpus/C2/SeqPart7.lean create mode 100644 SolidCore/Refinement/Corpus/C2/SeqPart8.lean create mode 100644 SolidCore/Refinement/Corpus/C2/SeqPart9.lean create mode 100644 SolidCore/Refinement/Corpus/C2/SeqStates.lean create mode 100644 SolidCore/Refinement/Corpus/C3.lean create mode 100644 SolidCore/Refinement/Corpus/C3/Defs.lean create mode 100644 SolidCore/Refinement/Corpus/C3/Dirty.lean create mode 100644 SolidCore/Refinement/Corpus/C3/Part0.lean create mode 100644 SolidCore/Refinement/Corpus/C3/Part1.lean create mode 100644 SolidCore/Refinement/Corpus/C3/Part10.lean create mode 100644 SolidCore/Refinement/Corpus/C3/Part11.lean create mode 100644 SolidCore/Refinement/Corpus/C3/Part12.lean create mode 100644 SolidCore/Refinement/Corpus/C3/Part13.lean create mode 100644 SolidCore/Refinement/Corpus/C3/Part14.lean create mode 100644 SolidCore/Refinement/Corpus/C3/Part15.lean create mode 100644 SolidCore/Refinement/Corpus/C3/Part2.lean create mode 100644 SolidCore/Refinement/Corpus/C3/Part3.lean create mode 100644 SolidCore/Refinement/Corpus/C3/Part4.lean create mode 100644 SolidCore/Refinement/Corpus/C3/Part5.lean create mode 100644 SolidCore/Refinement/Corpus/C3/Part6.lean create mode 100644 SolidCore/Refinement/Corpus/C3/Part7.lean create mode 100644 SolidCore/Refinement/Corpus/C3/Part8.lean create mode 100644 SolidCore/Refinement/Corpus/C3/Part9.lean create mode 100644 SolidCore/Refinement/Corpus/C3/Seq.lean create mode 100644 SolidCore/Refinement/Corpus/C3/SeqDefs.lean create mode 100644 SolidCore/Refinement/Corpus/C3/SeqPart0.lean create mode 100644 SolidCore/Refinement/Corpus/C3/SeqPart1.lean create mode 100644 SolidCore/Refinement/Corpus/C3/SeqPart10.lean create mode 100644 SolidCore/Refinement/Corpus/C3/SeqPart11.lean create mode 100644 SolidCore/Refinement/Corpus/C3/SeqPart12.lean create mode 100644 SolidCore/Refinement/Corpus/C3/SeqPart13.lean create mode 100644 SolidCore/Refinement/Corpus/C3/SeqPart14.lean create mode 100644 SolidCore/Refinement/Corpus/C3/SeqPart15.lean create mode 100644 SolidCore/Refinement/Corpus/C3/SeqPart2.lean create mode 100644 SolidCore/Refinement/Corpus/C3/SeqPart3.lean create mode 100644 SolidCore/Refinement/Corpus/C3/SeqPart4.lean create mode 100644 SolidCore/Refinement/Corpus/C3/SeqPart5.lean create mode 100644 SolidCore/Refinement/Corpus/C3/SeqPart6.lean create mode 100644 SolidCore/Refinement/Corpus/C3/SeqPart7.lean create mode 100644 SolidCore/Refinement/Corpus/C3/SeqPart8.lean create mode 100644 SolidCore/Refinement/Corpus/C3/SeqPart9.lean create mode 100644 SolidCore/Refinement/Corpus/C3/SeqStates.lean create mode 100644 SolidCore/Refinement/Corpus/C4.lean create mode 100644 SolidCore/Refinement/Corpus/C4/Defs.lean create mode 100644 SolidCore/Refinement/Corpus/C4/Dirty.lean create mode 100644 SolidCore/Refinement/Corpus/C4/Seq.lean create mode 100644 SolidCore/Refinement/Corpus/C4/SeqDefs.lean create mode 100644 SolidCore/Refinement/Corpus/C4/SeqPart0.lean create mode 100644 SolidCore/Refinement/Corpus/C4/SeqPart1.lean create mode 100644 SolidCore/Refinement/Corpus/C4/SeqPart10.lean create mode 100644 SolidCore/Refinement/Corpus/C4/SeqPart11.lean create mode 100644 SolidCore/Refinement/Corpus/C4/SeqPart12.lean create mode 100644 SolidCore/Refinement/Corpus/C4/SeqPart13.lean create mode 100644 SolidCore/Refinement/Corpus/C4/SeqPart14.lean create mode 100644 SolidCore/Refinement/Corpus/C4/SeqPart15.lean create mode 100644 SolidCore/Refinement/Corpus/C4/SeqPart2.lean create mode 100644 SolidCore/Refinement/Corpus/C4/SeqPart3.lean create mode 100644 SolidCore/Refinement/Corpus/C4/SeqPart4.lean create mode 100644 SolidCore/Refinement/Corpus/C4/SeqPart5.lean create mode 100644 SolidCore/Refinement/Corpus/C4/SeqPart6.lean create mode 100644 SolidCore/Refinement/Corpus/C4/SeqPart7.lean create mode 100644 SolidCore/Refinement/Corpus/C4/SeqPart8.lean create mode 100644 SolidCore/Refinement/Corpus/C4/SeqPart9.lean create mode 100644 SolidCore/Refinement/Corpus/C4/SeqStates.lean create mode 100644 SolidCore/Refinement/Corpus/C5.lean create mode 100644 SolidCore/Refinement/Corpus/C5/Defs.lean create mode 100644 SolidCore/Refinement/Corpus/C5/Dirty.lean create mode 100644 SolidCore/Refinement/Corpus/C5/Part0.lean create mode 100644 SolidCore/Refinement/Corpus/C5/Seq.lean create mode 100644 SolidCore/Refinement/Corpus/C5/SeqDefs.lean create mode 100644 SolidCore/Refinement/Corpus/C5/SeqPart0.lean create mode 100644 SolidCore/Refinement/Corpus/C5/SeqPart1.lean create mode 100644 SolidCore/Refinement/Corpus/C5/SeqPart10.lean create mode 100644 SolidCore/Refinement/Corpus/C5/SeqPart11.lean create mode 100644 SolidCore/Refinement/Corpus/C5/SeqPart12.lean create mode 100644 SolidCore/Refinement/Corpus/C5/SeqPart13.lean create mode 100644 SolidCore/Refinement/Corpus/C5/SeqPart14.lean create mode 100644 SolidCore/Refinement/Corpus/C5/SeqPart15.lean create mode 100644 SolidCore/Refinement/Corpus/C5/SeqPart16.lean create mode 100644 SolidCore/Refinement/Corpus/C5/SeqPart2.lean create mode 100644 SolidCore/Refinement/Corpus/C5/SeqPart3.lean create mode 100644 SolidCore/Refinement/Corpus/C5/SeqPart4.lean create mode 100644 SolidCore/Refinement/Corpus/C5/SeqPart5.lean create mode 100644 SolidCore/Refinement/Corpus/C5/SeqPart6.lean create mode 100644 SolidCore/Refinement/Corpus/C5/SeqPart7.lean create mode 100644 SolidCore/Refinement/Corpus/C5/SeqPart8.lean create mode 100644 SolidCore/Refinement/Corpus/C5/SeqPart9.lean create mode 100644 SolidCore/Refinement/Corpus/C5/SeqStates.lean create mode 100644 SolidCore/Refinement/Corpus/C6.lean create mode 100644 SolidCore/Refinement/Corpus/C6/Defs.lean create mode 100644 SolidCore/Refinement/Corpus/C6/Dirty.lean create mode 100644 SolidCore/Refinement/Corpus/C6/Part0.lean create mode 100644 SolidCore/Refinement/Corpus/C6/Seq.lean create mode 100644 SolidCore/Refinement/Corpus/C6/SeqDefs.lean create mode 100644 SolidCore/Refinement/Corpus/C6/SeqPart0.lean create mode 100644 SolidCore/Refinement/Corpus/C6/SeqStates.lean create mode 100644 SolidCore/Refinement/Corpus/C7.lean create mode 100644 SolidCore/Refinement/Corpus/C7/Defs.lean create mode 100644 SolidCore/Refinement/Corpus/C7/Dirty.lean create mode 100644 SolidCore/Refinement/Corpus/C7/Part0.lean create mode 100644 SolidCore/Refinement/Corpus/C7/Seq.lean create mode 100644 SolidCore/Refinement/Corpus/C7/SeqDefs.lean create mode 100644 SolidCore/Refinement/Corpus/C7/SeqPart0.lean create mode 100644 SolidCore/Refinement/Corpus/C7/SeqStates.lean create mode 100644 SolidCore/Refinement/Corpus/C8.lean create mode 100644 SolidCore/Refinement/Corpus/C8/Defs.lean create mode 100644 SolidCore/Refinement/Corpus/C8/Dirty.lean create mode 100644 SolidCore/Refinement/Corpus/C8/Part0.lean create mode 100644 SolidCore/Refinement/Corpus/C8/Seq.lean create mode 100644 SolidCore/Refinement/Corpus/C8/SeqDefs.lean create mode 100644 SolidCore/Refinement/Corpus/C8/SeqPart0.lean create mode 100644 SolidCore/Refinement/Corpus/C8/SeqStates.lean create mode 100644 SolidCore/Refinement/Corpus/C9.lean create mode 100644 SolidCore/Refinement/Corpus/C9/Defs.lean create mode 100644 SolidCore/Refinement/Corpus/C9/Dirty.lean create mode 100644 SolidCore/Refinement/Corpus/C9/Part0.lean create mode 100644 SolidCore/Refinement/Corpus/C9/Seq.lean create mode 100644 SolidCore/Refinement/Corpus/C9/SeqDefs.lean create mode 100644 SolidCore/Refinement/Corpus/C9/SeqPart0.lean create mode 100644 SolidCore/Refinement/Corpus/C9/SeqPart1.lean create mode 100644 SolidCore/Refinement/Corpus/C9/SeqPart10.lean create mode 100644 SolidCore/Refinement/Corpus/C9/SeqPart11.lean create mode 100644 SolidCore/Refinement/Corpus/C9/SeqPart12.lean create mode 100644 SolidCore/Refinement/Corpus/C9/SeqPart13.lean create mode 100644 SolidCore/Refinement/Corpus/C9/SeqPart14.lean create mode 100644 SolidCore/Refinement/Corpus/C9/SeqPart15.lean create mode 100644 SolidCore/Refinement/Corpus/C9/SeqPart16.lean create mode 100644 SolidCore/Refinement/Corpus/C9/SeqPart2.lean create mode 100644 SolidCore/Refinement/Corpus/C9/SeqPart3.lean create mode 100644 SolidCore/Refinement/Corpus/C9/SeqPart4.lean create mode 100644 SolidCore/Refinement/Corpus/C9/SeqPart5.lean create mode 100644 SolidCore/Refinement/Corpus/C9/SeqPart6.lean create mode 100644 SolidCore/Refinement/Corpus/C9/SeqPart7.lean create mode 100644 SolidCore/Refinement/Corpus/C9/SeqPart8.lean create mode 100644 SolidCore/Refinement/Corpus/C9/SeqPart9.lean create mode 100644 SolidCore/Refinement/Corpus/C9/SeqStates.lean create mode 100644 SolidCore/Refinement/Corpus/D1.lean create mode 100644 SolidCore/Refinement/Corpus/D1/Defs.lean create mode 100644 SolidCore/Refinement/Corpus/D1/Malformed.lean create mode 100644 SolidCore/Refinement/Corpus/D1/Part0.lean create mode 100644 SolidCore/Refinement/Corpus/D1/Part1.lean create mode 100644 SolidCore/Refinement/Corpus/D1/Part10.lean create mode 100644 SolidCore/Refinement/Corpus/D1/Part11.lean create mode 100644 SolidCore/Refinement/Corpus/D1/Part12.lean create mode 100644 SolidCore/Refinement/Corpus/D1/Part13.lean create mode 100644 SolidCore/Refinement/Corpus/D1/Part14.lean create mode 100644 SolidCore/Refinement/Corpus/D1/Part15.lean create mode 100644 SolidCore/Refinement/Corpus/D1/Part16.lean create mode 100644 SolidCore/Refinement/Corpus/D1/Part2.lean create mode 100644 SolidCore/Refinement/Corpus/D1/Part3.lean create mode 100644 SolidCore/Refinement/Corpus/D1/Part4.lean create mode 100644 SolidCore/Refinement/Corpus/D1/Part5.lean create mode 100644 SolidCore/Refinement/Corpus/D1/Part6.lean create mode 100644 SolidCore/Refinement/Corpus/D1/Part7.lean create mode 100644 SolidCore/Refinement/Corpus/D1/Part8.lean create mode 100644 SolidCore/Refinement/Corpus/D1/Part9.lean create mode 100644 SolidCore/Refinement/Corpus/D2.lean create mode 100644 SolidCore/Refinement/Corpus/D2/Defs.lean create mode 100644 SolidCore/Refinement/Corpus/D2/Malformed.lean create mode 100644 SolidCore/Refinement/Corpus/D2/Part0.lean create mode 100644 SolidCore/Refinement/Corpus/D2/Part1.lean create mode 100644 SolidCore/Refinement/Corpus/D2/Part10.lean create mode 100644 SolidCore/Refinement/Corpus/D2/Part11.lean create mode 100644 SolidCore/Refinement/Corpus/D2/Part12.lean create mode 100644 SolidCore/Refinement/Corpus/D2/Part13.lean create mode 100644 SolidCore/Refinement/Corpus/D2/Part14.lean create mode 100644 SolidCore/Refinement/Corpus/D2/Part15.lean create mode 100644 SolidCore/Refinement/Corpus/D2/Part16.lean create mode 100644 SolidCore/Refinement/Corpus/D2/Part2.lean create mode 100644 SolidCore/Refinement/Corpus/D2/Part3.lean create mode 100644 SolidCore/Refinement/Corpus/D2/Part4.lean create mode 100644 SolidCore/Refinement/Corpus/D2/Part5.lean create mode 100644 SolidCore/Refinement/Corpus/D2/Part6.lean create mode 100644 SolidCore/Refinement/Corpus/D2/Part7.lean create mode 100644 SolidCore/Refinement/Corpus/D2/Part8.lean create mode 100644 SolidCore/Refinement/Corpus/D2/Part9.lean create mode 100644 SolidCore/Refinement/Corpus/D3.lean create mode 100644 SolidCore/Refinement/Corpus/D3/Defs.lean create mode 100644 SolidCore/Refinement/Corpus/D3/Malformed.lean create mode 100644 SolidCore/Refinement/Corpus/D3/Part0.lean create mode 100644 SolidCore/Refinement/Corpus/D4.lean create mode 100644 SolidCore/Refinement/Corpus/D4/Defs.lean create mode 100644 SolidCore/Refinement/Corpus/D4/Malformed.lean create mode 100644 SolidCore/Refinement/Corpus/D4/Part0.lean create mode 100644 SolidCore/Refinement/Corpus/W1.lean create mode 100644 SolidCore/Refinement/Corpus/W2.lean create mode 100644 SolidCore/Refinement/Corpus/W3.lean create mode 100644 SolidCore/Refinement/Corpus/W4.lean create mode 100644 SolidCore/Refinement/Corpus/W5.lean diff --git a/SolidCore/Refinement/Corpus.lean b/SolidCore/Refinement/Corpus.lean new file mode 100644 index 00000000..7ee1aa92 --- /dev/null +++ b/SolidCore/Refinement/Corpus.lean @@ -0,0 +1,31 @@ +-- Generated by scripts/refinement/gen.sh. Do not edit. + +import SolidCore.Refinement.Corpus.B1 +import SolidCore.Refinement.Corpus.B2 +import SolidCore.Refinement.Corpus.B3 +import SolidCore.Refinement.Corpus.B4 +import SolidCore.Refinement.Corpus.B5 +import SolidCore.Refinement.Corpus.B6 +import SolidCore.Refinement.Corpus.B7 +import SolidCore.Refinement.Corpus.C1 +import SolidCore.Refinement.Corpus.C10 +import SolidCore.Refinement.Corpus.C11 +import SolidCore.Refinement.Corpus.C2 +import SolidCore.Refinement.Corpus.C3 +import SolidCore.Refinement.Corpus.C4 +import SolidCore.Refinement.Corpus.C5 +import SolidCore.Refinement.Corpus.C6 +import SolidCore.Refinement.Corpus.C7 +import SolidCore.Refinement.Corpus.C8 +import SolidCore.Refinement.Corpus.C9 +import SolidCore.Refinement.Corpus.D1 +import SolidCore.Refinement.Corpus.D2 +import SolidCore.Refinement.Corpus.D3 +import SolidCore.Refinement.Corpus.D4 +import SolidCore.Refinement.Corpus.W1 +import SolidCore.Refinement.Corpus.W2 +import SolidCore.Refinement.Corpus.W3 +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/B1.lean b/SolidCore/Refinement/Corpus/B1.lean new file mode 100644 index 00000000..6aeff9bf --- /dev/null +++ b/SolidCore/Refinement/Corpus/B1.lean @@ -0,0 +1,65 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/b1.sol. Do not edit. + +import SolidCore.Refinement.Corpus.B1.Part0 +import SolidCore.Refinement.Corpus.B1.Dirty + +/-! +# b1: solar's bytecode refines SolidCore's `Main` + +`refines` proves `Refines fuel contract code (· ∈ scope s)` for `Main` in +`scripts/refinement/corpus/b1.sol`, 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, 256 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 SolidCore.Refinement.Corpus.B1 + +open SolidCore.Refinement SolidCore.Refinement.Abi + +theorem parts_ok : ∀ i < parts, partOk i = true := fun i hi => + match i, hi with + | 0, _ => part0 + | n + 1, 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 SolidCore.Refinement.Corpus.B1 diff --git a/SolidCore/Refinement/Corpus/B1/Defs.lean b/SolidCore/Refinement/Corpus/B1/Defs.lean new file mode 100644 index 00000000..ab3ab946 --- /dev/null +++ b/SolidCore/Refinement/Corpus/B1/Defs.lean @@ -0,0 +1,50 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/b1.sol. Do not edit. + +import SolidCore.Refinement.Abi +import SolidCore.Refinement.Bytecode.B1 +import SolidCore.Refinement.Source.B1 + +/-! +# The scope of b1's refinement + +256 calls: every function of `Main` in `scripts/refinement/corpus/b1.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.B1 + +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.B1.Main.runtimeNat + Bytecode.B1.Main.runtimeSize + +/-- SolidCore's checked `Main`. -/ +def contract? : Except TypeCheck.TypeError TypeCheck.CheckedContract := + TypeCheck.CheckedInput.contract Source.B1.importedSourceUnit "Main" + +/-- The functions of `Main` and their parameters. -/ +def fns : List Fn := + [⟨Bytecode.B1.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.B1 diff --git a/SolidCore/Refinement/Corpus/B1/Dirty.lean b/SolidCore/Refinement/Corpus/B1/Dirty.lean new file mode 100644 index 00000000..3b1d510f --- /dev/null +++ b/SolidCore/Refinement/Corpus/B1/Dirty.lean @@ -0,0 +1,31 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/b1.sol. Do not edit. + +import SolidCore.Refinement.Evm.Symex +import SolidCore.Refinement.Dirty.Source +import SolidCore.Refinement.Corpus.B1.Defs + +/-! +# b1: EthLib rejects every dirty argument word + +For every function of `Main` in `scripts/refinement/corpus/b1.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.B1 + +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.B1.Main.fSelector [(.uint 8)] + (by dirty_symex [code, Bytecode.B1.Main.runtimeNat, Bytecode.B1.Main.runtimeSize, Bytecode.B1.Main.fSelector]) + +end SolidCore.Refinement.Corpus.B1 diff --git a/SolidCore/Refinement/Corpus/B1/Part0.lean b/SolidCore/Refinement/Corpus/B1/Part0.lean new file mode 100644 index 00000000..e83ad1ca --- /dev/null +++ b/SolidCore/Refinement/Corpus/B1/Part0.lean @@ -0,0 +1,9 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/b1.sol. Do not edit. + +import SolidCore.Refinement.Corpus.B1.Defs + +namespace SolidCore.Refinement.Corpus.B1 + +theorem part0 : partOk 0 = true := by native_decide + +end SolidCore.Refinement.Corpus.B1 diff --git a/SolidCore/Refinement/Corpus/B1/Seq.lean b/SolidCore/Refinement/Corpus/B1/Seq.lean new file mode 100644 index 00000000..87337af8 --- /dev/null +++ b/SolidCore/Refinement/Corpus/B1/Seq.lean @@ -0,0 +1,54 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/b1.sol. Do not edit. + +import SolidCore.Refinement.Corpus.B1 +import SolidCore.Refinement.Corpus.B1.SeqDefs +import SolidCore.Refinement.Corpus.B1.SeqPart0 + +/-! +# b1: 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/b1.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: 2 storage(s) in 2 level(s); `Seq.explore` found the closure. 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.B1 + +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.B1 diff --git a/SolidCore/Refinement/Corpus/B1/SeqDefs.lean b/SolidCore/Refinement/Corpus/B1/SeqDefs.lean new file mode 100644 index 00000000..b9d33049 --- /dev/null +++ b/SolidCore/Refinement/Corpus/B1/SeqDefs.lean @@ -0,0 +1,59 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/b1.sol. Do not edit. + +import SolidCore.Refinement.Seq.Check +import SolidCore.Refinement.Corpus.B1.Defs +import SolidCore.Refinement.Corpus.B1.SeqStates + +/-! +# The certificate of b1's sequence refinement + +The storages of `SeqStates.lean`, with the deployed storage `s` as level 0, are +closed: 2 storage(s) in 2 level(s); `Seq.explore` found the closure. 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, 512 calls, in 1 part(s), and every dirty call once +per storage. +-/ + +namespace SolidCore.Refinement.Corpus.B1 + +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.B1 diff --git a/SolidCore/Refinement/Corpus/B1/SeqPart0.lean b/SolidCore/Refinement/Corpus/B1/SeqPart0.lean new file mode 100644 index 00000000..b0bf68e4 --- /dev/null +++ b/SolidCore/Refinement/Corpus/B1/SeqPart0.lean @@ -0,0 +1,9 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/b1.sol. Do not edit. + +import SolidCore.Refinement.Corpus.B1.SeqDefs + +namespace SolidCore.Refinement.Corpus.B1 + +theorem seqPart0 : seqPartOk 0 = true := by native_decide + +end SolidCore.Refinement.Corpus.B1 diff --git a/SolidCore/Refinement/Corpus/B1/SeqStates.lean b/SolidCore/Refinement/Corpus/B1/SeqStates.lean new file mode 100644 index 00000000..4987bb32 --- /dev/null +++ b/SolidCore/Refinement/Corpus/B1/SeqStates.lean @@ -0,0 +1,22 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/b1.sol. Do not edit. + +/-! +# The storages b1's clean calls reach + +The certificate of the sequence refinement of `Main` in `scripts/refinement/corpus/b1.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.B1 + +/-- 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, 7)]]] + +end SolidCore.Refinement.Corpus.B1 diff --git a/SolidCore/Refinement/Corpus/B2.lean b/SolidCore/Refinement/Corpus/B2.lean new file mode 100644 index 00000000..931f5e08 --- /dev/null +++ b/SolidCore/Refinement/Corpus/B2.lean @@ -0,0 +1,65 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/b2.sol. Do not edit. + +import SolidCore.Refinement.Corpus.B2.Part0 +import SolidCore.Refinement.Corpus.B2.Dirty + +/-! +# b2: solar's bytecode refines SolidCore's `Main` + +`refines` proves `Refines fuel contract code (· ∈ scope s)` for `Main` in +`scripts/refinement/corpus/b2.sol`, 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, 2 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 SolidCore.Refinement.Corpus.B2 + +open SolidCore.Refinement SolidCore.Refinement.Abi + +theorem parts_ok : ∀ i < parts, partOk i = true := fun i hi => + match i, hi with + | 0, _ => part0 + | n + 1, 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 SolidCore.Refinement.Corpus.B2 diff --git a/SolidCore/Refinement/Corpus/B2/Defs.lean b/SolidCore/Refinement/Corpus/B2/Defs.lean new file mode 100644 index 00000000..b842e35c --- /dev/null +++ b/SolidCore/Refinement/Corpus/B2/Defs.lean @@ -0,0 +1,50 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/b2.sol. Do not edit. + +import SolidCore.Refinement.Abi +import SolidCore.Refinement.Bytecode.B2 +import SolidCore.Refinement.Source.B2 + +/-! +# The scope of b2's refinement + +2 calls: every function of `Main` in `scripts/refinement/corpus/b2.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.B2 + +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.B2.Main.runtimeNat + Bytecode.B2.Main.runtimeSize + +/-- SolidCore's checked `Main`. -/ +def contract? : Except TypeCheck.TypeError TypeCheck.CheckedContract := + TypeCheck.CheckedInput.contract Source.B2.importedSourceUnit "Main" + +/-- The functions of `Main` and their parameters. -/ +def fns : List Fn := + [⟨Bytecode.B2.Main.fSelector, [.bool]⟩] + +/-- 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.B2 diff --git a/SolidCore/Refinement/Corpus/B2/Dirty.lean b/SolidCore/Refinement/Corpus/B2/Dirty.lean new file mode 100644 index 00000000..a94a4350 --- /dev/null +++ b/SolidCore/Refinement/Corpus/B2/Dirty.lean @@ -0,0 +1,31 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/b2.sol. Do not edit. + +import SolidCore.Refinement.Evm.Symex +import SolidCore.Refinement.Dirty.Source +import SolidCore.Refinement.Corpus.B2.Defs + +/-! +# b2: EthLib rejects every dirty argument word + +For every function of `Main` in `scripts/refinement/corpus/b2.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.B2 + +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.B2.Main.fSelector [.bool] + (by dirty_symex [code, Bytecode.B2.Main.runtimeNat, Bytecode.B2.Main.runtimeSize, Bytecode.B2.Main.fSelector]) + +end SolidCore.Refinement.Corpus.B2 diff --git a/SolidCore/Refinement/Corpus/B2/Part0.lean b/SolidCore/Refinement/Corpus/B2/Part0.lean new file mode 100644 index 00000000..b186026e --- /dev/null +++ b/SolidCore/Refinement/Corpus/B2/Part0.lean @@ -0,0 +1,9 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/b2.sol. Do not edit. + +import SolidCore.Refinement.Corpus.B2.Defs + +namespace SolidCore.Refinement.Corpus.B2 + +theorem part0 : partOk 0 = true := by native_decide + +end SolidCore.Refinement.Corpus.B2 diff --git a/SolidCore/Refinement/Corpus/B2/Seq.lean b/SolidCore/Refinement/Corpus/B2/Seq.lean new file mode 100644 index 00000000..76c4a007 --- /dev/null +++ b/SolidCore/Refinement/Corpus/B2/Seq.lean @@ -0,0 +1,54 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/b2.sol. Do not edit. + +import SolidCore.Refinement.Corpus.B2 +import SolidCore.Refinement.Corpus.B2.SeqDefs +import SolidCore.Refinement.Corpus.B2.SeqPart0 + +/-! +# b2: 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/b2.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: 3 storage(s) in 2 level(s); `Seq.explore` found the closure. 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.B2 + +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.B2 diff --git a/SolidCore/Refinement/Corpus/B2/SeqDefs.lean b/SolidCore/Refinement/Corpus/B2/SeqDefs.lean new file mode 100644 index 00000000..633d7428 --- /dev/null +++ b/SolidCore/Refinement/Corpus/B2/SeqDefs.lean @@ -0,0 +1,59 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/b2.sol. Do not edit. + +import SolidCore.Refinement.Seq.Check +import SolidCore.Refinement.Corpus.B2.Defs +import SolidCore.Refinement.Corpus.B2.SeqStates + +/-! +# The certificate of b2's sequence refinement + +The storages of `SeqStates.lean`, with the deployed storage `s` as level 0, are +closed: 3 storage(s) in 2 level(s); `Seq.explore` found the closure. 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, 6 calls, in 1 part(s), and every dirty call once +per storage. +-/ + +namespace SolidCore.Refinement.Corpus.B2 + +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.B2 diff --git a/SolidCore/Refinement/Corpus/B2/SeqPart0.lean b/SolidCore/Refinement/Corpus/B2/SeqPart0.lean new file mode 100644 index 00000000..aaf5e8ec --- /dev/null +++ b/SolidCore/Refinement/Corpus/B2/SeqPart0.lean @@ -0,0 +1,9 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/b2.sol. Do not edit. + +import SolidCore.Refinement.Corpus.B2.SeqDefs + +namespace SolidCore.Refinement.Corpus.B2 + +theorem seqPart0 : seqPartOk 0 = true := by native_decide + +end SolidCore.Refinement.Corpus.B2 diff --git a/SolidCore/Refinement/Corpus/B2/SeqStates.lean b/SolidCore/Refinement/Corpus/B2/SeqStates.lean new file mode 100644 index 00000000..edf01854 --- /dev/null +++ b/SolidCore/Refinement/Corpus/B2/SeqStates.lean @@ -0,0 +1,23 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/b2.sol. Do not edit. + +/-! +# The storages b2's clean calls reach + +The certificate of the sequence refinement of `Main` in `scripts/refinement/corpus/b2.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.B2 + +/-- 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, 3)], + [(0, 1)]]] + +end SolidCore.Refinement.Corpus.B2 diff --git a/SolidCore/Refinement/Corpus/B3.lean b/SolidCore/Refinement/Corpus/B3.lean new file mode 100644 index 00000000..a92a71c3 --- /dev/null +++ b/SolidCore/Refinement/Corpus/B3.lean @@ -0,0 +1,65 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/b3.sol. Do not edit. + +import SolidCore.Refinement.Corpus.B3.Part0 +import SolidCore.Refinement.Corpus.B3.Dirty + +/-! +# b3: solar's bytecode refines SolidCore's `Main` + +`refines` proves `Refines fuel contract code (· ∈ scope s)` for `Main` in +`scripts/refinement/corpus/b3.sol`, 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, 2 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 SolidCore.Refinement.Corpus.B3 + +open SolidCore.Refinement SolidCore.Refinement.Abi + +theorem parts_ok : ∀ i < parts, partOk i = true := fun i hi => + match i, hi with + | 0, _ => part0 + | n + 1, 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 SolidCore.Refinement.Corpus.B3 diff --git a/SolidCore/Refinement/Corpus/B3/Defs.lean b/SolidCore/Refinement/Corpus/B3/Defs.lean new file mode 100644 index 00000000..395c144b --- /dev/null +++ b/SolidCore/Refinement/Corpus/B3/Defs.lean @@ -0,0 +1,50 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/b3.sol. Do not edit. + +import SolidCore.Refinement.Abi +import SolidCore.Refinement.Bytecode.B3 +import SolidCore.Refinement.Source.B3 + +/-! +# The scope of b3's refinement + +2 calls: every function of `Main` in `scripts/refinement/corpus/b3.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.B3 + +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.B3.Main.runtimeNat + Bytecode.B3.Main.runtimeSize + +/-- SolidCore's checked `Main`. -/ +def contract? : Except TypeCheck.TypeError TypeCheck.CheckedContract := + TypeCheck.CheckedInput.contract Source.B3.importedSourceUnit "Main" + +/-- The functions of `Main` and their parameters. -/ +def fns : List Fn := + [⟨Bytecode.B3.Main.fSelector, [.bool]⟩] + +/-- 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.B3 diff --git a/SolidCore/Refinement/Corpus/B3/Dirty.lean b/SolidCore/Refinement/Corpus/B3/Dirty.lean new file mode 100644 index 00000000..e50c6520 --- /dev/null +++ b/SolidCore/Refinement/Corpus/B3/Dirty.lean @@ -0,0 +1,31 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/b3.sol. Do not edit. + +import SolidCore.Refinement.Evm.Symex +import SolidCore.Refinement.Dirty.Source +import SolidCore.Refinement.Corpus.B3.Defs + +/-! +# b3: EthLib rejects every dirty argument word + +For every function of `Main` in `scripts/refinement/corpus/b3.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.B3 + +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.B3.Main.fSelector [.bool] + (by dirty_symex [code, Bytecode.B3.Main.runtimeNat, Bytecode.B3.Main.runtimeSize, Bytecode.B3.Main.fSelector]) + +end SolidCore.Refinement.Corpus.B3 diff --git a/SolidCore/Refinement/Corpus/B3/Part0.lean b/SolidCore/Refinement/Corpus/B3/Part0.lean new file mode 100644 index 00000000..cf034674 --- /dev/null +++ b/SolidCore/Refinement/Corpus/B3/Part0.lean @@ -0,0 +1,9 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/b3.sol. Do not edit. + +import SolidCore.Refinement.Corpus.B3.Defs + +namespace SolidCore.Refinement.Corpus.B3 + +theorem part0 : partOk 0 = true := by native_decide + +end SolidCore.Refinement.Corpus.B3 diff --git a/SolidCore/Refinement/Corpus/B3/Seq.lean b/SolidCore/Refinement/Corpus/B3/Seq.lean new file mode 100644 index 00000000..274049d4 --- /dev/null +++ b/SolidCore/Refinement/Corpus/B3/Seq.lean @@ -0,0 +1,54 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/b3.sol. Do not edit. + +import SolidCore.Refinement.Corpus.B3 +import SolidCore.Refinement.Corpus.B3.SeqDefs +import SolidCore.Refinement.Corpus.B3.SeqPart0 + +/-! +# b3: 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/b3.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.B3 + +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.B3 diff --git a/SolidCore/Refinement/Corpus/B3/SeqDefs.lean b/SolidCore/Refinement/Corpus/B3/SeqDefs.lean new file mode 100644 index 00000000..3a47d79c --- /dev/null +++ b/SolidCore/Refinement/Corpus/B3/SeqDefs.lean @@ -0,0 +1,59 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/b3.sol. Do not edit. + +import SolidCore.Refinement.Seq.Check +import SolidCore.Refinement.Corpus.B3.Defs +import SolidCore.Refinement.Corpus.B3.SeqStates + +/-! +# The certificate of b3'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, 2 calls, in 1 part(s), and every dirty call once +per storage. +-/ + +namespace SolidCore.Refinement.Corpus.B3 + +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.B3 diff --git a/SolidCore/Refinement/Corpus/B3/SeqPart0.lean b/SolidCore/Refinement/Corpus/B3/SeqPart0.lean new file mode 100644 index 00000000..215e1b58 --- /dev/null +++ b/SolidCore/Refinement/Corpus/B3/SeqPart0.lean @@ -0,0 +1,9 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/b3.sol. Do not edit. + +import SolidCore.Refinement.Corpus.B3.SeqDefs + +namespace SolidCore.Refinement.Corpus.B3 + +theorem seqPart0 : seqPartOk 0 = true := by native_decide + +end SolidCore.Refinement.Corpus.B3 diff --git a/SolidCore/Refinement/Corpus/B3/SeqStates.lean b/SolidCore/Refinement/Corpus/B3/SeqStates.lean new file mode 100644 index 00000000..295b3dc5 --- /dev/null +++ b/SolidCore/Refinement/Corpus/B3/SeqStates.lean @@ -0,0 +1,21 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/b3.sol. Do not edit. + +/-! +# The storages b3's clean calls reach + +The certificate of the sequence refinement of `Main` in `scripts/refinement/corpus/b3.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.B3 + +/-- 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.B3 diff --git a/SolidCore/Refinement/Corpus/B4.lean b/SolidCore/Refinement/Corpus/B4.lean new file mode 100644 index 00000000..8976af3b --- /dev/null +++ b/SolidCore/Refinement/Corpus/B4.lean @@ -0,0 +1,65 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/b4.sol. Do not edit. + +import SolidCore.Refinement.Corpus.B4.Part0 +import SolidCore.Refinement.Corpus.B4.Dirty + +/-! +# b4: solar's bytecode refines SolidCore's `Main` + +`refines` proves `Refines fuel contract code (· ∈ scope s)` for `Main` in +`scripts/refinement/corpus/b4.sol`, 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, 256 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 SolidCore.Refinement.Corpus.B4 + +open SolidCore.Refinement SolidCore.Refinement.Abi + +theorem parts_ok : ∀ i < parts, partOk i = true := fun i hi => + match i, hi with + | 0, _ => part0 + | n + 1, 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 SolidCore.Refinement.Corpus.B4 diff --git a/SolidCore/Refinement/Corpus/B4/Defs.lean b/SolidCore/Refinement/Corpus/B4/Defs.lean new file mode 100644 index 00000000..a83ef5ce --- /dev/null +++ b/SolidCore/Refinement/Corpus/B4/Defs.lean @@ -0,0 +1,50 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/b4.sol. Do not edit. + +import SolidCore.Refinement.Abi +import SolidCore.Refinement.Bytecode.B4 +import SolidCore.Refinement.Source.B4 + +/-! +# The scope of b4's refinement + +256 calls: every function of `Main` in `scripts/refinement/corpus/b4.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.B4 + +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.B4.Main.runtimeNat + Bytecode.B4.Main.runtimeSize + +/-- SolidCore's checked `Main`. -/ +def contract? : Except TypeCheck.TypeError TypeCheck.CheckedContract := + TypeCheck.CheckedInput.contract Source.B4.importedSourceUnit "Main" + +/-- The functions of `Main` and their parameters. -/ +def fns : List Fn := + [⟨Bytecode.B4.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.B4 diff --git a/SolidCore/Refinement/Corpus/B4/Dirty.lean b/SolidCore/Refinement/Corpus/B4/Dirty.lean new file mode 100644 index 00000000..56a976eb --- /dev/null +++ b/SolidCore/Refinement/Corpus/B4/Dirty.lean @@ -0,0 +1,31 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/b4.sol. Do not edit. + +import SolidCore.Refinement.Evm.Symex +import SolidCore.Refinement.Dirty.Source +import SolidCore.Refinement.Corpus.B4.Defs + +/-! +# b4: EthLib rejects every dirty argument word + +For every function of `Main` in `scripts/refinement/corpus/b4.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.B4 + +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.B4.Main.fSelector [(.uint 8)] + (by dirty_symex [code, Bytecode.B4.Main.runtimeNat, Bytecode.B4.Main.runtimeSize, Bytecode.B4.Main.fSelector]) + +end SolidCore.Refinement.Corpus.B4 diff --git a/SolidCore/Refinement/Corpus/B4/Part0.lean b/SolidCore/Refinement/Corpus/B4/Part0.lean new file mode 100644 index 00000000..ebc706a5 --- /dev/null +++ b/SolidCore/Refinement/Corpus/B4/Part0.lean @@ -0,0 +1,9 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/b4.sol. Do not edit. + +import SolidCore.Refinement.Corpus.B4.Defs + +namespace SolidCore.Refinement.Corpus.B4 + +theorem part0 : partOk 0 = true := by native_decide + +end SolidCore.Refinement.Corpus.B4 diff --git a/SolidCore/Refinement/Corpus/B4/Seq.lean b/SolidCore/Refinement/Corpus/B4/Seq.lean new file mode 100644 index 00000000..9405548d --- /dev/null +++ b/SolidCore/Refinement/Corpus/B4/Seq.lean @@ -0,0 +1,54 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/b4.sol. Do not edit. + +import SolidCore.Refinement.Corpus.B4 +import SolidCore.Refinement.Corpus.B4.SeqDefs +import SolidCore.Refinement.Corpus.B4.SeqPart0 + +/-! +# b4: 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/b4.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.B4 + +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.B4 diff --git a/SolidCore/Refinement/Corpus/B4/SeqDefs.lean b/SolidCore/Refinement/Corpus/B4/SeqDefs.lean new file mode 100644 index 00000000..730f635c --- /dev/null +++ b/SolidCore/Refinement/Corpus/B4/SeqDefs.lean @@ -0,0 +1,59 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/b4.sol. Do not edit. + +import SolidCore.Refinement.Seq.Check +import SolidCore.Refinement.Corpus.B4.Defs +import SolidCore.Refinement.Corpus.B4.SeqStates + +/-! +# The certificate of b4'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.B4 + +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.B4 diff --git a/SolidCore/Refinement/Corpus/B4/SeqPart0.lean b/SolidCore/Refinement/Corpus/B4/SeqPart0.lean new file mode 100644 index 00000000..9019c4e6 --- /dev/null +++ b/SolidCore/Refinement/Corpus/B4/SeqPart0.lean @@ -0,0 +1,9 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/b4.sol. Do not edit. + +import SolidCore.Refinement.Corpus.B4.SeqDefs + +namespace SolidCore.Refinement.Corpus.B4 + +theorem seqPart0 : seqPartOk 0 = true := by native_decide + +end SolidCore.Refinement.Corpus.B4 diff --git a/SolidCore/Refinement/Corpus/B4/SeqStates.lean b/SolidCore/Refinement/Corpus/B4/SeqStates.lean new file mode 100644 index 00000000..8a2367bc --- /dev/null +++ b/SolidCore/Refinement/Corpus/B4/SeqStates.lean @@ -0,0 +1,21 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/b4.sol. Do not edit. + +/-! +# The storages b4's clean calls reach + +The certificate of the sequence refinement of `Main` in `scripts/refinement/corpus/b4.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.B4 + +/-- 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.B4 diff --git a/SolidCore/Refinement/Corpus/B5.lean b/SolidCore/Refinement/Corpus/B5.lean new file mode 100644 index 00000000..312e0342 --- /dev/null +++ b/SolidCore/Refinement/Corpus/B5.lean @@ -0,0 +1,65 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/b5.sol. Do not edit. + +import SolidCore.Refinement.Corpus.B5.Part0 +import SolidCore.Refinement.Corpus.B5.Dirty + +/-! +# b5: solar's bytecode refines SolidCore's `Main` + +`refines` proves `Refines fuel contract code (· ∈ scope s)` for `Main` in +`scripts/refinement/corpus/b5.sol`, 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, 2 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 SolidCore.Refinement.Corpus.B5 + +open SolidCore.Refinement SolidCore.Refinement.Abi + +theorem parts_ok : ∀ i < parts, partOk i = true := fun i hi => + match i, hi with + | 0, _ => part0 + | n + 1, 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 SolidCore.Refinement.Corpus.B5 diff --git a/SolidCore/Refinement/Corpus/B5/Defs.lean b/SolidCore/Refinement/Corpus/B5/Defs.lean new file mode 100644 index 00000000..24157132 --- /dev/null +++ b/SolidCore/Refinement/Corpus/B5/Defs.lean @@ -0,0 +1,50 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/b5.sol. Do not edit. + +import SolidCore.Refinement.Abi +import SolidCore.Refinement.Bytecode.B5 +import SolidCore.Refinement.Source.B5 + +/-! +# The scope of b5's refinement + +2 calls: every function of `Main` in `scripts/refinement/corpus/b5.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.B5 + +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.B5.Main.runtimeNat + Bytecode.B5.Main.runtimeSize + +/-- SolidCore's checked `Main`. -/ +def contract? : Except TypeCheck.TypeError TypeCheck.CheckedContract := + TypeCheck.CheckedInput.contract Source.B5.importedSourceUnit "Main" + +/-- The functions of `Main` and their parameters. -/ +def fns : List Fn := + [⟨Bytecode.B5.Main.fSelector, [.bool]⟩] + +/-- 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.B5 diff --git a/SolidCore/Refinement/Corpus/B5/Dirty.lean b/SolidCore/Refinement/Corpus/B5/Dirty.lean new file mode 100644 index 00000000..93bbe297 --- /dev/null +++ b/SolidCore/Refinement/Corpus/B5/Dirty.lean @@ -0,0 +1,31 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/b5.sol. Do not edit. + +import SolidCore.Refinement.Evm.Symex +import SolidCore.Refinement.Dirty.Source +import SolidCore.Refinement.Corpus.B5.Defs + +/-! +# b5: EthLib rejects every dirty argument word + +For every function of `Main` in `scripts/refinement/corpus/b5.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.B5 + +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.B5.Main.fSelector [.bool] + (by dirty_symex [code, Bytecode.B5.Main.runtimeNat, Bytecode.B5.Main.runtimeSize, Bytecode.B5.Main.fSelector]) + +end SolidCore.Refinement.Corpus.B5 diff --git a/SolidCore/Refinement/Corpus/B5/Part0.lean b/SolidCore/Refinement/Corpus/B5/Part0.lean new file mode 100644 index 00000000..b47172d6 --- /dev/null +++ b/SolidCore/Refinement/Corpus/B5/Part0.lean @@ -0,0 +1,9 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/b5.sol. Do not edit. + +import SolidCore.Refinement.Corpus.B5.Defs + +namespace SolidCore.Refinement.Corpus.B5 + +theorem part0 : partOk 0 = true := by native_decide + +end SolidCore.Refinement.Corpus.B5 diff --git a/SolidCore/Refinement/Corpus/B5/Seq.lean b/SolidCore/Refinement/Corpus/B5/Seq.lean new file mode 100644 index 00000000..585feee6 --- /dev/null +++ b/SolidCore/Refinement/Corpus/B5/Seq.lean @@ -0,0 +1,54 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/b5.sol. Do not edit. + +import SolidCore.Refinement.Corpus.B5 +import SolidCore.Refinement.Corpus.B5.SeqDefs +import SolidCore.Refinement.Corpus.B5.SeqPart0 + +/-! +# b5: 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/b5.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: 2 storage(s) in 2 level(s); `Seq.explore` found the closure. 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.B5 + +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.B5 diff --git a/SolidCore/Refinement/Corpus/B5/SeqDefs.lean b/SolidCore/Refinement/Corpus/B5/SeqDefs.lean new file mode 100644 index 00000000..1e64e3dc --- /dev/null +++ b/SolidCore/Refinement/Corpus/B5/SeqDefs.lean @@ -0,0 +1,59 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/b5.sol. Do not edit. + +import SolidCore.Refinement.Seq.Check +import SolidCore.Refinement.Corpus.B5.Defs +import SolidCore.Refinement.Corpus.B5.SeqStates + +/-! +# The certificate of b5's sequence refinement + +The storages of `SeqStates.lean`, with the deployed storage `s` as level 0, are +closed: 2 storage(s) in 2 level(s); `Seq.explore` found the closure. 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, 4 calls, in 1 part(s), and every dirty call once +per storage. +-/ + +namespace SolidCore.Refinement.Corpus.B5 + +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.B5 diff --git a/SolidCore/Refinement/Corpus/B5/SeqPart0.lean b/SolidCore/Refinement/Corpus/B5/SeqPart0.lean new file mode 100644 index 00000000..09d36a82 --- /dev/null +++ b/SolidCore/Refinement/Corpus/B5/SeqPart0.lean @@ -0,0 +1,9 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/b5.sol. Do not edit. + +import SolidCore.Refinement.Corpus.B5.SeqDefs + +namespace SolidCore.Refinement.Corpus.B5 + +theorem seqPart0 : seqPartOk 0 = true := by native_decide + +end SolidCore.Refinement.Corpus.B5 diff --git a/SolidCore/Refinement/Corpus/B5/SeqStates.lean b/SolidCore/Refinement/Corpus/B5/SeqStates.lean new file mode 100644 index 00000000..5887804e --- /dev/null +++ b/SolidCore/Refinement/Corpus/B5/SeqStates.lean @@ -0,0 +1,22 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/b5.sol. Do not edit. + +/-! +# The storages b5's clean calls reach + +The certificate of the sequence refinement of `Main` in `scripts/refinement/corpus/b5.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.B5 + +/-- The slots a reached storage holds a word for. -/ +def seqKeys : List Nat := [0, 18569430475105882587588266137607568536673111973893317399460219858819262702947] + +/-- The reached storages, by level, from level 1. -/ +def seqLevels : List (List (List (Nat × Nat))) := [ + [[(0, 1), (18569430475105882587588266137607568536673111973893317399460219858819262702947, 7)]]] + +end SolidCore.Refinement.Corpus.B5 diff --git a/SolidCore/Refinement/Corpus/B6.lean b/SolidCore/Refinement/Corpus/B6.lean new file mode 100644 index 00000000..bbff2d58 --- /dev/null +++ b/SolidCore/Refinement/Corpus/B6.lean @@ -0,0 +1,65 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/b6.sol. Do not edit. + +import SolidCore.Refinement.Corpus.B6.Part0 +import SolidCore.Refinement.Corpus.B6.Dirty + +/-! +# b6: solar's bytecode refines SolidCore's `Main` + +`refines` proves `Refines fuel contract code (· ∈ scope s)` for `Main` in +`scripts/refinement/corpus/b6.sol`, 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, 2 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 SolidCore.Refinement.Corpus.B6 + +open SolidCore.Refinement SolidCore.Refinement.Abi + +theorem parts_ok : ∀ i < parts, partOk i = true := fun i hi => + match i, hi with + | 0, _ => part0 + | n + 1, 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 SolidCore.Refinement.Corpus.B6 diff --git a/SolidCore/Refinement/Corpus/B6/Defs.lean b/SolidCore/Refinement/Corpus/B6/Defs.lean new file mode 100644 index 00000000..d7e06a94 --- /dev/null +++ b/SolidCore/Refinement/Corpus/B6/Defs.lean @@ -0,0 +1,50 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/b6.sol. Do not edit. + +import SolidCore.Refinement.Abi +import SolidCore.Refinement.Bytecode.B6 +import SolidCore.Refinement.Source.B6 + +/-! +# The scope of b6's refinement + +2 calls: every function of `Main` in `scripts/refinement/corpus/b6.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.B6 + +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.B6.Main.runtimeNat + Bytecode.B6.Main.runtimeSize + +/-- SolidCore's checked `Main`. -/ +def contract? : Except TypeCheck.TypeError TypeCheck.CheckedContract := + TypeCheck.CheckedInput.contract Source.B6.importedSourceUnit "Main" + +/-- The functions of `Main` and their parameters. -/ +def fns : List Fn := + [⟨Bytecode.B6.Main.fSelector, [.bool]⟩] + +/-- 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.B6 diff --git a/SolidCore/Refinement/Corpus/B6/Dirty.lean b/SolidCore/Refinement/Corpus/B6/Dirty.lean new file mode 100644 index 00000000..beede472 --- /dev/null +++ b/SolidCore/Refinement/Corpus/B6/Dirty.lean @@ -0,0 +1,31 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/b6.sol. Do not edit. + +import SolidCore.Refinement.Evm.Symex +import SolidCore.Refinement.Dirty.Source +import SolidCore.Refinement.Corpus.B6.Defs + +/-! +# b6: EthLib rejects every dirty argument word + +For every function of `Main` in `scripts/refinement/corpus/b6.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.B6 + +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.B6.Main.fSelector [.bool] + (by dirty_symex [code, Bytecode.B6.Main.runtimeNat, Bytecode.B6.Main.runtimeSize, Bytecode.B6.Main.fSelector]) + +end SolidCore.Refinement.Corpus.B6 diff --git a/SolidCore/Refinement/Corpus/B6/Part0.lean b/SolidCore/Refinement/Corpus/B6/Part0.lean new file mode 100644 index 00000000..53808cb2 --- /dev/null +++ b/SolidCore/Refinement/Corpus/B6/Part0.lean @@ -0,0 +1,9 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/b6.sol. Do not edit. + +import SolidCore.Refinement.Corpus.B6.Defs + +namespace SolidCore.Refinement.Corpus.B6 + +theorem part0 : partOk 0 = true := by native_decide + +end SolidCore.Refinement.Corpus.B6 diff --git a/SolidCore/Refinement/Corpus/B6/Seq.lean b/SolidCore/Refinement/Corpus/B6/Seq.lean new file mode 100644 index 00000000..fbc09862 --- /dev/null +++ b/SolidCore/Refinement/Corpus/B6/Seq.lean @@ -0,0 +1,54 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/b6.sol. Do not edit. + +import SolidCore.Refinement.Corpus.B6 +import SolidCore.Refinement.Corpus.B6.SeqDefs +import SolidCore.Refinement.Corpus.B6.SeqPart0 + +/-! +# b6: 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/b6.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: 2 storage(s) in 2 level(s); `Seq.explore` found the closure. 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.B6 + +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.B6 diff --git a/SolidCore/Refinement/Corpus/B6/SeqDefs.lean b/SolidCore/Refinement/Corpus/B6/SeqDefs.lean new file mode 100644 index 00000000..74e1ee39 --- /dev/null +++ b/SolidCore/Refinement/Corpus/B6/SeqDefs.lean @@ -0,0 +1,59 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/b6.sol. Do not edit. + +import SolidCore.Refinement.Seq.Check +import SolidCore.Refinement.Corpus.B6.Defs +import SolidCore.Refinement.Corpus.B6.SeqStates + +/-! +# The certificate of b6's sequence refinement + +The storages of `SeqStates.lean`, with the deployed storage `s` as level 0, are +closed: 2 storage(s) in 2 level(s); `Seq.explore` found the closure. 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, 4 calls, in 1 part(s), and every dirty call once +per storage. +-/ + +namespace SolidCore.Refinement.Corpus.B6 + +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.B6 diff --git a/SolidCore/Refinement/Corpus/B6/SeqPart0.lean b/SolidCore/Refinement/Corpus/B6/SeqPart0.lean new file mode 100644 index 00000000..879b8f0d --- /dev/null +++ b/SolidCore/Refinement/Corpus/B6/SeqPart0.lean @@ -0,0 +1,9 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/b6.sol. Do not edit. + +import SolidCore.Refinement.Corpus.B6.SeqDefs + +namespace SolidCore.Refinement.Corpus.B6 + +theorem seqPart0 : seqPartOk 0 = true := by native_decide + +end SolidCore.Refinement.Corpus.B6 diff --git a/SolidCore/Refinement/Corpus/B6/SeqStates.lean b/SolidCore/Refinement/Corpus/B6/SeqStates.lean new file mode 100644 index 00000000..9d530d6f --- /dev/null +++ b/SolidCore/Refinement/Corpus/B6/SeqStates.lean @@ -0,0 +1,22 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/b6.sol. Do not edit. + +/-! +# The storages b6's clean calls reach + +The certificate of the sequence refinement of `Main` in `scripts/refinement/corpus/b6.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.B6 + +/-- The slots a reached storage holds a word for. -/ +def seqKeys : List Nat := [0, 18569430475105882587588266137607568536673111973893317399460219858819262702947] + +/-- The reached storages, by level, from level 1. -/ +def seqLevels : List (List (List (Nat × Nat))) := [ + [[(0, 1), (18569430475105882587588266137607568536673111973893317399460219858819262702947, 7)]]] + +end SolidCore.Refinement.Corpus.B6 diff --git a/SolidCore/Refinement/Corpus/B7.lean b/SolidCore/Refinement/Corpus/B7.lean new file mode 100644 index 00000000..db5f5139 --- /dev/null +++ b/SolidCore/Refinement/Corpus/B7.lean @@ -0,0 +1,65 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/b7.sol. Do not edit. + +import SolidCore.Refinement.Corpus.B7.Part0 +import SolidCore.Refinement.Corpus.B7.Dirty + +/-! +# b7: solar's bytecode refines SolidCore's `Main` + +`refines` proves `Refines fuel contract code (· ∈ scope s)` for `Main` in +`scripts/refinement/corpus/b7.sol`, 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, 2 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 SolidCore.Refinement.Corpus.B7 + +open SolidCore.Refinement SolidCore.Refinement.Abi + +theorem parts_ok : ∀ i < parts, partOk i = true := fun i hi => + match i, hi with + | 0, _ => part0 + | n + 1, 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 SolidCore.Refinement.Corpus.B7 diff --git a/SolidCore/Refinement/Corpus/B7/Defs.lean b/SolidCore/Refinement/Corpus/B7/Defs.lean new file mode 100644 index 00000000..a3462a48 --- /dev/null +++ b/SolidCore/Refinement/Corpus/B7/Defs.lean @@ -0,0 +1,50 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/b7.sol. Do not edit. + +import SolidCore.Refinement.Abi +import SolidCore.Refinement.Bytecode.B7 +import SolidCore.Refinement.Source.B7 + +/-! +# The scope of b7's refinement + +2 calls: every function of `Main` in `scripts/refinement/corpus/b7.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.B7 + +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.B7.Main.runtimeNat + Bytecode.B7.Main.runtimeSize + +/-- SolidCore's checked `Main`. -/ +def contract? : Except TypeCheck.TypeError TypeCheck.CheckedContract := + TypeCheck.CheckedInput.contract Source.B7.importedSourceUnit "Main" + +/-- The functions of `Main` and their parameters. -/ +def fns : List Fn := + [⟨Bytecode.B7.Main.fSelector, [.bool]⟩] + +/-- 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.B7 diff --git a/SolidCore/Refinement/Corpus/B7/Dirty.lean b/SolidCore/Refinement/Corpus/B7/Dirty.lean new file mode 100644 index 00000000..64416e9f --- /dev/null +++ b/SolidCore/Refinement/Corpus/B7/Dirty.lean @@ -0,0 +1,31 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/b7.sol. Do not edit. + +import SolidCore.Refinement.Evm.Symex +import SolidCore.Refinement.Dirty.Source +import SolidCore.Refinement.Corpus.B7.Defs + +/-! +# b7: EthLib rejects every dirty argument word + +For every function of `Main` in `scripts/refinement/corpus/b7.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.B7 + +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.B7.Main.fSelector [.bool] + (by dirty_symex [code, Bytecode.B7.Main.runtimeNat, Bytecode.B7.Main.runtimeSize, Bytecode.B7.Main.fSelector]) + +end SolidCore.Refinement.Corpus.B7 diff --git a/SolidCore/Refinement/Corpus/B7/Part0.lean b/SolidCore/Refinement/Corpus/B7/Part0.lean new file mode 100644 index 00000000..c2fe0de9 --- /dev/null +++ b/SolidCore/Refinement/Corpus/B7/Part0.lean @@ -0,0 +1,9 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/b7.sol. Do not edit. + +import SolidCore.Refinement.Corpus.B7.Defs + +namespace SolidCore.Refinement.Corpus.B7 + +theorem part0 : partOk 0 = true := by native_decide + +end SolidCore.Refinement.Corpus.B7 diff --git a/SolidCore/Refinement/Corpus/B7/Seq.lean b/SolidCore/Refinement/Corpus/B7/Seq.lean new file mode 100644 index 00000000..b9c490a1 --- /dev/null +++ b/SolidCore/Refinement/Corpus/B7/Seq.lean @@ -0,0 +1,54 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/b7.sol. Do not edit. + +import SolidCore.Refinement.Corpus.B7 +import SolidCore.Refinement.Corpus.B7.SeqDefs +import SolidCore.Refinement.Corpus.B7.SeqPart0 + +/-! +# b7: 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/b7.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: 2 storage(s) in 2 level(s); `Seq.explore` found the closure. 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.B7 + +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.B7 diff --git a/SolidCore/Refinement/Corpus/B7/SeqDefs.lean b/SolidCore/Refinement/Corpus/B7/SeqDefs.lean new file mode 100644 index 00000000..eec0010b --- /dev/null +++ b/SolidCore/Refinement/Corpus/B7/SeqDefs.lean @@ -0,0 +1,59 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/b7.sol. Do not edit. + +import SolidCore.Refinement.Seq.Check +import SolidCore.Refinement.Corpus.B7.Defs +import SolidCore.Refinement.Corpus.B7.SeqStates + +/-! +# The certificate of b7's sequence refinement + +The storages of `SeqStates.lean`, with the deployed storage `s` as level 0, are +closed: 2 storage(s) in 2 level(s); `Seq.explore` found the closure. 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, 4 calls, in 1 part(s), and every dirty call once +per storage. +-/ + +namespace SolidCore.Refinement.Corpus.B7 + +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.B7 diff --git a/SolidCore/Refinement/Corpus/B7/SeqPart0.lean b/SolidCore/Refinement/Corpus/B7/SeqPart0.lean new file mode 100644 index 00000000..65e41f34 --- /dev/null +++ b/SolidCore/Refinement/Corpus/B7/SeqPart0.lean @@ -0,0 +1,9 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/b7.sol. Do not edit. + +import SolidCore.Refinement.Corpus.B7.SeqDefs + +namespace SolidCore.Refinement.Corpus.B7 + +theorem seqPart0 : seqPartOk 0 = true := by native_decide + +end SolidCore.Refinement.Corpus.B7 diff --git a/SolidCore/Refinement/Corpus/B7/SeqStates.lean b/SolidCore/Refinement/Corpus/B7/SeqStates.lean new file mode 100644 index 00000000..20c4b06b --- /dev/null +++ b/SolidCore/Refinement/Corpus/B7/SeqStates.lean @@ -0,0 +1,22 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/b7.sol. Do not edit. + +/-! +# The storages b7's clean calls reach + +The certificate of the sequence refinement of `Main` in `scripts/refinement/corpus/b7.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.B7 + +/-- The slots a reached storage holds a word for. -/ +def seqKeys : List Nat := [0, 18569430475105882587588266137607568536673111973893317399460219858819262702947] + +/-- The reached storages, by level, from level 1. -/ +def seqLevels : List (List (List (Nat × Nat))) := [ + [[(0, 1), (18569430475105882587588266137607568536673111973893317399460219858819262702947, 7)]]] + +end SolidCore.Refinement.Corpus.B7 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/C10.lean b/SolidCore/Refinement/Corpus/C10.lean new file mode 100644 index 00000000..d03f7760 --- /dev/null +++ b/SolidCore/Refinement/Corpus/C10.lean @@ -0,0 +1,65 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/c10.sol. Do not edit. + +import SolidCore.Refinement.Corpus.C10.Part0 +import SolidCore.Refinement.Corpus.C10.Dirty + +/-! +# c10: solar's bytecode refines SolidCore's `Main` + +`refines` proves `Refines fuel contract code (· ∈ scope s)` for `Main` in +`scripts/refinement/corpus/c10.sol`, 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, 256 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 SolidCore.Refinement.Corpus.C10 + +open SolidCore.Refinement SolidCore.Refinement.Abi + +theorem parts_ok : ∀ i < parts, partOk i = true := fun i hi => + match i, hi with + | 0, _ => part0 + | n + 1, 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 SolidCore.Refinement.Corpus.C10 diff --git a/SolidCore/Refinement/Corpus/C10/Defs.lean b/SolidCore/Refinement/Corpus/C10/Defs.lean new file mode 100644 index 00000000..71259346 --- /dev/null +++ b/SolidCore/Refinement/Corpus/C10/Defs.lean @@ -0,0 +1,50 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/c10.sol. Do not edit. + +import SolidCore.Refinement.Abi +import SolidCore.Refinement.Bytecode.C10 +import SolidCore.Refinement.Source.C10 + +/-! +# The scope of c10's refinement + +256 calls: every function of `Main` in `scripts/refinement/corpus/c10.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.C10 + +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.C10.Main.runtimeNat + Bytecode.C10.Main.runtimeSize + +/-- SolidCore's checked `Main`. -/ +def contract? : Except TypeCheck.TypeError TypeCheck.CheckedContract := + TypeCheck.CheckedInput.contract Source.C10.importedSourceUnit "Main" + +/-- The functions of `Main` and their parameters. -/ +def fns : List Fn := + [⟨Bytecode.C10.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.C10 diff --git a/SolidCore/Refinement/Corpus/C10/Dirty.lean b/SolidCore/Refinement/Corpus/C10/Dirty.lean new file mode 100644 index 00000000..f5bc973d --- /dev/null +++ b/SolidCore/Refinement/Corpus/C10/Dirty.lean @@ -0,0 +1,31 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/c10.sol. Do not edit. + +import SolidCore.Refinement.Evm.Symex +import SolidCore.Refinement.Dirty.Source +import SolidCore.Refinement.Corpus.C10.Defs + +/-! +# c10: EthLib rejects every dirty argument word + +For every function of `Main` in `scripts/refinement/corpus/c10.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.C10 + +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.C10.Main.fSelector [(.uint 8)] + (by dirty_symex [code, Bytecode.C10.Main.runtimeNat, Bytecode.C10.Main.runtimeSize, Bytecode.C10.Main.fSelector]) + +end SolidCore.Refinement.Corpus.C10 diff --git a/SolidCore/Refinement/Corpus/C10/Part0.lean b/SolidCore/Refinement/Corpus/C10/Part0.lean new file mode 100644 index 00000000..a23dadc2 --- /dev/null +++ b/SolidCore/Refinement/Corpus/C10/Part0.lean @@ -0,0 +1,9 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/c10.sol. Do not edit. + +import SolidCore.Refinement.Corpus.C10.Defs + +namespace SolidCore.Refinement.Corpus.C10 + +theorem part0 : partOk 0 = true := by native_decide + +end SolidCore.Refinement.Corpus.C10 diff --git a/SolidCore/Refinement/Corpus/C10/Seq.lean b/SolidCore/Refinement/Corpus/C10/Seq.lean new file mode 100644 index 00000000..3421d89d --- /dev/null +++ b/SolidCore/Refinement/Corpus/C10/Seq.lean @@ -0,0 +1,54 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/c10.sol. Do not edit. + +import SolidCore.Refinement.Corpus.C10 +import SolidCore.Refinement.Corpus.C10.SeqDefs +import SolidCore.Refinement.Corpus.C10.SeqPart0 + +/-! +# c10: 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/c10.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.C10 + +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.C10 diff --git a/SolidCore/Refinement/Corpus/C10/SeqDefs.lean b/SolidCore/Refinement/Corpus/C10/SeqDefs.lean new file mode 100644 index 00000000..fdc02484 --- /dev/null +++ b/SolidCore/Refinement/Corpus/C10/SeqDefs.lean @@ -0,0 +1,59 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/c10.sol. Do not edit. + +import SolidCore.Refinement.Seq.Check +import SolidCore.Refinement.Corpus.C10.Defs +import SolidCore.Refinement.Corpus.C10.SeqStates + +/-! +# The certificate of c10'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.C10 + +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.C10 diff --git a/SolidCore/Refinement/Corpus/C10/SeqPart0.lean b/SolidCore/Refinement/Corpus/C10/SeqPart0.lean new file mode 100644 index 00000000..1e8592d6 --- /dev/null +++ b/SolidCore/Refinement/Corpus/C10/SeqPart0.lean @@ -0,0 +1,9 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/c10.sol. Do not edit. + +import SolidCore.Refinement.Corpus.C10.SeqDefs + +namespace SolidCore.Refinement.Corpus.C10 + +theorem seqPart0 : seqPartOk 0 = true := by native_decide + +end SolidCore.Refinement.Corpus.C10 diff --git a/SolidCore/Refinement/Corpus/C10/SeqStates.lean b/SolidCore/Refinement/Corpus/C10/SeqStates.lean new file mode 100644 index 00000000..6554737f --- /dev/null +++ b/SolidCore/Refinement/Corpus/C10/SeqStates.lean @@ -0,0 +1,21 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/c10.sol. Do not edit. + +/-! +# The storages c10's clean calls reach + +The certificate of the sequence refinement of `Main` in `scripts/refinement/corpus/c10.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.C10 + +/-- 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.C10 diff --git a/SolidCore/Refinement/Corpus/C11.lean b/SolidCore/Refinement/Corpus/C11.lean new file mode 100644 index 00000000..0ce147e1 --- /dev/null +++ b/SolidCore/Refinement/Corpus/C11.lean @@ -0,0 +1,65 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/c11.sol. Do not edit. + +import SolidCore.Refinement.Corpus.C11.Part0 +import SolidCore.Refinement.Corpus.C11.Dirty + +/-! +# c11: solar's bytecode refines SolidCore's `Main` + +`refines` proves `Refines fuel contract code (· ∈ scope s)` for `Main` in +`scripts/refinement/corpus/c11.sol`, 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, 256 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 SolidCore.Refinement.Corpus.C11 + +open SolidCore.Refinement SolidCore.Refinement.Abi + +theorem parts_ok : ∀ i < parts, partOk i = true := fun i hi => + match i, hi with + | 0, _ => part0 + | n + 1, 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 SolidCore.Refinement.Corpus.C11 diff --git a/SolidCore/Refinement/Corpus/C11/Defs.lean b/SolidCore/Refinement/Corpus/C11/Defs.lean new file mode 100644 index 00000000..ed113032 --- /dev/null +++ b/SolidCore/Refinement/Corpus/C11/Defs.lean @@ -0,0 +1,50 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/c11.sol. Do not edit. + +import SolidCore.Refinement.Abi +import SolidCore.Refinement.Bytecode.C11 +import SolidCore.Refinement.Source.C11 + +/-! +# The scope of c11's refinement + +256 calls: every function of `Main` in `scripts/refinement/corpus/c11.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.C11 + +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.C11.Main.runtimeNat + Bytecode.C11.Main.runtimeSize + +/-- SolidCore's checked `Main`. -/ +def contract? : Except TypeCheck.TypeError TypeCheck.CheckedContract := + TypeCheck.CheckedInput.contract Source.C11.importedSourceUnit "Main" + +/-- The functions of `Main` and their parameters. -/ +def fns : List Fn := + [⟨Bytecode.C11.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.C11 diff --git a/SolidCore/Refinement/Corpus/C11/Dirty.lean b/SolidCore/Refinement/Corpus/C11/Dirty.lean new file mode 100644 index 00000000..90c9037f --- /dev/null +++ b/SolidCore/Refinement/Corpus/C11/Dirty.lean @@ -0,0 +1,31 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/c11.sol. Do not edit. + +import SolidCore.Refinement.Evm.Symex +import SolidCore.Refinement.Dirty.Source +import SolidCore.Refinement.Corpus.C11.Defs + +/-! +# c11: EthLib rejects every dirty argument word + +For every function of `Main` in `scripts/refinement/corpus/c11.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.C11 + +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.C11.Main.fSelector [(.uint 8)] + (by dirty_symex [code, Bytecode.C11.Main.runtimeNat, Bytecode.C11.Main.runtimeSize, Bytecode.C11.Main.fSelector]) + +end SolidCore.Refinement.Corpus.C11 diff --git a/SolidCore/Refinement/Corpus/C11/Part0.lean b/SolidCore/Refinement/Corpus/C11/Part0.lean new file mode 100644 index 00000000..4b00dcbc --- /dev/null +++ b/SolidCore/Refinement/Corpus/C11/Part0.lean @@ -0,0 +1,9 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/c11.sol. Do not edit. + +import SolidCore.Refinement.Corpus.C11.Defs + +namespace SolidCore.Refinement.Corpus.C11 + +theorem part0 : partOk 0 = true := by native_decide + +end SolidCore.Refinement.Corpus.C11 diff --git a/SolidCore/Refinement/Corpus/C11/Seq.lean b/SolidCore/Refinement/Corpus/C11/Seq.lean new file mode 100644 index 00000000..1f511eac --- /dev/null +++ b/SolidCore/Refinement/Corpus/C11/Seq.lean @@ -0,0 +1,54 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/c11.sol. Do not edit. + +import SolidCore.Refinement.Corpus.C11 +import SolidCore.Refinement.Corpus.C11.SeqDefs +import SolidCore.Refinement.Corpus.C11.SeqPart0 + +/-! +# c11: 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/c11.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.C11 + +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.C11 diff --git a/SolidCore/Refinement/Corpus/C11/SeqDefs.lean b/SolidCore/Refinement/Corpus/C11/SeqDefs.lean new file mode 100644 index 00000000..444e9749 --- /dev/null +++ b/SolidCore/Refinement/Corpus/C11/SeqDefs.lean @@ -0,0 +1,59 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/c11.sol. Do not edit. + +import SolidCore.Refinement.Seq.Check +import SolidCore.Refinement.Corpus.C11.Defs +import SolidCore.Refinement.Corpus.C11.SeqStates + +/-! +# The certificate of c11'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.C11 + +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.C11 diff --git a/SolidCore/Refinement/Corpus/C11/SeqPart0.lean b/SolidCore/Refinement/Corpus/C11/SeqPart0.lean new file mode 100644 index 00000000..76c9b5d9 --- /dev/null +++ b/SolidCore/Refinement/Corpus/C11/SeqPart0.lean @@ -0,0 +1,9 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/c11.sol. Do not edit. + +import SolidCore.Refinement.Corpus.C11.SeqDefs + +namespace SolidCore.Refinement.Corpus.C11 + +theorem seqPart0 : seqPartOk 0 = true := by native_decide + +end SolidCore.Refinement.Corpus.C11 diff --git a/SolidCore/Refinement/Corpus/C11/SeqStates.lean b/SolidCore/Refinement/Corpus/C11/SeqStates.lean new file mode 100644 index 00000000..e8e2628f --- /dev/null +++ b/SolidCore/Refinement/Corpus/C11/SeqStates.lean @@ -0,0 +1,21 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/c11.sol. Do not edit. + +/-! +# The storages c11's clean calls reach + +The certificate of the sequence refinement of `Main` in `scripts/refinement/corpus/c11.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.C11 + +/-- 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.C11 diff --git a/SolidCore/Refinement/Corpus/C2.lean b/SolidCore/Refinement/Corpus/C2.lean new file mode 100644 index 00000000..ebfbfdcd --- /dev/null +++ b/SolidCore/Refinement/Corpus/C2.lean @@ -0,0 +1,95 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/c2.sol. Do not edit. + +import SolidCore.Refinement.Corpus.C2.Part0 +import SolidCore.Refinement.Corpus.C2.Part1 +import SolidCore.Refinement.Corpus.C2.Part2 +import SolidCore.Refinement.Corpus.C2.Part3 +import SolidCore.Refinement.Corpus.C2.Part4 +import SolidCore.Refinement.Corpus.C2.Part5 +import SolidCore.Refinement.Corpus.C2.Part6 +import SolidCore.Refinement.Corpus.C2.Part7 +import SolidCore.Refinement.Corpus.C2.Part8 +import SolidCore.Refinement.Corpus.C2.Part9 +import SolidCore.Refinement.Corpus.C2.Part10 +import SolidCore.Refinement.Corpus.C2.Part11 +import SolidCore.Refinement.Corpus.C2.Part12 +import SolidCore.Refinement.Corpus.C2.Part13 +import SolidCore.Refinement.Corpus.C2.Part14 +import SolidCore.Refinement.Corpus.C2.Part15 +import SolidCore.Refinement.Corpus.C2.Dirty + +/-! +# c2: solar's bytecode refines SolidCore's `Main` + +`refines` proves `Refines fuel contract code (· ∈ scope s)` for `Main` in +`scripts/refinement/corpus/c2.sol`, 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, 65536 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 SolidCore.Refinement.Corpus.C2 + +open SolidCore.Refinement SolidCore.Refinement.Abi + +theorem parts_ok : ∀ i < parts, partOk i = true := fun i hi => + match i, hi with + | 0, _ => part0 + | 1, _ => part1 + | 2, _ => part2 + | 3, _ => part3 + | 4, _ => part4 + | 5, _ => part5 + | 6, _ => part6 + | 7, _ => part7 + | 8, _ => part8 + | 9, _ => part9 + | 10, _ => part10 + | 11, _ => part11 + | 12, _ => part12 + | 13, _ => part13 + | 14, _ => part14 + | 15, _ => part15 + | n + 16, 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 SolidCore.Refinement.Corpus.C2 diff --git a/SolidCore/Refinement/Corpus/C2/Defs.lean b/SolidCore/Refinement/Corpus/C2/Defs.lean new file mode 100644 index 00000000..c8b5a729 --- /dev/null +++ b/SolidCore/Refinement/Corpus/C2/Defs.lean @@ -0,0 +1,50 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/c2.sol. Do not edit. + +import SolidCore.Refinement.Abi +import SolidCore.Refinement.Bytecode.C2 +import SolidCore.Refinement.Source.C2 + +/-! +# The scope of c2's refinement + +65536 calls: every function of `Main` in `scripts/refinement/corpus/c2.sol` on every list of clean +argument words, with no value, from the storage SolidCore's constructor leaves. +The check runs in 16 part(s), each in its own module. +-/ + +namespace SolidCore.Refinement.Corpus.C2 + +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.C2.Main.runtimeNat + Bytecode.C2.Main.runtimeSize + +/-- SolidCore's checked `Main`. -/ +def contract? : Except TypeCheck.TypeError TypeCheck.CheckedContract := + TypeCheck.CheckedInput.contract Source.C2.importedSourceUnit "Main" + +/-- The functions of `Main` and their parameters. -/ +def fns : List Fn := + [⟨Bytecode.C2.Main.fSelector, [(.int 8), (.int 8)]⟩] + +/-- The number of parts the check runs in. -/ +def parts : Nat := 16 + +/-- 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.C2 diff --git a/SolidCore/Refinement/Corpus/C2/Dirty.lean b/SolidCore/Refinement/Corpus/C2/Dirty.lean new file mode 100644 index 00000000..ccd032b8 --- /dev/null +++ b/SolidCore/Refinement/Corpus/C2/Dirty.lean @@ -0,0 +1,31 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/c2.sol. Do not edit. + +import SolidCore.Refinement.Evm.Symex +import SolidCore.Refinement.Dirty.Source +import SolidCore.Refinement.Corpus.C2.Defs + +/-! +# c2: EthLib rejects every dirty argument word + +For every function of `Main` in `scripts/refinement/corpus/c2.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.C2 + +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.C2.Main.fSelector [(.int 8), (.int 8)] + (by dirty_symex [code, Bytecode.C2.Main.runtimeNat, Bytecode.C2.Main.runtimeSize, Bytecode.C2.Main.fSelector]) + +end SolidCore.Refinement.Corpus.C2 diff --git a/SolidCore/Refinement/Corpus/C2/Part0.lean b/SolidCore/Refinement/Corpus/C2/Part0.lean new file mode 100644 index 00000000..d497c42c --- /dev/null +++ b/SolidCore/Refinement/Corpus/C2/Part0.lean @@ -0,0 +1,9 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/c2.sol. Do not edit. + +import SolidCore.Refinement.Corpus.C2.Defs + +namespace SolidCore.Refinement.Corpus.C2 + +theorem part0 : partOk 0 = true := by native_decide + +end SolidCore.Refinement.Corpus.C2 diff --git a/SolidCore/Refinement/Corpus/C2/Part1.lean b/SolidCore/Refinement/Corpus/C2/Part1.lean new file mode 100644 index 00000000..7f9d240c --- /dev/null +++ b/SolidCore/Refinement/Corpus/C2/Part1.lean @@ -0,0 +1,9 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/c2.sol. Do not edit. + +import SolidCore.Refinement.Corpus.C2.Defs + +namespace SolidCore.Refinement.Corpus.C2 + +theorem part1 : partOk 1 = true := by native_decide + +end SolidCore.Refinement.Corpus.C2 diff --git a/SolidCore/Refinement/Corpus/C2/Part10.lean b/SolidCore/Refinement/Corpus/C2/Part10.lean new file mode 100644 index 00000000..bc1f9ed0 --- /dev/null +++ b/SolidCore/Refinement/Corpus/C2/Part10.lean @@ -0,0 +1,9 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/c2.sol. Do not edit. + +import SolidCore.Refinement.Corpus.C2.Defs + +namespace SolidCore.Refinement.Corpus.C2 + +theorem part10 : partOk 10 = true := by native_decide + +end SolidCore.Refinement.Corpus.C2 diff --git a/SolidCore/Refinement/Corpus/C2/Part11.lean b/SolidCore/Refinement/Corpus/C2/Part11.lean new file mode 100644 index 00000000..688c8311 --- /dev/null +++ b/SolidCore/Refinement/Corpus/C2/Part11.lean @@ -0,0 +1,9 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/c2.sol. Do not edit. + +import SolidCore.Refinement.Corpus.C2.Defs + +namespace SolidCore.Refinement.Corpus.C2 + +theorem part11 : partOk 11 = true := by native_decide + +end SolidCore.Refinement.Corpus.C2 diff --git a/SolidCore/Refinement/Corpus/C2/Part12.lean b/SolidCore/Refinement/Corpus/C2/Part12.lean new file mode 100644 index 00000000..64b66795 --- /dev/null +++ b/SolidCore/Refinement/Corpus/C2/Part12.lean @@ -0,0 +1,9 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/c2.sol. Do not edit. + +import SolidCore.Refinement.Corpus.C2.Defs + +namespace SolidCore.Refinement.Corpus.C2 + +theorem part12 : partOk 12 = true := by native_decide + +end SolidCore.Refinement.Corpus.C2 diff --git a/SolidCore/Refinement/Corpus/C2/Part13.lean b/SolidCore/Refinement/Corpus/C2/Part13.lean new file mode 100644 index 00000000..e4efe2fa --- /dev/null +++ b/SolidCore/Refinement/Corpus/C2/Part13.lean @@ -0,0 +1,9 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/c2.sol. Do not edit. + +import SolidCore.Refinement.Corpus.C2.Defs + +namespace SolidCore.Refinement.Corpus.C2 + +theorem part13 : partOk 13 = true := by native_decide + +end SolidCore.Refinement.Corpus.C2 diff --git a/SolidCore/Refinement/Corpus/C2/Part14.lean b/SolidCore/Refinement/Corpus/C2/Part14.lean new file mode 100644 index 00000000..520f44dd --- /dev/null +++ b/SolidCore/Refinement/Corpus/C2/Part14.lean @@ -0,0 +1,9 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/c2.sol. Do not edit. + +import SolidCore.Refinement.Corpus.C2.Defs + +namespace SolidCore.Refinement.Corpus.C2 + +theorem part14 : partOk 14 = true := by native_decide + +end SolidCore.Refinement.Corpus.C2 diff --git a/SolidCore/Refinement/Corpus/C2/Part15.lean b/SolidCore/Refinement/Corpus/C2/Part15.lean new file mode 100644 index 00000000..f5e7642d --- /dev/null +++ b/SolidCore/Refinement/Corpus/C2/Part15.lean @@ -0,0 +1,9 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/c2.sol. Do not edit. + +import SolidCore.Refinement.Corpus.C2.Defs + +namespace SolidCore.Refinement.Corpus.C2 + +theorem part15 : partOk 15 = true := by native_decide + +end SolidCore.Refinement.Corpus.C2 diff --git a/SolidCore/Refinement/Corpus/C2/Part2.lean b/SolidCore/Refinement/Corpus/C2/Part2.lean new file mode 100644 index 00000000..1492cd3b --- /dev/null +++ b/SolidCore/Refinement/Corpus/C2/Part2.lean @@ -0,0 +1,9 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/c2.sol. Do not edit. + +import SolidCore.Refinement.Corpus.C2.Defs + +namespace SolidCore.Refinement.Corpus.C2 + +theorem part2 : partOk 2 = true := by native_decide + +end SolidCore.Refinement.Corpus.C2 diff --git a/SolidCore/Refinement/Corpus/C2/Part3.lean b/SolidCore/Refinement/Corpus/C2/Part3.lean new file mode 100644 index 00000000..189c8894 --- /dev/null +++ b/SolidCore/Refinement/Corpus/C2/Part3.lean @@ -0,0 +1,9 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/c2.sol. Do not edit. + +import SolidCore.Refinement.Corpus.C2.Defs + +namespace SolidCore.Refinement.Corpus.C2 + +theorem part3 : partOk 3 = true := by native_decide + +end SolidCore.Refinement.Corpus.C2 diff --git a/SolidCore/Refinement/Corpus/C2/Part4.lean b/SolidCore/Refinement/Corpus/C2/Part4.lean new file mode 100644 index 00000000..09d0fbd7 --- /dev/null +++ b/SolidCore/Refinement/Corpus/C2/Part4.lean @@ -0,0 +1,9 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/c2.sol. Do not edit. + +import SolidCore.Refinement.Corpus.C2.Defs + +namespace SolidCore.Refinement.Corpus.C2 + +theorem part4 : partOk 4 = true := by native_decide + +end SolidCore.Refinement.Corpus.C2 diff --git a/SolidCore/Refinement/Corpus/C2/Part5.lean b/SolidCore/Refinement/Corpus/C2/Part5.lean new file mode 100644 index 00000000..e2ce9248 --- /dev/null +++ b/SolidCore/Refinement/Corpus/C2/Part5.lean @@ -0,0 +1,9 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/c2.sol. Do not edit. + +import SolidCore.Refinement.Corpus.C2.Defs + +namespace SolidCore.Refinement.Corpus.C2 + +theorem part5 : partOk 5 = true := by native_decide + +end SolidCore.Refinement.Corpus.C2 diff --git a/SolidCore/Refinement/Corpus/C2/Part6.lean b/SolidCore/Refinement/Corpus/C2/Part6.lean new file mode 100644 index 00000000..6ce43a04 --- /dev/null +++ b/SolidCore/Refinement/Corpus/C2/Part6.lean @@ -0,0 +1,9 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/c2.sol. Do not edit. + +import SolidCore.Refinement.Corpus.C2.Defs + +namespace SolidCore.Refinement.Corpus.C2 + +theorem part6 : partOk 6 = true := by native_decide + +end SolidCore.Refinement.Corpus.C2 diff --git a/SolidCore/Refinement/Corpus/C2/Part7.lean b/SolidCore/Refinement/Corpus/C2/Part7.lean new file mode 100644 index 00000000..24d0f533 --- /dev/null +++ b/SolidCore/Refinement/Corpus/C2/Part7.lean @@ -0,0 +1,9 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/c2.sol. Do not edit. + +import SolidCore.Refinement.Corpus.C2.Defs + +namespace SolidCore.Refinement.Corpus.C2 + +theorem part7 : partOk 7 = true := by native_decide + +end SolidCore.Refinement.Corpus.C2 diff --git a/SolidCore/Refinement/Corpus/C2/Part8.lean b/SolidCore/Refinement/Corpus/C2/Part8.lean new file mode 100644 index 00000000..043cabe7 --- /dev/null +++ b/SolidCore/Refinement/Corpus/C2/Part8.lean @@ -0,0 +1,9 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/c2.sol. Do not edit. + +import SolidCore.Refinement.Corpus.C2.Defs + +namespace SolidCore.Refinement.Corpus.C2 + +theorem part8 : partOk 8 = true := by native_decide + +end SolidCore.Refinement.Corpus.C2 diff --git a/SolidCore/Refinement/Corpus/C2/Part9.lean b/SolidCore/Refinement/Corpus/C2/Part9.lean new file mode 100644 index 00000000..a3e82f9e --- /dev/null +++ b/SolidCore/Refinement/Corpus/C2/Part9.lean @@ -0,0 +1,9 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/c2.sol. Do not edit. + +import SolidCore.Refinement.Corpus.C2.Defs + +namespace SolidCore.Refinement.Corpus.C2 + +theorem part9 : partOk 9 = true := by native_decide + +end SolidCore.Refinement.Corpus.C2 diff --git a/SolidCore/Refinement/Corpus/C2/Seq.lean b/SolidCore/Refinement/Corpus/C2/Seq.lean new file mode 100644 index 00000000..1114e146 --- /dev/null +++ b/SolidCore/Refinement/Corpus/C2/Seq.lean @@ -0,0 +1,84 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/c2.sol. Do not edit. + +import SolidCore.Refinement.Corpus.C2 +import SolidCore.Refinement.Corpus.C2.SeqDefs +import SolidCore.Refinement.Corpus.C2.SeqPart0 +import SolidCore.Refinement.Corpus.C2.SeqPart1 +import SolidCore.Refinement.Corpus.C2.SeqPart2 +import SolidCore.Refinement.Corpus.C2.SeqPart3 +import SolidCore.Refinement.Corpus.C2.SeqPart4 +import SolidCore.Refinement.Corpus.C2.SeqPart5 +import SolidCore.Refinement.Corpus.C2.SeqPart6 +import SolidCore.Refinement.Corpus.C2.SeqPart7 +import SolidCore.Refinement.Corpus.C2.SeqPart8 +import SolidCore.Refinement.Corpus.C2.SeqPart9 +import SolidCore.Refinement.Corpus.C2.SeqPart10 +import SolidCore.Refinement.Corpus.C2.SeqPart11 +import SolidCore.Refinement.Corpus.C2.SeqPart12 +import SolidCore.Refinement.Corpus.C2.SeqPart13 +import SolidCore.Refinement.Corpus.C2.SeqPart14 +import SolidCore.Refinement.Corpus.C2.SeqPart15 + +/-! +# c2: 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/c2.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.C2 + +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 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.C2 diff --git a/SolidCore/Refinement/Corpus/C2/SeqDefs.lean b/SolidCore/Refinement/Corpus/C2/SeqDefs.lean new file mode 100644 index 00000000..72327ac0 --- /dev/null +++ b/SolidCore/Refinement/Corpus/C2/SeqDefs.lean @@ -0,0 +1,59 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/c2.sol. Do not edit. + +import SolidCore.Refinement.Seq.Check +import SolidCore.Refinement.Corpus.C2.Defs +import SolidCore.Refinement.Corpus.C2.SeqStates + +/-! +# The certificate of c2'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, 65536 calls, in 16 part(s), and every dirty call once +per storage. +-/ + +namespace SolidCore.Refinement.Corpus.C2 + +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 := 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.C2 diff --git a/SolidCore/Refinement/Corpus/C2/SeqPart0.lean b/SolidCore/Refinement/Corpus/C2/SeqPart0.lean new file mode 100644 index 00000000..30a2dbce --- /dev/null +++ b/SolidCore/Refinement/Corpus/C2/SeqPart0.lean @@ -0,0 +1,9 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/c2.sol. Do not edit. + +import SolidCore.Refinement.Corpus.C2.SeqDefs + +namespace SolidCore.Refinement.Corpus.C2 + +theorem seqPart0 : seqPartOk 0 = true := by native_decide + +end SolidCore.Refinement.Corpus.C2 diff --git a/SolidCore/Refinement/Corpus/C2/SeqPart1.lean b/SolidCore/Refinement/Corpus/C2/SeqPart1.lean new file mode 100644 index 00000000..ad396bda --- /dev/null +++ b/SolidCore/Refinement/Corpus/C2/SeqPart1.lean @@ -0,0 +1,9 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/c2.sol. Do not edit. + +import SolidCore.Refinement.Corpus.C2.SeqDefs + +namespace SolidCore.Refinement.Corpus.C2 + +theorem seqPart1 : seqPartOk 1 = true := by native_decide + +end SolidCore.Refinement.Corpus.C2 diff --git a/SolidCore/Refinement/Corpus/C2/SeqPart10.lean b/SolidCore/Refinement/Corpus/C2/SeqPart10.lean new file mode 100644 index 00000000..aa86436f --- /dev/null +++ b/SolidCore/Refinement/Corpus/C2/SeqPart10.lean @@ -0,0 +1,9 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/c2.sol. Do not edit. + +import SolidCore.Refinement.Corpus.C2.SeqDefs + +namespace SolidCore.Refinement.Corpus.C2 + +theorem seqPart10 : seqPartOk 10 = true := by native_decide + +end SolidCore.Refinement.Corpus.C2 diff --git a/SolidCore/Refinement/Corpus/C2/SeqPart11.lean b/SolidCore/Refinement/Corpus/C2/SeqPart11.lean new file mode 100644 index 00000000..8851a270 --- /dev/null +++ b/SolidCore/Refinement/Corpus/C2/SeqPart11.lean @@ -0,0 +1,9 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/c2.sol. Do not edit. + +import SolidCore.Refinement.Corpus.C2.SeqDefs + +namespace SolidCore.Refinement.Corpus.C2 + +theorem seqPart11 : seqPartOk 11 = true := by native_decide + +end SolidCore.Refinement.Corpus.C2 diff --git a/SolidCore/Refinement/Corpus/C2/SeqPart12.lean b/SolidCore/Refinement/Corpus/C2/SeqPart12.lean new file mode 100644 index 00000000..e1727504 --- /dev/null +++ b/SolidCore/Refinement/Corpus/C2/SeqPart12.lean @@ -0,0 +1,9 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/c2.sol. Do not edit. + +import SolidCore.Refinement.Corpus.C2.SeqDefs + +namespace SolidCore.Refinement.Corpus.C2 + +theorem seqPart12 : seqPartOk 12 = true := by native_decide + +end SolidCore.Refinement.Corpus.C2 diff --git a/SolidCore/Refinement/Corpus/C2/SeqPart13.lean b/SolidCore/Refinement/Corpus/C2/SeqPart13.lean new file mode 100644 index 00000000..a09cb6e1 --- /dev/null +++ b/SolidCore/Refinement/Corpus/C2/SeqPart13.lean @@ -0,0 +1,9 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/c2.sol. Do not edit. + +import SolidCore.Refinement.Corpus.C2.SeqDefs + +namespace SolidCore.Refinement.Corpus.C2 + +theorem seqPart13 : seqPartOk 13 = true := by native_decide + +end SolidCore.Refinement.Corpus.C2 diff --git a/SolidCore/Refinement/Corpus/C2/SeqPart14.lean b/SolidCore/Refinement/Corpus/C2/SeqPart14.lean new file mode 100644 index 00000000..f40dfe1c --- /dev/null +++ b/SolidCore/Refinement/Corpus/C2/SeqPart14.lean @@ -0,0 +1,9 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/c2.sol. Do not edit. + +import SolidCore.Refinement.Corpus.C2.SeqDefs + +namespace SolidCore.Refinement.Corpus.C2 + +theorem seqPart14 : seqPartOk 14 = true := by native_decide + +end SolidCore.Refinement.Corpus.C2 diff --git a/SolidCore/Refinement/Corpus/C2/SeqPart15.lean b/SolidCore/Refinement/Corpus/C2/SeqPart15.lean new file mode 100644 index 00000000..d5cf0d81 --- /dev/null +++ b/SolidCore/Refinement/Corpus/C2/SeqPart15.lean @@ -0,0 +1,9 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/c2.sol. Do not edit. + +import SolidCore.Refinement.Corpus.C2.SeqDefs + +namespace SolidCore.Refinement.Corpus.C2 + +theorem seqPart15 : seqPartOk 15 = true := by native_decide + +end SolidCore.Refinement.Corpus.C2 diff --git a/SolidCore/Refinement/Corpus/C2/SeqPart2.lean b/SolidCore/Refinement/Corpus/C2/SeqPart2.lean new file mode 100644 index 00000000..4e9fa528 --- /dev/null +++ b/SolidCore/Refinement/Corpus/C2/SeqPart2.lean @@ -0,0 +1,9 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/c2.sol. Do not edit. + +import SolidCore.Refinement.Corpus.C2.SeqDefs + +namespace SolidCore.Refinement.Corpus.C2 + +theorem seqPart2 : seqPartOk 2 = true := by native_decide + +end SolidCore.Refinement.Corpus.C2 diff --git a/SolidCore/Refinement/Corpus/C2/SeqPart3.lean b/SolidCore/Refinement/Corpus/C2/SeqPart3.lean new file mode 100644 index 00000000..89d30db5 --- /dev/null +++ b/SolidCore/Refinement/Corpus/C2/SeqPart3.lean @@ -0,0 +1,9 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/c2.sol. Do not edit. + +import SolidCore.Refinement.Corpus.C2.SeqDefs + +namespace SolidCore.Refinement.Corpus.C2 + +theorem seqPart3 : seqPartOk 3 = true := by native_decide + +end SolidCore.Refinement.Corpus.C2 diff --git a/SolidCore/Refinement/Corpus/C2/SeqPart4.lean b/SolidCore/Refinement/Corpus/C2/SeqPart4.lean new file mode 100644 index 00000000..7004e6c5 --- /dev/null +++ b/SolidCore/Refinement/Corpus/C2/SeqPart4.lean @@ -0,0 +1,9 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/c2.sol. Do not edit. + +import SolidCore.Refinement.Corpus.C2.SeqDefs + +namespace SolidCore.Refinement.Corpus.C2 + +theorem seqPart4 : seqPartOk 4 = true := by native_decide + +end SolidCore.Refinement.Corpus.C2 diff --git a/SolidCore/Refinement/Corpus/C2/SeqPart5.lean b/SolidCore/Refinement/Corpus/C2/SeqPart5.lean new file mode 100644 index 00000000..f8af8c8f --- /dev/null +++ b/SolidCore/Refinement/Corpus/C2/SeqPart5.lean @@ -0,0 +1,9 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/c2.sol. Do not edit. + +import SolidCore.Refinement.Corpus.C2.SeqDefs + +namespace SolidCore.Refinement.Corpus.C2 + +theorem seqPart5 : seqPartOk 5 = true := by native_decide + +end SolidCore.Refinement.Corpus.C2 diff --git a/SolidCore/Refinement/Corpus/C2/SeqPart6.lean b/SolidCore/Refinement/Corpus/C2/SeqPart6.lean new file mode 100644 index 00000000..230a765c --- /dev/null +++ b/SolidCore/Refinement/Corpus/C2/SeqPart6.lean @@ -0,0 +1,9 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/c2.sol. Do not edit. + +import SolidCore.Refinement.Corpus.C2.SeqDefs + +namespace SolidCore.Refinement.Corpus.C2 + +theorem seqPart6 : seqPartOk 6 = true := by native_decide + +end SolidCore.Refinement.Corpus.C2 diff --git a/SolidCore/Refinement/Corpus/C2/SeqPart7.lean b/SolidCore/Refinement/Corpus/C2/SeqPart7.lean new file mode 100644 index 00000000..e991492e --- /dev/null +++ b/SolidCore/Refinement/Corpus/C2/SeqPart7.lean @@ -0,0 +1,9 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/c2.sol. Do not edit. + +import SolidCore.Refinement.Corpus.C2.SeqDefs + +namespace SolidCore.Refinement.Corpus.C2 + +theorem seqPart7 : seqPartOk 7 = true := by native_decide + +end SolidCore.Refinement.Corpus.C2 diff --git a/SolidCore/Refinement/Corpus/C2/SeqPart8.lean b/SolidCore/Refinement/Corpus/C2/SeqPart8.lean new file mode 100644 index 00000000..04ed66f0 --- /dev/null +++ b/SolidCore/Refinement/Corpus/C2/SeqPart8.lean @@ -0,0 +1,9 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/c2.sol. Do not edit. + +import SolidCore.Refinement.Corpus.C2.SeqDefs + +namespace SolidCore.Refinement.Corpus.C2 + +theorem seqPart8 : seqPartOk 8 = true := by native_decide + +end SolidCore.Refinement.Corpus.C2 diff --git a/SolidCore/Refinement/Corpus/C2/SeqPart9.lean b/SolidCore/Refinement/Corpus/C2/SeqPart9.lean new file mode 100644 index 00000000..3f9348ad --- /dev/null +++ b/SolidCore/Refinement/Corpus/C2/SeqPart9.lean @@ -0,0 +1,9 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/c2.sol. Do not edit. + +import SolidCore.Refinement.Corpus.C2.SeqDefs + +namespace SolidCore.Refinement.Corpus.C2 + +theorem seqPart9 : seqPartOk 9 = true := by native_decide + +end SolidCore.Refinement.Corpus.C2 diff --git a/SolidCore/Refinement/Corpus/C2/SeqStates.lean b/SolidCore/Refinement/Corpus/C2/SeqStates.lean new file mode 100644 index 00000000..66108c4f --- /dev/null +++ b/SolidCore/Refinement/Corpus/C2/SeqStates.lean @@ -0,0 +1,21 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/c2.sol. Do not edit. + +/-! +# The storages c2's clean calls reach + +The certificate of the sequence refinement of `Main` in `scripts/refinement/corpus/c2.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.C2 + +/-- 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.C2 diff --git a/SolidCore/Refinement/Corpus/C3.lean b/SolidCore/Refinement/Corpus/C3.lean new file mode 100644 index 00000000..16a4a01e --- /dev/null +++ b/SolidCore/Refinement/Corpus/C3.lean @@ -0,0 +1,95 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/c3.sol. Do not edit. + +import SolidCore.Refinement.Corpus.C3.Part0 +import SolidCore.Refinement.Corpus.C3.Part1 +import SolidCore.Refinement.Corpus.C3.Part2 +import SolidCore.Refinement.Corpus.C3.Part3 +import SolidCore.Refinement.Corpus.C3.Part4 +import SolidCore.Refinement.Corpus.C3.Part5 +import SolidCore.Refinement.Corpus.C3.Part6 +import SolidCore.Refinement.Corpus.C3.Part7 +import SolidCore.Refinement.Corpus.C3.Part8 +import SolidCore.Refinement.Corpus.C3.Part9 +import SolidCore.Refinement.Corpus.C3.Part10 +import SolidCore.Refinement.Corpus.C3.Part11 +import SolidCore.Refinement.Corpus.C3.Part12 +import SolidCore.Refinement.Corpus.C3.Part13 +import SolidCore.Refinement.Corpus.C3.Part14 +import SolidCore.Refinement.Corpus.C3.Part15 +import SolidCore.Refinement.Corpus.C3.Dirty + +/-! +# c3: solar's bytecode refines SolidCore's `Main` + +`refines` proves `Refines fuel contract code (· ∈ scope s)` for `Main` in +`scripts/refinement/corpus/c3.sol`, 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, 65536 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 SolidCore.Refinement.Corpus.C3 + +open SolidCore.Refinement SolidCore.Refinement.Abi + +theorem parts_ok : ∀ i < parts, partOk i = true := fun i hi => + match i, hi with + | 0, _ => part0 + | 1, _ => part1 + | 2, _ => part2 + | 3, _ => part3 + | 4, _ => part4 + | 5, _ => part5 + | 6, _ => part6 + | 7, _ => part7 + | 8, _ => part8 + | 9, _ => part9 + | 10, _ => part10 + | 11, _ => part11 + | 12, _ => part12 + | 13, _ => part13 + | 14, _ => part14 + | 15, _ => part15 + | n + 16, 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 SolidCore.Refinement.Corpus.C3 diff --git a/SolidCore/Refinement/Corpus/C3/Defs.lean b/SolidCore/Refinement/Corpus/C3/Defs.lean new file mode 100644 index 00000000..3b234adb --- /dev/null +++ b/SolidCore/Refinement/Corpus/C3/Defs.lean @@ -0,0 +1,50 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/c3.sol. Do not edit. + +import SolidCore.Refinement.Abi +import SolidCore.Refinement.Bytecode.C3 +import SolidCore.Refinement.Source.C3 + +/-! +# The scope of c3's refinement + +65536 calls: every function of `Main` in `scripts/refinement/corpus/c3.sol` on every list of clean +argument words, with no value, from the storage SolidCore's constructor leaves. +The check runs in 16 part(s), each in its own module. +-/ + +namespace SolidCore.Refinement.Corpus.C3 + +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.C3.Main.runtimeNat + Bytecode.C3.Main.runtimeSize + +/-- SolidCore's checked `Main`. -/ +def contract? : Except TypeCheck.TypeError TypeCheck.CheckedContract := + TypeCheck.CheckedInput.contract Source.C3.importedSourceUnit "Main" + +/-- The functions of `Main` and their parameters. -/ +def fns : List Fn := + [⟨Bytecode.C3.Main.fSelector, [(.uint 8), (.uint 8)]⟩] + +/-- The number of parts the check runs in. -/ +def parts : Nat := 16 + +/-- 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.C3 diff --git a/SolidCore/Refinement/Corpus/C3/Dirty.lean b/SolidCore/Refinement/Corpus/C3/Dirty.lean new file mode 100644 index 00000000..787d4c50 --- /dev/null +++ b/SolidCore/Refinement/Corpus/C3/Dirty.lean @@ -0,0 +1,31 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/c3.sol. Do not edit. + +import SolidCore.Refinement.Evm.Symex +import SolidCore.Refinement.Dirty.Source +import SolidCore.Refinement.Corpus.C3.Defs + +/-! +# c3: EthLib rejects every dirty argument word + +For every function of `Main` in `scripts/refinement/corpus/c3.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.C3 + +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.C3.Main.fSelector [(.uint 8), (.uint 8)] + (by dirty_symex [code, Bytecode.C3.Main.runtimeNat, Bytecode.C3.Main.runtimeSize, Bytecode.C3.Main.fSelector]) + +end SolidCore.Refinement.Corpus.C3 diff --git a/SolidCore/Refinement/Corpus/C3/Part0.lean b/SolidCore/Refinement/Corpus/C3/Part0.lean new file mode 100644 index 00000000..ac3cd274 --- /dev/null +++ b/SolidCore/Refinement/Corpus/C3/Part0.lean @@ -0,0 +1,9 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/c3.sol. Do not edit. + +import SolidCore.Refinement.Corpus.C3.Defs + +namespace SolidCore.Refinement.Corpus.C3 + +theorem part0 : partOk 0 = true := by native_decide + +end SolidCore.Refinement.Corpus.C3 diff --git a/SolidCore/Refinement/Corpus/C3/Part1.lean b/SolidCore/Refinement/Corpus/C3/Part1.lean new file mode 100644 index 00000000..f7abc7fe --- /dev/null +++ b/SolidCore/Refinement/Corpus/C3/Part1.lean @@ -0,0 +1,9 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/c3.sol. Do not edit. + +import SolidCore.Refinement.Corpus.C3.Defs + +namespace SolidCore.Refinement.Corpus.C3 + +theorem part1 : partOk 1 = true := by native_decide + +end SolidCore.Refinement.Corpus.C3 diff --git a/SolidCore/Refinement/Corpus/C3/Part10.lean b/SolidCore/Refinement/Corpus/C3/Part10.lean new file mode 100644 index 00000000..486867eb --- /dev/null +++ b/SolidCore/Refinement/Corpus/C3/Part10.lean @@ -0,0 +1,9 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/c3.sol. Do not edit. + +import SolidCore.Refinement.Corpus.C3.Defs + +namespace SolidCore.Refinement.Corpus.C3 + +theorem part10 : partOk 10 = true := by native_decide + +end SolidCore.Refinement.Corpus.C3 diff --git a/SolidCore/Refinement/Corpus/C3/Part11.lean b/SolidCore/Refinement/Corpus/C3/Part11.lean new file mode 100644 index 00000000..75d6046b --- /dev/null +++ b/SolidCore/Refinement/Corpus/C3/Part11.lean @@ -0,0 +1,9 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/c3.sol. Do not edit. + +import SolidCore.Refinement.Corpus.C3.Defs + +namespace SolidCore.Refinement.Corpus.C3 + +theorem part11 : partOk 11 = true := by native_decide + +end SolidCore.Refinement.Corpus.C3 diff --git a/SolidCore/Refinement/Corpus/C3/Part12.lean b/SolidCore/Refinement/Corpus/C3/Part12.lean new file mode 100644 index 00000000..bec2d51a --- /dev/null +++ b/SolidCore/Refinement/Corpus/C3/Part12.lean @@ -0,0 +1,9 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/c3.sol. Do not edit. + +import SolidCore.Refinement.Corpus.C3.Defs + +namespace SolidCore.Refinement.Corpus.C3 + +theorem part12 : partOk 12 = true := by native_decide + +end SolidCore.Refinement.Corpus.C3 diff --git a/SolidCore/Refinement/Corpus/C3/Part13.lean b/SolidCore/Refinement/Corpus/C3/Part13.lean new file mode 100644 index 00000000..15e8f079 --- /dev/null +++ b/SolidCore/Refinement/Corpus/C3/Part13.lean @@ -0,0 +1,9 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/c3.sol. Do not edit. + +import SolidCore.Refinement.Corpus.C3.Defs + +namespace SolidCore.Refinement.Corpus.C3 + +theorem part13 : partOk 13 = true := by native_decide + +end SolidCore.Refinement.Corpus.C3 diff --git a/SolidCore/Refinement/Corpus/C3/Part14.lean b/SolidCore/Refinement/Corpus/C3/Part14.lean new file mode 100644 index 00000000..a278da8e --- /dev/null +++ b/SolidCore/Refinement/Corpus/C3/Part14.lean @@ -0,0 +1,9 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/c3.sol. Do not edit. + +import SolidCore.Refinement.Corpus.C3.Defs + +namespace SolidCore.Refinement.Corpus.C3 + +theorem part14 : partOk 14 = true := by native_decide + +end SolidCore.Refinement.Corpus.C3 diff --git a/SolidCore/Refinement/Corpus/C3/Part15.lean b/SolidCore/Refinement/Corpus/C3/Part15.lean new file mode 100644 index 00000000..d6cd500f --- /dev/null +++ b/SolidCore/Refinement/Corpus/C3/Part15.lean @@ -0,0 +1,9 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/c3.sol. Do not edit. + +import SolidCore.Refinement.Corpus.C3.Defs + +namespace SolidCore.Refinement.Corpus.C3 + +theorem part15 : partOk 15 = true := by native_decide + +end SolidCore.Refinement.Corpus.C3 diff --git a/SolidCore/Refinement/Corpus/C3/Part2.lean b/SolidCore/Refinement/Corpus/C3/Part2.lean new file mode 100644 index 00000000..f552840d --- /dev/null +++ b/SolidCore/Refinement/Corpus/C3/Part2.lean @@ -0,0 +1,9 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/c3.sol. Do not edit. + +import SolidCore.Refinement.Corpus.C3.Defs + +namespace SolidCore.Refinement.Corpus.C3 + +theorem part2 : partOk 2 = true := by native_decide + +end SolidCore.Refinement.Corpus.C3 diff --git a/SolidCore/Refinement/Corpus/C3/Part3.lean b/SolidCore/Refinement/Corpus/C3/Part3.lean new file mode 100644 index 00000000..a5ca39e6 --- /dev/null +++ b/SolidCore/Refinement/Corpus/C3/Part3.lean @@ -0,0 +1,9 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/c3.sol. Do not edit. + +import SolidCore.Refinement.Corpus.C3.Defs + +namespace SolidCore.Refinement.Corpus.C3 + +theorem part3 : partOk 3 = true := by native_decide + +end SolidCore.Refinement.Corpus.C3 diff --git a/SolidCore/Refinement/Corpus/C3/Part4.lean b/SolidCore/Refinement/Corpus/C3/Part4.lean new file mode 100644 index 00000000..8f675648 --- /dev/null +++ b/SolidCore/Refinement/Corpus/C3/Part4.lean @@ -0,0 +1,9 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/c3.sol. Do not edit. + +import SolidCore.Refinement.Corpus.C3.Defs + +namespace SolidCore.Refinement.Corpus.C3 + +theorem part4 : partOk 4 = true := by native_decide + +end SolidCore.Refinement.Corpus.C3 diff --git a/SolidCore/Refinement/Corpus/C3/Part5.lean b/SolidCore/Refinement/Corpus/C3/Part5.lean new file mode 100644 index 00000000..226cbfc7 --- /dev/null +++ b/SolidCore/Refinement/Corpus/C3/Part5.lean @@ -0,0 +1,9 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/c3.sol. Do not edit. + +import SolidCore.Refinement.Corpus.C3.Defs + +namespace SolidCore.Refinement.Corpus.C3 + +theorem part5 : partOk 5 = true := by native_decide + +end SolidCore.Refinement.Corpus.C3 diff --git a/SolidCore/Refinement/Corpus/C3/Part6.lean b/SolidCore/Refinement/Corpus/C3/Part6.lean new file mode 100644 index 00000000..93ddb00d --- /dev/null +++ b/SolidCore/Refinement/Corpus/C3/Part6.lean @@ -0,0 +1,9 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/c3.sol. Do not edit. + +import SolidCore.Refinement.Corpus.C3.Defs + +namespace SolidCore.Refinement.Corpus.C3 + +theorem part6 : partOk 6 = true := by native_decide + +end SolidCore.Refinement.Corpus.C3 diff --git a/SolidCore/Refinement/Corpus/C3/Part7.lean b/SolidCore/Refinement/Corpus/C3/Part7.lean new file mode 100644 index 00000000..0008c4f3 --- /dev/null +++ b/SolidCore/Refinement/Corpus/C3/Part7.lean @@ -0,0 +1,9 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/c3.sol. Do not edit. + +import SolidCore.Refinement.Corpus.C3.Defs + +namespace SolidCore.Refinement.Corpus.C3 + +theorem part7 : partOk 7 = true := by native_decide + +end SolidCore.Refinement.Corpus.C3 diff --git a/SolidCore/Refinement/Corpus/C3/Part8.lean b/SolidCore/Refinement/Corpus/C3/Part8.lean new file mode 100644 index 00000000..3f2026cb --- /dev/null +++ b/SolidCore/Refinement/Corpus/C3/Part8.lean @@ -0,0 +1,9 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/c3.sol. Do not edit. + +import SolidCore.Refinement.Corpus.C3.Defs + +namespace SolidCore.Refinement.Corpus.C3 + +theorem part8 : partOk 8 = true := by native_decide + +end SolidCore.Refinement.Corpus.C3 diff --git a/SolidCore/Refinement/Corpus/C3/Part9.lean b/SolidCore/Refinement/Corpus/C3/Part9.lean new file mode 100644 index 00000000..38d7761c --- /dev/null +++ b/SolidCore/Refinement/Corpus/C3/Part9.lean @@ -0,0 +1,9 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/c3.sol. Do not edit. + +import SolidCore.Refinement.Corpus.C3.Defs + +namespace SolidCore.Refinement.Corpus.C3 + +theorem part9 : partOk 9 = true := by native_decide + +end SolidCore.Refinement.Corpus.C3 diff --git a/SolidCore/Refinement/Corpus/C3/Seq.lean b/SolidCore/Refinement/Corpus/C3/Seq.lean new file mode 100644 index 00000000..c514cc6f --- /dev/null +++ b/SolidCore/Refinement/Corpus/C3/Seq.lean @@ -0,0 +1,84 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/c3.sol. Do not edit. + +import SolidCore.Refinement.Corpus.C3 +import SolidCore.Refinement.Corpus.C3.SeqDefs +import SolidCore.Refinement.Corpus.C3.SeqPart0 +import SolidCore.Refinement.Corpus.C3.SeqPart1 +import SolidCore.Refinement.Corpus.C3.SeqPart2 +import SolidCore.Refinement.Corpus.C3.SeqPart3 +import SolidCore.Refinement.Corpus.C3.SeqPart4 +import SolidCore.Refinement.Corpus.C3.SeqPart5 +import SolidCore.Refinement.Corpus.C3.SeqPart6 +import SolidCore.Refinement.Corpus.C3.SeqPart7 +import SolidCore.Refinement.Corpus.C3.SeqPart8 +import SolidCore.Refinement.Corpus.C3.SeqPart9 +import SolidCore.Refinement.Corpus.C3.SeqPart10 +import SolidCore.Refinement.Corpus.C3.SeqPart11 +import SolidCore.Refinement.Corpus.C3.SeqPart12 +import SolidCore.Refinement.Corpus.C3.SeqPart13 +import SolidCore.Refinement.Corpus.C3.SeqPart14 +import SolidCore.Refinement.Corpus.C3.SeqPart15 + +/-! +# c3: 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/c3.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.C3 + +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 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.C3 diff --git a/SolidCore/Refinement/Corpus/C3/SeqDefs.lean b/SolidCore/Refinement/Corpus/C3/SeqDefs.lean new file mode 100644 index 00000000..ab1c067c --- /dev/null +++ b/SolidCore/Refinement/Corpus/C3/SeqDefs.lean @@ -0,0 +1,59 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/c3.sol. Do not edit. + +import SolidCore.Refinement.Seq.Check +import SolidCore.Refinement.Corpus.C3.Defs +import SolidCore.Refinement.Corpus.C3.SeqStates + +/-! +# The certificate of c3'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, 65536 calls, in 16 part(s), and every dirty call once +per storage. +-/ + +namespace SolidCore.Refinement.Corpus.C3 + +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 := 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.C3 diff --git a/SolidCore/Refinement/Corpus/C3/SeqPart0.lean b/SolidCore/Refinement/Corpus/C3/SeqPart0.lean new file mode 100644 index 00000000..2ac73d82 --- /dev/null +++ b/SolidCore/Refinement/Corpus/C3/SeqPart0.lean @@ -0,0 +1,9 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/c3.sol. Do not edit. + +import SolidCore.Refinement.Corpus.C3.SeqDefs + +namespace SolidCore.Refinement.Corpus.C3 + +theorem seqPart0 : seqPartOk 0 = true := by native_decide + +end SolidCore.Refinement.Corpus.C3 diff --git a/SolidCore/Refinement/Corpus/C3/SeqPart1.lean b/SolidCore/Refinement/Corpus/C3/SeqPart1.lean new file mode 100644 index 00000000..4002c624 --- /dev/null +++ b/SolidCore/Refinement/Corpus/C3/SeqPart1.lean @@ -0,0 +1,9 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/c3.sol. Do not edit. + +import SolidCore.Refinement.Corpus.C3.SeqDefs + +namespace SolidCore.Refinement.Corpus.C3 + +theorem seqPart1 : seqPartOk 1 = true := by native_decide + +end SolidCore.Refinement.Corpus.C3 diff --git a/SolidCore/Refinement/Corpus/C3/SeqPart10.lean b/SolidCore/Refinement/Corpus/C3/SeqPart10.lean new file mode 100644 index 00000000..ae290d1e --- /dev/null +++ b/SolidCore/Refinement/Corpus/C3/SeqPart10.lean @@ -0,0 +1,9 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/c3.sol. Do not edit. + +import SolidCore.Refinement.Corpus.C3.SeqDefs + +namespace SolidCore.Refinement.Corpus.C3 + +theorem seqPart10 : seqPartOk 10 = true := by native_decide + +end SolidCore.Refinement.Corpus.C3 diff --git a/SolidCore/Refinement/Corpus/C3/SeqPart11.lean b/SolidCore/Refinement/Corpus/C3/SeqPart11.lean new file mode 100644 index 00000000..1f3b1993 --- /dev/null +++ b/SolidCore/Refinement/Corpus/C3/SeqPart11.lean @@ -0,0 +1,9 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/c3.sol. Do not edit. + +import SolidCore.Refinement.Corpus.C3.SeqDefs + +namespace SolidCore.Refinement.Corpus.C3 + +theorem seqPart11 : seqPartOk 11 = true := by native_decide + +end SolidCore.Refinement.Corpus.C3 diff --git a/SolidCore/Refinement/Corpus/C3/SeqPart12.lean b/SolidCore/Refinement/Corpus/C3/SeqPart12.lean new file mode 100644 index 00000000..2526a199 --- /dev/null +++ b/SolidCore/Refinement/Corpus/C3/SeqPart12.lean @@ -0,0 +1,9 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/c3.sol. Do not edit. + +import SolidCore.Refinement.Corpus.C3.SeqDefs + +namespace SolidCore.Refinement.Corpus.C3 + +theorem seqPart12 : seqPartOk 12 = true := by native_decide + +end SolidCore.Refinement.Corpus.C3 diff --git a/SolidCore/Refinement/Corpus/C3/SeqPart13.lean b/SolidCore/Refinement/Corpus/C3/SeqPart13.lean new file mode 100644 index 00000000..9fb41340 --- /dev/null +++ b/SolidCore/Refinement/Corpus/C3/SeqPart13.lean @@ -0,0 +1,9 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/c3.sol. Do not edit. + +import SolidCore.Refinement.Corpus.C3.SeqDefs + +namespace SolidCore.Refinement.Corpus.C3 + +theorem seqPart13 : seqPartOk 13 = true := by native_decide + +end SolidCore.Refinement.Corpus.C3 diff --git a/SolidCore/Refinement/Corpus/C3/SeqPart14.lean b/SolidCore/Refinement/Corpus/C3/SeqPart14.lean new file mode 100644 index 00000000..fb64ac60 --- /dev/null +++ b/SolidCore/Refinement/Corpus/C3/SeqPart14.lean @@ -0,0 +1,9 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/c3.sol. Do not edit. + +import SolidCore.Refinement.Corpus.C3.SeqDefs + +namespace SolidCore.Refinement.Corpus.C3 + +theorem seqPart14 : seqPartOk 14 = true := by native_decide + +end SolidCore.Refinement.Corpus.C3 diff --git a/SolidCore/Refinement/Corpus/C3/SeqPart15.lean b/SolidCore/Refinement/Corpus/C3/SeqPart15.lean new file mode 100644 index 00000000..d4952a6d --- /dev/null +++ b/SolidCore/Refinement/Corpus/C3/SeqPart15.lean @@ -0,0 +1,9 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/c3.sol. Do not edit. + +import SolidCore.Refinement.Corpus.C3.SeqDefs + +namespace SolidCore.Refinement.Corpus.C3 + +theorem seqPart15 : seqPartOk 15 = true := by native_decide + +end SolidCore.Refinement.Corpus.C3 diff --git a/SolidCore/Refinement/Corpus/C3/SeqPart2.lean b/SolidCore/Refinement/Corpus/C3/SeqPart2.lean new file mode 100644 index 00000000..1d7bdf68 --- /dev/null +++ b/SolidCore/Refinement/Corpus/C3/SeqPart2.lean @@ -0,0 +1,9 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/c3.sol. Do not edit. + +import SolidCore.Refinement.Corpus.C3.SeqDefs + +namespace SolidCore.Refinement.Corpus.C3 + +theorem seqPart2 : seqPartOk 2 = true := by native_decide + +end SolidCore.Refinement.Corpus.C3 diff --git a/SolidCore/Refinement/Corpus/C3/SeqPart3.lean b/SolidCore/Refinement/Corpus/C3/SeqPart3.lean new file mode 100644 index 00000000..dd39ae1a --- /dev/null +++ b/SolidCore/Refinement/Corpus/C3/SeqPart3.lean @@ -0,0 +1,9 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/c3.sol. Do not edit. + +import SolidCore.Refinement.Corpus.C3.SeqDefs + +namespace SolidCore.Refinement.Corpus.C3 + +theorem seqPart3 : seqPartOk 3 = true := by native_decide + +end SolidCore.Refinement.Corpus.C3 diff --git a/SolidCore/Refinement/Corpus/C3/SeqPart4.lean b/SolidCore/Refinement/Corpus/C3/SeqPart4.lean new file mode 100644 index 00000000..7cad1bbe --- /dev/null +++ b/SolidCore/Refinement/Corpus/C3/SeqPart4.lean @@ -0,0 +1,9 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/c3.sol. Do not edit. + +import SolidCore.Refinement.Corpus.C3.SeqDefs + +namespace SolidCore.Refinement.Corpus.C3 + +theorem seqPart4 : seqPartOk 4 = true := by native_decide + +end SolidCore.Refinement.Corpus.C3 diff --git a/SolidCore/Refinement/Corpus/C3/SeqPart5.lean b/SolidCore/Refinement/Corpus/C3/SeqPart5.lean new file mode 100644 index 00000000..0d1af8d9 --- /dev/null +++ b/SolidCore/Refinement/Corpus/C3/SeqPart5.lean @@ -0,0 +1,9 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/c3.sol. Do not edit. + +import SolidCore.Refinement.Corpus.C3.SeqDefs + +namespace SolidCore.Refinement.Corpus.C3 + +theorem seqPart5 : seqPartOk 5 = true := by native_decide + +end SolidCore.Refinement.Corpus.C3 diff --git a/SolidCore/Refinement/Corpus/C3/SeqPart6.lean b/SolidCore/Refinement/Corpus/C3/SeqPart6.lean new file mode 100644 index 00000000..365ef535 --- /dev/null +++ b/SolidCore/Refinement/Corpus/C3/SeqPart6.lean @@ -0,0 +1,9 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/c3.sol. Do not edit. + +import SolidCore.Refinement.Corpus.C3.SeqDefs + +namespace SolidCore.Refinement.Corpus.C3 + +theorem seqPart6 : seqPartOk 6 = true := by native_decide + +end SolidCore.Refinement.Corpus.C3 diff --git a/SolidCore/Refinement/Corpus/C3/SeqPart7.lean b/SolidCore/Refinement/Corpus/C3/SeqPart7.lean new file mode 100644 index 00000000..2c486234 --- /dev/null +++ b/SolidCore/Refinement/Corpus/C3/SeqPart7.lean @@ -0,0 +1,9 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/c3.sol. Do not edit. + +import SolidCore.Refinement.Corpus.C3.SeqDefs + +namespace SolidCore.Refinement.Corpus.C3 + +theorem seqPart7 : seqPartOk 7 = true := by native_decide + +end SolidCore.Refinement.Corpus.C3 diff --git a/SolidCore/Refinement/Corpus/C3/SeqPart8.lean b/SolidCore/Refinement/Corpus/C3/SeqPart8.lean new file mode 100644 index 00000000..a016b855 --- /dev/null +++ b/SolidCore/Refinement/Corpus/C3/SeqPart8.lean @@ -0,0 +1,9 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/c3.sol. Do not edit. + +import SolidCore.Refinement.Corpus.C3.SeqDefs + +namespace SolidCore.Refinement.Corpus.C3 + +theorem seqPart8 : seqPartOk 8 = true := by native_decide + +end SolidCore.Refinement.Corpus.C3 diff --git a/SolidCore/Refinement/Corpus/C3/SeqPart9.lean b/SolidCore/Refinement/Corpus/C3/SeqPart9.lean new file mode 100644 index 00000000..dc618995 --- /dev/null +++ b/SolidCore/Refinement/Corpus/C3/SeqPart9.lean @@ -0,0 +1,9 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/c3.sol. Do not edit. + +import SolidCore.Refinement.Corpus.C3.SeqDefs + +namespace SolidCore.Refinement.Corpus.C3 + +theorem seqPart9 : seqPartOk 9 = true := by native_decide + +end SolidCore.Refinement.Corpus.C3 diff --git a/SolidCore/Refinement/Corpus/C3/SeqStates.lean b/SolidCore/Refinement/Corpus/C3/SeqStates.lean new file mode 100644 index 00000000..dfcbf4b4 --- /dev/null +++ b/SolidCore/Refinement/Corpus/C3/SeqStates.lean @@ -0,0 +1,21 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/c3.sol. Do not edit. + +/-! +# The storages c3's clean calls reach + +The certificate of the sequence refinement of `Main` in `scripts/refinement/corpus/c3.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.C3 + +/-- 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.C3 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/C5.lean b/SolidCore/Refinement/Corpus/C5.lean new file mode 100644 index 00000000..f21df63e --- /dev/null +++ b/SolidCore/Refinement/Corpus/C5.lean @@ -0,0 +1,65 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/c5.sol. Do not edit. + +import SolidCore.Refinement.Corpus.C5.Part0 +import SolidCore.Refinement.Corpus.C5.Dirty + +/-! +# c5: solar's bytecode refines SolidCore's `Main` + +`refines` proves `Refines fuel contract code (· ∈ scope s)` for `Main` in +`scripts/refinement/corpus/c5.sol`, 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, 256 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 SolidCore.Refinement.Corpus.C5 + +open SolidCore.Refinement SolidCore.Refinement.Abi + +theorem parts_ok : ∀ i < parts, partOk i = true := fun i hi => + match i, hi with + | 0, _ => part0 + | n + 1, 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 SolidCore.Refinement.Corpus.C5 diff --git a/SolidCore/Refinement/Corpus/C5/Defs.lean b/SolidCore/Refinement/Corpus/C5/Defs.lean new file mode 100644 index 00000000..3e170f24 --- /dev/null +++ b/SolidCore/Refinement/Corpus/C5/Defs.lean @@ -0,0 +1,50 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/c5.sol. Do not edit. + +import SolidCore.Refinement.Abi +import SolidCore.Refinement.Bytecode.C5 +import SolidCore.Refinement.Source.C5 + +/-! +# The scope of c5's refinement + +256 calls: every function of `Main` in `scripts/refinement/corpus/c5.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.C5 + +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.C5.Main.runtimeNat + Bytecode.C5.Main.runtimeSize + +/-- SolidCore's checked `Main`. -/ +def contract? : Except TypeCheck.TypeError TypeCheck.CheckedContract := + TypeCheck.CheckedInput.contract Source.C5.importedSourceUnit "Main" + +/-- The functions of `Main` and their parameters. -/ +def fns : List Fn := + [⟨Bytecode.C5.Main.incSelector, [(.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.C5 diff --git a/SolidCore/Refinement/Corpus/C5/Dirty.lean b/SolidCore/Refinement/Corpus/C5/Dirty.lean new file mode 100644 index 00000000..05ea00f9 --- /dev/null +++ b/SolidCore/Refinement/Corpus/C5/Dirty.lean @@ -0,0 +1,31 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/c5.sol. Do not edit. + +import SolidCore.Refinement.Evm.Symex +import SolidCore.Refinement.Dirty.Source +import SolidCore.Refinement.Corpus.C5.Defs + +/-! +# c5: EthLib rejects every dirty argument word + +For every function of `Main` in `scripts/refinement/corpus/c5.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.C5 + +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.C5.Main.incSelector [(.uint 8)] + (by dirty_symex [code, Bytecode.C5.Main.runtimeNat, Bytecode.C5.Main.runtimeSize, Bytecode.C5.Main.incSelector]) + +end SolidCore.Refinement.Corpus.C5 diff --git a/SolidCore/Refinement/Corpus/C5/Part0.lean b/SolidCore/Refinement/Corpus/C5/Part0.lean new file mode 100644 index 00000000..bdb59842 --- /dev/null +++ b/SolidCore/Refinement/Corpus/C5/Part0.lean @@ -0,0 +1,9 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/c5.sol. Do not edit. + +import SolidCore.Refinement.Corpus.C5.Defs + +namespace SolidCore.Refinement.Corpus.C5 + +theorem part0 : partOk 0 = true := by native_decide + +end SolidCore.Refinement.Corpus.C5 diff --git a/SolidCore/Refinement/Corpus/C5/Seq.lean b/SolidCore/Refinement/Corpus/C5/Seq.lean new file mode 100644 index 00000000..a8b26975 --- /dev/null +++ b/SolidCore/Refinement/Corpus/C5/Seq.lean @@ -0,0 +1,89 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/c5.sol. Do not edit. + +import SolidCore.Refinement.Corpus.C5 +import SolidCore.Refinement.Corpus.C5.SeqDefs +import SolidCore.Refinement.Corpus.C5.SeqPart0 +import SolidCore.Refinement.Corpus.C5.SeqPart1 +import SolidCore.Refinement.Corpus.C5.SeqPart2 +import SolidCore.Refinement.Corpus.C5.SeqPart3 +import SolidCore.Refinement.Corpus.C5.SeqPart4 +import SolidCore.Refinement.Corpus.C5.SeqPart5 +import SolidCore.Refinement.Corpus.C5.SeqPart6 +import SolidCore.Refinement.Corpus.C5.SeqPart7 +import SolidCore.Refinement.Corpus.C5.SeqPart8 +import SolidCore.Refinement.Corpus.C5.SeqPart9 +import SolidCore.Refinement.Corpus.C5.SeqPart10 +import SolidCore.Refinement.Corpus.C5.SeqPart11 +import SolidCore.Refinement.Corpus.C5.SeqPart12 +import SolidCore.Refinement.Corpus.C5.SeqPart13 +import SolidCore.Refinement.Corpus.C5.SeqPart14 +import SolidCore.Refinement.Corpus.C5.SeqPart15 +import SolidCore.Refinement.Corpus.C5.SeqPart16 + +/-! +# c5: 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/c5.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), 257 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.C5 + +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 + | 16, _ => seqPart16 + | n + 17, 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.C5 diff --git a/SolidCore/Refinement/Corpus/C5/SeqDefs.lean b/SolidCore/Refinement/Corpus/C5/SeqDefs.lean new file mode 100644 index 00000000..0c3a3c9d --- /dev/null +++ b/SolidCore/Refinement/Corpus/C5/SeqDefs.lean @@ -0,0 +1,60 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/c5.sol. Do not edit. + +import SolidCore.Refinement.Seq.Check +import SolidCore.Refinement.Corpus.C5.Defs +import SolidCore.Refinement.Corpus.C5.SeqStates + +/-! +# The certificate of c5'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), 257 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, 65792 calls, in 17 part(s), and every dirty call once +per storage. +-/ + +namespace SolidCore.Refinement.Corpus.C5 + +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 := 17 + +/-- 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.C5 diff --git a/SolidCore/Refinement/Corpus/C5/SeqPart0.lean b/SolidCore/Refinement/Corpus/C5/SeqPart0.lean new file mode 100644 index 00000000..7e93e5ca --- /dev/null +++ b/SolidCore/Refinement/Corpus/C5/SeqPart0.lean @@ -0,0 +1,9 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/c5.sol. Do not edit. + +import SolidCore.Refinement.Corpus.C5.SeqDefs + +namespace SolidCore.Refinement.Corpus.C5 + +theorem seqPart0 : seqPartOk 0 = true := by native_decide + +end SolidCore.Refinement.Corpus.C5 diff --git a/SolidCore/Refinement/Corpus/C5/SeqPart1.lean b/SolidCore/Refinement/Corpus/C5/SeqPart1.lean new file mode 100644 index 00000000..4b4a04e6 --- /dev/null +++ b/SolidCore/Refinement/Corpus/C5/SeqPart1.lean @@ -0,0 +1,9 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/c5.sol. Do not edit. + +import SolidCore.Refinement.Corpus.C5.SeqDefs + +namespace SolidCore.Refinement.Corpus.C5 + +theorem seqPart1 : seqPartOk 1 = true := by native_decide + +end SolidCore.Refinement.Corpus.C5 diff --git a/SolidCore/Refinement/Corpus/C5/SeqPart10.lean b/SolidCore/Refinement/Corpus/C5/SeqPart10.lean new file mode 100644 index 00000000..a20b88a0 --- /dev/null +++ b/SolidCore/Refinement/Corpus/C5/SeqPart10.lean @@ -0,0 +1,9 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/c5.sol. Do not edit. + +import SolidCore.Refinement.Corpus.C5.SeqDefs + +namespace SolidCore.Refinement.Corpus.C5 + +theorem seqPart10 : seqPartOk 10 = true := by native_decide + +end SolidCore.Refinement.Corpus.C5 diff --git a/SolidCore/Refinement/Corpus/C5/SeqPart11.lean b/SolidCore/Refinement/Corpus/C5/SeqPart11.lean new file mode 100644 index 00000000..73c56d95 --- /dev/null +++ b/SolidCore/Refinement/Corpus/C5/SeqPart11.lean @@ -0,0 +1,9 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/c5.sol. Do not edit. + +import SolidCore.Refinement.Corpus.C5.SeqDefs + +namespace SolidCore.Refinement.Corpus.C5 + +theorem seqPart11 : seqPartOk 11 = true := by native_decide + +end SolidCore.Refinement.Corpus.C5 diff --git a/SolidCore/Refinement/Corpus/C5/SeqPart12.lean b/SolidCore/Refinement/Corpus/C5/SeqPart12.lean new file mode 100644 index 00000000..4a66e6f6 --- /dev/null +++ b/SolidCore/Refinement/Corpus/C5/SeqPart12.lean @@ -0,0 +1,9 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/c5.sol. Do not edit. + +import SolidCore.Refinement.Corpus.C5.SeqDefs + +namespace SolidCore.Refinement.Corpus.C5 + +theorem seqPart12 : seqPartOk 12 = true := by native_decide + +end SolidCore.Refinement.Corpus.C5 diff --git a/SolidCore/Refinement/Corpus/C5/SeqPart13.lean b/SolidCore/Refinement/Corpus/C5/SeqPart13.lean new file mode 100644 index 00000000..e5008ec2 --- /dev/null +++ b/SolidCore/Refinement/Corpus/C5/SeqPart13.lean @@ -0,0 +1,9 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/c5.sol. Do not edit. + +import SolidCore.Refinement.Corpus.C5.SeqDefs + +namespace SolidCore.Refinement.Corpus.C5 + +theorem seqPart13 : seqPartOk 13 = true := by native_decide + +end SolidCore.Refinement.Corpus.C5 diff --git a/SolidCore/Refinement/Corpus/C5/SeqPart14.lean b/SolidCore/Refinement/Corpus/C5/SeqPart14.lean new file mode 100644 index 00000000..dc22fb1f --- /dev/null +++ b/SolidCore/Refinement/Corpus/C5/SeqPart14.lean @@ -0,0 +1,9 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/c5.sol. Do not edit. + +import SolidCore.Refinement.Corpus.C5.SeqDefs + +namespace SolidCore.Refinement.Corpus.C5 + +theorem seqPart14 : seqPartOk 14 = true := by native_decide + +end SolidCore.Refinement.Corpus.C5 diff --git a/SolidCore/Refinement/Corpus/C5/SeqPart15.lean b/SolidCore/Refinement/Corpus/C5/SeqPart15.lean new file mode 100644 index 00000000..6d6834aa --- /dev/null +++ b/SolidCore/Refinement/Corpus/C5/SeqPart15.lean @@ -0,0 +1,9 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/c5.sol. Do not edit. + +import SolidCore.Refinement.Corpus.C5.SeqDefs + +namespace SolidCore.Refinement.Corpus.C5 + +theorem seqPart15 : seqPartOk 15 = true := by native_decide + +end SolidCore.Refinement.Corpus.C5 diff --git a/SolidCore/Refinement/Corpus/C5/SeqPart16.lean b/SolidCore/Refinement/Corpus/C5/SeqPart16.lean new file mode 100644 index 00000000..3c556066 --- /dev/null +++ b/SolidCore/Refinement/Corpus/C5/SeqPart16.lean @@ -0,0 +1,9 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/c5.sol. Do not edit. + +import SolidCore.Refinement.Corpus.C5.SeqDefs + +namespace SolidCore.Refinement.Corpus.C5 + +theorem seqPart16 : seqPartOk 16 = true := by native_decide + +end SolidCore.Refinement.Corpus.C5 diff --git a/SolidCore/Refinement/Corpus/C5/SeqPart2.lean b/SolidCore/Refinement/Corpus/C5/SeqPart2.lean new file mode 100644 index 00000000..f47c8817 --- /dev/null +++ b/SolidCore/Refinement/Corpus/C5/SeqPart2.lean @@ -0,0 +1,9 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/c5.sol. Do not edit. + +import SolidCore.Refinement.Corpus.C5.SeqDefs + +namespace SolidCore.Refinement.Corpus.C5 + +theorem seqPart2 : seqPartOk 2 = true := by native_decide + +end SolidCore.Refinement.Corpus.C5 diff --git a/SolidCore/Refinement/Corpus/C5/SeqPart3.lean b/SolidCore/Refinement/Corpus/C5/SeqPart3.lean new file mode 100644 index 00000000..3eb489dd --- /dev/null +++ b/SolidCore/Refinement/Corpus/C5/SeqPart3.lean @@ -0,0 +1,9 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/c5.sol. Do not edit. + +import SolidCore.Refinement.Corpus.C5.SeqDefs + +namespace SolidCore.Refinement.Corpus.C5 + +theorem seqPart3 : seqPartOk 3 = true := by native_decide + +end SolidCore.Refinement.Corpus.C5 diff --git a/SolidCore/Refinement/Corpus/C5/SeqPart4.lean b/SolidCore/Refinement/Corpus/C5/SeqPart4.lean new file mode 100644 index 00000000..4f601ad7 --- /dev/null +++ b/SolidCore/Refinement/Corpus/C5/SeqPart4.lean @@ -0,0 +1,9 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/c5.sol. Do not edit. + +import SolidCore.Refinement.Corpus.C5.SeqDefs + +namespace SolidCore.Refinement.Corpus.C5 + +theorem seqPart4 : seqPartOk 4 = true := by native_decide + +end SolidCore.Refinement.Corpus.C5 diff --git a/SolidCore/Refinement/Corpus/C5/SeqPart5.lean b/SolidCore/Refinement/Corpus/C5/SeqPart5.lean new file mode 100644 index 00000000..a8187c62 --- /dev/null +++ b/SolidCore/Refinement/Corpus/C5/SeqPart5.lean @@ -0,0 +1,9 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/c5.sol. Do not edit. + +import SolidCore.Refinement.Corpus.C5.SeqDefs + +namespace SolidCore.Refinement.Corpus.C5 + +theorem seqPart5 : seqPartOk 5 = true := by native_decide + +end SolidCore.Refinement.Corpus.C5 diff --git a/SolidCore/Refinement/Corpus/C5/SeqPart6.lean b/SolidCore/Refinement/Corpus/C5/SeqPart6.lean new file mode 100644 index 00000000..073bf7a1 --- /dev/null +++ b/SolidCore/Refinement/Corpus/C5/SeqPart6.lean @@ -0,0 +1,9 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/c5.sol. Do not edit. + +import SolidCore.Refinement.Corpus.C5.SeqDefs + +namespace SolidCore.Refinement.Corpus.C5 + +theorem seqPart6 : seqPartOk 6 = true := by native_decide + +end SolidCore.Refinement.Corpus.C5 diff --git a/SolidCore/Refinement/Corpus/C5/SeqPart7.lean b/SolidCore/Refinement/Corpus/C5/SeqPart7.lean new file mode 100644 index 00000000..cc15a359 --- /dev/null +++ b/SolidCore/Refinement/Corpus/C5/SeqPart7.lean @@ -0,0 +1,9 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/c5.sol. Do not edit. + +import SolidCore.Refinement.Corpus.C5.SeqDefs + +namespace SolidCore.Refinement.Corpus.C5 + +theorem seqPart7 : seqPartOk 7 = true := by native_decide + +end SolidCore.Refinement.Corpus.C5 diff --git a/SolidCore/Refinement/Corpus/C5/SeqPart8.lean b/SolidCore/Refinement/Corpus/C5/SeqPart8.lean new file mode 100644 index 00000000..53a6649a --- /dev/null +++ b/SolidCore/Refinement/Corpus/C5/SeqPart8.lean @@ -0,0 +1,9 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/c5.sol. Do not edit. + +import SolidCore.Refinement.Corpus.C5.SeqDefs + +namespace SolidCore.Refinement.Corpus.C5 + +theorem seqPart8 : seqPartOk 8 = true := by native_decide + +end SolidCore.Refinement.Corpus.C5 diff --git a/SolidCore/Refinement/Corpus/C5/SeqPart9.lean b/SolidCore/Refinement/Corpus/C5/SeqPart9.lean new file mode 100644 index 00000000..a630763b --- /dev/null +++ b/SolidCore/Refinement/Corpus/C5/SeqPart9.lean @@ -0,0 +1,9 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/c5.sol. Do not edit. + +import SolidCore.Refinement.Corpus.C5.SeqDefs + +namespace SolidCore.Refinement.Corpus.C5 + +theorem seqPart9 : seqPartOk 9 = true := by native_decide + +end SolidCore.Refinement.Corpus.C5 diff --git a/SolidCore/Refinement/Corpus/C5/SeqStates.lean b/SolidCore/Refinement/Corpus/C5/SeqStates.lean new file mode 100644 index 00000000..f5ba86f9 --- /dev/null +++ b/SolidCore/Refinement/Corpus/C5/SeqStates.lean @@ -0,0 +1,277 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/c5.sol. Do not edit. + +/-! +# The storages c5's clean calls reach + +The certificate of the sequence refinement of `Main` in `scripts/refinement/corpus/c5.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.C5 + +/-- The slots a reached storage holds a word for. -/ +def seqKeys : List Nat := [785377653105141805797970024993964143010236857130870283208420846897479170026, 799644054353182116819409674814862268228215137196486682061587368532786721193, 923611595825876214700736444482112465365779009101210803823586338541008743515, 1090028828071171958566632275270940446568241566856348647203407026706684869579, 2799812505952962443834604316686156113849555580394440851936817757181731562382, 3656362425506920687905657380766972183995946253862297485625541233869623726659, 6291455413658021769549683115764588939552595685480285555237734191500023421235, 7290387335634266486249037663595860854047133815481999773725367799777733655939, 8359096322321435740420496856757322524667871577305342498710005482925702664545, 8567644860763371221351102873100566022373200630661165526046193370264155498942, 8619526021121326297684418331725869188262301688300285701273135994950558811429, 8833443600437749042757196508506317049042078572378342592503992807371722412009, 9412340577509837745948896660169416811533076769787355737725153734567167785897, 9531444281093770316222528798842014596632672187733312100801353516819876605561, 9588833375853017759144432976803153699402552701172876473109190086455202642730, 12672427736653732334999699376457385029277601981814304931355705284498243384769, 12826611630915094713585692751787579525580317807897705089167775087588229310297, 12989514705740598333484151973466354555343510131890239912606811445340916416958, 13148593250806786124013289921591953984984629694961997431491991207599789091576, 13403776112023834337318221012384831821403364618916583869690140800041663172635, 13997274036241715770569949546454349465994187896353133401419363340028329628500, 14222158338378028755849854802906013856764867470341230141397555873674137909821, 14799885557910363837521763652770359868203035045512916878146874863246839236919, 16139728226176189574270658503457153979252390790990684767758958778331638965067, 16656159958526588396542275364770184213706846431984201267050426491816662575548, 16785070069242977186142043430427791646975797613521486648904909686816755002240, 16812500525204298049670936779042818567049991136123200639622240153821740115423, 17546573577872070049322014530302500066857064530340251253327426045428850326424, 17630675969583722191470744029273404954477703989011041494828601201845483849537, 18238647851773146204242376147149909195654171622042055867311491690536803598914, 18375907534388843971202198220513734266210116675666568231499221134236882820436, 18438574794618266995271062296840653083944084293150248855032010319677611705798, 18760121781013800388400736091885485061141680870169782946511884348940141811701, 19110318229691223672304115739220610509722015503858797286850199670438991824852, 19511599891424801449367108142964227787403202039135897967463264740723690140170, 19893286231922839207928962601128261290427500414225577489902211855861785849379, 20706849821414543309269754486121421285865641016941868705861275661204699334178, 20804442458093162342690477379961553198784948573553174956068938424859445751094, 21578785495152961521663696983433956183892569066947717819551339025684223116765, 22011238926374221297955128473445806789698243329891627010810163584757836485693, 22073773110316925674293423896419645890044337920441591863820164370640930073077, 22739549017527831145253558742181233789412337772632356867924940007088907039662, 22756765779589845761170775236260874230900367805402455632653690919156678150133, 23581821450077080102038791735251200316633889989564290066348703325627906851800, 23873795274536554141760578542171547695519348722282327125167597581669157281610, 24003893637958684882275078747705327686963818465531630532614307092076301060651, 24157522119968295071953353750455078060072770678802682358979618591467376281599, 24523879643966112771142501664940969237837881536754386530534564847052822294750, 24613032481519243699494608620987993648620524807064746098941144284630051899794, 24639138107251414624395588823366880866855749058156624935845532106667898154293, 25021195316953018556300927528933446171410382862238431216637541472623017484467, 25305248992181997481019551887572610781200588425129411322752374339976237456502, 25562807946348978164010301428613926153348344817204617933597747301230413541243, 25623290824728920756184549381325955993926162688056001432264638087367063257549, 26040296650574722187499729440338945248280062282726815258149101776336853416295, 26488312161312437458680116032741915151291023843796350625392977241255227277117, 26929859266906226753135478207994831052137272153404834887388983414887822213277, 27194948638893430968207648823002064550325950801508799881693198968418613648530, 28128362005401814584472854075374455407533226184131122176930602318878521848726, 28204386174496475358925224800018969744194020328474334991532821054689460348060, 28316780231992663356899387360795050299752000032466988729594309499906746629572, 28640721178945816610695353804721831245271712044697043134480601470196841240746, 29778868857966469716708518094984567390886394581107582036466037383035874934368, 29931802189033335019443449455296686386015373088323624751592238500795311205211, 31309610291621957806003076604376413594078470148894599583592287969410568225620, 31749060692446647957063798182256653453754019095992504686698698270233007961563, 33031563702596238271033088896094518276138564031298844509176288384372212513062, 33130157381101178152692861171422170109593024081617299873282060969362925563119, 33357877780324982306471076330286076487191694594323177705146874465028789223759, 33672598725513130442218507837030875226335582665785355436980649317037041083484, 33744506572927916092385862249051532488705003698715076447717958056162116804524, 33993479317926977340314087406925536987795144664433202465348644575330068317111, 34466675513563928959644158681441619776963090951983744593568923752242358029812, 34649904307950641685692557928318430218112468969593521341060784553302291890286, 35194500050690849880410069265747789450080604788810869248715741633195663291942, 35347474584631156893894774976140396373967260988043456059228024493165677000325, 35373381066494663916547017653784696502088539159320982027555375526209547059251, 36482186801264784031064171474479088528269423946836123719979863649473811490187, 36615405679831900287384546583137069845289693601158955458844133945766233381273, 37300442896938396431521828309165838615900663005569164769999796436588545805641, 37470079394597546017821359402343014298469527652371950473243809108734949064165, 38739427594694835873074603481621783694271576804488774522251665291055385678114, 39178881125236857557028483473591545956019451032181195740692908526345386921213, 40111963949295210159257552184144112388869083841758507514734703209905644620236, 40743020663061967729263291811679321452891423976506973270559018637784895172919, 41407063523202153779201919856959745600407059861221559387013478471919977319996, 41499514915934067763375373491891932804240891777929870272099712567144579566018, 41532502716476026394345200694722484464646490522752636861810767808724168489229, 41757575366747182177712362185223460452037791449309648460015483668913498988250, 42135843763098079287265802274788832664585984553229177428165683416103518516258, 42288275431917443957305987716171603607662217749962234244590842715486634707828, 42876087170416830341743310988581294610691002593638053381251540404100726689159, 42926116097441077918926826994340717673299826109623115061157533946134593030247, 43256635453065299975648550655905599432270588515817250786760751605470659934286, 43357072029091020756827108147437324412188381358685910599010836709114891867687, 44355349372257074959598820724407765760752581458598127991279639756049881788605, 44615743314895256965986528121830246128136045468485087047374538576816198192780, 44990203588671624464097672180277455536565044771833967521564869191618680928122, 45615373214537764644465214662938571807791802613132604979489428941581053415539, 45721165141960566383876966575218064238181594531406814696405494669324207630298, 46152474889557226364395084389017124352829182980214178038750070876090092337729, 46500423217328596694918186654239374818993336069778294413284991264679691917526, 46567939793927018756080282238176922330172480829060053777580906484729714253075, 47099455181088334305038857712740472110892796627083003929926130304907752277627, 47491707747248804774861235787103930217690023084003714664383154738624682683532, 47987341720427095639370440139677738845429111808761383581317923693198086548673, 48402570246221253280619204127503850567357088548850073173177773033218369543499, 48491489436287191140809376302550808640350670923611159302633162747079974016730, 48646531516588658748174857273336964586014186820404509465026446403412404208523, 49252644475482635042436945964266858281750521780446338431662986557548742232701, 49529967721848596832723806867876781795973160178870656924235821269595727297755, 50843052282620187567584695405763184177957050316467307734226725899394128231510, 51098198013455917446209769919619969880786065575688435462931279802436993327894, 51314561371977914930587975863183183873656764410071686651960207312485533478085, 51917322056620375432689146050972676567997595515292099008982447389317405380989, 52154138229345166819819310740014974622961096365565309962835836907179235852026, 52616945631811483891622113630822147683734470403576474313269608336556581779345, 53017671164176843150973674479173729470979484940492797662099425467806500645382, 53988645545977562568632206542058459134827844980496761706520554048667861702301, 54063658834738067084496540211663901730980781763788050429636181368935704665102, 54378519012454295053851589497647979762236247278810118161220373727993491242605, 54735413030395479294609845465073105735868722591114211538711460511982414183580, 56154372553858659047026741206451006073536809142875650527347373727200715860842, 56354237972228702270642743924928925432054518857446166923126227907160864930982, 56379375082099018722056789168509866372749978077076306672312729015938096605403, 57291668433907626782807202461029016749615472300770202472277437909122396545528, 58500625931013280029881945210801957733789509287178636558925534572635114344447, 59014633476227013232026298455333461683994448764411998030894372204064525358265, 59188717551942672301514773853996461229126055086162484385443628018648037582844, 60172305762817568703928238125768396205909137252576319443500128236401316086189, 61066341240856734250200229908154867864480630679181913661669668597419326467371, 61247559742107014645813721314132189750196138978462853954394552069673446645171, 61486714998490343122797170857096226924052201492004837224114561396144380615480, 61616826075723879356008722030089855107486813959063454787491471213113547571672, 61982690758583651325662399734623223020292172318792482292597957184969559732447, 63418599787721677537059800693434263169929361987350731842725980801845935182072, 64703441581317953377132278901698329160226626601734116218983995680062494260232, 64816002741425559331367998620864232489669791182112698487333629327003095846856, 65159830875257095075971815117575205209895972027913332062268757128365774586135, 65183651552598248064646810781808479576278432315083110161194716479859681455675, 65623166409519056520994908395722833037654924088690886984408315243991923873190, 65750850849933600998134139098884895314186991675841403906372108981595105076273, 65953406444726928824267262725844005978442041504524108131056758779075868468843, 66836886898801465132400996336733857972521392348932138996574531720499840256844, 66988692256413743606831087717669768972296584544487192143002102816320417939335, 68517036635979639225077357098826030748394806817056737307766907477495457241220, 68944739717082272106490248517471854333213415368679882962058263098392019588289, 69474183407012801928790001736961568456549020695295710491772555178666704323852, 69606713115603049201802638923557827578758711604829613299677181557391402349292, 70071673280682195483764887260534364274756468163004453082445387628464575262896, 71336474783394080197321810469482573231222347487862131686619557077352214456178, 71723012714503283754748199373868243855043561198354771694863849727884325187189, 72306943747623749014192575728455180284489618713377321608827217775231259677118, 73292565240730679315523573743189972315948611609426154754800424125467154216542, 73555895786918245468190752828418795965247207065870858797245859361449045122436, 73850753425616206499768033702552900820614942976543832997789279584203048650396, 74238383904887895474128013742620188794528857964205418046106315768645959215035, 74371192060872846199669259415181932529219385253384047563123972352064137618981, 74829709022468040910563011399410994215393005772961632492846271592132224026659, 74848376561780800242831821890995655988688240847854493809064534852391558998718, 74883205530718186496601380730572389711250411041873065682528539158028248861072, 75009579753178427995030696053184066298981361309917801366815301015703768926043, 75335222087818882579102525395129457290529687620811808292617818223217035843880, 76038433016463599060119891717085713360489941909709171796947574562413230994133, 76135350201379602412980831789280355683691988218374124821446963214781526387394, 76258091638193594312786839003401792933593372913384780593415976616852439493304, 76685048069377641832184063094342380430367912804174716703877786810256877496092, 76905768109786021000530205513046456659043104694231263761248924137519015878553, 76981213532761093632436164595075559182284015263722193214899447744440193917498, 77121120652924445981148520660670756224408166225447895920277457132774935058175, 77169314071708520005573833594584795692768513902771839118044262092465501248723, 77676537065960878698898692042018114106337750925255485067533933387271373890921, 78338746147236970124700731725183845421594913511827187288591969170390706184117, 78541660797044910968829902406342334108369226379826116161446442989268089806461, 78739476704930304988579239197006905304357004252669174447868514242810536319986, 79213231952977306971521252217977048118223116490459654252870649946752203657993, 79937154209765547948756703973095640792302913572818455402187192580652463382710, 79998271051857629023883964745044669620844965034408945211741818543939931671010, 80657740543437365260910055543208890025856639744218509819574480436654090528896, 80886230943476801478981904650999493880610961315983640305182522680206771954771, 80912266525110353631292841955423926008325719876124395632553705926009542888608, 81549753519496015132455364440609520288594725836063187203352161558076061404131, 81764179474894600055982417721835366024121034012668606526983649247373062113019, 82096730325534084889822286646397391381071040993798069064440087900396250658137, 82673407659281072722463828935472213152892066170835383138076602289316844073214, 83363837849203752469223267655300532748099588293840920674437329857707324529850, 83473566612942238936406928330396650259392671471126036881973111006474954194660, 83524974121842188908292911748546356912232132126674902970150532062113452986293, 84095892047511144011082731179495588773872287705314310072012296383456600768748, 84361483787859088378039807591050394110882469020922178022362089109707639016923, 84570509436453737706627678357167862216344930415770389958722338920174811589149, 85082712263291480078643414791642462099758889005035962676470758393887209169390, 86344347482212995437303289304305938691525364068858175849246830891390448961304, 87215972220595830758287894057770058837970451868891273346195029148334350278991, 87540151530774915512025123970633424775645795377724374510611578239635739209415, 88247134514094097032841563525692459032769447449331204233509935125882153413010, 88585537440794415532517880991531909092488955560373238251861958665094448819347, 88661900617021958259247006209488184561723918010236404418536658640789070462694, 89534585535335632630334761198300185143907537228490560849311822654140354860035, 90210319159504676149971049073377343373387366223961014285346678702984528568535, 90462935704248591514654943459352606552685662949764886616260132835914010554125, 93062377755616104076136263330022889994437597496579598849720231303361296941301, 93418077008685305483050925218806463481689706310739811801739342587661516880128, 93634265062437177817494350595967216260216147703913628840195613702286985985212, 93887130669182630639974887530059286507906335808973425097029840515226862121854, 94096208785182875279873124246085509649087555463662791812510057102495529206324, 94376770707860800088818712292414780952038890326714099953771676889341176737887, 95647830087882872312972159755980599319601445415563481383450681728607516025635, 96175813547198599514714253163752803764365311495028852023757621354506252344132, 96328734672689945026430155996551980769720754477971329129486200955627979553931, 96331120794480547586672214690511128492219579846099798616511880738107851788006, 96438018442023998757226547334333998243080018716505025334901572619406576967031, 96481402368221536778392010390537145661562602935121638741453425020727698388387, 96491614803638560672972006391329580542169724233889678455509076750297420919226, 96989598518465790580869093355009478768697647778666673649039865580726511607151, 97032426743845437131299457709060652747742863175948972364695840813069650109493, 97231920302833665476633129815073365612775921008304838115631216561950980939793, 98362030130520372488673582164329537794929189924025151866019614411796100577894, 98372265477199355752381146009313422161501591235184943318950495265345615073811, 98423476418156132283953110476807204783333253138130714805941856785055096307963, 98690462173535920362252665352475267102696426691687611768101680453674426419405, 99250614452718793745716874529723469606211306536461605127798665703543327928437, 99441866469013031425194890435376768787621702475199223563250258924552940670627, 99578389926443943009426491932587868765139972938117296631972251545666696457699, 99810599065707425481744774210214179115707437217338022473833123526329279667003, 100397848814505757692139955506131362401776580071653681998924726753788670264512, 100501195172664535830925975091664947533607165983939194257793843064591798272818, 100946154636297624928975014396287171807931400817315546416610288785552164325991, 101795305822934022406538637820123261602709228814887843806977580416631482005485, 102674448971776091366924212202375184013621490026184605368708991806576789522051, 103569436489534196737736671306484905858551923279649737027354538134095762817041, 103815352722017164410176195207968126103049081874433713207503865792324728875973, 104003728650891889486453736094339678643928298514337577072943108778149521712387, 104365551018422889170608122038538026227427594533781404909228900221631927427828, 104842719916419723074031643449247931589547438137195801512493061762316648376967, 105721182380816668089674224688318176007599331474316895725595425372587271692089, 106523937270577700510598490448522192078438635130572786825282769805981133685426, 106617042211741601969138829382995831523012608580195213941361723242131394956151, 107171975592367045768408505665000463948040305596855189828459688365256764215450, 107306908940897711083802607365080174569959332579430936179770432200593364772401, 107745012645103887505776599096575955233299144281780284455731598337740660635090, 107975190527143090426027141360918813367812314596138273687925412791128992887044, 108403773136507013356488875589870164133294178288502863284991106556715795235076, 108627778114904707933903146031001306129129030086019392996923114131297415212629, 109979302800437902617696420013528151065324428814718567237700249755597932001657, 110945061739611978068030233806095060310143576979896956364002768812055335222406, 111249423793328072669316117073095787495691608757316384608997725742964660810034, 111802156398775995605546506866474849404066674146698891073207541144325448905369, 112567181693694566944019622265511931059733292654356550160024394564862763532008, 112640983326606019455597968069966353162957514299120252244351371083120402690926, 112984037233880508886067784099116939769873727292768534458620947795757095774746, 113033377116645960109730773077471640474812483217578053587580941831293233652192, 113387580105269524496188576869462785562855358334345125578808450976458602359266, 113623423760229777392652065265720399763537642777271314780058875204057178059926, 115242573604793930731386066589433343398750024207778177874294445755956120976445, 115597572823987858626890768851390094301349834160935394353195088259626480289575] + +/-- The reached storages, by level, from level 1. -/ +def seqLevels : List (List (List (Nat × Nat))) := [ + [[(78338746147236970124700731725183845421594913511827187288591969170390706184117, 300)], + [(78338746147236970124700731725183845421594913511827187288591969170390706184117, 1), (78541660797044910968829902406342334108369226379826116161446442989268089806461, 300)], + [(7290387335634266486249037663595860854047133815481999773725367799777733655939, 2), (77676537065960878698898692042018114106337750925255485067533933387271373890921, 300)], + [(7290387335634266486249037663595860854047133815481999773725367799777733655939, 300), (77676537065960878698898692042018114106337750925255485067533933387271373890921, 3)], + [(19511599891424801449367108142964227787403202039135897967463264740723690140170, 4), (37470079394597546017821359402343014298469527652371950473243809108734949064165, 300)], + [(19511599891424801449367108142964227787403202039135897967463264740723690140170, 300), (37470079394597546017821359402343014298469527652371950473243809108734949064165, 5)], + [(44355349372257074959598820724407765760752581458598127991279639756049881788605, 300), (61066341240856734250200229908154867864480630679181913661669668597419326467371, 6)], + [(44355349372257074959598820724407765760752581458598127991279639756049881788605, 7), (61066341240856734250200229908154867864480630679181913661669668597419326467371, 300)], + [(22756765779589845761170775236260874230900367805402455632653690919156678150133, 8), (41407063523202153779201919856959745600407059861221559387013478471919977319996, 300)], + [(22756765779589845761170775236260874230900367805402455632653690919156678150133, 300), (41407063523202153779201919856959745600407059861221559387013478471919977319996, 9)], + [(28316780231992663356899387360795050299752000032466988729594309499906746629572, 300), (65623166409519056520994908395722833037654924088690886984408315243991923873190, 10)], + [(28316780231992663356899387360795050299752000032466988729594309499906746629572, 11), (65623166409519056520994908395722833037654924088690886984408315243991923873190, 300)], + [(56379375082099018722056789168509866372749978077076306672312729015938096605403, 12), (94376770707860800088818712292414780952038890326714099953771676889341176737887, 300)], + [(56379375082099018722056789168509866372749978077076306672312729015938096605403, 300), (94376770707860800088818712292414780952038890326714099953771676889341176737887, 13)], + [(53017671164176843150973674479173729470979484940492797662099425467806500645382, 14), (105721182380816668089674224688318176007599331474316895725595425372587271692089, 300)], + [(53017671164176843150973674479173729470979484940492797662099425467806500645382, 300), (105721182380816668089674224688318176007599331474316895725595425372587271692089, 15)], + [(923611595825876214700736444482112465365779009101210803823586338541008743515, 300), (73555895786918245468190752828418795965247207065870858797245859361449045122436, 16)], + [(923611595825876214700736444482112465365779009101210803823586338541008743515, 17), (73555895786918245468190752828418795965247207065870858797245859361449045122436, 300)], + [(12989514705740598333484151973466354555343510131890239912606811445340916416958, 300), (36482186801264784031064171474479088528269423946836123719979863649473811490187, 18)], + [(12989514705740598333484151973466354555343510131890239912606811445340916416958, 19), (36482186801264784031064171474479088528269423946836123719979863649473811490187, 300)], + [(37300442896938396431521828309165838615900663005569164769999796436588545805641, 20), (69474183407012801928790001736961568456549020695295710491772555178666704323852, 300)], + [(37300442896938396431521828309165838615900663005569164769999796436588545805641, 300), (69474183407012801928790001736961568456549020695295710491772555178666704323852, 21)], + [(81549753519496015132455364440609520288594725836063187203352161558076061404131, 300), (99578389926443943009426491932587868765139972938117296631972251545666696457699, 22)], + [(81549753519496015132455364440609520288594725836063187203352161558076061404131, 23), (99578389926443943009426491932587868765139972938117296631972251545666696457699, 300)], + [(13403776112023834337318221012384831821403364618916583869690140800041663172635, 300), (79937154209765547948756703973095640792302913572818455402187192580652463382710, 24)], + [(13403776112023834337318221012384831821403364618916583869690140800041663172635, 25), (79937154209765547948756703973095640792302913572818455402187192580652463382710, 300)], + [(9531444281093770316222528798842014596632672187733312100801353516819876605561, 26), (107306908940897711083802607365080174569959332579430936179770432200593364772401, 300)], + [(9531444281093770316222528798842014596632672187733312100801353516819876605561, 300), (107306908940897711083802607365080174569959332579430936179770432200593364772401, 27)], + [(83363837849203752469223267655300532748099588293840920674437329857707324529850, 28), (110945061739611978068030233806095060310143576979896956364002768812055335222406, 300)], + [(83363837849203752469223267655300532748099588293840920674437329857707324529850, 300), (110945061739611978068030233806095060310143576979896956364002768812055335222406, 29)], + [(16656159958526588396542275364770184213706846431984201267050426491816662575548, 300), (93062377755616104076136263330022889994437597496579598849720231303361296941301, 30)], + [(16656159958526588396542275364770184213706846431984201267050426491816662575548, 31), (93062377755616104076136263330022889994437597496579598849720231303361296941301, 300)], + [(14799885557910363837521763652770359868203035045512916878146874863246839236919, 32), (39178881125236857557028483473591545956019451032181195740692908526345386921213, 300)], + [(14799885557910363837521763652770359868203035045512916878146874863246839236919, 300), (39178881125236857557028483473591545956019451032181195740692908526345386921213, 33)], + [(19110318229691223672304115739220610509722015503858797286850199670438991824852, 34), (46152474889557226364395084389017124352829182980214178038750070876090092337729, 300)], + [(19110318229691223672304115739220610509722015503858797286850199670438991824852, 300), (46152474889557226364395084389017124352829182980214178038750070876090092337729, 35)], + [(96491614803638560672972006391329580542169724233889678455509076750297420919226, 36), (113387580105269524496188576869462785562855358334345125578808450976458602359266, 300)], + [(96491614803638560672972006391329580542169724233889678455509076750297420919226, 300), (113387580105269524496188576869462785562855358334345125578808450976458602359266, 37)], + [(96481402368221536778392010390537145661562602935121638741453425020727698388387, 300), (97032426743845437131299457709060652747742863175948972364695840813069650109493, 38)], + [(96481402368221536778392010390537145661562602935121638741453425020727698388387, 39), (97032426743845437131299457709060652747742863175948972364695840813069650109493, 300)], + [(33357877780324982306471076330286076487191694594323177705146874465028789223759, 40), (41499514915934067763375373491891932804240891777929870272099712567144579566018, 300)], + [(33357877780324982306471076330286076487191694594323177705146874465028789223759, 300), (41499514915934067763375373491891932804240891777929870272099712567144579566018, 41)], + [(45615373214537764644465214662938571807791802613132604979489428941581053415539, 300), (104842719916419723074031643449247931589547438137195801512493061762316648376967, 42)], + [(45615373214537764644465214662938571807791802613132604979489428941581053415539, 43), (104842719916419723074031643449247931589547438137195801512493061762316648376967, 300)], + [(12672427736653732334999699376457385029277601981814304931355705284498243384769, 44), (19893286231922839207928962601128261290427500414225577489902211855861785849379, 300)], + [(12672427736653732334999699376457385029277601981814304931355705284498243384769, 300), (19893286231922839207928962601128261290427500414225577489902211855861785849379, 45)], + [(50843052282620187567584695405763184177957050316467307734226725899394128231510, 46), (53988645545977562568632206542058459134827844980496761706520554048667861702301, 300)], + [(50843052282620187567584695405763184177957050316467307734226725899394128231510, 300), (53988645545977562568632206542058459134827844980496761706520554048667861702301, 47)], + [(18438574794618266995271062296840653083944084293150248855032010319677611705798, 300), (73292565240730679315523573743189972315948611609426154754800424125467154216542, 48)], + [(18438574794618266995271062296840653083944084293150248855032010319677611705798, 49), (73292565240730679315523573743189972315948611609426154754800424125467154216542, 300)], + [(25562807946348978164010301428613926153348344817204617933597747301230413541243, 50), (71723012714503283754748199373868243855043561198354771694863849727884325187189, 300)], + [(25562807946348978164010301428613926153348344817204617933597747301230413541243, 300), (71723012714503283754748199373868243855043561198354771694863849727884325187189, 51)], + [(6291455413658021769549683115764588939552595685480285555237734191500023421235, 52), (23873795274536554141760578542171547695519348722282327125167597581669157281610, 300)], + [(6291455413658021769549683115764588939552595685480285555237734191500023421235, 300), (23873795274536554141760578542171547695519348722282327125167597581669157281610, 53)], + [(35373381066494663916547017653784696502088539159320982027555375526209547059251, 54), (104365551018422889170608122038538026227427594533781404909228900221631927427828, 300)], + [(35373381066494663916547017653784696502088539159320982027555375526209547059251, 300), (104365551018422889170608122038538026227427594533781404909228900221631927427828, 55)], + [(31749060692446647957063798182256653453754019095992504686698698270233007961563, 300), (75335222087818882579102525395129457290529687620811808292617818223217035843880, 56)], + [(31749060692446647957063798182256653453754019095992504686698698270233007961563, 57), (75335222087818882579102525395129457290529687620811808292617818223217035843880, 300)], + [(8833443600437749042757196508506317049042078572378342592503992807371722412009, 58), (113623423760229777392652065265720399763537642777271314780058875204057178059926, 300)], + [(8833443600437749042757196508506317049042078572378342592503992807371722412009, 300), (113623423760229777392652065265720399763537642777271314780058875204057178059926, 59)], + [(76038433016463599060119891717085713360489941909709171796947574562413230994133, 60), (108403773136507013356488875589870164133294178288502863284991106556715795235076, 300)], + [(76038433016463599060119891717085713360489941909709171796947574562413230994133, 300), (108403773136507013356488875589870164133294178288502863284991106556715795235076, 61)], + [(41757575366747182177712362185223460452037791449309648460015483668913498988250, 62), (42926116097441077918926826994340717673299826109623115061157533946134593030247, 300)], + [(41757575366747182177712362185223460452037791449309648460015483668913498988250, 300), (42926116097441077918926826994340717673299826109623115061157533946134593030247, 63)], + [(24003893637958684882275078747705327686963818465531630532614307092076301060651, 64), (38739427594694835873074603481621783694271576804488774522251665291055385678114, 300)], + [(24003893637958684882275078747705327686963818465531630532614307092076301060651, 300), (38739427594694835873074603481621783694271576804488774522251665291055385678114, 65)], + [(8567644860763371221351102873100566022373200630661165526046193370264155498942, 66), (18238647851773146204242376147149909195654171622042055867311491690536803598914, 300)], + [(8567644860763371221351102873100566022373200630661165526046193370264155498942, 300), (18238647851773146204242376147149909195654171622042055867311491690536803598914, 67)], + [(59014633476227013232026298455333461683994448764411998030894372204064525358265, 68), (108627778114904707933903146031001306129129030086019392996923114131297415212629, 300)], + [(59014633476227013232026298455333461683994448764411998030894372204064525358265, 300), (108627778114904707933903146031001306129129030086019392996923114131297415212629, 69)], + [(43357072029091020756827108147437324412188381358685910599010836709114891867687, 300), (61982690758583651325662399734623223020292172318792482292597957184969559732447, 70)], + [(43357072029091020756827108147437324412188381358685910599010836709114891867687, 71), (61982690758583651325662399734623223020292172318792482292597957184969559732447, 300)], + [(65183651552598248064646810781808479576278432315083110161194716479859681455675, 72), (81764179474894600055982417721835366024121034012668606526983649247373062113019, 300)], + [(65183651552598248064646810781808479576278432315083110161194716479859681455675, 300), (81764179474894600055982417721835366024121034012668606526983649247373062113019, 73)], + [(14222158338378028755849854802906013856764867470341230141397555873674137909821, 74), (79213231952977306971521252217977048118223116490459654252870649946752203657993, 300)], + [(14222158338378028755849854802906013856764867470341230141397555873674137909821, 300), (79213231952977306971521252217977048118223116490459654252870649946752203657993, 75)], + [(70071673280682195483764887260534364274756468163004453082445387628464575262896, 76), (115242573604793930731386066589433343398750024207778177874294445755956120976445, 300)], + [(70071673280682195483764887260534364274756468163004453082445387628464575262896, 300), (115242573604793930731386066589433343398750024207778177874294445755956120976445, 77)], + [(28640721178945816610695353804721831245271712044697043134480601470196841240746, 78), (85082712263291480078643414791642462099758889005035962676470758393887209169390, 300)], + [(28640721178945816610695353804721831245271712044697043134480601470196841240746, 300), (85082712263291480078643414791642462099758889005035962676470758393887209169390, 79)], + [(93418077008685305483050925218806463481689706310739811801739342587661516880128, 300), (107171975592367045768408505665000463948040305596855189828459688365256764215450, 80)], + [(93418077008685305483050925218806463481689706310739811801739342587661516880128, 81), (107171975592367045768408505665000463948040305596855189828459688365256764215450, 300)], + [(46567939793927018756080282238176922330172480829060053777580906484729714253075, 82), (99441866469013031425194890435376768787621702475199223563250258924552940670627, 300)], + [(46567939793927018756080282238176922330172480829060053777580906484729714253075, 300), (99441866469013031425194890435376768787621702475199223563250258924552940670627, 83)], + [(16812500525204298049670936779042818567049991136123200639622240153821740115423, 300), (17630675969583722191470744029273404954477703989011041494828601201845483849537, 84)], + [(16812500525204298049670936779042818567049991136123200639622240153821740115423, 85), (17630675969583722191470744029273404954477703989011041494828601201845483849537, 300)], + [(21578785495152961521663696983433956183892569066947717819551339025684223116765, 300), (25623290824728920756184549381325955993926162688056001432264638087367063257549, 86)], + [(21578785495152961521663696983433956183892569066947717819551339025684223116765, 87), (25623290824728920756184549381325955993926162688056001432264638087367063257549, 300)], + [(2799812505952962443834604316686156113849555580394440851936817757181731562382, 300), (77169314071708520005573833594584795692768513902771839118044262092465501248723, 88)], + [(2799812505952962443834604316686156113849555580394440851936817757181731562382, 89), (77169314071708520005573833594584795692768513902771839118044262092465501248723, 300)], + [(51917322056620375432689146050972676567997595515292099008982447389317405380989, 300), (60172305762817568703928238125768396205909137252576319443500128236401316086189, 90)], + [(51917322056620375432689146050972676567997595515292099008982447389317405380989, 91), (60172305762817568703928238125768396205909137252576319443500128236401316086189, 300)], + [(58500625931013280029881945210801957733789509287178636558925534572635114344447, 92), (96438018442023998757226547334333998243080018716505025334901572619406576967031, 300)], + [(58500625931013280029881945210801957733789509287178636558925534572635114344447, 300), (96438018442023998757226547334333998243080018716505025334901572619406576967031, 93)], + [(98372265477199355752381146009313422161501591235184943318950495265345615073811, 94), (115597572823987858626890768851390094301349834160935394353195088259626480289575, 300)], + [(98372265477199355752381146009313422161501591235184943318950495265345615073811, 300), (115597572823987858626890768851390094301349834160935394353195088259626480289575, 95)], + [(33130157381101178152692861171422170109593024081617299873282060969362925563119, 300), (95647830087882872312972159755980599319601445415563481383450681728607516025635, 96)], + [(33130157381101178152692861171422170109593024081617299873282060969362925563119, 97), (95647830087882872312972159755980599319601445415563481383450681728607516025635, 300)], + [(799644054353182116819409674814862268228215137196486682061587368532786721193, 98), (59188717551942672301514773853996461229126055086162484385443628018648037582844, 300)], + [(799644054353182116819409674814862268228215137196486682061587368532786721193, 300), (59188717551942672301514773853996461229126055086162484385443628018648037582844, 99)], + [(33672598725513130442218507837030875226335582665785355436980649317037041083484, 100), (71336474783394080197321810469482573231222347487862131686619557077352214456178, 300)], + [(33672598725513130442218507837030875226335582665785355436980649317037041083484, 300), (71336474783394080197321810469482573231222347487862131686619557077352214456178, 101)], + [(29931802189033335019443449455296686386015373088323624751592238500795311205211, 300), (47099455181088334305038857712740472110892796627083003929926130304907752277627, 102)], + [(29931802189033335019443449455296686386015373088323624751592238500795311205211, 103), (47099455181088334305038857712740472110892796627083003929926130304907752277627, 300)], + [(24613032481519243699494608620987993648620524807064746098941144284630051899794, 104), (76905768109786021000530205513046456659043104694231263761248924137519015878553, 300)], + [(24613032481519243699494608620987993648620524807064746098941144284630051899794, 300), (76905768109786021000530205513046456659043104694231263761248924137519015878553, 105)], + [(20706849821414543309269754486121421285865641016941868705861275661204699334178, 106), (109979302800437902617696420013528151065324428814718567237700249755597932001657, 300)], + [(20706849821414543309269754486121421285865641016941868705861275661204699334178, 300), (109979302800437902617696420013528151065324428814718567237700249755597932001657, 107)], + [(27194948638893430968207648823002064550325950801508799881693198968418613648530, 300), (76981213532761093632436164595075559182284015263722193214899447744440193917498, 108)], + [(27194948638893430968207648823002064550325950801508799881693198968418613648530, 109), (76981213532761093632436164595075559182284015263722193214899447744440193917498, 300)], + [(49252644475482635042436945964266858281750521780446338431662986557548742232701, 300), (96175813547198599514714253163752803764365311495028852023757621354506252344132, 110)], + [(49252644475482635042436945964266858281750521780446338431662986557548742232701, 111), (96175813547198599514714253163752803764365311495028852023757621354506252344132, 300)], + [(74883205530718186496601380730572389711250411041873065682528539158028248861072, 112), (77121120652924445981148520660670756224408166225447895920277457132774935058175, 300)], + [(74883205530718186496601380730572389711250411041873065682528539158028248861072, 300), (77121120652924445981148520660670756224408166225447895920277457132774935058175, 113)], + [(65750850849933600998134139098884895314186991675841403906372108981595105076273, 114), (74238383904887895474128013742620188794528857964205418046106315768645959215035, 300)], + [(65750850849933600998134139098884895314186991675841403906372108981595105076273, 300), (74238383904887895474128013742620188794528857964205418046106315768645959215035, 115)], + [(16139728226176189574270658503457153979252390790990684767758958778331638965067, 300), (54063658834738067084496540211663901730980781763788050429636181368935704665102, 116)], + [(16139728226176189574270658503457153979252390790990684767758958778331638965067, 117), (54063658834738067084496540211663901730980781763788050429636181368935704665102, 300)], + [(1090028828071171958566632275270940446568241566856348647203407026706684869579, 118), (66836886898801465132400996336733857972521392348932138996574531720499840256844, 300)], + [(1090028828071171958566632275270940446568241566856348647203407026706684869579, 300), (66836886898801465132400996336733857972521392348932138996574531720499840256844, 119)], + [(72306943747623749014192575728455180284489618713377321608827217775231259677118, 300), (90210319159504676149971049073377343373387366223961014285346678702984528568535, 120)], + [(72306943747623749014192575728455180284489618713377321608827217775231259677118, 121), (90210319159504676149971049073377343373387366223961014285346678702984528568535, 300)], + [(47491707747248804774861235787103930217690023084003714664383154738624682683532, 300), (100501195172664535830925975091664947533607165983939194257793843064591798272818, 122)], + [(47491707747248804774861235787103930217690023084003714664383154738624682683532, 123), (100501195172664535830925975091664947533607165983939194257793843064591798272818, 300)], + [(45721165141960566383876966575218064238181594531406814696405494669324207630298, 124), (96331120794480547586672214690511128492219579846099798616511880738107851788006, 300)], + [(45721165141960566383876966575218064238181594531406814696405494669324207630298, 300), (96331120794480547586672214690511128492219579846099798616511880738107851788006, 125)], + [(76258091638193594312786839003401792933593372913384780593415976616852439493304, 300), (98423476418156132283953110476807204783333253138130714805941856785055096307963, 126)], + [(76258091638193594312786839003401792933593372913384780593415976616852439493304, 127), (98423476418156132283953110476807204783333253138130714805941856785055096307963, 300)], + [(51098198013455917446209769919619969880786065575688435462931279802436993327894, 128), (112984037233880508886067784099116939769873727292768534458620947795757095774746, 300)], + [(51098198013455917446209769919619969880786065575688435462931279802436993327894, 300), (112984037233880508886067784099116939769873727292768534458620947795757095774746, 129)], + [(8619526021121326297684418331725869188262301688300285701273135994950558811429, 300), (42876087170416830341743310988581294610691002593638053381251540404100726689159, 130)], + [(8619526021121326297684418331725869188262301688300285701273135994950558811429, 131), (42876087170416830341743310988581294610691002593638053381251540404100726689159, 300)], + [(26929859266906226753135478207994831052137272153404834887388983414887822213277, 300), (75009579753178427995030696053184066298981361309917801366815301015703768926043, 132)], + [(26929859266906226753135478207994831052137272153404834887388983414887822213277, 133), (75009579753178427995030696053184066298981361309917801366815301015703768926043, 300)], + [(69606713115603049201802638923557827578758711604829613299677181557391402349292, 300), (111802156398775995605546506866474849404066674146698891073207541144325448905369, 134)], + [(69606713115603049201802638923557827578758711604829613299677181557391402349292, 135), (111802156398775995605546506866474849404066674146698891073207541144325448905369, 300)], + [(42135843763098079287265802274788832664585984553229177428165683416103518516258, 300), (61616826075723879356008722030089855107486813959063454787491471213113547571672, 136)], + [(42135843763098079287265802274788832664585984553229177428165683416103518516258, 137), (61616826075723879356008722030089855107486813959063454787491471213113547571672, 300)], + [(24523879643966112771142501664940969237837881536754386530534564847052822294750, 138), (46500423217328596694918186654239374818993336069778294413284991264679691917526, 300)], + [(24523879643966112771142501664940969237837881536754386530534564847052822294750, 300), (46500423217328596694918186654239374818993336069778294413284991264679691917526, 139)], + [(34649904307950641685692557928318430218112468969593521341060784553302291890286, 140), (65159830875257095075971815117575205209895972027913332062268757128365774586135, 300)], + [(34649904307950641685692557928318430218112468969593521341060784553302291890286, 300), (65159830875257095075971815117575205209895972027913332062268757128365774586135, 141)], + [(33993479317926977340314087406925536987795144664433202465348644575330068317111, 300), (113033377116645960109730773077471640474812483217578053587580941831293233652192, 142)], + [(33993479317926977340314087406925536987795144664433202465348644575330068317111, 143), (113033377116645960109730773077471640474812483217578053587580941831293233652192, 300)], + [(24639138107251414624395588823366880866855749058156624935845532106667898154293, 300), (93887130669182630639974887530059286507906335808973425097029840515226862121854, 144)], + [(24639138107251414624395588823366880866855749058156624935845532106667898154293, 145), (93887130669182630639974887530059286507906335808973425097029840515226862121854, 300)], + [(88247134514094097032841563525692459032769447449331204233509935125882153413010, 146), (103815352722017164410176195207968126103049081874433713207503865792324728875973, 300)], + [(88247134514094097032841563525692459032769447449331204233509935125882153413010, 300), (103815352722017164410176195207968126103049081874433713207503865792324728875973, 147)], + [(3656362425506920687905657380766972183995946253862297485625541233869623726659, 300), (104003728650891889486453736094339678643928298514337577072943108778149521712387, 148)], + [(3656362425506920687905657380766972183995946253862297485625541233869623726659, 149), (104003728650891889486453736094339678643928298514337577072943108778149521712387, 300)], + [(80912266525110353631292841955423926008325719876124395632553705926009542888608, 300), (88585537440794415532517880991531909092488955560373238251861958665094448819347, 150)], + [(80912266525110353631292841955423926008325719876124395632553705926009542888608, 151), (88585537440794415532517880991531909092488955560373238251861958665094448819347, 300)], + [(28128362005401814584472854075374455407533226184131122176930602318878521848726, 300), (98690462173535920362252665352475267102696426691687611768101680453674426419405, 152)], + [(28128362005401814584472854075374455407533226184131122176930602318878521848726, 153), (98690462173535920362252665352475267102696426691687611768101680453674426419405, 300)], + [(42288275431917443957305987716171603607662217749962234244590842715486634707828, 300), (78739476704930304988579239197006905304357004252669174447868514242810536319986, 154)], + [(42288275431917443957305987716171603607662217749962234244590842715486634707828, 155), (78739476704930304988579239197006905304357004252669174447868514242810536319986, 300)], + [(23581821450077080102038791735251200316633889989564290066348703325627906851800, 156), (101795305822934022406538637820123261602709228814887843806977580416631482005485, 300)], + [(23581821450077080102038791735251200316633889989564290066348703325627906851800, 300), (101795305822934022406538637820123261602709228814887843806977580416631482005485, 157)], + [(64816002741425559331367998620864232489669791182112698487333629327003095846856, 300), (90462935704248591514654943459352606552685662949764886616260132835914010554125, 158)], + [(64816002741425559331367998620864232489669791182112698487333629327003095846856, 159), (90462935704248591514654943459352606552685662949764886616260132835914010554125, 300)], + [(74371192060872846199669259415181932529219385253384047563123972352064137618981, 160), (82673407659281072722463828935472213152892066170835383138076602289316844073214, 300)], + [(74371192060872846199669259415181932529219385253384047563123972352064137618981, 300), (82673407659281072722463828935472213152892066170835383138076602289316844073214, 161)], + [(64703441581317953377132278901698329160226626601734116218983995680062494260232, 300), (93634265062437177817494350595967216260216147703913628840195613702286985985212, 162)], + [(64703441581317953377132278901698329160226626601734116218983995680062494260232, 163), (93634265062437177817494350595967216260216147703913628840195613702286985985212, 300)], + [(83473566612942238936406928330396650259392671471126036881973111006474954194660, 300), (106617042211741601969138829382995831523012608580195213941361723242131394956151, 164)], + [(83473566612942238936406928330396650259392671471126036881973111006474954194660, 165), (106617042211741601969138829382995831523012608580195213941361723242131394956151, 300)], + [(52154138229345166819819310740014974622961096365565309962835836907179235852026, 166), (54378519012454295053851589497647979762236247278810118161220373727993491242605, 300)], + [(52154138229345166819819310740014974622961096365565309962835836907179235852026, 300), (54378519012454295053851589497647979762236247278810118161220373727993491242605, 167)], + [(84361483787859088378039807591050394110882469020922178022362089109707639016923, 300), (84570509436453737706627678357167862216344930415770389958722338920174811589149, 168)], + [(84361483787859088378039807591050394110882469020922178022362089109707639016923, 169), (84570509436453737706627678357167862216344930415770389958722338920174811589149, 300)], + [(24157522119968295071953353750455078060072770678802682358979618591467376281599, 170), (97231920302833665476633129815073365612775921008304838115631216561950980939793, 300)], + [(24157522119968295071953353750455078060072770678802682358979618591467376281599, 300), (97231920302833665476633129815073365612775921008304838115631216561950980939793, 171)], + [(79998271051857629023883964745044669620844965034408945211741818543939931671010, 300), (112567181693694566944019622265511931059733292654356550160024394564862763532008, 172)], + [(79998271051857629023883964745044669620844965034408945211741818543939931671010, 173), (112567181693694566944019622265511931059733292654356550160024394564862763532008, 300)], + [(44990203588671624464097672180277455536565044771833967521564869191618680928122, 174), (99810599065707425481744774210214179115707437217338022473833123526329279667003, 300)], + [(44990203588671624464097672180277455536565044771833967521564869191618680928122, 300), (99810599065707425481744774210214179115707437217338022473833123526329279667003, 175)], + [(16785070069242977186142043430427791646975797613521486648904909686816755002240, 176), (17546573577872070049322014530302500066857064530340251253327426045428850326424, 300)], + [(16785070069242977186142043430427791646975797613521486648904909686816755002240, 300), (17546573577872070049322014530302500066857064530340251253327426045428850326424, 177)], + [(18760121781013800388400736091885485061141680870169782946511884348940141811701, 300), (20804442458093162342690477379961553198784948573553174956068938424859445751094, 178)], + [(18760121781013800388400736091885485061141680870169782946511884348940141811701, 179), (20804442458093162342690477379961553198784948573553174956068938424859445751094, 300)], + [(80886230943476801478981904650999493880610961315983640305182522680206771954771, 300), (106523937270577700510598490448522192078438635130572786825282769805981133685426, 180)], + [(80886230943476801478981904650999493880610961315983640305182522680206771954771, 181), (106523937270577700510598490448522192078438635130572786825282769805981133685426, 300)], + [(48402570246221253280619204127503850567357088548850073173177773033218369543499, 182), (100397848814505757692139955506131362401776580071653681998924726753788670264512, 300)], + [(48402570246221253280619204127503850567357088548850073173177773033218369543499, 300), (100397848814505757692139955506131362401776580071653681998924726753788670264512, 183)], + [(26040296650574722187499729440338945248280062282726815258149101776336853416295, 184), (49529967721848596832723806867876781795973160178870656924235821269595727297755, 300)], + [(26040296650574722187499729440338945248280062282726815258149101776336853416295, 300), (49529967721848596832723806867876781795973160178870656924235821269595727297755, 185)], + [(57291668433907626782807202461029016749615472300770202472277437909122396545528, 186), (63418599787721677537059800693434263169929361987350731842725980801845935182072, 300)], + [(57291668433907626782807202461029016749615472300770202472277437909122396545528, 300), (63418599787721677537059800693434263169929361987350731842725980801845935182072, 187)], + [(94096208785182875279873124246085509649087555463662791812510057102495529206324, 188), (96328734672689945026430155996551980769720754477971329129486200955627979553931, 300)], + [(94096208785182875279873124246085509649087555463662791812510057102495529206324, 300), (96328734672689945026430155996551980769720754477971329129486200955627979553931, 189)], + [(22739549017527831145253558742181233789412337772632356867924940007088907039662, 300), (51314561371977914930587975863183183873656764410071686651960207312485533478085, 190)], + [(22739549017527831145253558742181233789412337772632356867924940007088907039662, 191), (51314561371977914930587975863183183873656764410071686651960207312485533478085, 300)], + [(33031563702596238271033088896094518276138564031298844509176288384372212513062, 300), (56154372553858659047026741206451006073536809142875650527347373727200715860842, 192)], + [(33031563702596238271033088896094518276138564031298844509176288384372212513062, 193), (56154372553858659047026741206451006073536809142875650527347373727200715860842, 300)], + [(96989598518465790580869093355009478768697647778666673649039865580726511607151, 300), (107745012645103887505776599096575955233299144281780284455731598337740660635090, 194)], + [(96989598518465790580869093355009478768697647778666673649039865580726511607151, 195), (107745012645103887505776599096575955233299144281780284455731598337740660635090, 300)], + [(35347474584631156893894774976140396373967260988043456059228024493165677000325, 300), (88661900617021958259247006209488184561723918010236404418536658640789070462694, 196)], + [(35347474584631156893894774976140396373967260988043456059228024493165677000325, 197), (88661900617021958259247006209488184561723918010236404418536658640789070462694, 300)], + [(12826611630915094713585692751787579525580317807897705089167775087588229310297, 198), (43256635453065299975648550655905599432270588515817250786760751605470659934286, 300)], + [(12826611630915094713585692751787579525580317807897705089167775087588229310297, 300), (43256635453065299975648550655905599432270588515817250786760751605470659934286, 199)], + [(31309610291621957806003076604376413594078470148894599583592287969410568225620, 200), (89534585535335632630334761198300185143907537228490560849311822654140354860035, 300)], + [(31309610291621957806003076604376413594078470148894599583592287969410568225620, 300), (89534585535335632630334761198300185143907537228490560849311822654140354860035, 201)], + [(61247559742107014645813721314132189750196138978462853954394552069673446645171, 300), (61486714998490343122797170857096226924052201492004837224114561396144380615480, 202)], + [(61247559742107014645813721314132189750196138978462853954394552069673446645171, 203), (61486714998490343122797170857096226924052201492004837224114561396144380615480, 300)], + [(22073773110316925674293423896419645890044337920441591863820164370640930073077, 204), (65953406444726928824267262725844005978442041504524108131056758779075868468843, 300)], + [(22073773110316925674293423896419645890044337920441591863820164370640930073077, 300), (65953406444726928824267262725844005978442041504524108131056758779075868468843, 205)], + [(54735413030395479294609845465073105735868722591114211538711460511982414183580, 206), (82096730325534084889822286646397391381071040993798069064440087900396250658137, 300)], + [(54735413030395479294609845465073105735868722591114211538711460511982414183580, 300), (82096730325534084889822286646397391381071040993798069064440087900396250658137, 207)], + [(9412340577509837745948896660169416811533076769787355737725153734567167785897, 300), (25021195316953018556300927528933446171410382862238431216637541472623017484467, 208)], + [(9412340577509837745948896660169416811533076769787355737725153734567167785897, 209), (25021195316953018556300927528933446171410382862238431216637541472623017484467, 300)], + [(74848376561780800242831821890995655988688240847854493809064534852391558998718, 210), (87215972220595830758287894057770058837970451868891273346195029148334350278991, 300)], + [(74848376561780800242831821890995655988688240847854493809064534852391558998718, 300), (87215972220595830758287894057770058837970451868891273346195029148334350278991, 211)], + [(29778868857966469716708518094984567390886394581107582036466037383035874934368, 300), (84095892047511144011082731179495588773872287705314310072012296383456600768748, 212)], + [(29778868857966469716708518094984567390886394581107582036466037383035874934368, 213), (84095892047511144011082731179495588773872287705314310072012296383456600768748, 300)], + [(48646531516588658748174857273336964586014186820404509465026446403412404208523, 300), (87540151530774915512025123970633424775645795377724374510611578239635739209415, 214)], + [(48646531516588658748174857273336964586014186820404509465026446403412404208523, 215), (87540151530774915512025123970633424775645795377724374510611578239635739209415, 300)], + [(48491489436287191140809376302550808640350670923611159302633162747079974016730, 216), (68517036635979639225077357098826030748394806817056737307766907477495457241220, 300)], + [(48491489436287191140809376302550808640350670923611159302633162747079974016730, 300), (68517036635979639225077357098826030748394806817056737307766907477495457241220, 217)], + [(8359096322321435740420496856757322524667871577305342498710005482925702664545, 218), (56354237972228702270642743924928925432054518857446166923126227907160864930982, 300)], + [(8359096322321435740420496856757322524667871577305342498710005482925702664545, 300), (56354237972228702270642743924928925432054518857446166923126227907160864930982, 219)], + [(35194500050690849880410069265747789450080604788810869248715741633195663291942, 220), (41532502716476026394345200694722484464646490522752636861810767808724168489229, 300)], + [(35194500050690849880410069265747789450080604788810869248715741633195663291942, 300), (41532502716476026394345200694722484464646490522752636861810767808724168489229, 221)], + [(25305248992181997481019551887572610781200588425129411322752374339976237456502, 300), (107975190527143090426027141360918813367812314596138273687925412791128992887044, 222)], + [(25305248992181997481019551887572610781200588425129411322752374339976237456502, 223), (107975190527143090426027141360918813367812314596138273687925412791128992887044, 300)], + [(785377653105141805797970024993964143010236857130870283208420846897479170026, 300), (44615743314895256965986528121830246128136045468485087047374538576816198192780, 224)], + [(785377653105141805797970024993964143010236857130870283208420846897479170026, 225), (44615743314895256965986528121830246128136045468485087047374538576816198192780, 300)], + [(36615405679831900287384546583137069845289693601158955458844133945766233381273, 300), (111249423793328072669316117073095787495691608757316384608997725742964660810034, 226)], + [(36615405679831900287384546583137069845289693601158955458844133945766233381273, 227), (111249423793328072669316117073095787495691608757316384608997725742964660810034, 300)], + [(76135350201379602412980831789280355683691988218374124821446963214781526387394, 228), (112640983326606019455597968069966353162957514299120252244351371083120402690926, 300)], + [(76135350201379602412980831789280355683691988218374124821446963214781526387394, 300), (112640983326606019455597968069966353162957514299120252244351371083120402690926, 229)], + [(102674448971776091366924212202375184013621490026184605368708991806576789522051, 300), (103569436489534196737736671306484905858551923279649737027354538134095762817041, 230)], + [(102674448971776091366924212202375184013621490026184605368708991806576789522051, 231), (103569436489534196737736671306484905858551923279649737027354538134095762817041, 300)], + [(18375907534388843971202198220513734266210116675666568231499221134236882820436, 232), (100946154636297624928975014396287171807931400817315546416610288785552164325991, 300)], + [(18375907534388843971202198220513734266210116675666568231499221134236882820436, 300), (100946154636297624928975014396287171807931400817315546416610288785552164325991, 233)], + [(9588833375853017759144432976803153699402552701172876473109190086455202642730, 234), (33744506572927916092385862249051532488705003698715076447717958056162116804524, 300)], + [(9588833375853017759144432976803153699402552701172876473109190086455202642730, 300), (33744506572927916092385862249051532488705003698715076447717958056162116804524, 235)], + [(13148593250806786124013289921591953984984629694961997431491991207599789091576, 300), (66988692256413743606831087717669768972296584544487192143002102816320417939335, 236)], + [(13148593250806786124013289921591953984984629694961997431491991207599789091576, 237), (66988692256413743606831087717669768972296584544487192143002102816320417939335, 300)], + [(83524974121842188908292911748546356912232132126674902970150532062113452986293, 238), (98362030130520372488673582164329537794929189924025151866019614411796100577894, 300)], + [(83524974121842188908292911748546356912232132126674902970150532062113452986293, 300), (98362030130520372488673582164329537794929189924025151866019614411796100577894, 239)], + [(74829709022468040910563011399410994215393005772961632492846271592132224026659, 240), (80657740543437365260910055543208890025856639744218509819574480436654090528896, 300)], + [(74829709022468040910563011399410994215393005772961632492846271592132224026659, 300), (80657740543437365260910055543208890025856639744218509819574480436654090528896, 241)], + [(28204386174496475358925224800018969744194020328474334991532821054689460348060, 242), (47987341720427095639370440139677738845429111808761383581317923693198086548673, 300)], + [(28204386174496475358925224800018969744194020328474334991532821054689460348060, 300), (47987341720427095639370440139677738845429111808761383581317923693198086548673, 243)], + [(22011238926374221297955128473445806789698243329891627010810163584757836485693, 300), (99250614452718793745716874529723469606211306536461605127798665703543327928437, 244)], + [(22011238926374221297955128473445806789698243329891627010810163584757836485693, 245), (99250614452718793745716874529723469606211306536461605127798665703543327928437, 300)], + [(13997274036241715770569949546454349465994187896353133401419363340028329628500, 300), (68944739717082272106490248517471854333213415368679882962058263098392019588289, 246)], + [(13997274036241715770569949546454349465994187896353133401419363340028329628500, 247), (68944739717082272106490248517471854333213415368679882962058263098392019588289, 300)], + [(40743020663061967729263291811679321452891423976506973270559018637784895172919, 248), (73850753425616206499768033702552900820614942976543832997789279584203048650396, 300)], + [(40743020663061967729263291811679321452891423976506973270559018637784895172919, 300), (73850753425616206499768033702552900820614942976543832997789279584203048650396, 249)], + [(34466675513563928959644158681441619776963090951983744593568923752242358029812, 250), (76685048069377641832184063094342380430367912804174716703877786810256877496092, 300)], + [(34466675513563928959644158681441619776963090951983744593568923752242358029812, 300), (76685048069377641832184063094342380430367912804174716703877786810256877496092, 251)], + [(52616945631811483891622113630822147683734470403576474313269608336556581779345, 300), (86344347482212995437303289304305938691525364068858175849246830891390448961304, 252)], + [(52616945631811483891622113630822147683734470403576474313269608336556581779345, 253), (86344347482212995437303289304305938691525364068858175849246830891390448961304, 300)], + [(26488312161312437458680116032741915151291023843796350625392977241255227277117, 300), (40111963949295210159257552184144112388869083841758507514734703209905644620236, 254)], + [(26488312161312437458680116032741915151291023843796350625392977241255227277117, 255), (40111963949295210159257552184144112388869083841758507514734703209905644620236, 300)]]] + +end SolidCore.Refinement.Corpus.C5 diff --git a/SolidCore/Refinement/Corpus/C6.lean b/SolidCore/Refinement/Corpus/C6.lean new file mode 100644 index 00000000..75cd0722 --- /dev/null +++ b/SolidCore/Refinement/Corpus/C6.lean @@ -0,0 +1,65 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/c6.sol. Do not edit. + +import SolidCore.Refinement.Corpus.C6.Part0 +import SolidCore.Refinement.Corpus.C6.Dirty + +/-! +# c6: solar's bytecode refines SolidCore's `Main` + +`refines` proves `Refines fuel contract code (· ∈ scope s)` for `Main` in +`scripts/refinement/corpus/c6.sol`, 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, 256 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 SolidCore.Refinement.Corpus.C6 + +open SolidCore.Refinement SolidCore.Refinement.Abi + +theorem parts_ok : ∀ i < parts, partOk i = true := fun i hi => + match i, hi with + | 0, _ => part0 + | n + 1, 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 SolidCore.Refinement.Corpus.C6 diff --git a/SolidCore/Refinement/Corpus/C6/Defs.lean b/SolidCore/Refinement/Corpus/C6/Defs.lean new file mode 100644 index 00000000..50001e64 --- /dev/null +++ b/SolidCore/Refinement/Corpus/C6/Defs.lean @@ -0,0 +1,50 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/c6.sol. Do not edit. + +import SolidCore.Refinement.Abi +import SolidCore.Refinement.Bytecode.C6 +import SolidCore.Refinement.Source.C6 + +/-! +# The scope of c6's refinement + +256 calls: every function of `Main` in `scripts/refinement/corpus/c6.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.C6 + +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.C6.Main.runtimeNat + Bytecode.C6.Main.runtimeSize + +/-- SolidCore's checked `Main`. -/ +def contract? : Except TypeCheck.TypeError TypeCheck.CheckedContract := + TypeCheck.CheckedInput.contract Source.C6.importedSourceUnit "Main" + +/-- The functions of `Main` and their parameters. -/ +def fns : List Fn := + [⟨Bytecode.C6.Main.sumSelector, [(.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.C6 diff --git a/SolidCore/Refinement/Corpus/C6/Dirty.lean b/SolidCore/Refinement/Corpus/C6/Dirty.lean new file mode 100644 index 00000000..c2c407f1 --- /dev/null +++ b/SolidCore/Refinement/Corpus/C6/Dirty.lean @@ -0,0 +1,31 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/c6.sol. Do not edit. + +import SolidCore.Refinement.Evm.Symex +import SolidCore.Refinement.Dirty.Source +import SolidCore.Refinement.Corpus.C6.Defs + +/-! +# c6: EthLib rejects every dirty argument word + +For every function of `Main` in `scripts/refinement/corpus/c6.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.C6 + +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.C6.Main.sumSelector [(.uint 8)] + (by dirty_symex [code, Bytecode.C6.Main.runtimeNat, Bytecode.C6.Main.runtimeSize, Bytecode.C6.Main.sumSelector]) + +end SolidCore.Refinement.Corpus.C6 diff --git a/SolidCore/Refinement/Corpus/C6/Part0.lean b/SolidCore/Refinement/Corpus/C6/Part0.lean new file mode 100644 index 00000000..4e0c0f19 --- /dev/null +++ b/SolidCore/Refinement/Corpus/C6/Part0.lean @@ -0,0 +1,9 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/c6.sol. Do not edit. + +import SolidCore.Refinement.Corpus.C6.Defs + +namespace SolidCore.Refinement.Corpus.C6 + +theorem part0 : partOk 0 = true := by native_decide + +end SolidCore.Refinement.Corpus.C6 diff --git a/SolidCore/Refinement/Corpus/C6/Seq.lean b/SolidCore/Refinement/Corpus/C6/Seq.lean new file mode 100644 index 00000000..ce3cdde4 --- /dev/null +++ b/SolidCore/Refinement/Corpus/C6/Seq.lean @@ -0,0 +1,54 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/c6.sol. Do not edit. + +import SolidCore.Refinement.Corpus.C6 +import SolidCore.Refinement.Corpus.C6.SeqDefs +import SolidCore.Refinement.Corpus.C6.SeqPart0 + +/-! +# c6: 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/c6.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.C6 + +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.C6 diff --git a/SolidCore/Refinement/Corpus/C6/SeqDefs.lean b/SolidCore/Refinement/Corpus/C6/SeqDefs.lean new file mode 100644 index 00000000..f3c95e32 --- /dev/null +++ b/SolidCore/Refinement/Corpus/C6/SeqDefs.lean @@ -0,0 +1,59 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/c6.sol. Do not edit. + +import SolidCore.Refinement.Seq.Check +import SolidCore.Refinement.Corpus.C6.Defs +import SolidCore.Refinement.Corpus.C6.SeqStates + +/-! +# The certificate of c6'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.C6 + +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.C6 diff --git a/SolidCore/Refinement/Corpus/C6/SeqPart0.lean b/SolidCore/Refinement/Corpus/C6/SeqPart0.lean new file mode 100644 index 00000000..92b0aa23 --- /dev/null +++ b/SolidCore/Refinement/Corpus/C6/SeqPart0.lean @@ -0,0 +1,9 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/c6.sol. Do not edit. + +import SolidCore.Refinement.Corpus.C6.SeqDefs + +namespace SolidCore.Refinement.Corpus.C6 + +theorem seqPart0 : seqPartOk 0 = true := by native_decide + +end SolidCore.Refinement.Corpus.C6 diff --git a/SolidCore/Refinement/Corpus/C6/SeqStates.lean b/SolidCore/Refinement/Corpus/C6/SeqStates.lean new file mode 100644 index 00000000..ed3226fa --- /dev/null +++ b/SolidCore/Refinement/Corpus/C6/SeqStates.lean @@ -0,0 +1,21 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/c6.sol. Do not edit. + +/-! +# The storages c6's clean calls reach + +The certificate of the sequence refinement of `Main` in `scripts/refinement/corpus/c6.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.C6 + +/-- 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.C6 diff --git a/SolidCore/Refinement/Corpus/C7.lean b/SolidCore/Refinement/Corpus/C7.lean new file mode 100644 index 00000000..0fde8c57 --- /dev/null +++ b/SolidCore/Refinement/Corpus/C7.lean @@ -0,0 +1,65 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/c7.sol. Do not edit. + +import SolidCore.Refinement.Corpus.C7.Part0 +import SolidCore.Refinement.Corpus.C7.Dirty + +/-! +# c7: solar's bytecode refines SolidCore's `Main` + +`refines` proves `Refines fuel contract code (· ∈ scope s)` for `Main` in +`scripts/refinement/corpus/c7.sol`, 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, 6 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 SolidCore.Refinement.Corpus.C7 + +open SolidCore.Refinement SolidCore.Refinement.Abi + +theorem parts_ok : ∀ i < parts, partOk i = true := fun i hi => + match i, hi with + | 0, _ => part0 + | n + 1, 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 SolidCore.Refinement.Corpus.C7 diff --git a/SolidCore/Refinement/Corpus/C7/Defs.lean b/SolidCore/Refinement/Corpus/C7/Defs.lean new file mode 100644 index 00000000..89b583e1 --- /dev/null +++ b/SolidCore/Refinement/Corpus/C7/Defs.lean @@ -0,0 +1,50 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/c7.sol. Do not edit. + +import SolidCore.Refinement.Abi +import SolidCore.Refinement.Bytecode.C7 +import SolidCore.Refinement.Source.C7 + +/-! +# The scope of c7's refinement + +6 calls: every function of `Main` in `scripts/refinement/corpus/c7.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.C7 + +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.C7.Main.runtimeNat + Bytecode.C7.Main.runtimeSize + +/-- SolidCore's checked `Main`. -/ +def contract? : Except TypeCheck.TypeError TypeCheck.CheckedContract := + TypeCheck.CheckedInput.contract Source.C7.importedSourceUnit "Main" + +/-- The functions of `Main` and their parameters. -/ +def fns : List Fn := + [⟨Bytecode.C7.Main.fSelector, [(.enum 3), .bool]⟩] + +/-- 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.C7 diff --git a/SolidCore/Refinement/Corpus/C7/Dirty.lean b/SolidCore/Refinement/Corpus/C7/Dirty.lean new file mode 100644 index 00000000..2fdd8153 --- /dev/null +++ b/SolidCore/Refinement/Corpus/C7/Dirty.lean @@ -0,0 +1,31 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/c7.sol. Do not edit. + +import SolidCore.Refinement.Evm.Symex +import SolidCore.Refinement.Dirty.Source +import SolidCore.Refinement.Corpus.C7.Defs + +/-! +# c7: EthLib rejects every dirty argument word + +For every function of `Main` in `scripts/refinement/corpus/c7.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.C7 + +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.C7.Main.fSelector [(.enum 3), .bool] + (by dirty_symex [code, Bytecode.C7.Main.runtimeNat, Bytecode.C7.Main.runtimeSize, Bytecode.C7.Main.fSelector]) + +end SolidCore.Refinement.Corpus.C7 diff --git a/SolidCore/Refinement/Corpus/C7/Part0.lean b/SolidCore/Refinement/Corpus/C7/Part0.lean new file mode 100644 index 00000000..df4bd2df --- /dev/null +++ b/SolidCore/Refinement/Corpus/C7/Part0.lean @@ -0,0 +1,9 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/c7.sol. Do not edit. + +import SolidCore.Refinement.Corpus.C7.Defs + +namespace SolidCore.Refinement.Corpus.C7 + +theorem part0 : partOk 0 = true := by native_decide + +end SolidCore.Refinement.Corpus.C7 diff --git a/SolidCore/Refinement/Corpus/C7/Seq.lean b/SolidCore/Refinement/Corpus/C7/Seq.lean new file mode 100644 index 00000000..3b7b4577 --- /dev/null +++ b/SolidCore/Refinement/Corpus/C7/Seq.lean @@ -0,0 +1,54 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/c7.sol. Do not edit. + +import SolidCore.Refinement.Corpus.C7 +import SolidCore.Refinement.Corpus.C7.SeqDefs +import SolidCore.Refinement.Corpus.C7.SeqPart0 + +/-! +# c7: 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/c7.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.C7 + +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.C7 diff --git a/SolidCore/Refinement/Corpus/C7/SeqDefs.lean b/SolidCore/Refinement/Corpus/C7/SeqDefs.lean new file mode 100644 index 00000000..5c757258 --- /dev/null +++ b/SolidCore/Refinement/Corpus/C7/SeqDefs.lean @@ -0,0 +1,59 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/c7.sol. Do not edit. + +import SolidCore.Refinement.Seq.Check +import SolidCore.Refinement.Corpus.C7.Defs +import SolidCore.Refinement.Corpus.C7.SeqStates + +/-! +# The certificate of c7'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, 6 calls, in 1 part(s), and every dirty call once +per storage. +-/ + +namespace SolidCore.Refinement.Corpus.C7 + +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.C7 diff --git a/SolidCore/Refinement/Corpus/C7/SeqPart0.lean b/SolidCore/Refinement/Corpus/C7/SeqPart0.lean new file mode 100644 index 00000000..6941bb8d --- /dev/null +++ b/SolidCore/Refinement/Corpus/C7/SeqPart0.lean @@ -0,0 +1,9 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/c7.sol. Do not edit. + +import SolidCore.Refinement.Corpus.C7.SeqDefs + +namespace SolidCore.Refinement.Corpus.C7 + +theorem seqPart0 : seqPartOk 0 = true := by native_decide + +end SolidCore.Refinement.Corpus.C7 diff --git a/SolidCore/Refinement/Corpus/C7/SeqStates.lean b/SolidCore/Refinement/Corpus/C7/SeqStates.lean new file mode 100644 index 00000000..0ddaa6d3 --- /dev/null +++ b/SolidCore/Refinement/Corpus/C7/SeqStates.lean @@ -0,0 +1,21 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/c7.sol. Do not edit. + +/-! +# The storages c7's clean calls reach + +The certificate of the sequence refinement of `Main` in `scripts/refinement/corpus/c7.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.C7 + +/-- 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.C7 diff --git a/SolidCore/Refinement/Corpus/C8.lean b/SolidCore/Refinement/Corpus/C8.lean new file mode 100644 index 00000000..79f4c1e9 --- /dev/null +++ b/SolidCore/Refinement/Corpus/C8.lean @@ -0,0 +1,65 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/c8.sol. Do not edit. + +import SolidCore.Refinement.Corpus.C8.Part0 +import SolidCore.Refinement.Corpus.C8.Dirty + +/-! +# c8: solar's bytecode refines SolidCore's `Main` + +`refines` proves `Refines fuel contract code (· ∈ scope s)` for `Main` in +`scripts/refinement/corpus/c8.sol`, 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, 256 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 SolidCore.Refinement.Corpus.C8 + +open SolidCore.Refinement SolidCore.Refinement.Abi + +theorem parts_ok : ∀ i < parts, partOk i = true := fun i hi => + match i, hi with + | 0, _ => part0 + | n + 1, 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 SolidCore.Refinement.Corpus.C8 diff --git a/SolidCore/Refinement/Corpus/C8/Defs.lean b/SolidCore/Refinement/Corpus/C8/Defs.lean new file mode 100644 index 00000000..d32b1ed9 --- /dev/null +++ b/SolidCore/Refinement/Corpus/C8/Defs.lean @@ -0,0 +1,50 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/c8.sol. Do not edit. + +import SolidCore.Refinement.Abi +import SolidCore.Refinement.Bytecode.C8 +import SolidCore.Refinement.Source.C8 + +/-! +# The scope of c8's refinement + +256 calls: every function of `Main` in `scripts/refinement/corpus/c8.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.C8 + +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.C8.Main.runtimeNat + Bytecode.C8.Main.runtimeSize + +/-- SolidCore's checked `Main`. -/ +def contract? : Except TypeCheck.TypeError TypeCheck.CheckedContract := + TypeCheck.CheckedInput.contract Source.C8.importedSourceUnit "Main" + +/-- The functions of `Main` and their parameters. -/ +def fns : List Fn := + [⟨Bytecode.C8.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.C8 diff --git a/SolidCore/Refinement/Corpus/C8/Dirty.lean b/SolidCore/Refinement/Corpus/C8/Dirty.lean new file mode 100644 index 00000000..bf367a2b --- /dev/null +++ b/SolidCore/Refinement/Corpus/C8/Dirty.lean @@ -0,0 +1,31 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/c8.sol. Do not edit. + +import SolidCore.Refinement.Evm.Symex +import SolidCore.Refinement.Dirty.Source +import SolidCore.Refinement.Corpus.C8.Defs + +/-! +# c8: EthLib rejects every dirty argument word + +For every function of `Main` in `scripts/refinement/corpus/c8.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.C8 + +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.C8.Main.fSelector [(.uint 8)] + (by dirty_symex [code, Bytecode.C8.Main.runtimeNat, Bytecode.C8.Main.runtimeSize, Bytecode.C8.Main.fSelector]) + +end SolidCore.Refinement.Corpus.C8 diff --git a/SolidCore/Refinement/Corpus/C8/Part0.lean b/SolidCore/Refinement/Corpus/C8/Part0.lean new file mode 100644 index 00000000..c6bff256 --- /dev/null +++ b/SolidCore/Refinement/Corpus/C8/Part0.lean @@ -0,0 +1,9 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/c8.sol. Do not edit. + +import SolidCore.Refinement.Corpus.C8.Defs + +namespace SolidCore.Refinement.Corpus.C8 + +theorem part0 : partOk 0 = true := by native_decide + +end SolidCore.Refinement.Corpus.C8 diff --git a/SolidCore/Refinement/Corpus/C8/Seq.lean b/SolidCore/Refinement/Corpus/C8/Seq.lean new file mode 100644 index 00000000..9415f47d --- /dev/null +++ b/SolidCore/Refinement/Corpus/C8/Seq.lean @@ -0,0 +1,54 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/c8.sol. Do not edit. + +import SolidCore.Refinement.Corpus.C8 +import SolidCore.Refinement.Corpus.C8.SeqDefs +import SolidCore.Refinement.Corpus.C8.SeqPart0 + +/-! +# c8: 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/c8.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.C8 + +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.C8 diff --git a/SolidCore/Refinement/Corpus/C8/SeqDefs.lean b/SolidCore/Refinement/Corpus/C8/SeqDefs.lean new file mode 100644 index 00000000..df562c0d --- /dev/null +++ b/SolidCore/Refinement/Corpus/C8/SeqDefs.lean @@ -0,0 +1,59 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/c8.sol. Do not edit. + +import SolidCore.Refinement.Seq.Check +import SolidCore.Refinement.Corpus.C8.Defs +import SolidCore.Refinement.Corpus.C8.SeqStates + +/-! +# The certificate of c8'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.C8 + +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.C8 diff --git a/SolidCore/Refinement/Corpus/C8/SeqPart0.lean b/SolidCore/Refinement/Corpus/C8/SeqPart0.lean new file mode 100644 index 00000000..11403560 --- /dev/null +++ b/SolidCore/Refinement/Corpus/C8/SeqPart0.lean @@ -0,0 +1,9 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/c8.sol. Do not edit. + +import SolidCore.Refinement.Corpus.C8.SeqDefs + +namespace SolidCore.Refinement.Corpus.C8 + +theorem seqPart0 : seqPartOk 0 = true := by native_decide + +end SolidCore.Refinement.Corpus.C8 diff --git a/SolidCore/Refinement/Corpus/C8/SeqStates.lean b/SolidCore/Refinement/Corpus/C8/SeqStates.lean new file mode 100644 index 00000000..2f8331ad --- /dev/null +++ b/SolidCore/Refinement/Corpus/C8/SeqStates.lean @@ -0,0 +1,21 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/c8.sol. Do not edit. + +/-! +# The storages c8's clean calls reach + +The certificate of the sequence refinement of `Main` in `scripts/refinement/corpus/c8.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.C8 + +/-- 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.C8 diff --git a/SolidCore/Refinement/Corpus/C9.lean b/SolidCore/Refinement/Corpus/C9.lean new file mode 100644 index 00000000..9c61dbbf --- /dev/null +++ b/SolidCore/Refinement/Corpus/C9.lean @@ -0,0 +1,65 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/c9.sol. Do not edit. + +import SolidCore.Refinement.Corpus.C9.Part0 +import SolidCore.Refinement.Corpus.C9.Dirty + +/-! +# c9: solar's bytecode refines SolidCore's `Main` + +`refines` proves `Refines fuel contract code (· ∈ scope s)` for `Main` in +`scripts/refinement/corpus/c9.sol`, 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, 256 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 SolidCore.Refinement.Corpus.C9 + +open SolidCore.Refinement SolidCore.Refinement.Abi + +theorem parts_ok : ∀ i < parts, partOk i = true := fun i hi => + match i, hi with + | 0, _ => part0 + | n + 1, 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 SolidCore.Refinement.Corpus.C9 diff --git a/SolidCore/Refinement/Corpus/C9/Defs.lean b/SolidCore/Refinement/Corpus/C9/Defs.lean new file mode 100644 index 00000000..95e83b65 --- /dev/null +++ b/SolidCore/Refinement/Corpus/C9/Defs.lean @@ -0,0 +1,50 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/c9.sol. Do not edit. + +import SolidCore.Refinement.Abi +import SolidCore.Refinement.Bytecode.C9 +import SolidCore.Refinement.Source.C9 + +/-! +# The scope of c9's refinement + +256 calls: every function of `Main` in `scripts/refinement/corpus/c9.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.C9 + +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.C9.Main.runtimeNat + Bytecode.C9.Main.runtimeSize + +/-- SolidCore's checked `Main`. -/ +def contract? : Except TypeCheck.TypeError TypeCheck.CheckedContract := + TypeCheck.CheckedInput.contract Source.C9.importedSourceUnit "Main" + +/-- The functions of `Main` and their parameters. -/ +def fns : List Fn := + [⟨Bytecode.C9.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.C9 diff --git a/SolidCore/Refinement/Corpus/C9/Dirty.lean b/SolidCore/Refinement/Corpus/C9/Dirty.lean new file mode 100644 index 00000000..bef67f6c --- /dev/null +++ b/SolidCore/Refinement/Corpus/C9/Dirty.lean @@ -0,0 +1,31 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/c9.sol. Do not edit. + +import SolidCore.Refinement.Evm.Symex +import SolidCore.Refinement.Dirty.Source +import SolidCore.Refinement.Corpus.C9.Defs + +/-! +# c9: EthLib rejects every dirty argument word + +For every function of `Main` in `scripts/refinement/corpus/c9.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.C9 + +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.C9.Main.fSelector [(.uint 8)] + (by dirty_symex [code, Bytecode.C9.Main.runtimeNat, Bytecode.C9.Main.runtimeSize, Bytecode.C9.Main.fSelector]) + +end SolidCore.Refinement.Corpus.C9 diff --git a/SolidCore/Refinement/Corpus/C9/Part0.lean b/SolidCore/Refinement/Corpus/C9/Part0.lean new file mode 100644 index 00000000..e911e6d4 --- /dev/null +++ b/SolidCore/Refinement/Corpus/C9/Part0.lean @@ -0,0 +1,9 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/c9.sol. Do not edit. + +import SolidCore.Refinement.Corpus.C9.Defs + +namespace SolidCore.Refinement.Corpus.C9 + +theorem part0 : partOk 0 = true := by native_decide + +end SolidCore.Refinement.Corpus.C9 diff --git a/SolidCore/Refinement/Corpus/C9/Seq.lean b/SolidCore/Refinement/Corpus/C9/Seq.lean new file mode 100644 index 00000000..6b9e4015 --- /dev/null +++ b/SolidCore/Refinement/Corpus/C9/Seq.lean @@ -0,0 +1,89 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/c9.sol. Do not edit. + +import SolidCore.Refinement.Corpus.C9 +import SolidCore.Refinement.Corpus.C9.SeqDefs +import SolidCore.Refinement.Corpus.C9.SeqPart0 +import SolidCore.Refinement.Corpus.C9.SeqPart1 +import SolidCore.Refinement.Corpus.C9.SeqPart2 +import SolidCore.Refinement.Corpus.C9.SeqPart3 +import SolidCore.Refinement.Corpus.C9.SeqPart4 +import SolidCore.Refinement.Corpus.C9.SeqPart5 +import SolidCore.Refinement.Corpus.C9.SeqPart6 +import SolidCore.Refinement.Corpus.C9.SeqPart7 +import SolidCore.Refinement.Corpus.C9.SeqPart8 +import SolidCore.Refinement.Corpus.C9.SeqPart9 +import SolidCore.Refinement.Corpus.C9.SeqPart10 +import SolidCore.Refinement.Corpus.C9.SeqPart11 +import SolidCore.Refinement.Corpus.C9.SeqPart12 +import SolidCore.Refinement.Corpus.C9.SeqPart13 +import SolidCore.Refinement.Corpus.C9.SeqPart14 +import SolidCore.Refinement.Corpus.C9.SeqPart15 +import SolidCore.Refinement.Corpus.C9.SeqPart16 + +/-! +# c9: 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/c9.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), 257 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.C9 + +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 + | 16, _ => seqPart16 + | n + 17, 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.C9 diff --git a/SolidCore/Refinement/Corpus/C9/SeqDefs.lean b/SolidCore/Refinement/Corpus/C9/SeqDefs.lean new file mode 100644 index 00000000..8e80dab8 --- /dev/null +++ b/SolidCore/Refinement/Corpus/C9/SeqDefs.lean @@ -0,0 +1,60 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/c9.sol. Do not edit. + +import SolidCore.Refinement.Seq.Check +import SolidCore.Refinement.Corpus.C9.Defs +import SolidCore.Refinement.Corpus.C9.SeqStates + +/-! +# The certificate of c9'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), 257 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, 65792 calls, in 17 part(s), and every dirty call once +per storage. +-/ + +namespace SolidCore.Refinement.Corpus.C9 + +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 := 17 + +/-- 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.C9 diff --git a/SolidCore/Refinement/Corpus/C9/SeqPart0.lean b/SolidCore/Refinement/Corpus/C9/SeqPart0.lean new file mode 100644 index 00000000..54f346c0 --- /dev/null +++ b/SolidCore/Refinement/Corpus/C9/SeqPart0.lean @@ -0,0 +1,9 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/c9.sol. Do not edit. + +import SolidCore.Refinement.Corpus.C9.SeqDefs + +namespace SolidCore.Refinement.Corpus.C9 + +theorem seqPart0 : seqPartOk 0 = true := by native_decide + +end SolidCore.Refinement.Corpus.C9 diff --git a/SolidCore/Refinement/Corpus/C9/SeqPart1.lean b/SolidCore/Refinement/Corpus/C9/SeqPart1.lean new file mode 100644 index 00000000..0355aabc --- /dev/null +++ b/SolidCore/Refinement/Corpus/C9/SeqPart1.lean @@ -0,0 +1,9 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/c9.sol. Do not edit. + +import SolidCore.Refinement.Corpus.C9.SeqDefs + +namespace SolidCore.Refinement.Corpus.C9 + +theorem seqPart1 : seqPartOk 1 = true := by native_decide + +end SolidCore.Refinement.Corpus.C9 diff --git a/SolidCore/Refinement/Corpus/C9/SeqPart10.lean b/SolidCore/Refinement/Corpus/C9/SeqPart10.lean new file mode 100644 index 00000000..30c0c05d --- /dev/null +++ b/SolidCore/Refinement/Corpus/C9/SeqPart10.lean @@ -0,0 +1,9 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/c9.sol. Do not edit. + +import SolidCore.Refinement.Corpus.C9.SeqDefs + +namespace SolidCore.Refinement.Corpus.C9 + +theorem seqPart10 : seqPartOk 10 = true := by native_decide + +end SolidCore.Refinement.Corpus.C9 diff --git a/SolidCore/Refinement/Corpus/C9/SeqPart11.lean b/SolidCore/Refinement/Corpus/C9/SeqPart11.lean new file mode 100644 index 00000000..027ab8ec --- /dev/null +++ b/SolidCore/Refinement/Corpus/C9/SeqPart11.lean @@ -0,0 +1,9 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/c9.sol. Do not edit. + +import SolidCore.Refinement.Corpus.C9.SeqDefs + +namespace SolidCore.Refinement.Corpus.C9 + +theorem seqPart11 : seqPartOk 11 = true := by native_decide + +end SolidCore.Refinement.Corpus.C9 diff --git a/SolidCore/Refinement/Corpus/C9/SeqPart12.lean b/SolidCore/Refinement/Corpus/C9/SeqPart12.lean new file mode 100644 index 00000000..07bd6ca0 --- /dev/null +++ b/SolidCore/Refinement/Corpus/C9/SeqPart12.lean @@ -0,0 +1,9 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/c9.sol. Do not edit. + +import SolidCore.Refinement.Corpus.C9.SeqDefs + +namespace SolidCore.Refinement.Corpus.C9 + +theorem seqPart12 : seqPartOk 12 = true := by native_decide + +end SolidCore.Refinement.Corpus.C9 diff --git a/SolidCore/Refinement/Corpus/C9/SeqPart13.lean b/SolidCore/Refinement/Corpus/C9/SeqPart13.lean new file mode 100644 index 00000000..9afe4ea4 --- /dev/null +++ b/SolidCore/Refinement/Corpus/C9/SeqPart13.lean @@ -0,0 +1,9 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/c9.sol. Do not edit. + +import SolidCore.Refinement.Corpus.C9.SeqDefs + +namespace SolidCore.Refinement.Corpus.C9 + +theorem seqPart13 : seqPartOk 13 = true := by native_decide + +end SolidCore.Refinement.Corpus.C9 diff --git a/SolidCore/Refinement/Corpus/C9/SeqPart14.lean b/SolidCore/Refinement/Corpus/C9/SeqPart14.lean new file mode 100644 index 00000000..cbe7a953 --- /dev/null +++ b/SolidCore/Refinement/Corpus/C9/SeqPart14.lean @@ -0,0 +1,9 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/c9.sol. Do not edit. + +import SolidCore.Refinement.Corpus.C9.SeqDefs + +namespace SolidCore.Refinement.Corpus.C9 + +theorem seqPart14 : seqPartOk 14 = true := by native_decide + +end SolidCore.Refinement.Corpus.C9 diff --git a/SolidCore/Refinement/Corpus/C9/SeqPart15.lean b/SolidCore/Refinement/Corpus/C9/SeqPart15.lean new file mode 100644 index 00000000..72b90cfe --- /dev/null +++ b/SolidCore/Refinement/Corpus/C9/SeqPart15.lean @@ -0,0 +1,9 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/c9.sol. Do not edit. + +import SolidCore.Refinement.Corpus.C9.SeqDefs + +namespace SolidCore.Refinement.Corpus.C9 + +theorem seqPart15 : seqPartOk 15 = true := by native_decide + +end SolidCore.Refinement.Corpus.C9 diff --git a/SolidCore/Refinement/Corpus/C9/SeqPart16.lean b/SolidCore/Refinement/Corpus/C9/SeqPart16.lean new file mode 100644 index 00000000..592e4ddf --- /dev/null +++ b/SolidCore/Refinement/Corpus/C9/SeqPart16.lean @@ -0,0 +1,9 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/c9.sol. Do not edit. + +import SolidCore.Refinement.Corpus.C9.SeqDefs + +namespace SolidCore.Refinement.Corpus.C9 + +theorem seqPart16 : seqPartOk 16 = true := by native_decide + +end SolidCore.Refinement.Corpus.C9 diff --git a/SolidCore/Refinement/Corpus/C9/SeqPart2.lean b/SolidCore/Refinement/Corpus/C9/SeqPart2.lean new file mode 100644 index 00000000..762bb38d --- /dev/null +++ b/SolidCore/Refinement/Corpus/C9/SeqPart2.lean @@ -0,0 +1,9 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/c9.sol. Do not edit. + +import SolidCore.Refinement.Corpus.C9.SeqDefs + +namespace SolidCore.Refinement.Corpus.C9 + +theorem seqPart2 : seqPartOk 2 = true := by native_decide + +end SolidCore.Refinement.Corpus.C9 diff --git a/SolidCore/Refinement/Corpus/C9/SeqPart3.lean b/SolidCore/Refinement/Corpus/C9/SeqPart3.lean new file mode 100644 index 00000000..d5d7d62a --- /dev/null +++ b/SolidCore/Refinement/Corpus/C9/SeqPart3.lean @@ -0,0 +1,9 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/c9.sol. Do not edit. + +import SolidCore.Refinement.Corpus.C9.SeqDefs + +namespace SolidCore.Refinement.Corpus.C9 + +theorem seqPart3 : seqPartOk 3 = true := by native_decide + +end SolidCore.Refinement.Corpus.C9 diff --git a/SolidCore/Refinement/Corpus/C9/SeqPart4.lean b/SolidCore/Refinement/Corpus/C9/SeqPart4.lean new file mode 100644 index 00000000..df7c321a --- /dev/null +++ b/SolidCore/Refinement/Corpus/C9/SeqPart4.lean @@ -0,0 +1,9 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/c9.sol. Do not edit. + +import SolidCore.Refinement.Corpus.C9.SeqDefs + +namespace SolidCore.Refinement.Corpus.C9 + +theorem seqPart4 : seqPartOk 4 = true := by native_decide + +end SolidCore.Refinement.Corpus.C9 diff --git a/SolidCore/Refinement/Corpus/C9/SeqPart5.lean b/SolidCore/Refinement/Corpus/C9/SeqPart5.lean new file mode 100644 index 00000000..d389a597 --- /dev/null +++ b/SolidCore/Refinement/Corpus/C9/SeqPart5.lean @@ -0,0 +1,9 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/c9.sol. Do not edit. + +import SolidCore.Refinement.Corpus.C9.SeqDefs + +namespace SolidCore.Refinement.Corpus.C9 + +theorem seqPart5 : seqPartOk 5 = true := by native_decide + +end SolidCore.Refinement.Corpus.C9 diff --git a/SolidCore/Refinement/Corpus/C9/SeqPart6.lean b/SolidCore/Refinement/Corpus/C9/SeqPart6.lean new file mode 100644 index 00000000..11ed46f2 --- /dev/null +++ b/SolidCore/Refinement/Corpus/C9/SeqPart6.lean @@ -0,0 +1,9 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/c9.sol. Do not edit. + +import SolidCore.Refinement.Corpus.C9.SeqDefs + +namespace SolidCore.Refinement.Corpus.C9 + +theorem seqPart6 : seqPartOk 6 = true := by native_decide + +end SolidCore.Refinement.Corpus.C9 diff --git a/SolidCore/Refinement/Corpus/C9/SeqPart7.lean b/SolidCore/Refinement/Corpus/C9/SeqPart7.lean new file mode 100644 index 00000000..27c30521 --- /dev/null +++ b/SolidCore/Refinement/Corpus/C9/SeqPart7.lean @@ -0,0 +1,9 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/c9.sol. Do not edit. + +import SolidCore.Refinement.Corpus.C9.SeqDefs + +namespace SolidCore.Refinement.Corpus.C9 + +theorem seqPart7 : seqPartOk 7 = true := by native_decide + +end SolidCore.Refinement.Corpus.C9 diff --git a/SolidCore/Refinement/Corpus/C9/SeqPart8.lean b/SolidCore/Refinement/Corpus/C9/SeqPart8.lean new file mode 100644 index 00000000..b709b442 --- /dev/null +++ b/SolidCore/Refinement/Corpus/C9/SeqPart8.lean @@ -0,0 +1,9 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/c9.sol. Do not edit. + +import SolidCore.Refinement.Corpus.C9.SeqDefs + +namespace SolidCore.Refinement.Corpus.C9 + +theorem seqPart8 : seqPartOk 8 = true := by native_decide + +end SolidCore.Refinement.Corpus.C9 diff --git a/SolidCore/Refinement/Corpus/C9/SeqPart9.lean b/SolidCore/Refinement/Corpus/C9/SeqPart9.lean new file mode 100644 index 00000000..d7a38cc7 --- /dev/null +++ b/SolidCore/Refinement/Corpus/C9/SeqPart9.lean @@ -0,0 +1,9 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/c9.sol. Do not edit. + +import SolidCore.Refinement.Corpus.C9.SeqDefs + +namespace SolidCore.Refinement.Corpus.C9 + +theorem seqPart9 : seqPartOk 9 = true := by native_decide + +end SolidCore.Refinement.Corpus.C9 diff --git a/SolidCore/Refinement/Corpus/C9/SeqStates.lean b/SolidCore/Refinement/Corpus/C9/SeqStates.lean new file mode 100644 index 00000000..3a62ff21 --- /dev/null +++ b/SolidCore/Refinement/Corpus/C9/SeqStates.lean @@ -0,0 +1,277 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/c9.sol. Do not edit. + +/-! +# The storages c9's clean calls reach + +The certificate of the sequence refinement of `Main` in `scripts/refinement/corpus/c9.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.C9 + +/-- The slots a reached storage holds a word for. -/ +def seqKeys : List Nat := [0, 18569430475105882587588266137607568536673111973893317399460219858819262702947, 18569430475105882587588266137607568536673111973893317399460219858819262702948] + +/-- The reached storages, by level, from level 1. -/ +def seqLevels : List (List (List (Nat × Nat))) := [ + [[(0, 2), (18569430475105882587588266137607568536673111973893317399460219858819262702948, 5)], + [(0, 2), (18569430475105882587588266137607568536673111973893317399460219858819262702947, 1), (18569430475105882587588266137607568536673111973893317399460219858819262702948, 5)], + [(0, 2), (18569430475105882587588266137607568536673111973893317399460219858819262702947, 2), (18569430475105882587588266137607568536673111973893317399460219858819262702948, 5)], + [(0, 2), (18569430475105882587588266137607568536673111973893317399460219858819262702947, 3), (18569430475105882587588266137607568536673111973893317399460219858819262702948, 5)], + [(0, 2), (18569430475105882587588266137607568536673111973893317399460219858819262702947, 4), (18569430475105882587588266137607568536673111973893317399460219858819262702948, 5)], + [(0, 2), (18569430475105882587588266137607568536673111973893317399460219858819262702947, 5), (18569430475105882587588266137607568536673111973893317399460219858819262702948, 5)], + [(0, 2), (18569430475105882587588266137607568536673111973893317399460219858819262702947, 6), (18569430475105882587588266137607568536673111973893317399460219858819262702948, 5)], + [(0, 2), (18569430475105882587588266137607568536673111973893317399460219858819262702947, 7), (18569430475105882587588266137607568536673111973893317399460219858819262702948, 5)], + [(0, 2), (18569430475105882587588266137607568536673111973893317399460219858819262702947, 8), (18569430475105882587588266137607568536673111973893317399460219858819262702948, 5)], + [(0, 2), (18569430475105882587588266137607568536673111973893317399460219858819262702947, 9), (18569430475105882587588266137607568536673111973893317399460219858819262702948, 5)], + [(0, 2), (18569430475105882587588266137607568536673111973893317399460219858819262702947, 10), (18569430475105882587588266137607568536673111973893317399460219858819262702948, 5)], + [(0, 2), (18569430475105882587588266137607568536673111973893317399460219858819262702947, 11), (18569430475105882587588266137607568536673111973893317399460219858819262702948, 5)], + [(0, 2), (18569430475105882587588266137607568536673111973893317399460219858819262702947, 12), (18569430475105882587588266137607568536673111973893317399460219858819262702948, 5)], + [(0, 2), (18569430475105882587588266137607568536673111973893317399460219858819262702947, 13), (18569430475105882587588266137607568536673111973893317399460219858819262702948, 5)], + [(0, 2), (18569430475105882587588266137607568536673111973893317399460219858819262702947, 14), (18569430475105882587588266137607568536673111973893317399460219858819262702948, 5)], + [(0, 2), (18569430475105882587588266137607568536673111973893317399460219858819262702947, 15), (18569430475105882587588266137607568536673111973893317399460219858819262702948, 5)], + [(0, 2), (18569430475105882587588266137607568536673111973893317399460219858819262702947, 16), (18569430475105882587588266137607568536673111973893317399460219858819262702948, 5)], + [(0, 2), (18569430475105882587588266137607568536673111973893317399460219858819262702947, 17), (18569430475105882587588266137607568536673111973893317399460219858819262702948, 5)], + [(0, 2), (18569430475105882587588266137607568536673111973893317399460219858819262702947, 18), (18569430475105882587588266137607568536673111973893317399460219858819262702948, 5)], + [(0, 2), (18569430475105882587588266137607568536673111973893317399460219858819262702947, 19), (18569430475105882587588266137607568536673111973893317399460219858819262702948, 5)], + [(0, 2), (18569430475105882587588266137607568536673111973893317399460219858819262702947, 20), (18569430475105882587588266137607568536673111973893317399460219858819262702948, 5)], + [(0, 2), (18569430475105882587588266137607568536673111973893317399460219858819262702947, 21), (18569430475105882587588266137607568536673111973893317399460219858819262702948, 5)], + [(0, 2), (18569430475105882587588266137607568536673111973893317399460219858819262702947, 22), (18569430475105882587588266137607568536673111973893317399460219858819262702948, 5)], + [(0, 2), (18569430475105882587588266137607568536673111973893317399460219858819262702947, 23), (18569430475105882587588266137607568536673111973893317399460219858819262702948, 5)], + [(0, 2), (18569430475105882587588266137607568536673111973893317399460219858819262702947, 24), (18569430475105882587588266137607568536673111973893317399460219858819262702948, 5)], + [(0, 2), (18569430475105882587588266137607568536673111973893317399460219858819262702947, 25), (18569430475105882587588266137607568536673111973893317399460219858819262702948, 5)], + [(0, 2), (18569430475105882587588266137607568536673111973893317399460219858819262702947, 26), (18569430475105882587588266137607568536673111973893317399460219858819262702948, 5)], + [(0, 2), (18569430475105882587588266137607568536673111973893317399460219858819262702947, 27), (18569430475105882587588266137607568536673111973893317399460219858819262702948, 5)], + [(0, 2), (18569430475105882587588266137607568536673111973893317399460219858819262702947, 28), (18569430475105882587588266137607568536673111973893317399460219858819262702948, 5)], + [(0, 2), (18569430475105882587588266137607568536673111973893317399460219858819262702947, 29), (18569430475105882587588266137607568536673111973893317399460219858819262702948, 5)], + [(0, 2), (18569430475105882587588266137607568536673111973893317399460219858819262702947, 30), (18569430475105882587588266137607568536673111973893317399460219858819262702948, 5)], + [(0, 2), (18569430475105882587588266137607568536673111973893317399460219858819262702947, 31), (18569430475105882587588266137607568536673111973893317399460219858819262702948, 5)], + [(0, 2), (18569430475105882587588266137607568536673111973893317399460219858819262702947, 32), (18569430475105882587588266137607568536673111973893317399460219858819262702948, 5)], + [(0, 2), (18569430475105882587588266137607568536673111973893317399460219858819262702947, 33), (18569430475105882587588266137607568536673111973893317399460219858819262702948, 5)], + [(0, 2), (18569430475105882587588266137607568536673111973893317399460219858819262702947, 34), (18569430475105882587588266137607568536673111973893317399460219858819262702948, 5)], + [(0, 2), (18569430475105882587588266137607568536673111973893317399460219858819262702947, 35), (18569430475105882587588266137607568536673111973893317399460219858819262702948, 5)], + [(0, 2), (18569430475105882587588266137607568536673111973893317399460219858819262702947, 36), (18569430475105882587588266137607568536673111973893317399460219858819262702948, 5)], + [(0, 2), (18569430475105882587588266137607568536673111973893317399460219858819262702947, 37), (18569430475105882587588266137607568536673111973893317399460219858819262702948, 5)], + [(0, 2), (18569430475105882587588266137607568536673111973893317399460219858819262702947, 38), (18569430475105882587588266137607568536673111973893317399460219858819262702948, 5)], + [(0, 2), (18569430475105882587588266137607568536673111973893317399460219858819262702947, 39), (18569430475105882587588266137607568536673111973893317399460219858819262702948, 5)], + [(0, 2), (18569430475105882587588266137607568536673111973893317399460219858819262702947, 40), (18569430475105882587588266137607568536673111973893317399460219858819262702948, 5)], + [(0, 2), (18569430475105882587588266137607568536673111973893317399460219858819262702947, 41), (18569430475105882587588266137607568536673111973893317399460219858819262702948, 5)], + [(0, 2), (18569430475105882587588266137607568536673111973893317399460219858819262702947, 42), (18569430475105882587588266137607568536673111973893317399460219858819262702948, 5)], + [(0, 2), (18569430475105882587588266137607568536673111973893317399460219858819262702947, 43), (18569430475105882587588266137607568536673111973893317399460219858819262702948, 5)], + [(0, 2), (18569430475105882587588266137607568536673111973893317399460219858819262702947, 44), (18569430475105882587588266137607568536673111973893317399460219858819262702948, 5)], + [(0, 2), (18569430475105882587588266137607568536673111973893317399460219858819262702947, 45), (18569430475105882587588266137607568536673111973893317399460219858819262702948, 5)], + [(0, 2), (18569430475105882587588266137607568536673111973893317399460219858819262702947, 46), (18569430475105882587588266137607568536673111973893317399460219858819262702948, 5)], + [(0, 2), (18569430475105882587588266137607568536673111973893317399460219858819262702947, 47), (18569430475105882587588266137607568536673111973893317399460219858819262702948, 5)], + [(0, 2), (18569430475105882587588266137607568536673111973893317399460219858819262702947, 48), (18569430475105882587588266137607568536673111973893317399460219858819262702948, 5)], + [(0, 2), (18569430475105882587588266137607568536673111973893317399460219858819262702947, 49), (18569430475105882587588266137607568536673111973893317399460219858819262702948, 5)], + [(0, 2), (18569430475105882587588266137607568536673111973893317399460219858819262702947, 50), (18569430475105882587588266137607568536673111973893317399460219858819262702948, 5)], + [(0, 2), (18569430475105882587588266137607568536673111973893317399460219858819262702947, 51), (18569430475105882587588266137607568536673111973893317399460219858819262702948, 5)], + [(0, 2), (18569430475105882587588266137607568536673111973893317399460219858819262702947, 52), (18569430475105882587588266137607568536673111973893317399460219858819262702948, 5)], + [(0, 2), (18569430475105882587588266137607568536673111973893317399460219858819262702947, 53), (18569430475105882587588266137607568536673111973893317399460219858819262702948, 5)], + [(0, 2), (18569430475105882587588266137607568536673111973893317399460219858819262702947, 54), (18569430475105882587588266137607568536673111973893317399460219858819262702948, 5)], + [(0, 2), (18569430475105882587588266137607568536673111973893317399460219858819262702947, 55), (18569430475105882587588266137607568536673111973893317399460219858819262702948, 5)], + [(0, 2), (18569430475105882587588266137607568536673111973893317399460219858819262702947, 56), (18569430475105882587588266137607568536673111973893317399460219858819262702948, 5)], + [(0, 2), (18569430475105882587588266137607568536673111973893317399460219858819262702947, 57), (18569430475105882587588266137607568536673111973893317399460219858819262702948, 5)], + [(0, 2), (18569430475105882587588266137607568536673111973893317399460219858819262702947, 58), (18569430475105882587588266137607568536673111973893317399460219858819262702948, 5)], + [(0, 2), (18569430475105882587588266137607568536673111973893317399460219858819262702947, 59), (18569430475105882587588266137607568536673111973893317399460219858819262702948, 5)], + [(0, 2), (18569430475105882587588266137607568536673111973893317399460219858819262702947, 60), (18569430475105882587588266137607568536673111973893317399460219858819262702948, 5)], + [(0, 2), (18569430475105882587588266137607568536673111973893317399460219858819262702947, 61), (18569430475105882587588266137607568536673111973893317399460219858819262702948, 5)], + [(0, 2), (18569430475105882587588266137607568536673111973893317399460219858819262702947, 62), (18569430475105882587588266137607568536673111973893317399460219858819262702948, 5)], + [(0, 2), (18569430475105882587588266137607568536673111973893317399460219858819262702947, 63), (18569430475105882587588266137607568536673111973893317399460219858819262702948, 5)], + [(0, 2), (18569430475105882587588266137607568536673111973893317399460219858819262702947, 64), (18569430475105882587588266137607568536673111973893317399460219858819262702948, 5)], + [(0, 2), (18569430475105882587588266137607568536673111973893317399460219858819262702947, 65), (18569430475105882587588266137607568536673111973893317399460219858819262702948, 5)], + [(0, 2), (18569430475105882587588266137607568536673111973893317399460219858819262702947, 66), (18569430475105882587588266137607568536673111973893317399460219858819262702948, 5)], + [(0, 2), (18569430475105882587588266137607568536673111973893317399460219858819262702947, 67), (18569430475105882587588266137607568536673111973893317399460219858819262702948, 5)], + [(0, 2), (18569430475105882587588266137607568536673111973893317399460219858819262702947, 68), (18569430475105882587588266137607568536673111973893317399460219858819262702948, 5)], + [(0, 2), (18569430475105882587588266137607568536673111973893317399460219858819262702947, 69), (18569430475105882587588266137607568536673111973893317399460219858819262702948, 5)], + [(0, 2), (18569430475105882587588266137607568536673111973893317399460219858819262702947, 70), (18569430475105882587588266137607568536673111973893317399460219858819262702948, 5)], + [(0, 2), (18569430475105882587588266137607568536673111973893317399460219858819262702947, 71), (18569430475105882587588266137607568536673111973893317399460219858819262702948, 5)], + [(0, 2), (18569430475105882587588266137607568536673111973893317399460219858819262702947, 72), (18569430475105882587588266137607568536673111973893317399460219858819262702948, 5)], + [(0, 2), (18569430475105882587588266137607568536673111973893317399460219858819262702947, 73), (18569430475105882587588266137607568536673111973893317399460219858819262702948, 5)], + [(0, 2), (18569430475105882587588266137607568536673111973893317399460219858819262702947, 74), (18569430475105882587588266137607568536673111973893317399460219858819262702948, 5)], + [(0, 2), (18569430475105882587588266137607568536673111973893317399460219858819262702947, 75), (18569430475105882587588266137607568536673111973893317399460219858819262702948, 5)], + [(0, 2), (18569430475105882587588266137607568536673111973893317399460219858819262702947, 76), (18569430475105882587588266137607568536673111973893317399460219858819262702948, 5)], + [(0, 2), (18569430475105882587588266137607568536673111973893317399460219858819262702947, 77), (18569430475105882587588266137607568536673111973893317399460219858819262702948, 5)], + [(0, 2), (18569430475105882587588266137607568536673111973893317399460219858819262702947, 78), (18569430475105882587588266137607568536673111973893317399460219858819262702948, 5)], + [(0, 2), (18569430475105882587588266137607568536673111973893317399460219858819262702947, 79), (18569430475105882587588266137607568536673111973893317399460219858819262702948, 5)], + [(0, 2), (18569430475105882587588266137607568536673111973893317399460219858819262702947, 80), (18569430475105882587588266137607568536673111973893317399460219858819262702948, 5)], + [(0, 2), (18569430475105882587588266137607568536673111973893317399460219858819262702947, 81), (18569430475105882587588266137607568536673111973893317399460219858819262702948, 5)], + [(0, 2), (18569430475105882587588266137607568536673111973893317399460219858819262702947, 82), (18569430475105882587588266137607568536673111973893317399460219858819262702948, 5)], + [(0, 2), (18569430475105882587588266137607568536673111973893317399460219858819262702947, 83), (18569430475105882587588266137607568536673111973893317399460219858819262702948, 5)], + [(0, 2), (18569430475105882587588266137607568536673111973893317399460219858819262702947, 84), (18569430475105882587588266137607568536673111973893317399460219858819262702948, 5)], + [(0, 2), (18569430475105882587588266137607568536673111973893317399460219858819262702947, 85), (18569430475105882587588266137607568536673111973893317399460219858819262702948, 5)], + [(0, 2), (18569430475105882587588266137607568536673111973893317399460219858819262702947, 86), (18569430475105882587588266137607568536673111973893317399460219858819262702948, 5)], + [(0, 2), (18569430475105882587588266137607568536673111973893317399460219858819262702947, 87), (18569430475105882587588266137607568536673111973893317399460219858819262702948, 5)], + [(0, 2), (18569430475105882587588266137607568536673111973893317399460219858819262702947, 88), (18569430475105882587588266137607568536673111973893317399460219858819262702948, 5)], + [(0, 2), (18569430475105882587588266137607568536673111973893317399460219858819262702947, 89), (18569430475105882587588266137607568536673111973893317399460219858819262702948, 5)], + [(0, 2), (18569430475105882587588266137607568536673111973893317399460219858819262702947, 90), (18569430475105882587588266137607568536673111973893317399460219858819262702948, 5)], + [(0, 2), (18569430475105882587588266137607568536673111973893317399460219858819262702947, 91), (18569430475105882587588266137607568536673111973893317399460219858819262702948, 5)], + [(0, 2), (18569430475105882587588266137607568536673111973893317399460219858819262702947, 92), (18569430475105882587588266137607568536673111973893317399460219858819262702948, 5)], + [(0, 2), (18569430475105882587588266137607568536673111973893317399460219858819262702947, 93), (18569430475105882587588266137607568536673111973893317399460219858819262702948, 5)], + [(0, 2), (18569430475105882587588266137607568536673111973893317399460219858819262702947, 94), (18569430475105882587588266137607568536673111973893317399460219858819262702948, 5)], + [(0, 2), (18569430475105882587588266137607568536673111973893317399460219858819262702947, 95), (18569430475105882587588266137607568536673111973893317399460219858819262702948, 5)], + [(0, 2), (18569430475105882587588266137607568536673111973893317399460219858819262702947, 96), (18569430475105882587588266137607568536673111973893317399460219858819262702948, 5)], + [(0, 2), (18569430475105882587588266137607568536673111973893317399460219858819262702947, 97), (18569430475105882587588266137607568536673111973893317399460219858819262702948, 5)], + [(0, 2), (18569430475105882587588266137607568536673111973893317399460219858819262702947, 98), (18569430475105882587588266137607568536673111973893317399460219858819262702948, 5)], + [(0, 2), (18569430475105882587588266137607568536673111973893317399460219858819262702947, 99), (18569430475105882587588266137607568536673111973893317399460219858819262702948, 5)], + [(0, 2), (18569430475105882587588266137607568536673111973893317399460219858819262702947, 100), (18569430475105882587588266137607568536673111973893317399460219858819262702948, 5)], + [(0, 2), (18569430475105882587588266137607568536673111973893317399460219858819262702947, 101), (18569430475105882587588266137607568536673111973893317399460219858819262702948, 5)], + [(0, 2), (18569430475105882587588266137607568536673111973893317399460219858819262702947, 102), (18569430475105882587588266137607568536673111973893317399460219858819262702948, 5)], + [(0, 2), (18569430475105882587588266137607568536673111973893317399460219858819262702947, 103), (18569430475105882587588266137607568536673111973893317399460219858819262702948, 5)], + [(0, 2), (18569430475105882587588266137607568536673111973893317399460219858819262702947, 104), (18569430475105882587588266137607568536673111973893317399460219858819262702948, 5)], + [(0, 2), (18569430475105882587588266137607568536673111973893317399460219858819262702947, 105), (18569430475105882587588266137607568536673111973893317399460219858819262702948, 5)], + [(0, 2), (18569430475105882587588266137607568536673111973893317399460219858819262702947, 106), (18569430475105882587588266137607568536673111973893317399460219858819262702948, 5)], + [(0, 2), (18569430475105882587588266137607568536673111973893317399460219858819262702947, 107), (18569430475105882587588266137607568536673111973893317399460219858819262702948, 5)], + [(0, 2), (18569430475105882587588266137607568536673111973893317399460219858819262702947, 108), (18569430475105882587588266137607568536673111973893317399460219858819262702948, 5)], + [(0, 2), (18569430475105882587588266137607568536673111973893317399460219858819262702947, 109), (18569430475105882587588266137607568536673111973893317399460219858819262702948, 5)], + [(0, 2), (18569430475105882587588266137607568536673111973893317399460219858819262702947, 110), (18569430475105882587588266137607568536673111973893317399460219858819262702948, 5)], + [(0, 2), (18569430475105882587588266137607568536673111973893317399460219858819262702947, 111), (18569430475105882587588266137607568536673111973893317399460219858819262702948, 5)], + [(0, 2), (18569430475105882587588266137607568536673111973893317399460219858819262702947, 112), (18569430475105882587588266137607568536673111973893317399460219858819262702948, 5)], + [(0, 2), (18569430475105882587588266137607568536673111973893317399460219858819262702947, 113), (18569430475105882587588266137607568536673111973893317399460219858819262702948, 5)], + [(0, 2), (18569430475105882587588266137607568536673111973893317399460219858819262702947, 114), (18569430475105882587588266137607568536673111973893317399460219858819262702948, 5)], + [(0, 2), (18569430475105882587588266137607568536673111973893317399460219858819262702947, 115), (18569430475105882587588266137607568536673111973893317399460219858819262702948, 5)], + [(0, 2), (18569430475105882587588266137607568536673111973893317399460219858819262702947, 116), (18569430475105882587588266137607568536673111973893317399460219858819262702948, 5)], + [(0, 2), (18569430475105882587588266137607568536673111973893317399460219858819262702947, 117), (18569430475105882587588266137607568536673111973893317399460219858819262702948, 5)], + [(0, 2), (18569430475105882587588266137607568536673111973893317399460219858819262702947, 118), (18569430475105882587588266137607568536673111973893317399460219858819262702948, 5)], + [(0, 2), (18569430475105882587588266137607568536673111973893317399460219858819262702947, 119), (18569430475105882587588266137607568536673111973893317399460219858819262702948, 5)], + [(0, 2), (18569430475105882587588266137607568536673111973893317399460219858819262702947, 120), (18569430475105882587588266137607568536673111973893317399460219858819262702948, 5)], + [(0, 2), (18569430475105882587588266137607568536673111973893317399460219858819262702947, 121), (18569430475105882587588266137607568536673111973893317399460219858819262702948, 5)], + [(0, 2), (18569430475105882587588266137607568536673111973893317399460219858819262702947, 122), (18569430475105882587588266137607568536673111973893317399460219858819262702948, 5)], + [(0, 2), (18569430475105882587588266137607568536673111973893317399460219858819262702947, 123), (18569430475105882587588266137607568536673111973893317399460219858819262702948, 5)], + [(0, 2), (18569430475105882587588266137607568536673111973893317399460219858819262702947, 124), (18569430475105882587588266137607568536673111973893317399460219858819262702948, 5)], + [(0, 2), (18569430475105882587588266137607568536673111973893317399460219858819262702947, 125), (18569430475105882587588266137607568536673111973893317399460219858819262702948, 5)], + [(0, 2), (18569430475105882587588266137607568536673111973893317399460219858819262702947, 126), (18569430475105882587588266137607568536673111973893317399460219858819262702948, 5)], + [(0, 2), (18569430475105882587588266137607568536673111973893317399460219858819262702947, 127), (18569430475105882587588266137607568536673111973893317399460219858819262702948, 5)], + [(0, 2), (18569430475105882587588266137607568536673111973893317399460219858819262702947, 128), (18569430475105882587588266137607568536673111973893317399460219858819262702948, 5)], + [(0, 2), (18569430475105882587588266137607568536673111973893317399460219858819262702947, 129), (18569430475105882587588266137607568536673111973893317399460219858819262702948, 5)], + [(0, 2), (18569430475105882587588266137607568536673111973893317399460219858819262702947, 130), (18569430475105882587588266137607568536673111973893317399460219858819262702948, 5)], + [(0, 2), (18569430475105882587588266137607568536673111973893317399460219858819262702947, 131), (18569430475105882587588266137607568536673111973893317399460219858819262702948, 5)], + [(0, 2), (18569430475105882587588266137607568536673111973893317399460219858819262702947, 132), (18569430475105882587588266137607568536673111973893317399460219858819262702948, 5)], + [(0, 2), (18569430475105882587588266137607568536673111973893317399460219858819262702947, 133), (18569430475105882587588266137607568536673111973893317399460219858819262702948, 5)], + [(0, 2), (18569430475105882587588266137607568536673111973893317399460219858819262702947, 134), (18569430475105882587588266137607568536673111973893317399460219858819262702948, 5)], + [(0, 2), (18569430475105882587588266137607568536673111973893317399460219858819262702947, 135), (18569430475105882587588266137607568536673111973893317399460219858819262702948, 5)], + [(0, 2), (18569430475105882587588266137607568536673111973893317399460219858819262702947, 136), (18569430475105882587588266137607568536673111973893317399460219858819262702948, 5)], + [(0, 2), (18569430475105882587588266137607568536673111973893317399460219858819262702947, 137), (18569430475105882587588266137607568536673111973893317399460219858819262702948, 5)], + [(0, 2), (18569430475105882587588266137607568536673111973893317399460219858819262702947, 138), (18569430475105882587588266137607568536673111973893317399460219858819262702948, 5)], + [(0, 2), (18569430475105882587588266137607568536673111973893317399460219858819262702947, 139), (18569430475105882587588266137607568536673111973893317399460219858819262702948, 5)], + [(0, 2), (18569430475105882587588266137607568536673111973893317399460219858819262702947, 140), (18569430475105882587588266137607568536673111973893317399460219858819262702948, 5)], + [(0, 2), (18569430475105882587588266137607568536673111973893317399460219858819262702947, 141), (18569430475105882587588266137607568536673111973893317399460219858819262702948, 5)], + [(0, 2), (18569430475105882587588266137607568536673111973893317399460219858819262702947, 142), (18569430475105882587588266137607568536673111973893317399460219858819262702948, 5)], + [(0, 2), (18569430475105882587588266137607568536673111973893317399460219858819262702947, 143), (18569430475105882587588266137607568536673111973893317399460219858819262702948, 5)], + [(0, 2), (18569430475105882587588266137607568536673111973893317399460219858819262702947, 144), (18569430475105882587588266137607568536673111973893317399460219858819262702948, 5)], + [(0, 2), (18569430475105882587588266137607568536673111973893317399460219858819262702947, 145), (18569430475105882587588266137607568536673111973893317399460219858819262702948, 5)], + [(0, 2), (18569430475105882587588266137607568536673111973893317399460219858819262702947, 146), (18569430475105882587588266137607568536673111973893317399460219858819262702948, 5)], + [(0, 2), (18569430475105882587588266137607568536673111973893317399460219858819262702947, 147), (18569430475105882587588266137607568536673111973893317399460219858819262702948, 5)], + [(0, 2), (18569430475105882587588266137607568536673111973893317399460219858819262702947, 148), (18569430475105882587588266137607568536673111973893317399460219858819262702948, 5)], + [(0, 2), (18569430475105882587588266137607568536673111973893317399460219858819262702947, 149), (18569430475105882587588266137607568536673111973893317399460219858819262702948, 5)], + [(0, 2), (18569430475105882587588266137607568536673111973893317399460219858819262702947, 150), (18569430475105882587588266137607568536673111973893317399460219858819262702948, 5)], + [(0, 2), (18569430475105882587588266137607568536673111973893317399460219858819262702947, 151), (18569430475105882587588266137607568536673111973893317399460219858819262702948, 5)], + [(0, 2), (18569430475105882587588266137607568536673111973893317399460219858819262702947, 152), (18569430475105882587588266137607568536673111973893317399460219858819262702948, 5)], + [(0, 2), (18569430475105882587588266137607568536673111973893317399460219858819262702947, 153), (18569430475105882587588266137607568536673111973893317399460219858819262702948, 5)], + [(0, 2), (18569430475105882587588266137607568536673111973893317399460219858819262702947, 154), (18569430475105882587588266137607568536673111973893317399460219858819262702948, 5)], + [(0, 2), (18569430475105882587588266137607568536673111973893317399460219858819262702947, 155), (18569430475105882587588266137607568536673111973893317399460219858819262702948, 5)], + [(0, 2), (18569430475105882587588266137607568536673111973893317399460219858819262702947, 156), (18569430475105882587588266137607568536673111973893317399460219858819262702948, 5)], + [(0, 2), (18569430475105882587588266137607568536673111973893317399460219858819262702947, 157), (18569430475105882587588266137607568536673111973893317399460219858819262702948, 5)], + [(0, 2), (18569430475105882587588266137607568536673111973893317399460219858819262702947, 158), (18569430475105882587588266137607568536673111973893317399460219858819262702948, 5)], + [(0, 2), (18569430475105882587588266137607568536673111973893317399460219858819262702947, 159), (18569430475105882587588266137607568536673111973893317399460219858819262702948, 5)], + [(0, 2), (18569430475105882587588266137607568536673111973893317399460219858819262702947, 160), (18569430475105882587588266137607568536673111973893317399460219858819262702948, 5)], + [(0, 2), (18569430475105882587588266137607568536673111973893317399460219858819262702947, 161), (18569430475105882587588266137607568536673111973893317399460219858819262702948, 5)], + [(0, 2), (18569430475105882587588266137607568536673111973893317399460219858819262702947, 162), (18569430475105882587588266137607568536673111973893317399460219858819262702948, 5)], + [(0, 2), (18569430475105882587588266137607568536673111973893317399460219858819262702947, 163), (18569430475105882587588266137607568536673111973893317399460219858819262702948, 5)], + [(0, 2), (18569430475105882587588266137607568536673111973893317399460219858819262702947, 164), (18569430475105882587588266137607568536673111973893317399460219858819262702948, 5)], + [(0, 2), (18569430475105882587588266137607568536673111973893317399460219858819262702947, 165), (18569430475105882587588266137607568536673111973893317399460219858819262702948, 5)], + [(0, 2), (18569430475105882587588266137607568536673111973893317399460219858819262702947, 166), (18569430475105882587588266137607568536673111973893317399460219858819262702948, 5)], + [(0, 2), (18569430475105882587588266137607568536673111973893317399460219858819262702947, 167), (18569430475105882587588266137607568536673111973893317399460219858819262702948, 5)], + [(0, 2), (18569430475105882587588266137607568536673111973893317399460219858819262702947, 168), (18569430475105882587588266137607568536673111973893317399460219858819262702948, 5)], + [(0, 2), (18569430475105882587588266137607568536673111973893317399460219858819262702947, 169), (18569430475105882587588266137607568536673111973893317399460219858819262702948, 5)], + [(0, 2), (18569430475105882587588266137607568536673111973893317399460219858819262702947, 170), (18569430475105882587588266137607568536673111973893317399460219858819262702948, 5)], + [(0, 2), (18569430475105882587588266137607568536673111973893317399460219858819262702947, 171), (18569430475105882587588266137607568536673111973893317399460219858819262702948, 5)], + [(0, 2), (18569430475105882587588266137607568536673111973893317399460219858819262702947, 172), (18569430475105882587588266137607568536673111973893317399460219858819262702948, 5)], + [(0, 2), (18569430475105882587588266137607568536673111973893317399460219858819262702947, 173), (18569430475105882587588266137607568536673111973893317399460219858819262702948, 5)], + [(0, 2), (18569430475105882587588266137607568536673111973893317399460219858819262702947, 174), (18569430475105882587588266137607568536673111973893317399460219858819262702948, 5)], + [(0, 2), (18569430475105882587588266137607568536673111973893317399460219858819262702947, 175), (18569430475105882587588266137607568536673111973893317399460219858819262702948, 5)], + [(0, 2), (18569430475105882587588266137607568536673111973893317399460219858819262702947, 176), (18569430475105882587588266137607568536673111973893317399460219858819262702948, 5)], + [(0, 2), (18569430475105882587588266137607568536673111973893317399460219858819262702947, 177), (18569430475105882587588266137607568536673111973893317399460219858819262702948, 5)], + [(0, 2), (18569430475105882587588266137607568536673111973893317399460219858819262702947, 178), (18569430475105882587588266137607568536673111973893317399460219858819262702948, 5)], + [(0, 2), (18569430475105882587588266137607568536673111973893317399460219858819262702947, 179), (18569430475105882587588266137607568536673111973893317399460219858819262702948, 5)], + [(0, 2), (18569430475105882587588266137607568536673111973893317399460219858819262702947, 180), (18569430475105882587588266137607568536673111973893317399460219858819262702948, 5)], + [(0, 2), (18569430475105882587588266137607568536673111973893317399460219858819262702947, 181), (18569430475105882587588266137607568536673111973893317399460219858819262702948, 5)], + [(0, 2), (18569430475105882587588266137607568536673111973893317399460219858819262702947, 182), (18569430475105882587588266137607568536673111973893317399460219858819262702948, 5)], + [(0, 2), (18569430475105882587588266137607568536673111973893317399460219858819262702947, 183), (18569430475105882587588266137607568536673111973893317399460219858819262702948, 5)], + [(0, 2), (18569430475105882587588266137607568536673111973893317399460219858819262702947, 184), (18569430475105882587588266137607568536673111973893317399460219858819262702948, 5)], + [(0, 2), (18569430475105882587588266137607568536673111973893317399460219858819262702947, 185), (18569430475105882587588266137607568536673111973893317399460219858819262702948, 5)], + [(0, 2), (18569430475105882587588266137607568536673111973893317399460219858819262702947, 186), (18569430475105882587588266137607568536673111973893317399460219858819262702948, 5)], + [(0, 2), (18569430475105882587588266137607568536673111973893317399460219858819262702947, 187), (18569430475105882587588266137607568536673111973893317399460219858819262702948, 5)], + [(0, 2), (18569430475105882587588266137607568536673111973893317399460219858819262702947, 188), (18569430475105882587588266137607568536673111973893317399460219858819262702948, 5)], + [(0, 2), (18569430475105882587588266137607568536673111973893317399460219858819262702947, 189), (18569430475105882587588266137607568536673111973893317399460219858819262702948, 5)], + [(0, 2), (18569430475105882587588266137607568536673111973893317399460219858819262702947, 190), (18569430475105882587588266137607568536673111973893317399460219858819262702948, 5)], + [(0, 2), (18569430475105882587588266137607568536673111973893317399460219858819262702947, 191), (18569430475105882587588266137607568536673111973893317399460219858819262702948, 5)], + [(0, 2), (18569430475105882587588266137607568536673111973893317399460219858819262702947, 192), (18569430475105882587588266137607568536673111973893317399460219858819262702948, 5)], + [(0, 2), (18569430475105882587588266137607568536673111973893317399460219858819262702947, 193), (18569430475105882587588266137607568536673111973893317399460219858819262702948, 5)], + [(0, 2), (18569430475105882587588266137607568536673111973893317399460219858819262702947, 194), (18569430475105882587588266137607568536673111973893317399460219858819262702948, 5)], + [(0, 2), (18569430475105882587588266137607568536673111973893317399460219858819262702947, 195), (18569430475105882587588266137607568536673111973893317399460219858819262702948, 5)], + [(0, 2), (18569430475105882587588266137607568536673111973893317399460219858819262702947, 196), (18569430475105882587588266137607568536673111973893317399460219858819262702948, 5)], + [(0, 2), (18569430475105882587588266137607568536673111973893317399460219858819262702947, 197), (18569430475105882587588266137607568536673111973893317399460219858819262702948, 5)], + [(0, 2), (18569430475105882587588266137607568536673111973893317399460219858819262702947, 198), (18569430475105882587588266137607568536673111973893317399460219858819262702948, 5)], + [(0, 2), (18569430475105882587588266137607568536673111973893317399460219858819262702947, 199), (18569430475105882587588266137607568536673111973893317399460219858819262702948, 5)], + [(0, 2), (18569430475105882587588266137607568536673111973893317399460219858819262702947, 200), (18569430475105882587588266137607568536673111973893317399460219858819262702948, 5)], + [(0, 2), (18569430475105882587588266137607568536673111973893317399460219858819262702947, 201), (18569430475105882587588266137607568536673111973893317399460219858819262702948, 5)], + [(0, 2), (18569430475105882587588266137607568536673111973893317399460219858819262702947, 202), (18569430475105882587588266137607568536673111973893317399460219858819262702948, 5)], + [(0, 2), (18569430475105882587588266137607568536673111973893317399460219858819262702947, 203), (18569430475105882587588266137607568536673111973893317399460219858819262702948, 5)], + [(0, 2), (18569430475105882587588266137607568536673111973893317399460219858819262702947, 204), (18569430475105882587588266137607568536673111973893317399460219858819262702948, 5)], + [(0, 2), (18569430475105882587588266137607568536673111973893317399460219858819262702947, 205), (18569430475105882587588266137607568536673111973893317399460219858819262702948, 5)], + [(0, 2), (18569430475105882587588266137607568536673111973893317399460219858819262702947, 206), (18569430475105882587588266137607568536673111973893317399460219858819262702948, 5)], + [(0, 2), (18569430475105882587588266137607568536673111973893317399460219858819262702947, 207), (18569430475105882587588266137607568536673111973893317399460219858819262702948, 5)], + [(0, 2), (18569430475105882587588266137607568536673111973893317399460219858819262702947, 208), (18569430475105882587588266137607568536673111973893317399460219858819262702948, 5)], + [(0, 2), (18569430475105882587588266137607568536673111973893317399460219858819262702947, 209), (18569430475105882587588266137607568536673111973893317399460219858819262702948, 5)], + [(0, 2), (18569430475105882587588266137607568536673111973893317399460219858819262702947, 210), (18569430475105882587588266137607568536673111973893317399460219858819262702948, 5)], + [(0, 2), (18569430475105882587588266137607568536673111973893317399460219858819262702947, 211), (18569430475105882587588266137607568536673111973893317399460219858819262702948, 5)], + [(0, 2), (18569430475105882587588266137607568536673111973893317399460219858819262702947, 212), (18569430475105882587588266137607568536673111973893317399460219858819262702948, 5)], + [(0, 2), (18569430475105882587588266137607568536673111973893317399460219858819262702947, 213), (18569430475105882587588266137607568536673111973893317399460219858819262702948, 5)], + [(0, 2), (18569430475105882587588266137607568536673111973893317399460219858819262702947, 214), (18569430475105882587588266137607568536673111973893317399460219858819262702948, 5)], + [(0, 2), (18569430475105882587588266137607568536673111973893317399460219858819262702947, 215), (18569430475105882587588266137607568536673111973893317399460219858819262702948, 5)], + [(0, 2), (18569430475105882587588266137607568536673111973893317399460219858819262702947, 216), (18569430475105882587588266137607568536673111973893317399460219858819262702948, 5)], + [(0, 2), (18569430475105882587588266137607568536673111973893317399460219858819262702947, 217), (18569430475105882587588266137607568536673111973893317399460219858819262702948, 5)], + [(0, 2), (18569430475105882587588266137607568536673111973893317399460219858819262702947, 218), (18569430475105882587588266137607568536673111973893317399460219858819262702948, 5)], + [(0, 2), (18569430475105882587588266137607568536673111973893317399460219858819262702947, 219), (18569430475105882587588266137607568536673111973893317399460219858819262702948, 5)], + [(0, 2), (18569430475105882587588266137607568536673111973893317399460219858819262702947, 220), (18569430475105882587588266137607568536673111973893317399460219858819262702948, 5)], + [(0, 2), (18569430475105882587588266137607568536673111973893317399460219858819262702947, 221), (18569430475105882587588266137607568536673111973893317399460219858819262702948, 5)], + [(0, 2), (18569430475105882587588266137607568536673111973893317399460219858819262702947, 222), (18569430475105882587588266137607568536673111973893317399460219858819262702948, 5)], + [(0, 2), (18569430475105882587588266137607568536673111973893317399460219858819262702947, 223), (18569430475105882587588266137607568536673111973893317399460219858819262702948, 5)], + [(0, 2), (18569430475105882587588266137607568536673111973893317399460219858819262702947, 224), (18569430475105882587588266137607568536673111973893317399460219858819262702948, 5)], + [(0, 2), (18569430475105882587588266137607568536673111973893317399460219858819262702947, 225), (18569430475105882587588266137607568536673111973893317399460219858819262702948, 5)], + [(0, 2), (18569430475105882587588266137607568536673111973893317399460219858819262702947, 226), (18569430475105882587588266137607568536673111973893317399460219858819262702948, 5)], + [(0, 2), (18569430475105882587588266137607568536673111973893317399460219858819262702947, 227), (18569430475105882587588266137607568536673111973893317399460219858819262702948, 5)], + [(0, 2), (18569430475105882587588266137607568536673111973893317399460219858819262702947, 228), (18569430475105882587588266137607568536673111973893317399460219858819262702948, 5)], + [(0, 2), (18569430475105882587588266137607568536673111973893317399460219858819262702947, 229), (18569430475105882587588266137607568536673111973893317399460219858819262702948, 5)], + [(0, 2), (18569430475105882587588266137607568536673111973893317399460219858819262702947, 230), (18569430475105882587588266137607568536673111973893317399460219858819262702948, 5)], + [(0, 2), (18569430475105882587588266137607568536673111973893317399460219858819262702947, 231), (18569430475105882587588266137607568536673111973893317399460219858819262702948, 5)], + [(0, 2), (18569430475105882587588266137607568536673111973893317399460219858819262702947, 232), (18569430475105882587588266137607568536673111973893317399460219858819262702948, 5)], + [(0, 2), (18569430475105882587588266137607568536673111973893317399460219858819262702947, 233), (18569430475105882587588266137607568536673111973893317399460219858819262702948, 5)], + [(0, 2), (18569430475105882587588266137607568536673111973893317399460219858819262702947, 234), (18569430475105882587588266137607568536673111973893317399460219858819262702948, 5)], + [(0, 2), (18569430475105882587588266137607568536673111973893317399460219858819262702947, 235), (18569430475105882587588266137607568536673111973893317399460219858819262702948, 5)], + [(0, 2), (18569430475105882587588266137607568536673111973893317399460219858819262702947, 236), (18569430475105882587588266137607568536673111973893317399460219858819262702948, 5)], + [(0, 2), (18569430475105882587588266137607568536673111973893317399460219858819262702947, 237), (18569430475105882587588266137607568536673111973893317399460219858819262702948, 5)], + [(0, 2), (18569430475105882587588266137607568536673111973893317399460219858819262702947, 238), (18569430475105882587588266137607568536673111973893317399460219858819262702948, 5)], + [(0, 2), (18569430475105882587588266137607568536673111973893317399460219858819262702947, 239), (18569430475105882587588266137607568536673111973893317399460219858819262702948, 5)], + [(0, 2), (18569430475105882587588266137607568536673111973893317399460219858819262702947, 240), (18569430475105882587588266137607568536673111973893317399460219858819262702948, 5)], + [(0, 2), (18569430475105882587588266137607568536673111973893317399460219858819262702947, 241), (18569430475105882587588266137607568536673111973893317399460219858819262702948, 5)], + [(0, 2), (18569430475105882587588266137607568536673111973893317399460219858819262702947, 242), (18569430475105882587588266137607568536673111973893317399460219858819262702948, 5)], + [(0, 2), (18569430475105882587588266137607568536673111973893317399460219858819262702947, 243), (18569430475105882587588266137607568536673111973893317399460219858819262702948, 5)], + [(0, 2), (18569430475105882587588266137607568536673111973893317399460219858819262702947, 244), (18569430475105882587588266137607568536673111973893317399460219858819262702948, 5)], + [(0, 2), (18569430475105882587588266137607568536673111973893317399460219858819262702947, 245), (18569430475105882587588266137607568536673111973893317399460219858819262702948, 5)], + [(0, 2), (18569430475105882587588266137607568536673111973893317399460219858819262702947, 246), (18569430475105882587588266137607568536673111973893317399460219858819262702948, 5)], + [(0, 2), (18569430475105882587588266137607568536673111973893317399460219858819262702947, 247), (18569430475105882587588266137607568536673111973893317399460219858819262702948, 5)], + [(0, 2), (18569430475105882587588266137607568536673111973893317399460219858819262702947, 248), (18569430475105882587588266137607568536673111973893317399460219858819262702948, 5)], + [(0, 2), (18569430475105882587588266137607568536673111973893317399460219858819262702947, 249), (18569430475105882587588266137607568536673111973893317399460219858819262702948, 5)], + [(0, 2), (18569430475105882587588266137607568536673111973893317399460219858819262702947, 250), (18569430475105882587588266137607568536673111973893317399460219858819262702948, 5)], + [(0, 2), (18569430475105882587588266137607568536673111973893317399460219858819262702947, 251), (18569430475105882587588266137607568536673111973893317399460219858819262702948, 5)], + [(0, 2), (18569430475105882587588266137607568536673111973893317399460219858819262702947, 252), (18569430475105882587588266137607568536673111973893317399460219858819262702948, 5)], + [(0, 2), (18569430475105882587588266137607568536673111973893317399460219858819262702947, 253), (18569430475105882587588266137607568536673111973893317399460219858819262702948, 5)], + [(0, 2), (18569430475105882587588266137607568536673111973893317399460219858819262702947, 254), (18569430475105882587588266137607568536673111973893317399460219858819262702948, 5)], + [(0, 2), (18569430475105882587588266137607568536673111973893317399460219858819262702947, 255), (18569430475105882587588266137607568536673111973893317399460219858819262702948, 5)]]] + +end SolidCore.Refinement.Corpus.C9 diff --git a/SolidCore/Refinement/Corpus/D1.lean b/SolidCore/Refinement/Corpus/D1.lean new file mode 100644 index 00000000..db4c3a4f --- /dev/null +++ b/SolidCore/Refinement/Corpus/D1.lean @@ -0,0 +1,95 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/d1.sol. Do not edit. + +import SolidCore.Refinement.Corpus.D1.Part0 +import SolidCore.Refinement.Corpus.D1.Part1 +import SolidCore.Refinement.Corpus.D1.Part2 +import SolidCore.Refinement.Corpus.D1.Part3 +import SolidCore.Refinement.Corpus.D1.Part4 +import SolidCore.Refinement.Corpus.D1.Part5 +import SolidCore.Refinement.Corpus.D1.Part6 +import SolidCore.Refinement.Corpus.D1.Part7 +import SolidCore.Refinement.Corpus.D1.Part8 +import SolidCore.Refinement.Corpus.D1.Part9 +import SolidCore.Refinement.Corpus.D1.Part10 +import SolidCore.Refinement.Corpus.D1.Part11 +import SolidCore.Refinement.Corpus.D1.Part12 +import SolidCore.Refinement.Corpus.D1.Part13 +import SolidCore.Refinement.Corpus.D1.Part14 +import SolidCore.Refinement.Corpus.D1.Part15 +import SolidCore.Refinement.Corpus.D1.Part16 +import SolidCore.Refinement.Corpus.D1.Malformed + +/-! +# d1: solar's bytecode refines SolidCore's `Main` on dynamic parameters + +`refines` proves `Refines fuel contract code (· ∈ scope s)` for `Main` in `scripts/refinement/corpus/d1.sol`, +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, 65793 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 SolidCore.Refinement.Corpus.D1 + +open SolidCore.Refinement SolidCore.Refinement.Abi SolidCore.Refinement.Dyn + +theorem parts_ok : ∀ i < parts, partOk i = true := fun i hi => + match i, hi with + | 0, _ => part0 + | 1, _ => part1 + | 2, _ => part2 + | 3, _ => part3 + | 4, _ => part4 + | 5, _ => part5 + | 6, _ => part6 + | 7, _ => part7 + | 8, _ => part8 + | 9, _ => part9 + | 10, _ => part10 + | 11, _ => part11 + | 12, _ => part12 + | 13, _ => part13 + | 14, _ => part14 + | 15, _ => part15 + | 16, _ => part16 + | n + 17, 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 SolidCore.Refinement.Corpus.D1 diff --git a/SolidCore/Refinement/Corpus/D1/Defs.lean b/SolidCore/Refinement/Corpus/D1/Defs.lean new file mode 100644 index 00000000..a86905ff --- /dev/null +++ b/SolidCore/Refinement/Corpus/D1/Defs.lean @@ -0,0 +1,51 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/d1.sol. Do not edit. + +import SolidCore.Refinement.Dyn.Abi +import SolidCore.Refinement.Check +import SolidCore.Refinement.Bytecode.D1 +import SolidCore.Refinement.Source.D1 + +/-! +# The scope of d1's refinement + +65793 calls: every function of `Main` in `scripts/refinement/corpus/d1.sol` 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 17 part(s), each in its own module. +-/ + +namespace SolidCore.Refinement.Corpus.D1 + +open SolidCore.Refinement SolidCore.Refinement.Abi SolidCore.Refinement.Dyn 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.D1.Main.runtimeNat + Bytecode.D1.Main.runtimeSize + +/-- SolidCore's checked `Main`. -/ +def contract? : Except TypeCheck.TypeError TypeCheck.CheckedContract := + TypeCheck.CheckedInput.contract Source.D1.importedSourceUnit "Main" + +/-- The functions of `Main` and their parameters, with the bounds of their encodings. -/ +def fns : List DFn := + [⟨Bytecode.D1.Main.fSelector, [(.bytes 2)]⟩] + +/-- The number of parts the check runs in. -/ +def parts : Nat := 17 + +/-- 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 SolidCore.Refinement.Corpus.D1 diff --git a/SolidCore/Refinement/Corpus/D1/Malformed.lean b/SolidCore/Refinement/Corpus/D1/Malformed.lean new file mode 100644 index 00000000..5c11a3d0 --- /dev/null +++ b/SolidCore/Refinement/Corpus/D1/Malformed.lean @@ -0,0 +1,30 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/d1.sol. Do not edit. + +import SolidCore.Refinement.Dyn.Refines +import SolidCore.Refinement.Corpus.D1.Defs + +/-! +# d1: EthLib rejects malformed call data + +For every function of `Main` in `scripts/refinement/corpus/d1.sol`, 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 SolidCore.Refinement.Corpus.D1 + +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 rfl + · exact malformed_of_frame code Bytecode.D1.Main.fSelector [(.bytes 2)] + (by dyn_symex [code, Bytecode.D1.Main.runtimeNat, Bytecode.D1.Main.runtimeSize, Bytecode.D1.Main.fSelector]) + +end SolidCore.Refinement.Corpus.D1 diff --git a/SolidCore/Refinement/Corpus/D1/Part0.lean b/SolidCore/Refinement/Corpus/D1/Part0.lean new file mode 100644 index 00000000..8f5b598d --- /dev/null +++ b/SolidCore/Refinement/Corpus/D1/Part0.lean @@ -0,0 +1,9 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/d1.sol. Do not edit. + +import SolidCore.Refinement.Corpus.D1.Defs + +namespace SolidCore.Refinement.Corpus.D1 + +theorem part0 : partOk 0 = true := by native_decide + +end SolidCore.Refinement.Corpus.D1 diff --git a/SolidCore/Refinement/Corpus/D1/Part1.lean b/SolidCore/Refinement/Corpus/D1/Part1.lean new file mode 100644 index 00000000..ef43133b --- /dev/null +++ b/SolidCore/Refinement/Corpus/D1/Part1.lean @@ -0,0 +1,9 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/d1.sol. Do not edit. + +import SolidCore.Refinement.Corpus.D1.Defs + +namespace SolidCore.Refinement.Corpus.D1 + +theorem part1 : partOk 1 = true := by native_decide + +end SolidCore.Refinement.Corpus.D1 diff --git a/SolidCore/Refinement/Corpus/D1/Part10.lean b/SolidCore/Refinement/Corpus/D1/Part10.lean new file mode 100644 index 00000000..07d896d9 --- /dev/null +++ b/SolidCore/Refinement/Corpus/D1/Part10.lean @@ -0,0 +1,9 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/d1.sol. Do not edit. + +import SolidCore.Refinement.Corpus.D1.Defs + +namespace SolidCore.Refinement.Corpus.D1 + +theorem part10 : partOk 10 = true := by native_decide + +end SolidCore.Refinement.Corpus.D1 diff --git a/SolidCore/Refinement/Corpus/D1/Part11.lean b/SolidCore/Refinement/Corpus/D1/Part11.lean new file mode 100644 index 00000000..74d68793 --- /dev/null +++ b/SolidCore/Refinement/Corpus/D1/Part11.lean @@ -0,0 +1,9 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/d1.sol. Do not edit. + +import SolidCore.Refinement.Corpus.D1.Defs + +namespace SolidCore.Refinement.Corpus.D1 + +theorem part11 : partOk 11 = true := by native_decide + +end SolidCore.Refinement.Corpus.D1 diff --git a/SolidCore/Refinement/Corpus/D1/Part12.lean b/SolidCore/Refinement/Corpus/D1/Part12.lean new file mode 100644 index 00000000..c3742064 --- /dev/null +++ b/SolidCore/Refinement/Corpus/D1/Part12.lean @@ -0,0 +1,9 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/d1.sol. Do not edit. + +import SolidCore.Refinement.Corpus.D1.Defs + +namespace SolidCore.Refinement.Corpus.D1 + +theorem part12 : partOk 12 = true := by native_decide + +end SolidCore.Refinement.Corpus.D1 diff --git a/SolidCore/Refinement/Corpus/D1/Part13.lean b/SolidCore/Refinement/Corpus/D1/Part13.lean new file mode 100644 index 00000000..bd733988 --- /dev/null +++ b/SolidCore/Refinement/Corpus/D1/Part13.lean @@ -0,0 +1,9 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/d1.sol. Do not edit. + +import SolidCore.Refinement.Corpus.D1.Defs + +namespace SolidCore.Refinement.Corpus.D1 + +theorem part13 : partOk 13 = true := by native_decide + +end SolidCore.Refinement.Corpus.D1 diff --git a/SolidCore/Refinement/Corpus/D1/Part14.lean b/SolidCore/Refinement/Corpus/D1/Part14.lean new file mode 100644 index 00000000..52d67eda --- /dev/null +++ b/SolidCore/Refinement/Corpus/D1/Part14.lean @@ -0,0 +1,9 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/d1.sol. Do not edit. + +import SolidCore.Refinement.Corpus.D1.Defs + +namespace SolidCore.Refinement.Corpus.D1 + +theorem part14 : partOk 14 = true := by native_decide + +end SolidCore.Refinement.Corpus.D1 diff --git a/SolidCore/Refinement/Corpus/D1/Part15.lean b/SolidCore/Refinement/Corpus/D1/Part15.lean new file mode 100644 index 00000000..8b3caca7 --- /dev/null +++ b/SolidCore/Refinement/Corpus/D1/Part15.lean @@ -0,0 +1,9 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/d1.sol. Do not edit. + +import SolidCore.Refinement.Corpus.D1.Defs + +namespace SolidCore.Refinement.Corpus.D1 + +theorem part15 : partOk 15 = true := by native_decide + +end SolidCore.Refinement.Corpus.D1 diff --git a/SolidCore/Refinement/Corpus/D1/Part16.lean b/SolidCore/Refinement/Corpus/D1/Part16.lean new file mode 100644 index 00000000..16957d78 --- /dev/null +++ b/SolidCore/Refinement/Corpus/D1/Part16.lean @@ -0,0 +1,9 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/d1.sol. Do not edit. + +import SolidCore.Refinement.Corpus.D1.Defs + +namespace SolidCore.Refinement.Corpus.D1 + +theorem part16 : partOk 16 = true := by native_decide + +end SolidCore.Refinement.Corpus.D1 diff --git a/SolidCore/Refinement/Corpus/D1/Part2.lean b/SolidCore/Refinement/Corpus/D1/Part2.lean new file mode 100644 index 00000000..1ad1ca7f --- /dev/null +++ b/SolidCore/Refinement/Corpus/D1/Part2.lean @@ -0,0 +1,9 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/d1.sol. Do not edit. + +import SolidCore.Refinement.Corpus.D1.Defs + +namespace SolidCore.Refinement.Corpus.D1 + +theorem part2 : partOk 2 = true := by native_decide + +end SolidCore.Refinement.Corpus.D1 diff --git a/SolidCore/Refinement/Corpus/D1/Part3.lean b/SolidCore/Refinement/Corpus/D1/Part3.lean new file mode 100644 index 00000000..3a0b415d --- /dev/null +++ b/SolidCore/Refinement/Corpus/D1/Part3.lean @@ -0,0 +1,9 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/d1.sol. Do not edit. + +import SolidCore.Refinement.Corpus.D1.Defs + +namespace SolidCore.Refinement.Corpus.D1 + +theorem part3 : partOk 3 = true := by native_decide + +end SolidCore.Refinement.Corpus.D1 diff --git a/SolidCore/Refinement/Corpus/D1/Part4.lean b/SolidCore/Refinement/Corpus/D1/Part4.lean new file mode 100644 index 00000000..27cfff8c --- /dev/null +++ b/SolidCore/Refinement/Corpus/D1/Part4.lean @@ -0,0 +1,9 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/d1.sol. Do not edit. + +import SolidCore.Refinement.Corpus.D1.Defs + +namespace SolidCore.Refinement.Corpus.D1 + +theorem part4 : partOk 4 = true := by native_decide + +end SolidCore.Refinement.Corpus.D1 diff --git a/SolidCore/Refinement/Corpus/D1/Part5.lean b/SolidCore/Refinement/Corpus/D1/Part5.lean new file mode 100644 index 00000000..17eac74b --- /dev/null +++ b/SolidCore/Refinement/Corpus/D1/Part5.lean @@ -0,0 +1,9 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/d1.sol. Do not edit. + +import SolidCore.Refinement.Corpus.D1.Defs + +namespace SolidCore.Refinement.Corpus.D1 + +theorem part5 : partOk 5 = true := by native_decide + +end SolidCore.Refinement.Corpus.D1 diff --git a/SolidCore/Refinement/Corpus/D1/Part6.lean b/SolidCore/Refinement/Corpus/D1/Part6.lean new file mode 100644 index 00000000..0731bd93 --- /dev/null +++ b/SolidCore/Refinement/Corpus/D1/Part6.lean @@ -0,0 +1,9 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/d1.sol. Do not edit. + +import SolidCore.Refinement.Corpus.D1.Defs + +namespace SolidCore.Refinement.Corpus.D1 + +theorem part6 : partOk 6 = true := by native_decide + +end SolidCore.Refinement.Corpus.D1 diff --git a/SolidCore/Refinement/Corpus/D1/Part7.lean b/SolidCore/Refinement/Corpus/D1/Part7.lean new file mode 100644 index 00000000..78dff669 --- /dev/null +++ b/SolidCore/Refinement/Corpus/D1/Part7.lean @@ -0,0 +1,9 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/d1.sol. Do not edit. + +import SolidCore.Refinement.Corpus.D1.Defs + +namespace SolidCore.Refinement.Corpus.D1 + +theorem part7 : partOk 7 = true := by native_decide + +end SolidCore.Refinement.Corpus.D1 diff --git a/SolidCore/Refinement/Corpus/D1/Part8.lean b/SolidCore/Refinement/Corpus/D1/Part8.lean new file mode 100644 index 00000000..2d8590d1 --- /dev/null +++ b/SolidCore/Refinement/Corpus/D1/Part8.lean @@ -0,0 +1,9 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/d1.sol. Do not edit. + +import SolidCore.Refinement.Corpus.D1.Defs + +namespace SolidCore.Refinement.Corpus.D1 + +theorem part8 : partOk 8 = true := by native_decide + +end SolidCore.Refinement.Corpus.D1 diff --git a/SolidCore/Refinement/Corpus/D1/Part9.lean b/SolidCore/Refinement/Corpus/D1/Part9.lean new file mode 100644 index 00000000..0e3dac4b --- /dev/null +++ b/SolidCore/Refinement/Corpus/D1/Part9.lean @@ -0,0 +1,9 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/d1.sol. Do not edit. + +import SolidCore.Refinement.Corpus.D1.Defs + +namespace SolidCore.Refinement.Corpus.D1 + +theorem part9 : partOk 9 = true := by native_decide + +end SolidCore.Refinement.Corpus.D1 diff --git a/SolidCore/Refinement/Corpus/D2.lean b/SolidCore/Refinement/Corpus/D2.lean new file mode 100644 index 00000000..0c71b83b --- /dev/null +++ b/SolidCore/Refinement/Corpus/D2.lean @@ -0,0 +1,95 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/d2.sol. Do not edit. + +import SolidCore.Refinement.Corpus.D2.Part0 +import SolidCore.Refinement.Corpus.D2.Part1 +import SolidCore.Refinement.Corpus.D2.Part2 +import SolidCore.Refinement.Corpus.D2.Part3 +import SolidCore.Refinement.Corpus.D2.Part4 +import SolidCore.Refinement.Corpus.D2.Part5 +import SolidCore.Refinement.Corpus.D2.Part6 +import SolidCore.Refinement.Corpus.D2.Part7 +import SolidCore.Refinement.Corpus.D2.Part8 +import SolidCore.Refinement.Corpus.D2.Part9 +import SolidCore.Refinement.Corpus.D2.Part10 +import SolidCore.Refinement.Corpus.D2.Part11 +import SolidCore.Refinement.Corpus.D2.Part12 +import SolidCore.Refinement.Corpus.D2.Part13 +import SolidCore.Refinement.Corpus.D2.Part14 +import SolidCore.Refinement.Corpus.D2.Part15 +import SolidCore.Refinement.Corpus.D2.Part16 +import SolidCore.Refinement.Corpus.D2.Malformed + +/-! +# d2: solar's bytecode refines SolidCore's `Main` on dynamic parameters + +`refines` proves `Refines fuel contract code (· ∈ scope s)` for `Main` in `scripts/refinement/corpus/d2.sol`, +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, 65793 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 SolidCore.Refinement.Corpus.D2 + +open SolidCore.Refinement SolidCore.Refinement.Abi SolidCore.Refinement.Dyn + +theorem parts_ok : ∀ i < parts, partOk i = true := fun i hi => + match i, hi with + | 0, _ => part0 + | 1, _ => part1 + | 2, _ => part2 + | 3, _ => part3 + | 4, _ => part4 + | 5, _ => part5 + | 6, _ => part6 + | 7, _ => part7 + | 8, _ => part8 + | 9, _ => part9 + | 10, _ => part10 + | 11, _ => part11 + | 12, _ => part12 + | 13, _ => part13 + | 14, _ => part14 + | 15, _ => part15 + | 16, _ => part16 + | n + 17, 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 SolidCore.Refinement.Corpus.D2 diff --git a/SolidCore/Refinement/Corpus/D2/Defs.lean b/SolidCore/Refinement/Corpus/D2/Defs.lean new file mode 100644 index 00000000..22ffe037 --- /dev/null +++ b/SolidCore/Refinement/Corpus/D2/Defs.lean @@ -0,0 +1,51 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/d2.sol. Do not edit. + +import SolidCore.Refinement.Dyn.Abi +import SolidCore.Refinement.Check +import SolidCore.Refinement.Bytecode.D2 +import SolidCore.Refinement.Source.D2 + +/-! +# The scope of d2's refinement + +65793 calls: every function of `Main` in `scripts/refinement/corpus/d2.sol` 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 17 part(s), each in its own module. +-/ + +namespace SolidCore.Refinement.Corpus.D2 + +open SolidCore.Refinement SolidCore.Refinement.Abi SolidCore.Refinement.Dyn 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.D2.Main.runtimeNat + Bytecode.D2.Main.runtimeSize + +/-- SolidCore's checked `Main`. -/ +def contract? : Except TypeCheck.TypeError TypeCheck.CheckedContract := + TypeCheck.CheckedInput.contract Source.D2.importedSourceUnit "Main" + +/-- The functions of `Main` and their parameters, with the bounds of their encodings. -/ +def fns : List DFn := + [⟨Bytecode.D2.Main.fSelector, [(.array (.uint 8) 2)]⟩] + +/-- The number of parts the check runs in. -/ +def parts : Nat := 17 + +/-- 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 SolidCore.Refinement.Corpus.D2 diff --git a/SolidCore/Refinement/Corpus/D2/Malformed.lean b/SolidCore/Refinement/Corpus/D2/Malformed.lean new file mode 100644 index 00000000..dc54974d --- /dev/null +++ b/SolidCore/Refinement/Corpus/D2/Malformed.lean @@ -0,0 +1,30 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/d2.sol. Do not edit. + +import SolidCore.Refinement.Dyn.Refines +import SolidCore.Refinement.Corpus.D2.Defs + +/-! +# d2: EthLib rejects malformed call data + +For every function of `Main` in `scripts/refinement/corpus/d2.sol`, 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 SolidCore.Refinement.Corpus.D2 + +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 rfl + · exact malformed_of_frame code Bytecode.D2.Main.fSelector [(.array (.uint 8) 2)] + (by dyn_symex [code, Bytecode.D2.Main.runtimeNat, Bytecode.D2.Main.runtimeSize, Bytecode.D2.Main.fSelector]) + +end SolidCore.Refinement.Corpus.D2 diff --git a/SolidCore/Refinement/Corpus/D2/Part0.lean b/SolidCore/Refinement/Corpus/D2/Part0.lean new file mode 100644 index 00000000..0b8bf1ac --- /dev/null +++ b/SolidCore/Refinement/Corpus/D2/Part0.lean @@ -0,0 +1,9 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/d2.sol. Do not edit. + +import SolidCore.Refinement.Corpus.D2.Defs + +namespace SolidCore.Refinement.Corpus.D2 + +theorem part0 : partOk 0 = true := by native_decide + +end SolidCore.Refinement.Corpus.D2 diff --git a/SolidCore/Refinement/Corpus/D2/Part1.lean b/SolidCore/Refinement/Corpus/D2/Part1.lean new file mode 100644 index 00000000..d8f09352 --- /dev/null +++ b/SolidCore/Refinement/Corpus/D2/Part1.lean @@ -0,0 +1,9 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/d2.sol. Do not edit. + +import SolidCore.Refinement.Corpus.D2.Defs + +namespace SolidCore.Refinement.Corpus.D2 + +theorem part1 : partOk 1 = true := by native_decide + +end SolidCore.Refinement.Corpus.D2 diff --git a/SolidCore/Refinement/Corpus/D2/Part10.lean b/SolidCore/Refinement/Corpus/D2/Part10.lean new file mode 100644 index 00000000..e7f9e752 --- /dev/null +++ b/SolidCore/Refinement/Corpus/D2/Part10.lean @@ -0,0 +1,9 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/d2.sol. Do not edit. + +import SolidCore.Refinement.Corpus.D2.Defs + +namespace SolidCore.Refinement.Corpus.D2 + +theorem part10 : partOk 10 = true := by native_decide + +end SolidCore.Refinement.Corpus.D2 diff --git a/SolidCore/Refinement/Corpus/D2/Part11.lean b/SolidCore/Refinement/Corpus/D2/Part11.lean new file mode 100644 index 00000000..6ce078c6 --- /dev/null +++ b/SolidCore/Refinement/Corpus/D2/Part11.lean @@ -0,0 +1,9 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/d2.sol. Do not edit. + +import SolidCore.Refinement.Corpus.D2.Defs + +namespace SolidCore.Refinement.Corpus.D2 + +theorem part11 : partOk 11 = true := by native_decide + +end SolidCore.Refinement.Corpus.D2 diff --git a/SolidCore/Refinement/Corpus/D2/Part12.lean b/SolidCore/Refinement/Corpus/D2/Part12.lean new file mode 100644 index 00000000..b3a019d3 --- /dev/null +++ b/SolidCore/Refinement/Corpus/D2/Part12.lean @@ -0,0 +1,9 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/d2.sol. Do not edit. + +import SolidCore.Refinement.Corpus.D2.Defs + +namespace SolidCore.Refinement.Corpus.D2 + +theorem part12 : partOk 12 = true := by native_decide + +end SolidCore.Refinement.Corpus.D2 diff --git a/SolidCore/Refinement/Corpus/D2/Part13.lean b/SolidCore/Refinement/Corpus/D2/Part13.lean new file mode 100644 index 00000000..a4b370dd --- /dev/null +++ b/SolidCore/Refinement/Corpus/D2/Part13.lean @@ -0,0 +1,9 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/d2.sol. Do not edit. + +import SolidCore.Refinement.Corpus.D2.Defs + +namespace SolidCore.Refinement.Corpus.D2 + +theorem part13 : partOk 13 = true := by native_decide + +end SolidCore.Refinement.Corpus.D2 diff --git a/SolidCore/Refinement/Corpus/D2/Part14.lean b/SolidCore/Refinement/Corpus/D2/Part14.lean new file mode 100644 index 00000000..3c489f0f --- /dev/null +++ b/SolidCore/Refinement/Corpus/D2/Part14.lean @@ -0,0 +1,9 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/d2.sol. Do not edit. + +import SolidCore.Refinement.Corpus.D2.Defs + +namespace SolidCore.Refinement.Corpus.D2 + +theorem part14 : partOk 14 = true := by native_decide + +end SolidCore.Refinement.Corpus.D2 diff --git a/SolidCore/Refinement/Corpus/D2/Part15.lean b/SolidCore/Refinement/Corpus/D2/Part15.lean new file mode 100644 index 00000000..4008c211 --- /dev/null +++ b/SolidCore/Refinement/Corpus/D2/Part15.lean @@ -0,0 +1,9 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/d2.sol. Do not edit. + +import SolidCore.Refinement.Corpus.D2.Defs + +namespace SolidCore.Refinement.Corpus.D2 + +theorem part15 : partOk 15 = true := by native_decide + +end SolidCore.Refinement.Corpus.D2 diff --git a/SolidCore/Refinement/Corpus/D2/Part16.lean b/SolidCore/Refinement/Corpus/D2/Part16.lean new file mode 100644 index 00000000..d5e106f2 --- /dev/null +++ b/SolidCore/Refinement/Corpus/D2/Part16.lean @@ -0,0 +1,9 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/d2.sol. Do not edit. + +import SolidCore.Refinement.Corpus.D2.Defs + +namespace SolidCore.Refinement.Corpus.D2 + +theorem part16 : partOk 16 = true := by native_decide + +end SolidCore.Refinement.Corpus.D2 diff --git a/SolidCore/Refinement/Corpus/D2/Part2.lean b/SolidCore/Refinement/Corpus/D2/Part2.lean new file mode 100644 index 00000000..d6e840d5 --- /dev/null +++ b/SolidCore/Refinement/Corpus/D2/Part2.lean @@ -0,0 +1,9 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/d2.sol. Do not edit. + +import SolidCore.Refinement.Corpus.D2.Defs + +namespace SolidCore.Refinement.Corpus.D2 + +theorem part2 : partOk 2 = true := by native_decide + +end SolidCore.Refinement.Corpus.D2 diff --git a/SolidCore/Refinement/Corpus/D2/Part3.lean b/SolidCore/Refinement/Corpus/D2/Part3.lean new file mode 100644 index 00000000..08f3eaf4 --- /dev/null +++ b/SolidCore/Refinement/Corpus/D2/Part3.lean @@ -0,0 +1,9 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/d2.sol. Do not edit. + +import SolidCore.Refinement.Corpus.D2.Defs + +namespace SolidCore.Refinement.Corpus.D2 + +theorem part3 : partOk 3 = true := by native_decide + +end SolidCore.Refinement.Corpus.D2 diff --git a/SolidCore/Refinement/Corpus/D2/Part4.lean b/SolidCore/Refinement/Corpus/D2/Part4.lean new file mode 100644 index 00000000..ee799f06 --- /dev/null +++ b/SolidCore/Refinement/Corpus/D2/Part4.lean @@ -0,0 +1,9 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/d2.sol. Do not edit. + +import SolidCore.Refinement.Corpus.D2.Defs + +namespace SolidCore.Refinement.Corpus.D2 + +theorem part4 : partOk 4 = true := by native_decide + +end SolidCore.Refinement.Corpus.D2 diff --git a/SolidCore/Refinement/Corpus/D2/Part5.lean b/SolidCore/Refinement/Corpus/D2/Part5.lean new file mode 100644 index 00000000..50ab8df5 --- /dev/null +++ b/SolidCore/Refinement/Corpus/D2/Part5.lean @@ -0,0 +1,9 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/d2.sol. Do not edit. + +import SolidCore.Refinement.Corpus.D2.Defs + +namespace SolidCore.Refinement.Corpus.D2 + +theorem part5 : partOk 5 = true := by native_decide + +end SolidCore.Refinement.Corpus.D2 diff --git a/SolidCore/Refinement/Corpus/D2/Part6.lean b/SolidCore/Refinement/Corpus/D2/Part6.lean new file mode 100644 index 00000000..8754b37f --- /dev/null +++ b/SolidCore/Refinement/Corpus/D2/Part6.lean @@ -0,0 +1,9 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/d2.sol. Do not edit. + +import SolidCore.Refinement.Corpus.D2.Defs + +namespace SolidCore.Refinement.Corpus.D2 + +theorem part6 : partOk 6 = true := by native_decide + +end SolidCore.Refinement.Corpus.D2 diff --git a/SolidCore/Refinement/Corpus/D2/Part7.lean b/SolidCore/Refinement/Corpus/D2/Part7.lean new file mode 100644 index 00000000..4366a15e --- /dev/null +++ b/SolidCore/Refinement/Corpus/D2/Part7.lean @@ -0,0 +1,9 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/d2.sol. Do not edit. + +import SolidCore.Refinement.Corpus.D2.Defs + +namespace SolidCore.Refinement.Corpus.D2 + +theorem part7 : partOk 7 = true := by native_decide + +end SolidCore.Refinement.Corpus.D2 diff --git a/SolidCore/Refinement/Corpus/D2/Part8.lean b/SolidCore/Refinement/Corpus/D2/Part8.lean new file mode 100644 index 00000000..95b68710 --- /dev/null +++ b/SolidCore/Refinement/Corpus/D2/Part8.lean @@ -0,0 +1,9 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/d2.sol. Do not edit. + +import SolidCore.Refinement.Corpus.D2.Defs + +namespace SolidCore.Refinement.Corpus.D2 + +theorem part8 : partOk 8 = true := by native_decide + +end SolidCore.Refinement.Corpus.D2 diff --git a/SolidCore/Refinement/Corpus/D2/Part9.lean b/SolidCore/Refinement/Corpus/D2/Part9.lean new file mode 100644 index 00000000..76ec1ae5 --- /dev/null +++ b/SolidCore/Refinement/Corpus/D2/Part9.lean @@ -0,0 +1,9 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/d2.sol. Do not edit. + +import SolidCore.Refinement.Corpus.D2.Defs + +namespace SolidCore.Refinement.Corpus.D2 + +theorem part9 : partOk 9 = true := by native_decide + +end SolidCore.Refinement.Corpus.D2 diff --git a/SolidCore/Refinement/Corpus/D3.lean b/SolidCore/Refinement/Corpus/D3.lean new file mode 100644 index 00000000..01740ea8 --- /dev/null +++ b/SolidCore/Refinement/Corpus/D3.lean @@ -0,0 +1,63 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/d3.sol. Do not edit. + +import SolidCore.Refinement.Corpus.D3.Part0 +import SolidCore.Refinement.Corpus.D3.Malformed + +/-! +# d3: solar's bytecode refines SolidCore's `Main` on dynamic parameters + +`refines` proves `Refines fuel contract code (· ∈ scope s)` for `Main` in `scripts/refinement/corpus/d3.sol`, +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, 512 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 SolidCore.Refinement.Corpus.D3 + +open SolidCore.Refinement SolidCore.Refinement.Abi SolidCore.Refinement.Dyn + +theorem parts_ok : ∀ i < parts, partOk i = true := fun i hi => + match i, hi with + | 0, _ => part0 + | n + 1, 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 SolidCore.Refinement.Corpus.D3 diff --git a/SolidCore/Refinement/Corpus/D3/Defs.lean b/SolidCore/Refinement/Corpus/D3/Defs.lean new file mode 100644 index 00000000..f25a56eb --- /dev/null +++ b/SolidCore/Refinement/Corpus/D3/Defs.lean @@ -0,0 +1,51 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/d3.sol. Do not edit. + +import SolidCore.Refinement.Dyn.Abi +import SolidCore.Refinement.Check +import SolidCore.Refinement.Bytecode.D3 +import SolidCore.Refinement.Source.D3 + +/-! +# The scope of d3's refinement + +512 calls: every function of `Main` in `scripts/refinement/corpus/d3.sol` 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 1 part(s), each in its own module. +-/ + +namespace SolidCore.Refinement.Corpus.D3 + +open SolidCore.Refinement SolidCore.Refinement.Abi SolidCore.Refinement.Dyn 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.D3.Main.runtimeNat + Bytecode.D3.Main.runtimeSize + +/-- SolidCore's checked `Main`. -/ +def contract? : Except TypeCheck.TypeError TypeCheck.CheckedContract := + TypeCheck.CheckedInput.contract Source.D3.importedSourceUnit "Main" + +/-- The functions of `Main` and their parameters, with the bounds of their encodings. -/ +def fns : List DFn := + [⟨Bytecode.D3.Main.fSelector, [(.struct [(.uint 8), .bool])]⟩] + +/-- The number of parts the check runs in. -/ +def parts : Nat := 1 + +/-- 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 SolidCore.Refinement.Corpus.D3 diff --git a/SolidCore/Refinement/Corpus/D3/Malformed.lean b/SolidCore/Refinement/Corpus/D3/Malformed.lean new file mode 100644 index 00000000..719454d6 --- /dev/null +++ b/SolidCore/Refinement/Corpus/D3/Malformed.lean @@ -0,0 +1,30 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/d3.sol. Do not edit. + +import SolidCore.Refinement.Dyn.Refines +import SolidCore.Refinement.Corpus.D3.Defs + +/-! +# d3: EthLib rejects malformed call data + +For every function of `Main` in `scripts/refinement/corpus/d3.sol`, 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 SolidCore.Refinement.Corpus.D3 + +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 rfl + · exact malformed_of_frame code Bytecode.D3.Main.fSelector [(.struct [(.uint 8), .bool])] + (by dyn_symex [code, Bytecode.D3.Main.runtimeNat, Bytecode.D3.Main.runtimeSize, Bytecode.D3.Main.fSelector]) + +end SolidCore.Refinement.Corpus.D3 diff --git a/SolidCore/Refinement/Corpus/D3/Part0.lean b/SolidCore/Refinement/Corpus/D3/Part0.lean new file mode 100644 index 00000000..05116671 --- /dev/null +++ b/SolidCore/Refinement/Corpus/D3/Part0.lean @@ -0,0 +1,9 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/d3.sol. Do not edit. + +import SolidCore.Refinement.Corpus.D3.Defs + +namespace SolidCore.Refinement.Corpus.D3 + +theorem part0 : partOk 0 = true := by native_decide + +end SolidCore.Refinement.Corpus.D3 diff --git a/SolidCore/Refinement/Corpus/D4.lean b/SolidCore/Refinement/Corpus/D4.lean new file mode 100644 index 00000000..c70287dd --- /dev/null +++ b/SolidCore/Refinement/Corpus/D4.lean @@ -0,0 +1,63 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/d4.sol. Do not edit. + +import SolidCore.Refinement.Corpus.D4.Part0 +import SolidCore.Refinement.Corpus.D4.Malformed + +/-! +# d4: solar's bytecode refines SolidCore's `Main` on dynamic parameters + +`refines` proves `Refines fuel contract code (· ∈ scope s)` for `Main` in `scripts/refinement/corpus/d4.sol`, +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, 512 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 SolidCore.Refinement.Corpus.D4 + +open SolidCore.Refinement SolidCore.Refinement.Abi SolidCore.Refinement.Dyn + +theorem parts_ok : ∀ i < parts, partOk i = true := fun i hi => + match i, hi with + | 0, _ => part0 + | n + 1, 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 SolidCore.Refinement.Corpus.D4 diff --git a/SolidCore/Refinement/Corpus/D4/Defs.lean b/SolidCore/Refinement/Corpus/D4/Defs.lean new file mode 100644 index 00000000..baee5e56 --- /dev/null +++ b/SolidCore/Refinement/Corpus/D4/Defs.lean @@ -0,0 +1,51 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/d4.sol. Do not edit. + +import SolidCore.Refinement.Dyn.Abi +import SolidCore.Refinement.Check +import SolidCore.Refinement.Bytecode.D4 +import SolidCore.Refinement.Source.D4 + +/-! +# The scope of d4's refinement + +512 calls: every function of `Main` in `scripts/refinement/corpus/d4.sol` 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 1 part(s), each in its own module. +-/ + +namespace SolidCore.Refinement.Corpus.D4 + +open SolidCore.Refinement SolidCore.Refinement.Abi SolidCore.Refinement.Dyn 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.D4.Main.runtimeNat + Bytecode.D4.Main.runtimeSize + +/-- SolidCore's checked `Main`. -/ +def contract? : Except TypeCheck.TypeError TypeCheck.CheckedContract := + TypeCheck.CheckedInput.contract Source.D4.importedSourceUnit "Main" + +/-- The functions of `Main` and their parameters, with the bounds of their encodings. -/ +def fns : List DFn := + [⟨Bytecode.D4.Main.fSelector, [(.struct [(.uint 8), .bool])]⟩] + +/-- The number of parts the check runs in. -/ +def parts : Nat := 1 + +/-- 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 SolidCore.Refinement.Corpus.D4 diff --git a/SolidCore/Refinement/Corpus/D4/Malformed.lean b/SolidCore/Refinement/Corpus/D4/Malformed.lean new file mode 100644 index 00000000..f19688cf --- /dev/null +++ b/SolidCore/Refinement/Corpus/D4/Malformed.lean @@ -0,0 +1,30 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/d4.sol. Do not edit. + +import SolidCore.Refinement.Dyn.Refines +import SolidCore.Refinement.Corpus.D4.Defs + +/-! +# d4: EthLib rejects malformed call data + +For every function of `Main` in `scripts/refinement/corpus/d4.sol`, 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 SolidCore.Refinement.Corpus.D4 + +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 rfl + · exact malformed_of_frame code Bytecode.D4.Main.fSelector [(.struct [(.uint 8), .bool])] + (by dyn_symex [code, Bytecode.D4.Main.runtimeNat, Bytecode.D4.Main.runtimeSize, Bytecode.D4.Main.fSelector]) + +end SolidCore.Refinement.Corpus.D4 diff --git a/SolidCore/Refinement/Corpus/D4/Part0.lean b/SolidCore/Refinement/Corpus/D4/Part0.lean new file mode 100644 index 00000000..921ef9f5 --- /dev/null +++ b/SolidCore/Refinement/Corpus/D4/Part0.lean @@ -0,0 +1,9 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/d4.sol. Do not edit. + +import SolidCore.Refinement.Corpus.D4.Defs + +namespace SolidCore.Refinement.Corpus.D4 + +theorem part0 : partOk 0 = true := by native_decide + +end SolidCore.Refinement.Corpus.D4 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/W2.lean b/SolidCore/Refinement/Corpus/W2.lean new file mode 100644 index 00000000..da0978ba --- /dev/null +++ b/SolidCore/Refinement/Corpus/W2.lean @@ -0,0 +1,286 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/w2.sol. Do not edit. + +import SolidCore.Refinement.Wide.Refines +import SolidCore.Refinement.Bytecode.W2 +import SolidCore.Refinement.Source.W2 +import SolidCore.Refinement.KernelCopies +import SolidCore.Refinement.KernelRfl + +/-! +# w2: 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/w2.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`, and by `bv_decide` (which +trusts Lean's compiler) only where those fail. +-/ + +namespace SolidCore.Refinement.Corpus.W2 + +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.W2.Main.runtimeNat + Bytecode.W2.Main.runtimeSize + +/-- SolidCore's checked `Main`. -/ +def contract? : Except TypeCheck.TypeError TypeCheck.CheckedContract := + TypeCheck.CheckedInput.contract Source.W2.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.W2.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.ifElse + (SolidCore.Solidity.Source.Expr.binary + (SolidCore.Solidity.Source.BinaryOp.gt) + (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"))) + (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.sub) + (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"))))]) + (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.sub) + (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 "a"))))])]], + 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.ifElse + (SolidCore.Solidity.Source.Expr.binary + (SolidCore.Solidity.Source.BinaryOp.gt) + (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"))) + (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.sub) + (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"))))]) + (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.sub) + (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 "a"))))])]], + 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.W2.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.W2.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.W2.Main.fSelector ws) = some obs ∧ + Target.run code (callOf Bytecode.W2.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.W2.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.W2.Main.runtimeNat, Bytecode.W2.Main.runtimeSize, Bytecode.W2.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.W2 diff --git a/SolidCore/Refinement/Corpus/W3.lean b/SolidCore/Refinement/Corpus/W3.lean new file mode 100644 index 00000000..2bcb7fb6 --- /dev/null +++ b/SolidCore/Refinement/Corpus/W3.lean @@ -0,0 +1,198 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/w3.sol. Do not edit. + +import SolidCore.Refinement.Wide.Refines +import SolidCore.Refinement.Bytecode.W3 +import SolidCore.Refinement.Source.W3 +import SolidCore.Refinement.KernelCopies +import SolidCore.Refinement.KernelRfl + +/-! +# w3: 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/w3.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`, and by `bv_decide` (which +trusts Lean's compiler) only where those fail. +-/ + +namespace SolidCore.Refinement.Corpus.W3 + +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.W3.Main.runtimeNat + Bytecode.W3.Main.runtimeSize + +/-- SolidCore's checked `Main`. -/ +def contract? : Except TypeCheck.TypeError TypeCheck.CheckedContract := + TypeCheck.CheckedInput.contract Source.W3.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.W3.Main.fSelector, [(.uint 160)]⟩] + +/-- SolidCore's core contract of `Main`, as the generator printed it. -/ +def coreLit : Contract := + { storageFields := [], + immutableFields := [], + eventDecls := [], + errorDecls := [], + functions := [{ name := "f", + selector? := some 4234695194, + payable := false, + params := [{ name := "a", 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) + 160 + (SolidCore.Solidity.Source.Expr.binary + (SolidCore.Solidity.Source.BinaryOp.bitXor) + (SolidCore.Solidity.Source.Expr.castOp + (SolidCore.Solidity.Source.CastKind.uintCast) + 160 + (SolidCore.Solidity.Source.Expr.var "a")) + (SolidCore.Solidity.Source.Expr.castOp + (SolidCore.Solidity.Source.CastKind.uintCast) + 160 + (SolidCore.Solidity.Source.Expr.word 1)))]]], + dispatchId? := none }, + { name := "__internal_f(address)#[SolidCore.Solidity.Ty.address false]", + selector? := none, + payable := false, + params := [{ name := "a", 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) + 160 + (SolidCore.Solidity.Source.Expr.binary + (SolidCore.Solidity.Source.BinaryOp.bitXor) + (SolidCore.Solidity.Source.Expr.castOp + (SolidCore.Solidity.Source.CastKind.uintCast) + 160 + (SolidCore.Solidity.Source.Expr.var "a")) + (SolidCore.Solidity.Source.Expr.castOp + (SolidCore.Solidity.Source.CastKind.uintCast) + 160 + (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(address)" + +kernel_rfl selF_eq selF Bytecode.W3.Main.fSelector + +/-- `ABI.selectorFromSignature`, with `Main`'s signatures by table. -/ +def selectorTable (s : String) : SolidCore.Solidity.Shared.Word := + if s = "f(address)" then Bytecode.W3.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(address)" + · 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.W3.Main.fSelector ws) = some obs ∧ + Target.run code (callOf Bytecode.W3.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.W3.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.W3.Main.runtimeNat, Bytecode.W3.Main.runtimeSize, Bytecode.W3.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.W3 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 From 013c9559eac33b48c0531b071883ee346ca54cb3 Mon Sep 17 00:00:00 2001 From: alpharush <0xalpharush@protonmail.com> Date: Thu, 12 Nov 2026 22:24:44 -0600 Subject: [PATCH 3/3] feat(refinement): certify bank and events from any caller --- SolidCore/Refinement/Axioms/Main.lean | 15 ++ SolidCore/Refinement/Compose.lean | 14 ++ SolidCore/Refinement/Generic/Event.lean | 11 + SolidCore/Refinement/Generic/Mir.lean | 8 +- SolidCore/Refinement/Generic/MirRun.lean | 9 +- SolidCore/Refinement/Generic/Simp.lean | 7 + SolidCore/Refinement/Generic/Source.lean | 6 +- SolidCore/Refinement/Generic/SourceRun.lean | 47 ++-- SolidCore/Refinement/Generic/SourceStmt.lean | 4 +- SolidCore/Refinement/Generic/Stage.lean | 154 +++++++++++-- SolidCore/Refinement/Generic/Tree.lean | 8 + SolidCore/Refinement/Generic/Value.lean | 70 ++++-- SolidCore/Refinement/Solar/AssembleSim.lean | 218 +++++++++++++++++- SolidCore/Refinement/Solar/Bank/Assembly.lean | 22 ++ .../Refinement/Solar/Bank/Certified.lean | 127 ++++++++++ SolidCore/Refinement/Solar/Bank/Lowering.lean | 38 +++ .../Refinement/Solar/Events/Assembly.lean | 22 ++ .../Refinement/Solar/Events/Certified.lean | 75 ++++++ .../Refinement/Solar/Events/Lowering.lean | 39 ++++ SolidCore/Refinement/Statement.lean | 90 ++++++++ SolidCore/Refinement/Wide/Refines.lean | 19 ++ 21 files changed, 931 insertions(+), 72 deletions(-) diff --git a/SolidCore/Refinement/Axioms/Main.lean b/SolidCore/Refinement/Axioms/Main.lean index 7deebaa5..d6f813b4 100644 --- a/SolidCore/Refinement/Axioms/Main.lean +++ b/SolidCore/Refinement/Axioms/Main.lean @@ -76,9 +76,18 @@ sweep must report no violation. Run with `scripts/refinement/axiom-audit.sh`. -/ #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.certifiedFrom +#print axioms SolidCore.Refinement.Solar.Bank.certifiedValueFrom +#print axioms SolidCore.Refinement.Solar.Bank.certifiedFrom' +#print axioms SolidCore.Refinement.Solar.Bank.certifiedValueFrom' +#print axioms SolidCore.Refinement.Solar.Bank.certifiedManifestFrom +#print axioms SolidCore.Refinement.Solar.Bank.certifiedManifestFrom' +#print axioms SolidCore.Refinement.Solar.Bank.loweringFrom +#print axioms SolidCore.Refinement.Solar.Bank.loweringValueFrom #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_fixedCaller #print axioms SolidCore.Refinement.Solar.Bank.check_rejects_topic -- events. #print axioms SolidCore.Refinement.Solar.Events.certified @@ -86,8 +95,14 @@ sweep must report no violation. Run with `scripts/refinement/axiom-audit.sh`. -/ #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.certifiedFrom +#print axioms SolidCore.Refinement.Solar.Events.certifiedValueFrom +#print axioms SolidCore.Refinement.Solar.Events.certifiedManifestFrom +#print axioms SolidCore.Refinement.Solar.Events.loweringFrom +#print axioms SolidCore.Refinement.Solar.Events.loweringValueFrom #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_fixedCaller #print axioms SolidCore.Refinement.Solar.Events.check_rejects_topic #print axioms SolidCore.Refinement.Solar.Events.check_rejects_order diff --git a/SolidCore/Refinement/Compose.lean b/SolidCore/Refinement/Compose.lean index d4d68df8..b0d0e536 100644 --- a/SolidCore/Refinement/Compose.lean +++ b/SolidCore/Refinement/Compose.lean @@ -35,6 +35,20 @@ def solidCore (fuel : Nat) : Sem := /-- EthLib on runtime bytecode. -/ def ethLib : Sem := { Prog := ByteArray, run := Target.run } +/-- SolidCore with fixed fuel, on checked contracts, called from the account `caller`. -/ +def solidCoreFrom (caller fuel : Nat) : Sem := + { Prog := SolidCore.Solidity.TypeCheck.CheckedContract, run := Source.runFrom caller fuel } + +/-- EthLib on runtime bytecode, called from the account `caller`. -/ +def ethLibFrom (caller : Nat) : Sem := { Prog := ByteArray, run := Target.runFrom caller } + +theorem solidCoreFrom_callerAddress (fuel : Nat) : solidCoreFrom callerAddress fuel = solidCore fuel := + rfl + +theorem ethLibFrom_callerAddress : ethLibFrom callerAddress = ethLib := by + unfold ethLibFrom ethLib + rw [Target.runFrom_callerAddress] + /-- 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} diff --git a/SolidCore/Refinement/Generic/Event.lean b/SolidCore/Refinement/Generic/Event.lean index 5c5c2213..42ce5ca7 100644 --- a/SolidCore/Refinement/Generic/Event.lean +++ b/SolidCore/Refinement/Generic/Event.lean @@ -57,6 +57,7 @@ def evFieldOk (f : EventField) (w : WExpr) : Bool := match f.ty, w with | .uint256, _ => true | .address, .lit n => decide (n < 2 ^ 160) + | .address, .caller => true | _, _ => false /-- Whether every field is one the fragment logs, with its word. -/ @@ -99,6 +100,16 @@ theorem evFieldOk_static (ρ : Val) {f : EventField} {w : WExpr} (h : evFieldOk some (wordToBytesBE wordBytes ((WExpr.lit n).eval ρ)) := by simp [abiStaticBytes?, abiAddressFits, WExpr.eval, norm_mod, Nat.mod_mod, hn'] exact ⟨hb, hb, rfl, rfl, rfl⟩ + · rename_i hty + rw [hty] + have h1 : ρ.caller % 1461501637330902918203684832716283019655932542976 % wordSize < + 1461501637330902918203684832716283019655932542976 := by + rw [Nat.mod_eq_of_lt (Nat.lt_of_lt_of_le (Nat.mod_lt _ (by decide)) (by decide))] + exact Nat.mod_lt _ (by decide) + have hb : abiStaticBytes? Ty.address (.word (WExpr.caller.eval ρ)) = + some (wordToBytesBE wordBytes (WExpr.caller.eval ρ)) := by + simp [abiStaticBytes?, abiAddressFits, WExpr.eval, norm_mod, h1] + exact ⟨hb, hb, rfl, rfl, rfl⟩ · simp at h theorem encode_ok (ρ : Val) : ∀ (fs : List EventField) (ws : List WExpr), evOk fs ws = true → diff --git a/SolidCore/Refinement/Generic/Mir.lean b/SolidCore/Refinement/Generic/Mir.lean index 34750ee1..240243fe 100644 --- a/SolidCore/Refinement/Generic/Mir.lean +++ b/SolidCore/Refinement/Generic/Mir.lean @@ -27,8 +27,8 @@ the position (SolarTV's `Pos`), the symbolic values, the symbolic state and the 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 +* with the environment flags `env` (`EnvFlags`), `caller` is the call's sender, the word `WExpr.caller`, 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 @@ -133,7 +133,7 @@ def symPure (sel : Nat) : EVM.Op → List SV → Option SV 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 +/-- The environment reads the symbolic run may take: `caller` (as the word `WExpr.caller`) and `keccak256` of two words (as `hash`). -/ structure EnvFlags where caller : Bool @@ -159,7 +159,7 @@ def symEffect (ev : EnvFlags) (cv : SV) (n : Nat) : Effect → List SV → SStat | .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 }) - | .caller, [], st => if ev.caller = true then some (some (.w (.lit callerWord)), st) else none + | .caller, [], st => if ev.caller = true then some (some (.w .caller), 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 diff --git a/SolidCore/Refinement/Generic/MirRun.lean b/SolidCore/Refinement/Generic/MirRun.lean index 5f18e969..8064df6d 100644 --- a/SolidCore/Refinement/Generic/MirRun.lean +++ b/SolidCore/Refinement/Generic/MirRun.lean @@ -7,7 +7,7 @@ import SolidCore.Refinement.Generic.Mir 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 +environment flag set, the oracle must be one `EnvOk` describes: its caller is the call's, `ρ.caller`, 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`). @@ -39,16 +39,16 @@ 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. -/ +is the call's, `ρ.caller` below `2 ^ 160`, 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 + caller : (o.caller.setWidth 256).toNat = ρ.caller % 2 ^ 160 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 = callerWord + caller : ev.caller = true → (o.caller.setWidth 256).toNat = ρ.caller % 2 ^ 160 hash : ev.hash = true → ∀ a b, a < wordSize → b < wordSize → (o.keccak (wordBytes a ++ wordBytes b)).toNat = ρ.hash a b % wordSize @@ -527,7 +527,6 @@ theorem symEffect_sound {ev : EnvFlags} {cv : SV} {sel n : Nat} {ρ : Val} {call | [], _ => refine ⟨_, _, rfl, ?_, hs⟩ simp only [OptRel, SV.Rel, WExpr.eval, henv.caller hev] - exact (Nat.mod_eq_of_lt callerWord_lt).symm · simp at h · -- keccak256 rename_i off size diff --git a/SolidCore/Refinement/Generic/Simp.lean b/SolidCore/Refinement/Generic/Simp.lean index 317494a5..7b539257 100644 --- a/SolidCore/Refinement/Generic/Simp.lean +++ b/SolidCore/Refinement/Generic/Simp.lean @@ -209,6 +209,7 @@ def bound (K : Facts) : WExpr → Nat | .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 => 2 ^ 160 - 1 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) @@ -303,6 +304,10 @@ theorem bound_sound {ρ : Val} {K : Facts} (h : K.Hold ρ) : ∀ e : WExpr, e.ev 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 => by + simp only [bound, WExpr.eval] + have := Nat.mod_lt ρ.caller (show 0 < 2 ^ 160 by decide) + omega | .sel c a b => by simp only [bound, WExpr.eval] have := bound_sound h a @@ -391,6 +396,7 @@ def WExpr.simp (K : Facts) : WExpr → WExpr | 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 @@ -567,6 +573,7 @@ theorem WExpr.eval_simp {ρ : Val} {K : Facts} (h : K.Hold ρ) : ∀ e : WExpr, 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] diff --git a/SolidCore/Refinement/Generic/Source.lean b/SolidCore/Refinement/Generic/Source.lean index 7428a2ef..dcf06b2b 100644 --- a/SolidCore/Refinement/Generic/Source.lean +++ b/SolidCore/Refinement/Generic/Source.lean @@ -138,7 +138,7 @@ 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 ([], .lit callerWord) + | .caller => some ([], .caller) | .castOp .uintCleanup b e => do let (gs, v) ← eraseExpr fields S e if b = 256 then some (gs, v) @@ -400,7 +400,7 @@ structure ExprRel (ρ : Val) (fields : List StorageField) (ctx : Context) (rt : (S : SymState) : Prop where fields : ctx.storageFields = fields checked : ctx.checked = true - sender : ctx.sender = callerWord + sender : ctx.sender = ρ.caller % 2 ^ 160 hash : ρ.hash = solHash ok : ρ.Ok locals : ∀ x e, Scopes.get? S.scopes x = some e → rt.lookupLocal? x = some (.word (e.eval ρ)) @@ -732,7 +732,7 @@ theorem eval_erase (ρ : Val) (fields : List StorageField) (ctx : Context) (rt : 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, WExpr.eval, - hrel.sender, callerWord] + hrel.sender] rfl | storageRead m x idx => cases m diff --git a/SolidCore/Refinement/Generic/SourceRun.lean b/SolidCore/Refinement/Generic/SourceRun.lean index e9cb4abd..fc64ffe9 100644 --- a/SolidCore/Refinement/Generic/SourceRun.lean +++ b/SolidCore/Refinement/Generic/SourceRun.lean @@ -8,10 +8,10 @@ import SolidCore.Refinement.Dirty.Source `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⟩).obs`, where `T` is the erasure `eraseFn` of `fn` in the +when `σ` writes every slot `s` does (`Covers s σ`), SolidCore's `Source.runFrom caller` shows +`(T.eval ⟨args, slotValue σ, solHash, caller⟩).obs`, from any `caller` below `2 ^ 160`, 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`. +argument words, its storage, SolidCore's slot hash `solHash` and its sender. 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 @@ -20,7 +20,7 @@ dirty for its parameter's width reverts with empty data (`run_rejected`), as the 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 +runtime that `StmtRel` relates to `initState`: the context's caller is the call's 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 @@ -593,12 +593,12 @@ theorem paramGuards_eval (ρ : Val) (t : Tree) (hρ : ∀ a ∈ ρ.args, a < wor /-- **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} +theorem run_rejected (caller : 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.run fuel c { calldata := Abi.calldata sel args, callvalue := 0, storage := σ } = + Source.runFrom caller 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 @@ -606,7 +606,7 @@ theorem run_rejected {fuel : Nat} {c : TypeCheck.CheckedContract} {d : Source.St split at hdep case h_2 => simp at hdep rename_i deployed st hcons - simp only [Source.run, Source.result?, hcons, + simp only [Source.runFrom, Source.resultFrom?, hcons, TypeCheck.CheckedContract.callCalldataAtFromWithContext?, ABI.Contract.callCalldataAtFromWithContext?, Dirty.bytes_calldata, Dirty.readSelector_calldata _ hsel, hfind] @@ -640,7 +640,7 @@ theorem eraseFn_widths {E : EraseEnv} {fuel : Nat} {fn : FunctionDef} {T : Tree} /-- 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} +theorem source_run_clean (caller : Nat) (hcaller : caller < 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} @@ -650,10 +650,10 @@ theorem source_run_clean {fuel : Nat} {c : TypeCheck.CheckedContract} {d : Sourc (hT : brTree fn b = some T) (args : List Nat) (hlen : args.length = fn.params.length) (hargs : ∀ a ∈ args, a < 2 ^ 256) (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⟩).obs := by + Source.runFrom caller fuel c { calldata := Abi.calldata sel args, callvalue := 0, storage := σ } = + some (T.eval ⟨args, slotValue σ, solHash, caller⟩).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] + SolidCore.Refinement.Wide.run_eq_atFrom caller 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] @@ -662,7 +662,7 @@ theorem source_run_clean {fuel : Nat} {c : TypeCheck.CheckedContract} {d : Sourc have hp := (widthsOf_spec hw).2.2.1 have hr : ∀ r ∈ fn.returns, r.ty = .uint256 ∧ 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 + generalize hctx : ABI.Contract.callContextAtWithBase c.core (Wide.ctxOf c) selfAddress caller 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 @@ -670,7 +670,7 @@ theorem source_run_clean {fuel : Nat} {c : TypeCheck.CheckedContract} {d : Sourc 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⟩ with hρ + set ρ : Val := ⟨args, slotValue σ, solHash, caller⟩ with hρ have hρok : ρ.Ok := slotValue_store σ have hframe : fn.initialFrame? (args.map .word) = some (frameOf ρ (paramLocals fn.params 0 ++ fn.returns.map fun r => (r.name, .lit 0))) := by @@ -689,7 +689,14 @@ theorem source_run_clean {fuel : Nat} {c : TypeCheck.CheckedContract} {d : Sourc { fields := by subst hctx; rfl events := by subst hctx; rfl checked := by subst hctx; rfl - sender := by subst hctx; rfl + sender := by + subst hctx + have h256 : caller < SolidCore.Solidity.Shared.wordModulus := + Nat.lt_of_lt_of_le hcaller (by decide) + have h160 : caller % 1461501637330902918203684832716283019655932542976 = caller := + Nat.mod_eq_of_lt hcaller + simp [ABI.Contract.callContextAtWithBase, SolidCore.Solidity.Shared.norm, + Nat.mod_eq_of_lt h256, h160, hρ] hash := rfl ok := hρok frames := rfl @@ -783,14 +790,14 @@ theorem source_run_clean {fuel : Nat} {c : TypeCheck.CheckedContract} {d : Sourc /-- **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} +theorem source_run (caller : Nat) (hcaller : caller < 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 : 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⟩).obs := by + Source.runFrom caller fuel c { calldata := Abi.calldata sel args, callvalue := 0, storage := σ } = + some (T.eval ⟨args, slotValue σ, solHash, caller⟩).obs := by unfold eraseFn at hT split at hT · simp at hT @@ -800,15 +807,15 @@ theorem source_run {fuel : Nat} {c : TypeCheck.CheckedContract} {d : Source.Stat 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⟩ t hargs ws 0, List.drop_zero] + rw [paramGuards_eval ⟨args, slotValue σ, solHash, caller⟩ 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 hdec + exact source_run_clean caller hcaller hd hcov hsel hfind hw hret hb ht args hlen hargs hdec · rw [if_neg hclean] rw [if_neg hclean] at hdec - rw [run_rejected hd hsel hfind args hdec σ] + rw [run_rejected caller hd hsel hfind args hdec σ] rfl end SolidCore.Refinement.Generic diff --git a/SolidCore/Refinement/Generic/SourceStmt.lean b/SolidCore/Refinement/Generic/SourceStmt.lean index 94882736..0ab595a5 100644 --- a/SolidCore/Refinement/Generic/SourceStmt.lean +++ b/SolidCore/Refinement/Generic/SourceStmt.lean @@ -334,14 +334,14 @@ def logOf (ev : Event) : List Nat × List Nat := 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`, +storage fields and events are the erasure's, arithmetic is checked, the caller is the call's, `ρ.caller`, 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 = callerWord + sender : ctx.sender = ρ.caller % 2 ^ 160 hash : ρ.hash = solHash ok : ρ.Ok frames : rt.locals = S.scopes.map (frameOf ρ) diff --git a/SolidCore/Refinement/Generic/Stage.lean b/SolidCore/Refinement/Generic/Stage.lean index 0caac7bb..3a72bcec 100644 --- a/SolidCore/Refinement/Generic/Stage.lean +++ b/SolidCore/Refinement/Generic/Stage.lean @@ -29,6 +29,12 @@ its Keccak-256 of the 64 bytes of two words is SolidCore's slot hash `solHash` o module that reads the caller and hashes nothing, under every oracle with SolidCore's caller. Nothing else of the oracle is assumed. +The caller is not fixed: `stageAtWithFrom` is the stage from SolidCore called from any account +`a` below `2 ^ 160` (`solidCoreFrom a`), under every oracle whose caller is `a` when the flags +read it (`SourceAskAt a`), since both trees read the caller as the symbolic word `WExpr.caller`. +`stageAtEnvFrom`, `stageEnvFrom`, `stageAtCallerFrom` and `stageCallerFrom` are its cases, and +the stages above are its case `a = callerAddress`. + 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`-word returns, checked `+`, `-`, `*` with narrow cleanups, truncating casts such as `uint256(a)`, bitwise `&`, `|`, `^`, @@ -92,11 +98,11 @@ theorem calldataWord_eq (call : Call) (off : BitVec 256) : 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⟩`. -/ -theorem callFacts (sel : Nat) (hsel : sel < 2 ^ 32) (args : List Nat) +symbolic run its facts, with the argument words, the storage, SolidCore's slot hash and any +sender `caller`: `⟨args, slotValue σ, solHash, caller⟩`. -/ +theorem callFacts (caller : Nat) (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⟩ + CallFacts sel args.length ⟨args, slotValue σ, solHash, caller⟩ { calldata := Abi.calldata sel args, callvalue := 0, storage := σ } := by have hcd := calldata_eq_cdOf sel args hargs refine ⟨rfl, ?_, ?_, ?_, rfl, slotValue_store σ⟩ @@ -134,18 +140,71 @@ 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⟩ := +/-- The oracle's caller is the account `a`. -/ +def CallerAt (a : Nat) (o : Oracle) : Prop := (o.caller.setWidth 256).toNat = a + +/-- What the stages with the environment flag ask of the oracle on a call from the account `a`: +its caller is `a` (`CallerAt`) and `HashOk`. -/ +structure SourceEnvOkAt (a : Nat) (o : Oracle) : Prop where + caller : CallerAt a o + hash : HashOk o + +/-- An oracle with SolidCore's caller has the caller `callerAddress`. -/ +theorem CallerOk.at {o : Oracle} (h : CallerOk o) : CallerAt callerAddress o := h + +/-- An oracle `SourceEnvOk` describes is one `SourceEnvOkAt callerAddress` describes. -/ +theorem SourceEnvOk.at {o : Oracle} (h : SourceEnvOk o) : SourceEnvOkAt callerAddress o := ⟨h.caller, h.hash⟩ +/-- An oracle `SourceEnvOkAt a` describes is one the symbolic run with the environment flag takes, +for every call from `a` whose hash is `solHash`. -/ +theorem SourceEnvOkAt.envOk {a : Nat} (ha : a < 2 ^ 160) {o : Oracle} (h : SourceEnvOkAt a o) + (args : List Nat) (store : Nat → Nat) : EnvOk o ⟨args, store, solHash, a⟩ := + ⟨by rw [h.caller, Nat.mod_eq_of_lt ha], h.hash⟩ + +/-- An oracle `SourceEnvOk` describes is one the symbolic run with the environment flag takes, for +every call from `callerAddress` whose hash is `solHash`. -/ +theorem SourceEnvOk.envOk {o : Oracle} (h : SourceEnvOk o) (args : List Nat) (store : Nat → Nat) : + EnvOk o ⟨args, store, solHash, callerAddress⟩ := + h.at.envOk (by decide) args store + /-- 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 +/-- What the flags `env` ask of the oracle on a call from the account `a`: the caller `a` when +they read the caller, and SolidCore's hash of two words when they hash. -/ +structure SourceAskAt (a : Nat) (env : EnvFlags) (o : Oracle) : Prop where + caller : env.caller = true → CallerAt a o + hash : env.hash = true → HashOk o + +/-- What `SourceAsk` asks is what `SourceAskAt callerAddress` asks. -/ +theorem SourceAsk.at {env : EnvFlags} {o : Oracle} (h : SourceAsk env o) : + SourceAskAt callerAddress env o := + ⟨h.caller, h.hash⟩ + +/-- The flags off ask nothing, from any account. -/ +theorem SourceAskAt.off {a : Nat} {o : Oracle} : SourceAskAt a .off o := + ⟨fun h => by simp [EnvFlags.off] at h, fun h => by simp [EnvFlags.off] at h⟩ + +/-- An oracle `SourceEnvOkAt a` describes gives every flag what it asks on a call from `a`. -/ +theorem SourceEnvOkAt.ask {a : Nat} {o : Oracle} (h : SourceEnvOkAt a o) {env : EnvFlags} : + SourceAskAt a env o := + ⟨fun _ => h.caller, fun _ => h.hash⟩ + +/-- An oracle with the caller `a` gives the caller-only flags what they ask on a call from `a`. -/ +theorem CallerAt.ask {a : Nat} {o : Oracle} (h : CallerAt a o) : SourceAskAt a .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 from `a` whose hash is +`solHash`. -/ +theorem SourceAskAt.envAsk {a : Nat} (ha : a < 2 ^ 160) {env : EnvFlags} {o : Oracle} + (h : SourceAskAt a env o) (args : List Nat) (store : Nat → Nat) : + EnvAsk env o ⟨args, store, solHash, a⟩ := + ⟨fun hc => by rw [h.caller hc, Nat.mod_eq_of_lt ha], h.hash⟩ + /-- 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⟩ @@ -158,10 +217,11 @@ theorem SourceEnvOk.ask {o : Oracle} (h : SourceEnvOk o) {env : EnvFlags} : Sour 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`. -/ +/-- What the flags ask of the oracle, for the symbolic run on a call from `callerAddress` 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⟩ := - ⟨h.caller, h.hash⟩ + (store : Nat → Nat) : EnvAsk env o ⟨args, store, solHash, callerAddress⟩ := + h.at.envAsk (by decide) args store /-! ## The check and the stage -/ @@ -185,13 +245,17 @@ def check (fuel mirFuel : Nat) (core : Contract) (m : Module) (fns : List Fn) (e 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) +/-- **The generic source stage from any caller**, for `check` with the environment flag `env`: +SolidCore called from the account `a` (any address, below `2 ^ 160`) to the module's lowered MIR +semantics under every oracle when the flag is off, and under every oracle whose caller is `a` +and, when the flags hash, whose hash is SolidCore's (`SourceAskAt a env`). -/ +theorem stageAtWithFrom (a : Nat) (ha : a < 2 ^ 160) (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 : SourceAskAt a 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 + 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 checkFn at hcf @@ -206,14 +270,23 @@ theorem stageAtWith (o : Oracle) {fuel mirFuel : Nat} {c : TypeCheck.CheckedCont | some t2 => simp only [hfind, ht1, ht2, Bool.and_eq_true, decide_eq_true_eq] at hcf obtain ⟨hsel, hpl, hcf⟩ := 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 + have hsrc := source_run 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 (callFacts f.sel hsel args hargs σ) o m (henv.envAsk _ _) ht2, + rw [symTree_sound (callFacts a f.sel hsel args hargs σ) o m (henv.envAsk ha _ _) ht2, ← Tree.eval_canon, ← hcf, Tree.eval_canon] +/-- 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) := + stageAtWithFrom callerAddress (by decide) o hd henv.at hchk + /-- **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 @@ -287,4 +360,45 @@ theorem stageCaller (o : Oracle) (henv : CallerOk o) {fuel mirFuel : Nat} SolarTV.Stage.mono (stageAtCaller o henv hd hchk) fun _ ⟨σ, h⟩ => ⟨σ, fun _ hkv => absurd hkv List.not_mem_nil, h⟩ +/-- **The generic source stage with the environment flag, from any caller**: `stageAtEnv` on calls +from the account `a`, under every oracle whose caller is `a` and whose Keccak-256 of two words is +`solHash` (`SourceEnvOkAt a`). -/ +theorem stageAtEnvFrom (a : Nat) (ha : a < 2 ^ 160) (o : Oracle) (henv : SourceEnvOkAt 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 : check fuel mirFuel c.core m fns .all = true) : + Stage (solidCoreFrom a fuel) (moduleSem o) c m + (fun call => ∃ σ, Covers s σ ∧ fullScope fns σ call) := + stageAtWithFrom a ha o hd henv.ask hchk + +/-- The generic source stage with the environment flag from any caller, for a contract whose +constructor leaves no storage, from any storage. -/ +theorem stageEnvFrom (a : Nat) (ha : a < 2 ^ 160) (o : Oracle) (henv : SourceEnvOkAt a 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 (solidCoreFrom a fuel) (moduleSem o) c m (fun call => ∃ σ, fullScope fns σ call) := + SolarTV.Stage.mono (stageAtEnvFrom a ha o henv hd hchk) fun _ ⟨σ, h⟩ => + ⟨σ, fun _ hkv => absurd hkv List.not_mem_nil, h⟩ + +/-- **The caller-only stage from any caller**: `stageAtCaller` on calls from the account `a`, +under every oracle whose caller is `a`. -/ +theorem stageAtCallerFrom (a : Nat) (ha : a < 2 ^ 160) (o : Oracle) (henv : CallerAt 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 : check fuel mirFuel c.core m fns .callerOnly = true) : + Stage (solidCoreFrom a fuel) (moduleSem o) c m + (fun call => ∃ σ, Covers s σ ∧ fullScope fns σ call) := + stageAtWithFrom a ha o hd henv.ask hchk + +/-- The caller-only stage from any caller, for a contract whose constructor leaves no storage, +from any storage. -/ +theorem stageCallerFrom (a : Nat) (ha : a < 2 ^ 160) (o : Oracle) (henv : CallerAt a 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 (solidCoreFrom a fuel) (moduleSem o) c m (fun call => ∃ σ, fullScope fns σ call) := + SolarTV.Stage.mono (stageAtCallerFrom a ha 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/Tree.lean b/SolidCore/Refinement/Generic/Tree.lean index 41bbf7d1..468452ceb 100644 --- a/SolidCore/Refinement/Generic/Tree.lean +++ b/SolidCore/Refinement/Generic/Tree.lean @@ -88,6 +88,8 @@ inductive WExpr where | 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, an address (`Val.caller`, below `2 ^ 160`). -/ + | caller deriving DecidableEq, Repr /-- What a call reads: its argument words, the callee's storage before it, and the hash of two @@ -97,6 +99,8 @@ structure Val where args : List Nat store : Nat → Nat hash : Nat → Nat → Nat + /-- The account that sent the call (`WExpr.caller` reads it below `2 ^ 160`). -/ + caller : Nat /-- The value of a word of the call, below `2 ^ 256`. -/ def WExpr.eval (ρ : Val) : WExpr → Nat @@ -108,6 +112,7 @@ def WExpr.eval (ρ : Val) : WExpr → Nat | .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 % 2 ^ 160 theorem WExpr.eval_lt (ρ : Val) : ∀ e : WExpr, e.eval ρ < wordSize | .sel c a b => by @@ -117,6 +122,7 @@ theorem WExpr.eval_lt (ρ : Val) : ∀ e : WExpr, e.eval ρ < wordSize · exact WExpr.eval_lt ρ a | .lit _ | .arg _ | .init _ | .un _ _ | .bin _ _ _ | .sinit _ | .hash _ _ => Nat.mod_lt _ (by decide) + | .caller => Nat.lt_of_lt_of_le (Nat.mod_lt _ (by decide)) (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 @@ -385,6 +391,7 @@ def WExpr.norm : WExpr → WExpr | .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] @@ -398,6 +405,7 @@ theorem WExpr.eval_norm (ρ : Val) : ∀ e : WExpr, e.norm.eval ρ = e.eval ρ 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 diff --git a/SolidCore/Refinement/Generic/Value.lean b/SolidCore/Refinement/Generic/Value.lean index 406553ac..1f6f6d01 100644 --- a/SolidCore/Refinement/Generic/Value.lean +++ b/SolidCore/Refinement/Generic/Value.lean @@ -62,14 +62,14 @@ theorem fullScopeValue_zero (fns : List Fn) (s : List (Nat × Nat)) (call : Call /-- **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} +theorem source_run_value (caller : 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) {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 := σ } = + Source.runFrom caller fuel c { calldata := Abi.calldata sel args, callvalue := v, storage := σ } = some (rejected σ) := by obtain ⟨s0, hdep⟩ := deployedStorage_of hd unfold Abi.deployedStorage at hdep @@ -91,7 +91,7 @@ theorem source_run_value {fuel : Nat} {c : TypeCheck.CheckedContract} {d : Sourc 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', + simp only [Source.runFrom, Source.resultFrom?, hcons', TypeCheck.CheckedContract.callCalldataAtFromWithContext?, ABI.Contract.callCalldataAtFromWithContext?, Dirty.bytes_calldata, Dirty.readSelector_calldata _ hsel, hfind] @@ -147,21 +147,21 @@ def checkValue (mirFuel : Nat) (core : Contract) (m : Module) (fns : List Fn) (e /-! ## 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)} +/-- **The generic source stage at every value from any caller**, for `check` and `checkValue` with +the environment flag `env`: SolidCore called from the account `a` below `2 ^ 160`, under every +oracle when the flag is off and every oracle `SourceAskAt a env` describes when it is on. -/ +theorem stageAtValueWithFrom (a : Nat) (ha : a < 2 ^ 160) (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) + {m : Module} {fns : List Fn} {env : EnvFlags} (henv : SourceAskAt a 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 + Stage (solidCoreFrom a 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 + exact stageAtWithFrom a ha 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 @@ -180,12 +180,12 @@ theorem stageAtValueWith (o : Oracle) {fuel mirFuel : Nat} {c : TypeCheck.Checke 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 + have hsrc := source_run_value a hd hsel hfind hw hpay args (by rw [hlen, hpl]) hargs hv0 hv σ + change Source.runFrom a 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⟩ + have hc0 := callFacts a f.sel hsel args hargs σ + have hcfv : CallFactsAt .paid f.sel args.length ⟨args, slotValue σ, solHash, a⟩ { calldata := Abi.calldata f.sel args, callvalue := v, storage := σ } := { value := by show BitVec.ofNat 256 v ≠ 0 @@ -200,9 +200,22 @@ theorem stageAtValueWith (o : Oracle) {fuel mirFuel : Nat} {c : TypeCheck.Checke store := hc0.store ok := hc0.ok } rw [← hlen] at ht2 - rw [symTreeValue_sound hcfv o m (henv.envAsk _ _) ht2, Tree.eval_revertsEmpty _ _ hrev] + rw [symTreeValue_sound hcfv o m (henv.envAsk ha _ _) ht2, Tree.eval_revertsEmpty _ _ hrev] rfl +/-- 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) := + stageAtValueWithFrom callerAddress (by decide) o hd henv.at hchk hval + /-- **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 @@ -282,4 +295,29 @@ theorem stageValueCaller (o : Oracle) (henv : CallerOk o) {fuel mirFuel : Nat} SolarTV.Stage.mono (stageAtValueWith o hd henv.ask 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 from any caller, for a +contract whose constructor leaves no storage, from any storage, under every oracle +`SourceEnvOkAt a` describes. -/ +theorem stageValueEnvFrom (a : Nat) (ha : a < 2 ^ 160) (o : Oracle) (henv : SourceEnvOkAt a 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 (solidCoreFrom a fuel) (moduleSem o) c m + (fun call => ∃ σ v, fullScopeValue fns σ v call) := + SolarTV.Stage.mono (stageAtValueWithFrom a ha o hd henv.ask hchk hval) fun _ ⟨σ, v, h⟩ => + ⟨σ, v, fun _ hkv => absurd hkv List.not_mem_nil, h⟩ + +/-- The caller-only stage at every value from any caller, for a contract whose constructor leaves +no storage, from any storage, under every oracle whose caller is `a`. -/ +theorem stageValueCallerFrom (a : Nat) (ha : a < 2 ^ 160) (o : Oracle) (henv : CallerAt a 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 (solidCoreFrom a fuel) (moduleSem o) c m + (fun call => ∃ σ v, fullScopeValue fns σ v call) := + SolarTV.Stage.mono (stageAtValueWithFrom a ha 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/Solar/AssembleSim.lean b/SolidCore/Refinement/Solar/AssembleSim.lean index 7b466576..2987344b 100644 --- a/SolidCore/Refinement/Solar/AssembleSim.lean +++ b/SolidCore/Refinement/Solar/AssembleSim.lean @@ -747,6 +747,14 @@ 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⟩ } +/-- An oracle whose CALLER is the account `a`, the caller of `Target.runFrom a`'s calls, and whose +hash is EthLib's. `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 + 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⟩ @@ -770,9 +778,10 @@ open SolarTV.EVM.Program in 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} + {a : Nat} (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) + (hcaller : msg.caller = Target.address a) (ho : c.env = true → OracleOkAt a 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) @@ -1391,9 +1400,10 @@ open SolarTV.EVM.Program in 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} + {a : Nat} (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) : + (hcaller : msg.caller = Target.address a) (ho : c.env = true → OracleOkAt a 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), @@ -1763,6 +1773,210 @@ theorem run_of_rel (code : ByteArray) (call : SolarTV.Call) (s : SolarTV.Machine · simp only [ite_true] exact (hst hs).2 slot +section CallFrom + +open EthLib.Execution.State + +/-! ## Calls from any caller + +`Target.runFrom a` is `Target.run` with the account `a` as the caller and origin, holding the +call's value. The lemmas above hold for it as long as `a`'s account is not the contract's +(`Target.address selfAddress ≠ Target.address a`): the contract's account and storage are the +same, the caller holds exactly the call's value, and CALLER is `a`. -/ + +/-- 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_messageFrom (a : Nat) (code : ByteArray) (call : SolarTV.Call) : + precompileAddress .fusaka (Target.messageFrom a 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`. -/ +theorem rel_initialFrom (a : Nat) (hAB : Target.address selfAddress ≠ Target.address a) + (code : ByteArray) (call : SolarTV.Call) : + Rel (Target.messageFrom a code call) Substate.empty (Target.preStateFrom a code call) + Substate.empty (SolarTV.Machine.State.initial call) := by + have htgt : (Target.messageFrom a 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` from the account `a`: `Target.runFrom a` of any call, with or without value. -/ +theorem run_of_relFrom (a : 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.messageFrom a code call) Substate.empty st Substate.empty + (SolarTV.Machine.State.initial call) → + Spec .fusaka (At code (Target.messageFrom a code call) 0 [] .empty 10000000 st Substate.empty + .empty) (PostL call (Target.address selfAddress) Substate.empty s halt)) : + Target.runFrom a code call = some (SolarTV.Machine.observe call s halt) := by + have key : ∃ evm, processMessage (Meter := Nat) .fusaka (Target.messageFrom a 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.messageFrom a code call).value = 0 + · exact processMessage_postL _ rfl hv (precompileAddress_messageFrom a code call) _ _ _ _ _ + (h _ (rel_initialFrom a 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 hAB code call + have R : Rel (Target.messageFrom a 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_messageFrom a 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.runFrom, 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 any caller**: `stage_of_check_env` with EthLib called from the account +`a` (`ethLibFrom a`), any account but the contract's, under every oracle whose caller is `a` +and whose hash is EthLib's when the program reads them. -/ +theorem stage_of_check_envFrom (a : Nat) (hAB : Target.address selfAddress ≠ Target.address a) + {p : Program} {code : ByteArray} {c : Cert} (hc : check p code c = true) + (o : SolarTV.Machine.Oracle) (ho : c.env = true → OracleOkAt a o) (scope : SolarTV.Call → Prop) : + SolarTV.Stage (SolarTV.evmirSem o) (SolidCore.Refinement.ethLibFrom a) p + (show (SolidCore.Refinement.ethLibFrom a).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_relFrom a hAB code call r.2 r.1 fun st R => + run_sim (msg := Target.messageFrom a code call) + (ss0 := Substate.empty) G rfl (by simp [Target.messageFrom]) 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_envFrom' depends on axioms: [propext, Classical.choice, Quot.sound] +-/ +#guard_msgs in +#print axioms stage_of_check_envFrom + +end CallFrom + /-- 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 diff --git a/SolidCore/Refinement/Solar/Bank/Assembly.lean b/SolidCore/Refinement/Solar/Bank/Assembly.lean index 05bcc04a..c70f9bd0 100644 --- a/SolidCore/Refinement/Solar/Bank/Assembly.lean +++ b/SolidCore/Refinement/Solar/Bank/Assembly.lean @@ -89,6 +89,24 @@ theorem backend (o : SolarTV.Machine.Oracle) (ho : Assemble.OracleOk o) SolarTV.Stage.trans (B := SolarTV.evmirSem o) (fun call _ => SolarTV.Milestone.Bank.bank_mir_to_evmir o call trivial) (stageOk o ho scope) +/-- EVM IR to bytecode from any caller: on every call from the account `a`, any account but the +contract's, under every oracle whose caller is `a` and whose hash is EthLib's. -/ +theorem stageOkFrom (a : Nat) (hAB : Target.address selfAddress ≠ Target.address a) + (o : SolarTV.Machine.Oracle) (ho : Assemble.OracleOkAt a o) (scope : SolarTV.Call → Prop) : + SolarTV.Stage (SolarTV.evmirSem o) (SolidCore.Refinement.ethLibFrom a) evm11 + (show (SolidCore.Refinement.ethLibFrom a).Prog from code) scope := + Assemble.stage_of_check_envFrom a hAB check_ok o (fun _ => ho) scope + +/-- The backend from any caller: solar-tv's stages from stage0 to evm11, then the assembly stage, +on every call from the account `a`, under every oracle whose caller is `a` and whose hash is +EthLib's. -/ +theorem backendFrom (a : Nat) (hAB : Target.address selfAddress ≠ Target.address a) + (o : SolarTV.Machine.Oracle) (ho : Assemble.OracleOkAt a o) (scope : SolarTV.Call → Prop) : + SolarTV.Stage (SolarTV.mirSem o) (SolidCore.Refinement.ethLibFrom a) stage0 + (show (SolidCore.Refinement.ethLibFrom a).Prog from code) scope := + SolarTV.Stage.trans (B := SolarTV.evmirSem o) + (fun call _ => SolarTV.Milestone.Bank.bank_mir_to_evmir o call trivial) (stageOkFrom a hAB o ho scope) + /-- info: 'SolidCore.Refinement.Solar.Bank.check_ok' depends on axioms: [propext, Quot.sound] -/ #guard_msgs in #print axioms check_ok @@ -101,4 +119,8 @@ theorem backend (o : SolarTV.Machine.Oracle) (ho : Assemble.OracleOk o) #guard_msgs in #print axioms backend +/-- info: 'SolidCore.Refinement.Solar.Bank.backendFrom' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms backendFrom + end SolidCore.Refinement.Solar.Bank diff --git a/SolidCore/Refinement/Solar/Bank/Certified.lean b/SolidCore/Refinement/Solar/Bank/Certified.lean index bf83b3f9..447613ab 100644 --- a/SolidCore/Refinement/Solar/Bank/Certified.lean +++ b/SolidCore/Refinement/Solar/Bank/Certified.lean @@ -35,6 +35,12 @@ decode to those bytes. The sha256s are of the files, checked outside the kernel 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`). +The caller is not fixed: `certifiedFrom`, `certifiedValueFrom` and their primed forms are the same +stages with both sides called from any account `a` below `2 ^ 160` other than the contract's +(`solidCoreFrom a`, `ethLibFrom a`), under every oracle whose caller is `a` and whose hash is +EthLib's (`Assemble.OracleOkAt a`); `certified` and the rest are their case `callerAddress`. +`certifiedManifestFrom` and `certifiedManifestFrom'` bind them to the manifest. + No sorry, native_decide or bv_decide: the theorems depend on propext, Classical.choice and Quot.sound only (pinned below). -/ @@ -82,6 +88,40 @@ theorem certifiedValue (o : SolarTV.Machine.Oracle) (ho : Assemble.OracleOk o) 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 _) +/-- An oracle whose caller is EthLib's caller `a`, an address, has the caller `a` as a word. -/ +theorem callerAt_of (a : Nat) (ha : a < 2 ^ 160) (o : SolarTV.Machine.Oracle) + (ho : Assemble.OracleOkAt a o) : Generic.CallerAt a o := by + unfold Generic.CallerAt + rw [ho.1] + exact Assemble.address_toNat ha + +/-- An oracle with EthLib's caller `a` and hash is one the source stage from `a` takes, when +EthLib's and SolidCore's Keccak-256 agree on two words. -/ +theorem sourceEnvOkAt_of (a : Nat) (ha : a < 2 ^ 160) (o : SolarTV.Machine.Oracle) + (ho : Assemble.OracleOkAt a o) (hk : EthKeccakAgree) : Generic.SourceEnvOkAt a o := + ⟨callerAt_of a ha o ho, fun x y hx hy => by rw [ho.2]; exact hk x y hx hy⟩ + +/-- **Bank from SolidCore to solar's bytecode, from any caller**: every result SolidCore's `Bank` +gives on a call of `deposit`, `depositFor` and `balanceOf` from the account `a` (any address +below `2 ^ 160` but the contract's) on any argument words, no value, from any storage, the +bytecode gives under EthLib called from `a`, for every oracle whose caller is `a` and whose +hash is EthLib's. -/ +theorem certifiedFrom (a : Nat) (ha : a < 2 ^ 160) (hself : a ≠ selfAddress) + (o : SolarTV.Machine.Oracle) (ho : Assemble.OracleOkAt a o) (hk : EthKeccakAgree) + {c : TypeCheck.CheckedContract} (hc : contract? = .ok c) : + Stage (solidCoreFrom a fuel) (ethLibFrom a) c code (fun call => ∃ σ, fullScope fns σ call) := + (loweringFrom a ha o (sourceEnvOkAt_of a ha o ho hk) hc).trans + (backendFrom a (Assemble.address_ne_self ha hself) o ho _) + +/-- **Bank from SolidCore to solar's bytecode at every value, from any caller**. -/ +theorem certifiedValueFrom (a : Nat) (ha : a < 2 ^ 160) (hself : a ≠ selfAddress) + (o : SolarTV.Machine.Oracle) (ho : Assemble.OracleOkAt a o) (hk : EthKeccakAgree) + {c : TypeCheck.CheckedContract} (hc : contract? = .ok c) : + Stage (solidCoreFrom a fuel) (ethLibFrom a) c code + (fun call => ∃ σ v, Generic.fullScopeValue fns σ v call) := + (loweringValueFrom a ha o (sourceEnvOkAt_of a ha o ho hk) hc).trans + (backendFrom a (Assemble.address_ne_self ha hself) 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. -/ @@ -174,6 +214,69 @@ theorem certifiedManifest' (o : SolarTV.Machine.Oracle) (ho : Assemble.OracleOk Stage (solidCore fuel) ethLib c code (fun call => ∃ σ v, Generic.fullScopeValue fns σ v call) := certifiedManifest o ho ethKeccakAgree hc +/-- **Bank from SolidCore to solar's bytecode from any caller**, with no Keccak hypothesis. -/ +theorem certifiedFrom' (a : Nat) (ha : a < 2 ^ 160) (hself : a ≠ selfAddress) + (o : SolarTV.Machine.Oracle) (ho : Assemble.OracleOkAt a o) + {c : TypeCheck.CheckedContract} (hc : contract? = .ok c) : + Stage (solidCoreFrom a fuel) (ethLibFrom a) c code (fun call => ∃ σ, fullScope fns σ call) := + certifiedFrom a ha hself o ho ethKeccakAgree hc + +/-- **Bank from SolidCore to solar's bytecode at every value from any caller**, with no Keccak +hypothesis. -/ +theorem certifiedValueFrom' (a : Nat) (ha : a < 2 ^ 160) (hself : a ≠ selfAddress) + (o : SolarTV.Machine.Oracle) (ho : Assemble.OracleOkAt a o) + {c : TypeCheck.CheckedContract} (hc : contract? = .ok c) : + Stage (solidCoreFrom a fuel) (ethLibFrom a) c code + (fun call => ∃ σ v, Generic.fullScopeValue fns σ v call) := + certifiedValueFrom a ha hself o ho ethKeccakAgree hc + +open SolarTV.Export.Bank Hex in +/-- **The certified translation of bank from any caller**, bound to its manifest: +`certifiedManifest`'s conjunction with the stages on every call from the account `a` (any address +below `2 ^ 160` but the contract's), under every oracle whose caller is `a` and whose hash is +EthLib's, given `EthKeccakAgree` (`certifiedManifestFrom'` discharges it). -/ +theorem certifiedManifestFrom (a : Nat) (ha : a < 2 ^ 160) (hself : a ≠ selfAddress) + (o : SolarTV.Machine.Oracle) (ho : Assemble.OracleOkAt a o) (hk : EthKeccakAgree) + {c : TypeCheck.CheckedContract} (hc : contract? = .ok c) : + Manifest.sources = [("solar-tv/milestone/bank/bank.sol", + "513398d47335b204a6b047493dd86e9c05066e950ba1300ba5d25850a5f8cb1f")] ∧ + Manifest.compiler = "0.8.38+commit.4a7d9ede.solar.0.3.0-dev" ∧ + Manifest.arguments = ["solar-tv/milestone/bank/bank.sol", "-Ogas", "--evm-version", "osaka", + "--emit=bin-runtime", "-Zemit-lean-stages=solar-tv/milestone/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 (solidCoreFrom a fuel) (ethLibFrom a) c code (fun call => ∃ σ, fullScope fns σ call) ∧ + Stage (solidCoreFrom a fuel) (ethLibFrom a) c code + (fun call => ∃ σ v, Generic.fullScopeValue fns σ v call) := + ⟨rfl, rfl, rfl, rfl, rfl, rfl, rfl, manifest_hex, bytecode_of_manifest, rfl, + certifiedFrom a ha hself o ho hk hc, certifiedValueFrom a ha hself o ho hk hc⟩ + +open SolarTV.Export.Bank Hex in +/-- **The certified translation of bank from any caller, with no Keccak hypothesis**, bound to its +manifest: `certifiedManifestFrom` with `EthKeccakAgree` discharged by `ethKeccakAgree`. -/ +theorem certifiedManifestFrom' (a : Nat) (ha : a < 2 ^ 160) (hself : a ≠ selfAddress) + (o : SolarTV.Machine.Oracle) (ho : Assemble.OracleOkAt a o) + {c : TypeCheck.CheckedContract} (hc : contract? = .ok c) : + Manifest.sources = [("solar-tv/milestone/bank/bank.sol", + "513398d47335b204a6b047493dd86e9c05066e950ba1300ba5d25850a5f8cb1f")] ∧ + Manifest.compiler = "0.8.38+commit.4a7d9ede.solar.0.3.0-dev" ∧ + Manifest.arguments = ["solar-tv/milestone/bank/bank.sol", "-Ogas", "--evm-version", "osaka", + "--emit=bin-runtime", "-Zemit-lean-stages=solar-tv/milestone/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 (solidCoreFrom a fuel) (ethLibFrom a) c code (fun call => ∃ σ, fullScope fns σ call) ∧ + Stage (solidCoreFrom a fuel) (ethLibFrom a) c code + (fun call => ∃ σ v, Generic.fullScopeValue fns σ v call) := + certifiedManifestFrom a ha hself o ho ethKeccakAgree hc + /-- info: 'SolidCore.Refinement.Solar.Bank.callerOk_of' depends on axioms: [propext, Quot.sound] -/ #guard_msgs in #print axioms callerOk_of @@ -214,4 +317,28 @@ theorem certifiedManifest' (o : SolarTV.Machine.Oracle) (ho : Assemble.OracleOk #guard_msgs in #print axioms certifiedManifest' +/-- info: 'SolidCore.Refinement.Solar.Bank.certifiedFrom' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms certifiedFrom + +/-- info: 'SolidCore.Refinement.Solar.Bank.certifiedValueFrom' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms certifiedValueFrom + +/-- info: 'SolidCore.Refinement.Solar.Bank.certifiedFrom'' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms certifiedFrom' + +/-- info: 'SolidCore.Refinement.Solar.Bank.certifiedValueFrom'' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms certifiedValueFrom' + +/-- info: 'SolidCore.Refinement.Solar.Bank.certifiedManifestFrom' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms certifiedManifestFrom + +/-- info: 'SolidCore.Refinement.Solar.Bank.certifiedManifestFrom'' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms certifiedManifestFrom' + end SolidCore.Refinement.Solar.Bank diff --git a/SolidCore/Refinement/Solar/Bank/Lowering.lean b/SolidCore/Refinement/Solar/Bank/Lowering.lean index 2be635fb..bfb3967e 100644 --- a/SolidCore/Refinement/Solar/Bank/Lowering.lean +++ b/SolidCore/Refinement/Solar/Bank/Lowering.lean @@ -555,6 +555,13 @@ def noCaller : SolarTV.MIR.Lowered.Inst → SolarTV.MIR.Lowered.Inst | .effect (some 1) .caller [] => .effect (some 1) .calldataload [.const 4] | i => i +/-- `deposit` crediting the constant word 0x2000, SolidCore's `callerAddress`, instead of +`msg.sender`: the generic check reads the caller as a symbolic word (`WExpr.caller`), not as that +constant, so it tells a module that reads CALLER from one that assumes a fixed caller. -/ +def fixedCaller : SolarTV.MIR.Lowered.Inst → SolarTV.MIR.Lowered.Inst + | .effect (some 1) .caller [] => .pure 1 .add [.const 0x2000, .const 0] + | 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] @@ -572,6 +579,12 @@ 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` crediting the constant 0x2000. -/ +theorem check_rejects_fixedCaller : + Generic.check fuel mirFuel coreLit (mapFn 1 fixedCaller) [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 : @@ -608,6 +621,25 @@ theorem loweringValue (o : SolarTV.Machine.Oracle) (henv : Generic.SourceEnvOk o exact Generic.stageValueEnv o henv hd (by rw [hk]; exact check_stage0) (by rw [hk]; exact checkValue_stage0) +/-- **The source stage of `Bank` from any caller**: `lowering` with SolidCore called from the +account `a` (any address, below `2 ^ 160`), under every oracle whose caller is `a` and whose +Keccak-256 of two words is SolidCore's (`Generic.SourceEnvOkAt a`). -/ +theorem loweringFrom (a : Nat) (ha : a < 2 ^ 160) (o : SolarTV.Machine.Oracle) + (henv : Generic.SourceEnvOkAt a o) {c : TypeCheck.CheckedContract} (hc : contract? = .ok c) : + Stage (solidCoreFrom a 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.stageEnvFrom a ha o henv hd (by rw [hk]; exact check_stage0) + +/-- **The source stage of `Bank` at every value from any caller**. -/ +theorem loweringValueFrom (a : Nat) (ha : a < 2 ^ 160) (o : SolarTV.Machine.Oracle) + (henv : Generic.SourceEnvOkAt a o) {c : TypeCheck.CheckedContract} (hc : contract? = .ok c) : + Stage (solidCoreFrom a 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.stageValueEnvFrom a ha o henv hd (by rw [hk]; exact check_stage0) + (by rw [hk]; exact checkValue_stage0) + #print axioms selector_eq #print axioms digest_eq @@ -624,8 +656,14 @@ theorem loweringValue (o : SolarTV.Machine.Oracle) (henv : Generic.SourceEnvOk o #print axioms check_rejects_topic +#print axioms check_rejects_fixedCaller + #print axioms lowering #print axioms loweringValue +#print axioms loweringFrom + +#print axioms loweringValueFrom + end SolidCore.Refinement.Solar.Bank diff --git a/SolidCore/Refinement/Solar/Events/Assembly.lean b/SolidCore/Refinement/Solar/Events/Assembly.lean index e70083c8..ed77e191 100644 --- a/SolidCore/Refinement/Solar/Events/Assembly.lean +++ b/SolidCore/Refinement/Solar/Events/Assembly.lean @@ -99,6 +99,24 @@ theorem mutantOffset_check : Assemble.check evm5 (mutant 0x46 0x59) cert = false rw [Assemble.check_eq_checkFast] decide +kernel +/-- EVM IR to bytecode from any caller: on every call from the account `a`, any account but the +contract's, under every oracle whose caller is `a` and whose hash is EthLib's. -/ +theorem stageOkFrom (a : Nat) (hAB : Target.address selfAddress ≠ Target.address a) + (o : SolarTV.Machine.Oracle) (ho : Assemble.OracleOkAt a o) (scope : SolarTV.Call → Prop) : + SolarTV.Stage (SolarTV.evmirSem o) (SolidCore.Refinement.ethLibFrom a) evm5 + (show (SolidCore.Refinement.ethLibFrom a).Prog from code) scope := + Assemble.stage_of_check_envFrom a hAB check_ok o (fun _ => ho) scope + +/-- The backend from any caller: solar-tv's stages from stage0 to evm5, then the assembly stage, +on every call from the account `a`, under every oracle whose caller is `a` and whose hash is +EthLib's. -/ +theorem backendFrom (a : Nat) (hAB : Target.address selfAddress ≠ Target.address a) + (o : SolarTV.Machine.Oracle) (ho : Assemble.OracleOkAt a o) (scope : SolarTV.Call → Prop) : + SolarTV.Stage (SolarTV.mirSem o) (SolidCore.Refinement.ethLibFrom a) stage0 + (show (SolidCore.Refinement.ethLibFrom a).Prog from code) scope := + SolarTV.Stage.trans (B := SolarTV.evmirSem o) + (fun call _ => SolarTV.Milestone.Events.events_mir_to_evmir o call trivial) (stageOkFrom a hAB o ho scope) + /-- info: 'SolidCore.Refinement.Solar.Events.check_ok' depends on axioms: [propext, Quot.sound] -/ #guard_msgs in #print axioms check_ok @@ -107,4 +125,8 @@ theorem mutantOffset_check : Assemble.check evm5 (mutant 0x46 0x59) cert = false #guard_msgs in #print axioms backend +/-- info: 'SolidCore.Refinement.Solar.Events.backendFrom' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms backendFrom + end SolidCore.Refinement.Solar.Events diff --git a/SolidCore/Refinement/Solar/Events/Certified.lean b/SolidCore/Refinement/Solar/Events/Certified.lean index a30e0d50..d5bd5bf8 100644 --- a/SolidCore/Refinement/Solar/Events/Certified.lean +++ b/SolidCore/Refinement/Solar/Events/Certified.lean @@ -20,6 +20,12 @@ An oracle with EthLib's caller has SolidCore's (`callerOk_of`), so `certified` h `Assemble.OracleOk` alone, for every call of `transfer` on any argument words, from any storage, with no value, and `certifiedValue` with any value. +The caller is not fixed: `certifiedFrom` and `certifiedValueFrom` are the same stages with both +sides called from any account `a` below `2 ^ 160` other than the contract's (`solidCoreFrom a`, +`ethLibFrom a`), under every oracle whose caller is `a` and whose hash is EthLib's +(`Assemble.OracleOkAt a`), and `certified` and `certifiedValue` are their case `callerAddress`. +`certifiedManifestFrom` binds them to the manifest as `certifiedManifest` does. + `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 @@ -62,6 +68,33 @@ theorem certifiedValue (o : SolarTV.Machine.Oracle) (ho : Assemble.OracleOk o) 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 _) +/-- An oracle whose caller is EthLib's caller `a`, an address, has the caller `a` as a word. -/ +theorem callerAt_of (a : Nat) (ha : a < 2 ^ 160) (o : SolarTV.Machine.Oracle) + (ho : Assemble.OracleOkAt a o) : Generic.CallerAt a o := by + unfold Generic.CallerAt + rw [ho.1] + exact Assemble.address_toNat ha + +/-- **Events from SolidCore to solar's bytecode, from any caller**: every result SolidCore's +`Events` gives on a call of `transfer` from the account `a` (any address below `2 ^ 160` but the +contract's) on any argument words, no value, from any storage, the bytecode gives under EthLib +called from `a`, for every oracle whose caller is `a` and whose hash is EthLib's. -/ +theorem certifiedFrom (a : Nat) (ha : a < 2 ^ 160) (hself : a ≠ selfAddress) + (o : SolarTV.Machine.Oracle) (ho : Assemble.OracleOkAt a o) + {c : TypeCheck.CheckedContract} (hc : contract? = .ok c) : + Stage (solidCoreFrom a fuel) (ethLibFrom a) c code (fun call => ∃ σ, fullScope fns σ call) := + (loweringFrom a ha o (callerAt_of a ha o ho) hc).trans + (backendFrom a (Assemble.address_ne_self ha hself) o ho _) + +/-- **Events from SolidCore to solar's bytecode at every value, from any caller**. -/ +theorem certifiedValueFrom (a : Nat) (ha : a < 2 ^ 160) (hself : a ≠ selfAddress) + (o : SolarTV.Machine.Oracle) (ho : Assemble.OracleOkAt a o) + {c : TypeCheck.CheckedContract} (hc : contract? = .ok c) : + Stage (solidCoreFrom a fuel) (ethLibFrom a) c code + (fun call => ∃ σ v, Generic.fullScopeValue fns σ v call) := + (loweringValueFrom a ha o (callerAt_of a ha o ho) hc).trans + (backendFrom a (Assemble.address_ne_self ha hself) 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. -/ @@ -110,6 +143,32 @@ theorem certifiedManifest (o : SolarTV.Machine.Oracle) (ho : Assemble.OracleOk o ⟨rfl, rfl, rfl, rfl, rfl, rfl, rfl, manifest_hex, bytecode_of_manifest, rfl, certified o ho hc, certifiedValue o ho hc⟩ +open SolarTV.Export.Events Hex in +/-- **The certified translation of events from any caller**, bound to its manifest: +`certifiedManifest`'s conjunction with the stages from SolidCore's checked `Events` to those bytes +on every call from the account `a` (any address below `2 ^ 160` but the contract's), with no +value and with any value, from any storage, under every oracle whose caller is `a` and whose hash +is EthLib's. -/ +theorem certifiedManifestFrom (a : Nat) (ha : a < 2 ^ 160) (hself : a ≠ selfAddress) + (o : SolarTV.Machine.Oracle) (ho : Assemble.OracleOkAt a o) + {c : TypeCheck.CheckedContract} (hc : contract? = .ok c) : + Manifest.sources = [("solar-tv/milestone/events/events.sol", + "8b951679cab695d07c193e56dd5d96d14a1c63976673c79a72c690f07c50b5b0")] ∧ + Manifest.compiler = "0.8.38+commit.0a455fda.solar.0.3.0-dev" ∧ + Manifest.arguments = ["solar-tv/milestone/events/events.sol", "-Ogas", "--evm-version", "osaka", + "--emit=bin-runtime", "-Zemit-lean-stages=solar-tv/milestone/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 (solidCoreFrom a fuel) (ethLibFrom a) c code (fun call => ∃ σ, fullScope fns σ call) ∧ + Stage (solidCoreFrom a fuel) (ethLibFrom a) c code + (fun call => ∃ σ v, Generic.fullScopeValue fns σ v call) := + ⟨rfl, rfl, rfl, rfl, rfl, rfl, rfl, manifest_hex, bytecode_of_manifest, rfl, + certifiedFrom a ha hself o ho hc, certifiedValueFrom a ha hself o ho hc⟩ + /-- info: 'SolidCore.Refinement.Solar.Events.callerOk_of' depends on axioms: [propext, Quot.sound] -/ #guard_msgs in #print axioms callerOk_of @@ -134,4 +193,20 @@ theorem certifiedManifest (o : SolarTV.Machine.Oracle) (ho : Assemble.OracleOk o #guard_msgs in #print axioms certifiedManifest +/-- info: 'SolidCore.Refinement.Solar.Events.callerAt_of' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms callerAt_of + +/-- info: 'SolidCore.Refinement.Solar.Events.certifiedFrom' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms certifiedFrom + +/-- info: 'SolidCore.Refinement.Solar.Events.certifiedValueFrom' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms certifiedValueFrom + +/-- info: 'SolidCore.Refinement.Solar.Events.certifiedManifestFrom' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms certifiedManifestFrom + end SolidCore.Refinement.Solar.Events diff --git a/SolidCore/Refinement/Solar/Events/Lowering.lean b/SolidCore/Refinement/Solar/Events/Lowering.lean index df4349aa..5d2453a5 100644 --- a/SolidCore/Refinement/Solar/Events/Lowering.lean +++ b/SolidCore/Refinement/Solar/Events/Lowering.lean @@ -215,6 +215,13 @@ def noCaller : SolarTV.MIR.Lowered.Inst → SolarTV.MIR.Lowered.Inst | .effect (some 3) .caller [] => .effect (some 3) .calldataload [.const 36] | i => i +/-- `transfer` logging the constant word 0x2000, SolidCore's `callerAddress`, as the caller topic: +the generic check reads the caller as a symbolic word (`WExpr.caller`), not as that constant, so it +tells a module that reads CALLER from one that assumes a fixed caller. -/ +def fixedCaller : SolarTV.MIR.Lowered.Inst → SolarTV.MIR.Lowered.Inst + | .effect (some 3) .caller [] => .pure 3 .add [.const 0x2000, .const 0] + | 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] @@ -231,6 +238,13 @@ 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` logging the constant 0x2000 for the +caller. -/ +theorem check_rejects_fixedCaller : + Generic.check fuel mirFuel coreLit (mapFn 0 fixedCaller) 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 : @@ -273,6 +287,25 @@ theorem loweringValue (o : SolarTV.Machine.Oracle) (henv : Generic.CallerOk o) exact Generic.stageValueCaller o henv hd (by rw [hk]; exact check_stage0) (by rw [hk]; exact checkValue_stage0) +/-- **The source stage of `Events` from any caller**: `lowering` with SolidCore called from the +account `a` (any address, below `2 ^ 160`), under every oracle whose caller is `a` +(`Generic.CallerAt a`). -/ +theorem loweringFrom (a : Nat) (ha : a < 2 ^ 160) (o : SolarTV.Machine.Oracle) + (henv : Generic.CallerAt a o) {c : TypeCheck.CheckedContract} (hc : contract? = .ok c) : + Stage (solidCoreFrom a 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.stageCallerFrom a ha o henv hd (by rw [hk]; exact check_stage0) + +/-- **The source stage of `Events` at every value from any caller**. -/ +theorem loweringValueFrom (a : Nat) (ha : a < 2 ^ 160) (o : SolarTV.Machine.Oracle) + (henv : Generic.CallerAt a o) {c : TypeCheck.CheckedContract} (hc : contract? = .ok c) : + Stage (solidCoreFrom a 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.stageValueCallerFrom a ha o henv hd (by rw [hk]; exact check_stage0) + (by rw [hk]; exact checkValue_stage0) + #print axioms selector_eq #print axioms digest_eq @@ -287,10 +320,16 @@ theorem loweringValue (o : SolarTV.Machine.Oracle) (henv : Generic.CallerOk o) #print axioms check_rejects_topic +#print axioms check_rejects_fixedCaller + #print axioms check_rejects_order #print axioms lowering #print axioms loweringValue +#print axioms loweringFrom + +#print axioms loweringValueFrom + end SolidCore.Refinement.Solar.Events diff --git a/SolidCore/Refinement/Statement.lean b/SolidCore/Refinement/Statement.lean index 7ee9c35d..4cf0a8b8 100644 --- a/SolidCore/Refinement/Statement.lean +++ b/SolidCore/Refinement/Statement.lean @@ -91,6 +91,28 @@ def result? (fuel : Nat) (contract : TypeCheck.CheckedContract) (call : Call) : (call.calldata.data.toList.map (·.toNat)) | _ => none +/-- SolidCore's result for `call` from the account `caller`: the contract is constructed as +`result?` constructs it (from `callerAddress`, its deployer), its storage replaced with the +call's, and then called through the ABI dispatcher from `caller`, which the dispatcher's call +context takes as `msg.sender`. From `callerAddress` it is `result?` +(`resultFrom?_callerAddress`). -/ +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 + +theorem resultFrom?_callerAddress : resultFrom? callerAddress = result? := rfl + /-- What `result` shows outside the callee. -/ def observe (call : Call) (result : TypeCheck.CoreAbiCallResult) : Observable := { success := result.success @@ -107,6 +129,13 @@ def run (fuel : Nat) (contract : TypeCheck.CheckedContract) (call : Call) : Option Observable := (result? fuel contract call).map (observe call) +/-- Run `call` against `contract` in SolidCore with `fuel`, from the account `caller`. -/ +def runFrom (caller : Nat) (fuel : Nat) (contract : TypeCheck.CheckedContract) (call : Call) : + Option Observable := + (resultFrom? caller fuel contract call).map (observe call) + +theorem runFrom_callerAddress : runFrom callerAddress = run := rfl + end Source namespace Target @@ -178,6 +207,67 @@ def run (code : ByteArray) (call : Call) : Option Observable := if success then (evm.state.getStorage (address selfAddress) (storageKey slot)).toNat else slotValue call.storage slot } +/-- 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`: `gasLimit` gas to `selfAddress`. -/ +def messageFrom (caller : Nat) (code : ByteArray) (call : Call) : Message .fusaka := + { blockEnv, txEnv := txEnvFrom caller, caller := address caller, + 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 from the account `caller` (its sender and origin). +From `callerAddress` it is `run` (`runFrom_callerAddress`). -/ +def runFrom (caller : Nat) (code : ByteArray) (call : Call) : Option Observable := + match processMessage (Meter := Nat) .fusaka (messageFrom caller code call) + (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 (address selfAddress) (storageKey slot)).toNat + else slotValue call.storage slot } + +theorem preStateFrom_callerAddress : preStateFrom callerAddress = preState := rfl + +theorem messageFrom_callerAddress : messageFrom callerAddress = message := rfl + +theorem runFrom_callerAddress : runFrom callerAddress = run := by + funext code call + simp only [runFrom, run, messageFrom_callerAddress, preStateFrom_callerAddress] + split <;> rename_i h <;> rw [h] + end Target /-- `code` implements `contract` on every call `scope` admits: SolidCore with diff --git a/SolidCore/Refinement/Wide/Refines.lean b/SolidCore/Refinement/Wide/Refines.lean index 386b6d47..3e4408d1 100644 --- a/SolidCore/Refinement/Wide/Refines.lean +++ b/SolidCore/Refinement/Wide/Refines.lean @@ -166,6 +166,25 @@ theorem run_eq_at {fuel : Nat} {c : TypeCheck.CheckedContract} {d : Source.State Source.Context) = ctxOf c from rfl, hc] simp only [TypeCheck.CheckedContract.callCalldataAtFromWithContext?, Dirty.bytes_calldata] +/-- `Source.runFrom caller` of a call from the storage `σ`, once the constructor's result is +known: `run_eq_at` with the dispatcher called from `caller`. -/ +theorem run_eq_atFrom (caller : Nat) {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.runFrom caller 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 caller 0 + ((natToBytes 4 sel).map (·.toNat) ++ Dirty.argBytes (ws.map (·.toNat)))) := by + obtain ⟨vs, hc⟩ := hd.cons + simp only [Source.runFrom, Source.resultFrom?, 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]