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/8] 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/8] 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 73d820a30d8ac320dec17f5ecd02b175af0dbfd3 Mon Sep 17 00:00:00 2001 From: alpharush <0xalpharush@protonmail.com> Date: Thu, 12 Nov 2026 17:36:38 -0600 Subject: [PATCH 3/8] feat(token): certify token's source stage --- SolidCore/Refinement/Generic/Event.lean | 66 +- SolidCore/Refinement/Generic/Mir.lean | 11 +- SolidCore/Refinement/Generic/MirRun.lean | 11 +- SolidCore/Refinement/Generic/Simp.lean | 26 +- SolidCore/Refinement/Generic/Source.lean | 477 ++++++- SolidCore/Refinement/Generic/SourceCall.lean | 87 +- SolidCore/Refinement/Generic/SourceRun.lean | 276 ++-- SolidCore/Refinement/Generic/SourceStmt.lean | 252 +++- SolidCore/Refinement/Generic/Stage.lean | 25 +- SolidCore/Refinement/Generic/Tree.lean | 22 +- SolidCore/Refinement/Solar/Assemble.lean | 13 +- SolidCore/Refinement/Solar/AssembleSim.lean | 49 +- .../Refinement/Solar/Token/Assembly.lean | 103 ++ .../Refinement/Solar/Token/Lowering.lean | 1143 +++++++++++++++++ SolidCore/Refinement/Solar/Token/Mutants.lean | 91 ++ SolidCore/Refinement/Source/Token.lean | 152 +++ SolidCore/Solidity/Ast.lean | 5 +- lakefile.lean | 12 + scripts/refinement/token/mir_to_lean.py | 168 +++ scripts/refinement/token/stage0.mir | 283 ++++ scripts/refinement/token/token.sol | 60 + 21 files changed, 3112 insertions(+), 220 deletions(-) create mode 100644 SolidCore/Refinement/Solar/Token/Assembly.lean create mode 100644 SolidCore/Refinement/Solar/Token/Lowering.lean create mode 100644 SolidCore/Refinement/Solar/Token/Mutants.lean create mode 100644 SolidCore/Refinement/Source/Token.lean create mode 100644 scripts/refinement/token/mir_to_lean.py create mode 100644 scripts/refinement/token/stage0.mir create mode 100644 scripts/refinement/token/token.sol diff --git a/SolidCore/Refinement/Generic/Event.lean b/SolidCore/Refinement/Generic/Event.lean index 5c5c2213..013820e3 100644 --- a/SolidCore/Refinement/Generic/Event.lean +++ b/SolidCore/Refinement/Generic/Event.lean @@ -1,12 +1,15 @@ import SolidCore.Refinement.Generic.Source +import SolidCore.Refinement.Generic.Simp /-! # Events of the fragment: SolidCore's encoding of a log A log of the fragment has a non-anonymous event's signature topic, then its indexed fields' words as topics, and its other fields' words, ABI-encoded, as data. Each field is a `uint256` -word, or an `address` 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` +word, or an `address` word that fits in 160 bits on every path the facts `K` hold on (`evOk K`: +its upper bound `bound K w` is below `2 ^ 160`, as for a constant such as `msg.sender`'s +`callerWord`, an `address` parameter, whose argument check `K` records, or a masked storage +read; SolidCore reverts on an address that does not fit, which the fragment leaves out). `encode_ok` and `encodeValues_ok` compute SolidCore's `EventDecl.encodeFields?` on such words: the topics are the indexed words (`evTopics`), the data the 32-byte big-endian encodings of the others (`evData`). -/ @@ -51,18 +54,18 @@ theorem wordBytes_eval (ρ : Val) (e : WExpr) : 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 +/-- A field the fragment logs, with its word: any `uint256` word, or an `address` word whose bound +on the facts `K` fits in 160 bits. -/ +def evFieldOk (K : Facts) (f : EventField) (w : WExpr) : Bool := + match f.ty with + | .uint256 => true + | .address => decide (bound K w < 2 ^ 160) + | _ => false /-- Whether every field is one the fragment logs, with its word. -/ -def evOk : List EventField → List WExpr → Bool +def evOk (K : Facts) : List EventField → List WExpr → Bool | [], [] => true - | f :: fs, w :: ws => evFieldOk f w && evOk fs ws + | f :: fs, w :: ws => evFieldOk K f w && evOk K fs ws | _, _ => false /-- The words of the indexed fields: the log's topics after the signature's. -/ @@ -80,7 +83,8 @@ 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) : +theorem evFieldOk_static (ρ : Val) {K : Facts} (hK : K.Hold ρ) {f : EventField} {w : WExpr} + (h : evFieldOk K f w = true) : abiStaticBytes? f.ty (.word (w.eval ρ)) = some (wordToBytesBE wordBytes (w.eval ρ)) ∧ abiEncodeStaticValue? f.ty (.word (w.eval ρ)) = some (wordToBytesBE wordBytes (w.eval ρ)) ∧ Ty.isHashedEventIndexed f.ty = false ∧ Ty.isDynamicAbi f.ty = false ∧ @@ -90,26 +94,27 @@ theorem evFieldOk_static (ρ : Val) {f : EventField} {w : WExpr} (h : evFieldOk · rename_i hty rw [hty] exact ⟨rfl, rfl, rfl, rfl, rfl⟩ - · rename_i n hty + · rename_i 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 + have hn : w.eval ρ < 1461501637330902918203684832716283019655932542976 := + Nat.lt_of_le_of_lt (bound_sound hK w) h 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'] + have hb : abiStaticBytes? Ty.address (.word (w.eval ρ)) = + some (wordToBytesBE wordBytes (w.eval ρ)) := by + simp [abiStaticBytes?, abiAddressFits, norm_mod, Nat.mod_eq_of_lt (w.eval_lt ρ), hn] exact ⟨hb, hb, rfl, rfl, rfl⟩ · simp at h -theorem encode_ok (ρ : Val) : ∀ (fs : List EventField) (ws : List WExpr), evOk fs ws = true → +theorem encode_ok (ρ : Val) {K : Facts} (hK : K.Hold ρ) : + ∀ (fs : List EventField) (ws : List WExpr), evOk K fs ws = true → ∃ a b, EventDecl.encodeFields?.encode fs (ws.map fun e => Value.word (e.eval ρ)) = some ((evTopics fs ws).map (WExpr.eval ρ), evDataTys fs ws, (evData fs ws).map (fun e => Value.word (e.eval ρ)), a, b) | [], [], _ => ⟨[], [], rfl⟩ | f :: fs, w :: ws, h => by simp only [evOk, Bool.and_eq_true] at h - obtain ⟨a, b, ih⟩ := encode_ok ρ fs ws h.2 - obtain ⟨hs, -, hh, -, -⟩ := evFieldOk_static ρ h.1 + obtain ⟨a, b, ih⟩ := encode_ok ρ hK fs ws h.2 + obtain ⟨hs, -, hh, -, -⟩ := evFieldOk_static ρ hK h.1 simp only [List.map_cons, EventDecl.encodeFields?.encode, ih, bind, Option.bind] by_cases hi : f.indexed = true · simp only [hi, ↓reduceIte, evTopics, evDataTys, evData, abiEventTopic?, hh, @@ -119,16 +124,16 @@ theorem encode_ok (ρ : Val) : ∀ (fs : List EventField) (ws : List WExpr), evO 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), +theorem evData_ok {K : Facts} : ∀ (fs : List EventField) (ws : List WExpr), evOk K fs ws = true → + ∀ (ρ : Val), K.Hold ρ → ∀ (off : Nat), Ty.listAbiHeadWords? (evDataTys fs ws) = some (evData fs ws).length ∧ abiEncodeValuesAux? (evDataTys fs ws) ((evData fs ws).map fun e => Value.word (e.eval ρ)) off = some (((evData fs ws).flatMap wordOBytes).map (OByte.eval ρ), [], off) - | [], [], _, _, _ => ⟨rfl, rfl⟩ - | f :: fs, w :: ws, h, ρ, off => by + | [], [], _, _, _, _ => ⟨rfl, rfl⟩ + | f :: fs, w :: ws, h, ρ, hK, off => by simp only [evOk, Bool.and_eq_true] at h - obtain ⟨ih1, ih2⟩ := evData_ok fs ws h.2 ρ off - obtain ⟨-, hs, -, hd, hw⟩ := evFieldOk_static ρ h.1 + obtain ⟨ih1, ih2⟩ := evData_ok fs ws h.2 ρ hK off + obtain ⟨-, hs, -, hd, hw⟩ := evFieldOk_static ρ hK h.1 by_cases hi : f.indexed = true · simp only [evDataTys, evData, hi, ↓reduceIte] exact ⟨ih1, ih2⟩ @@ -137,12 +142,13 @@ theorem evData_ok : ∀ (fs : List EventField) (ws : List WExpr), evOk fs ws = t 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 + | [], _ :: _, h, _, _, _ | _ :: _, [], h, _, _, _ => by simp [evOk] at h -theorem encodeValues_ok (ρ : Val) (fs : List EventField) (ws : List WExpr) (h : evOk fs ws = true) : +theorem encodeValues_ok (ρ : Val) {K : Facts} (hK : K.Hold ρ) (fs : List EventField) + (ws : List WExpr) (h : evOk K fs ws = true) : abiEncodeValues? (evDataTys fs ws) ((evData fs ws).map fun e => Value.word (e.eval ρ)) = some (((evData fs ws).flatMap wordOBytes).map (OByte.eval ρ)) := by - obtain ⟨h1, h2⟩ := evData_ok fs ws h ρ (wordBytes * (evData fs ws).length) + obtain ⟨h1, h2⟩ := evData_ok fs ws h ρ hK (wordBytes * (evData fs ws).length) simp [abiEncodeValues?, h1, h2, bind, Option.bind] end SolidCore.Refinement.Generic diff --git a/SolidCore/Refinement/Generic/Mir.lean b/SolidCore/Refinement/Generic/Mir.lean index 34750ee1..be6f70f1 100644 --- a/SolidCore/Refinement/Generic/Mir.lean +++ b/SolidCore/Refinement/Generic/Mir.lean @@ -21,7 +21,7 @@ the position (SolarTV's `Pos`), the symbolic values, the symbolic state and the 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 + (`mkBin`, `mkUn`), and a widening cast (`Inst.word`: `zext` to 256 bits) keeps its word; memory is a function from byte offsets to `OByte`s, written by `mstore` at constant offsets; * storage is the writes of the run (`Writes`): `sload` and `sstore` take any slot word, `sload` reading `Writes.read` and `sstore` writing `Writes.set`; @@ -210,8 +210,13 @@ def symInsts (ev : EnvFlags) (cv : SV) (sel n : Nat) (K : Facts) : 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 + -- A widening cast (`zext`, `inttoptr`, `ptrtoint` to 256 bits) keeps its word. + | .word dst a :: rest, env, st => + match SV.ofOperand env a with + | .w e => symInsts ev cv sel n K rest (env.set dst (.w e)) st + | _ => none + -- Outside the fragment (a low-bits mask, a select, a heap floor, an allocation) or an + -- internal call, which -- `symSegment` splits off first: no run. | _ :: _, _, _ => none diff --git a/SolidCore/Refinement/Generic/MirRun.lean b/SolidCore/Refinement/Generic/MirRun.lean index 5f18e969..f1fb6cf1 100644 --- a/SolidCore/Refinement/Generic/MirRun.lean +++ b/SolidCore/Refinement/Generic/MirRun.lean @@ -700,7 +700,16 @@ theorem symInsts_sound {ev : EnvFlags} {cv : SV} {sel n : Nat} {ρ : Val} {call 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 + | .word dst a :: rest, senv, senv', st, st', h, env, s, he, hs => by + simp only [symInsts] at h + split at h + · rename_i e hx + have ha := rel_operand he a + rw [hx] at ha + obtain ⟨env', s', h1, h2, h3⟩ := + symInsts_sound hc henv hK rest _ _ _ _ h _ s (he.set ha dst) hs + exact ⟨env', s', by simp only [execInsts]; exact h1, h2, h3⟩ + · simp at h | .low .. :: _, _, _, _, _, h, _, _, _, _ => by simp [symInsts] at h | .select .. :: _, _, _, _, _, h, _, _, _, _ => by simp [symInsts] at h | .call .. :: _, _, _, _, _, h, _, _, _, _ => by simp [symInsts] at h diff --git a/SolidCore/Refinement/Generic/Simp.lean b/SolidCore/Refinement/Generic/Simp.lean index 317494a5..a78bfd5a 100644 --- a/SolidCore/Refinement/Generic/Simp.lean +++ b/SolidCore/Refinement/Generic/Simp.lean @@ -19,7 +19,8 @@ checks with `or`. `canon` brings both trees to one form, which the kernel then c `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 + `a` with its sides swapped, a branch on `not a` (solar's `a != type(uint256).max`) into a + branch on `eq a maxWord` with its sides swapped, and splits the disjunctions the simplification left, such as `uint256`'s mul overflow check `iszero (or (iszero r) …)` against solar's branch on `or (eq r 0) …`; a second `Tree.simp` simplifies along the new paths. @@ -671,12 +672,14 @@ theorem Tree.eval_simp {ρ : Val} : ∀ {K : Facts}, K.Hold ρ → ∀ T : Tree, /-! ## 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. -/ +with its sides swapped, a branch on `not a` (zero exactly when `a` is the largest word) into a +branch on `eq a maxWord` with its sides swapped, and a disjunction split as `splitCond` does. -/ def splitNeg : WExpr → Tree → Tree → Tree | .un .iszero a, t, e => splitNeg a e t | .bin .eq a (.lit 0), t, e => splitNeg a e t | .bin .eq (.lit 0) a, t, e => splitNeg a e t | .bin .or a b, t, e => splitNeg a t (splitNeg b t e) + | .un .not a, t, e => .ite (.bin .eq a (.lit maxWord)) e t | c, t, e => .ite c t e /-- Every branch of a tree, its negations and disjunctions split. -/ @@ -702,7 +705,24 @@ theorem splitNeg_eval (ρ : Val) (c : WExpr) (t e : Tree) : 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 + | case5 a t e => + have ha := a.eval_le ρ + have hm : maxWord % wordSize = maxWord := Nat.mod_eq_of_lt (by decide) + simp only [Tree.eval, WExpr.eval, BinOp.eval, UnOp.eval, hm] + by_cases h : a.eval ρ = maxWord + · simp [h] + · have hlt := a.eval_lt ρ + have h3 : (wordSize - 1 - a.eval ρ) % wordSize ≠ 0 := by + rw [Nat.mod_eq_of_lt (by omega)] + simp only [maxWord] at h + omega + have h4 : (if a.eval ρ = maxWord then 1 else 0) % wordSize = 0 := by + split + · exact absurd ‹_› h + · rfl + rw [h4, if_pos rfl] + exact (ite_cond_eq_false _ _ (eq_false h3)).symm + | case6 => rfl theorem Tree.eval_splitNeg (ρ : Val) : ∀ T : Tree, T.splitNeg.eval ρ = T.eval ρ | .halt _ _ _ _ => rfl diff --git a/SolidCore/Refinement/Generic/Source.lean b/SolidCore/Refinement/Generic/Source.lean index 7428a2ef..fc1317f7 100644 --- a/SolidCore/Refinement/Generic/Source.lean +++ b/SolidCore/Refinement/Generic/Source.lean @@ -44,6 +44,48 @@ def mapOf? (fields : List StorageField) (x : String) : Option Nat := | some f => if mapOk f then some f.slot else none | none => none +/-- A mapping from `address` or `uint256` keys to `bool` values, not transient. -/ +def boolMapOk (f : StorageField) : Bool := + (match f.layout? with + | some (.mapping .address (.scalar .bool)) => true + | some (.mapping .uint256 (.scalar .bool)) => true + | _ => false) && !f.transient && decide (f.slot < wordSize) + +/-- The slot of the mapping to `bool` `x`, when the fragment reads and writes it. -/ +def boolMapOf? (fields : List StorageField) (x : String) : Option Nat := + match fields.find? (fun f => f.name == x) with + | some f => if boolMapOk f then some f.slot else none + | none => none + +/-- A mapping from `address` keys to mappings from `address` keys to `uint256` words, as +an ERC-20 allowance table, not transient. -/ +def map2Ok (f : StorageField) : Bool := + (match f.layout? with + | some (.mapping .address (.mapping .address (.scalar .uint256))) => true + | _ => false) && !f.transient && decide (f.slot < wordSize) + +/-- The slot of the nested mapping `x`, when the fragment reads and writes it. -/ +def map2Of? (fields : List StorageField) (x : String) : Option Nat := + match fields.find? (fun f => f.name == x) with + | some f => if map2Ok f then some f.slot else none + | none => none + +/-- An `address` field the fragment reads: 20 bytes at byte offset `packedOffset` of its +slot, not transient. -/ +def addrFieldOk (f : StorageField) : Bool := + (match f.layout? with | some (.scalar .address) => true | _ => false) && !f.transient && + decide (f.packedBytes = 20) && decide (f.packedOffset + 20 ≤ 32) && decide (f.slot < wordSize) + +/-- The slot and byte offset of the `address` field `x`, when the fragment reads it. -/ +def addrFieldOf? (fields : List StorageField) (x : String) : Option (Nat × Nat) := + match fields.find? (fun f => f.name == x) with + | some f => if addrFieldOk f then some (f.slot, f.packedOffset) else none + | none => none + +/-- The `bool` SolidCore reads from a storage word: whether its low byte is not zero, spelled +as solar's `ne (and w 255) 0`. -/ +def boolOfWord (w : WExpr) : WExpr := .un .iszero (.bin .eq (.bin .and w (.lit 255)) (.lit 0)) + /-- The slot, byte offset and size of the storage field `x`, when the fragment reads and writes it. -/ def fieldOf? (fields : List StorageField) (x : String) : Option (Nat × Nat × Nat) := @@ -133,6 +175,14 @@ def binOf : BinaryOp → Option BinOp | .bitXor => some .xor | _ => none +/-- The fragment's negated comparisons: `a >= b` is `iszero (lt a b)`, `a <= b` is +`iszero (gt a b)`, `a != b` is `iszero (eq a b)`. -/ +def negOf : BinaryOp → Option BinOp + | .ge => some .lt + | .le => some .gt + | .ne => some .eq + | _ => none + /-- 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) @@ -149,21 +199,44 @@ def eraseExpr (fields : List StorageField) (S : SymState) : Expr → Option (Lis 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) + | .binary op l r => + match binOf op with + | some o => do + let (gl, vl) ← eraseExpr fields S l + let (gr, vr) ← eraseExpr fields S r + match overflow o vl vr with + | some g => some (gl ++ gr ++ [g], .bin o vl vr) + | none => some (gl ++ gr, .bin o vl vr) + | none => do + let o ← negOf op + let (gl, vl) ← eraseExpr fields S l + let (gr, vr) ← eraseExpr fields S r + some (gl ++ gr, .un .iszero (.bin o vl vr)) + | .unary .logicalNot e => do + let (gs, v) ← eraseExpr fields S e + some (gs, .un .iszero v) | .storageRead .header x [] => - (fieldOf? fields x).map fun (k, off, bytes) => ([], readField (S.writes.read (.lit k)) off bytes) + match fieldOf? fields x with + | some (k, off, bytes) => some ([], readField (S.writes.read (.lit k)) off bytes) + | none => (addrFieldOf? fields x).map fun (k, off) => ([], readField (S.writes.read (.lit k)) off 20) | .storageRead .ref x [] => - (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))) + match fieldOf? fields x with + | some (k, off, bytes) => some ([], readField (S.writes.read (.lit k)) off bytes) + | none => (addrFieldOf? fields x).map fun (k, off) => ([], readField (S.writes.read (.lit k)) off 20) + | .storageRead .element x [idx] => + match mapOf? fields x with + | some k => do + let (gs, v) ← eraseExpr fields S idx + some (gs, S.writes.read (.hash v (.lit k))) + | none => do + let k ← boolMapOf? fields x + let (gs, v) ← eraseExpr fields S idx + some (gs, boolOfWord (S.writes.read (.hash v (.lit k)))) + | .index (.storageRead .element x [i1]) i2 => do + let k ← map2Of? fields x + let (g1, v1) ← eraseExpr fields S i1 + let (g2, v2) ← eraseExpr fields S i2 + some (g1 ++ g2, S.writes.read (.hash v2 (.hash v1 (.lit k)))) | _ => none @@ -258,6 +331,33 @@ theorem apply_eq (a b : Nat) (ha : a < wordSize) (hb : b < wordSize) : simp [BinaryOp.apply, Value.forceAbiLazy, bind, Except.bind, Functor.map, Except.map, boolWord, wordEq, norm_lt ha, norm_lt hb] +theorem apply_ne (a b : Nat) (ha : a < wordSize) (hb : b < wordSize) : + BinaryOp.apply true .ne (.word a) (.word b) = .ok (.word (if a = b then 0 else 1)) := by + by_cases h : a = b <;> + simp [BinaryOp.apply, Value.forceAbiLazy, bind, Except.bind, Functor.map, Except.map, boolWord, wordEq, + norm_lt ha, norm_lt hb, h] + +theorem apply_ge (a b : Nat) (ha : a < wordSize) (hb : b < wordSize) : + BinaryOp.apply true .ge (.word a) (.word b) = .ok (.word (if a < b then 0 else 1)) := by + by_cases h : a < b <;> + simp [BinaryOp.apply, Value.forceAbiLazy, BinaryOp.applyWord, bind, Except.bind, Functor.map, + Except.map, ltWord_eq, Nat.mod_eq_of_lt ha, Nat.mod_eq_of_lt hb, boolWord, wordTruthy, h, + SolidCore.Solidity.Shared.norm, modulus_eq] + +theorem apply_le (a b : Nat) (ha : a < wordSize) (hb : b < wordSize) : + BinaryOp.apply true .le (.word a) (.word b) = .ok (.word (if b < a then 0 else 1)) := by + by_cases h : b < a <;> + simp [BinaryOp.apply, Value.forceAbiLazy, BinaryOp.applyWord, bind, Except.bind, Functor.map, + Except.map, gtWord_eq, Nat.mod_eq_of_lt ha, Nat.mod_eq_of_lt hb, boolWord, wordTruthy, h, + SolidCore.Solidity.Shared.norm, modulus_eq] + +/-- SolidCore's \`!\` on a word is \`iszero\`. -/ +theorem apply_not (a : Nat) (ha : a < wordSize) : + UnaryOp.apply true .logicalNot (.word a) = .ok (.word (if a = 0 then 1 else 0)) := by + by_cases h : a = 0 <;> + simp [UnaryOp.apply, boolWord, wordTruthy, SolidCore.Solidity.Shared.norm, modulus_eq, + Nat.mod_eq_of_lt ha, h] + theorem fieldOk_spec {f : StorageField} (h : fieldOk f = true) : f.layout? = some (.scalar .uint256) ∧ f.transient = false ∧ 0 < f.packedBytes ∧ f.packedOffset + f.packedBytes ≤ 32 ∧ f.slot < wordSize := by @@ -489,6 +589,9 @@ theorem guard_mul (ρ : Val) (l r : WExpr) : · have : wordSize ≤ a * b := Nat.not_lt.mp (fun h' => h (key.mpr h')) simp [h, this] +theorem bind_done_ok' {α β : Type} (a : α) (k : α → SolI β) : + ((.done (.ok a) : SolI α) >>= k) = k a := rfl + theorem bind_exprResult {α : Type} (ρ : Val) (gs : List WExpr) (v : WExpr) (rt : Runtime) (k : Value × Runtime → SolI α) : (exprResult ρ gs v rt >>= k) = @@ -541,6 +644,85 @@ theorem norm_mod (n : Nat) : SolidCore.Solidity.Shared.norm n = n % wordSize := theorem loadSlot_mod (st : State) (k : Nat) : st.loadSlot (k % wordSize) = st.loadSlot k := by simp only [State.loadSlot, StorageMap.lookup?, norm_mod, Nat.mod_mod] +/-- SolidCore hashes an `address` or `uint256` mapping key word as itself. -/ +theorem key_word {ty : Ty} (hty : ty = .address ∨ ty = .uint256) {w : Nat} (h : w < wordSize) : + coerceMappingKeyWordAs ty (.word w) = .ok w := by + rcases hty with rfl | rfl <;> + simp [coerceMappingKeyWordAs, Value.forceAbiLazy, Ty.coerceValue?, Value.asStorageWord?, norm_lt h, + bind, Except.bind] + +/-- The slot of a mapping's entry at an `address` or `uint256` key word: `solHash key slot`. -/ +theorem slot_key (slot : Nat) {ty : Ty} (hty : ty = .address ∨ ty = .uint256) {w : Nat} + (h : w < wordSize) : mappingStorageSlotForKey slot ty (.word w) = .ok (solHash w slot) := by + have hk := key_word hty h + rcases hty with rfl | rfl <;> + simp only [mappingStorageSlotForKey, hk, bind, Except.bind, mappingStorageSlot_eq] + +/-- One key of a storage path through a mapping. -/ +theorem resolve_step (st : State) (slot : Nat) {ty : Ty} (hty : ty = .address ∨ ty = .uint256) + (l : StorageLayout) (rest : List Value) {w : Nat} (h : w < wordSize) : + st.resolveStoragePathSlot slot (.mapping ty l) (.word w :: rest) = + st.resolveStoragePathSlot (solHash w slot) l rest := by + rw [State.resolveStoragePathSlot.eq_2, slot_key _ hty h] + rfl + +/-- SolidCore's slot hash is a word. -/ +theorem solHash_lt (a b : Nat) : solHash a b < wordSize := by + simp only [solHash, keccakWord, bytesToWordBE, norm_mod] + exact Nat.mod_lt _ (by decide) + +/-- What the fragment knows of a nested mapping it reads and writes. -/ +structure Map2Ok (ctx : Context) (x : String) (f : StorageField) : Prop where + find : ctx.storageField? x = some f + layout : f.layout? = some (.mapping .address (.mapping .address (.scalar .uint256))) + transient : f.transient = false + slot : f.slot < wordSize + +theorem map2Of?_spec {fields : List StorageField} {ctx : Context} (hf : ctx.storageFields = fields) + {x : String} {k : Nat} (h : map2Of? fields x = some k) : + ∃ f, Map2Ok ctx x f ∧ f.slot = k := by + unfold map2Of? at h + split at h + · rename_i f hfind + split at h + · rename_i hs + simp only [Option.some.injEq] at h + subst h + unfold map2Ok at hs + simp only [Bool.and_eq_true, Bool.not_eq_true', decide_eq_true_eq] at hs + obtain ⟨⟨hl, ht⟩, hsl⟩ := hs + refine ⟨f, ⟨by simp [Context.storageField?, hf, hfind], ?_, ht, hsl⟩, rfl⟩ + split at hl + · rename_i h; exact h + · simp at hl + · simp at h + · simp at h + +/-- The slot of the entry of a nested mapping at two key words. -/ +theorem resolve_map2 {ctx : Context} {rt : Runtime} {x : String} {f : StorageField} + (hf : Map2Ok ctx x f) {w1 w2 : Nat} (h1 : w1 < wordSize) (h2 : w2 < wordSize) : + rt.resolveStorageBasePath ctx (.field x) [.word w1, .word w2] = + .ok (solHash w2 (solHash w1 f.slot), .scalar .uint256) := by + have ha : (Ty.address = .address ∨ Ty.address = .uint256) := .inl rfl + simp only [Runtime.resolveStorageBasePath, Runtime.storageBaseAnchor, hf.find, hf.layout, + hf.transient, Bool.false_and, Bool.false_eq_true, ↓reduceIte, bind, Except.bind, pure, + Except.pure] + rw [resolve_step _ _ ha _ _ h1, resolve_step _ _ ha _ _ h2, State.resolveStoragePathSlot.eq_1] + +/-- SolidCore reads the entry of a nested mapping at two key words as the writes' read of the slot +word `hash key2 (hash key1 slot)`. -/ +theorem loadPath_map2 {ρ : Val} {fields : List StorageField} {ctx : Context} {rt : Runtime} + {S : SymState} (hrel : ExprRel ρ fields ctx rt S) {x : String} {k : Nat} + (hk : map2Of? fields x = some k) {w1 w2 : Nat} (h1 : w1 < wordSize) (h2 : w2 < wordSize) : + rt.loadStorageBasePath ctx (.field x) [.word w1, .word w2] = + .ok (.word (Writes.store ρ S.writes (solHash w2 (solHash w1 k % wordSize) % wordSize))) := by + obtain ⟨f, hf, rfl⟩ := map2Of?_spec hrel.fields hk + rw [Runtime.loadStorageBasePath, resolve_map2 hf h1 h2] + simp only [bind, Except.bind, State.loadStorageLayoutAt, StorageLayout.depth, + State.loadStorageLayoutAtFuel, loadStorageWordAs, Ty.storageValueFromWord?] + rw [Nat.mod_eq_of_lt (solHash_lt w1 f.slot), ← loadSlot_mod, + hrel.store _ (Nat.mod_lt _ (by decide))] + /-- What the fragment knows of a mapping it reads and writes. -/ structure MapOk (ctx : Context) (x : String) (f : StorageField) : Prop where find : ctx.storageField? x = some f @@ -570,6 +752,7 @@ theorem mapOf?_spec {fields : List StorageField} {ctx : Context} (hf : ctx.stora · 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} @@ -586,6 +769,120 @@ theorem loadIndex_map {ρ : Val} {fields : List StorageField} {ctx : Context} {r State.loadStorageLayoutAt, State.loadStorageLayoutAtFuel, loadStorageWordAs, Ty.storageValueFromWord?, mappingStorageSlot_eq, hsl, pure, Except.pure, StorageLayout.depth] +/-- What the fragment knows of a mapping to `bool` it reads and writes. -/ +structure BoolMapOk (ctx : Context) (x : String) (f : StorageField) : Prop where + find : ctx.storageField? x = some f + layout : f.layout? = some (.mapping .address (.scalar .bool)) ∨ + f.layout? = some (.mapping .uint256 (.scalar .bool)) + transient : f.transient = false + slot : f.slot < wordSize + +theorem boolMapOf?_spec {fields : List StorageField} {ctx : Context} (hf : ctx.storageFields = fields) + {x : String} {k : Nat} (h : boolMapOf? fields x = some k) : + ∃ f, BoolMapOk ctx x f ∧ f.slot = k := by + unfold boolMapOf? at h + split at h + · rename_i f hfind + split at h + · rename_i hs + simp only [Option.some.injEq] at h + subst h + unfold boolMapOk at hs + simp only [Bool.and_eq_true, Bool.not_eq_true', decide_eq_true_eq] at hs + obtain ⟨⟨hl, ht⟩, hsl⟩ := hs + refine ⟨f, ⟨by simp [Context.storageField?, hf, hfind], ?_, ht, hsl⟩, rfl⟩ + split at hl + · rename_i h; exact .inl h + · rename_i h; exact .inr h + · simp at hl + · simp at h + · simp at h + +/-- The `bool` of a storage word, as `boolOfWord` computes it: whether its low byte is not zero. -/ +theorem boolOfWord_eval (ρ : Val) (w : WExpr) : + (boolOfWord w).eval ρ = if w.eval ρ % 256 = 0 then 0 else 1 := by + have hm : (w.eval ρ &&& 255 % wordSize) % wordSize = w.eval ρ % 256 := by + rw [Nat.mod_eq_of_lt (show 255 < wordSize by decide), show (255 : Nat) = 2 ^ 8 - 1 from rfl, + Nat.and_two_pow_sub_one_eq_mod] + exact Nat.mod_eq_of_lt (Nat.lt_of_lt_of_le (Nat.mod_lt _ (by decide)) (by decide)) + simp only [boolOfWord, WExpr.eval, BinOp.eval, UnOp.eval, hm, Nat.zero_mod] + by_cases h : w.eval ρ % 256 = 0 <;> simp [h] + +/-- SolidCore reads the entry of a mapping to `bool` at a key word as whether the low byte of the +writes' read of the slot word `hash key slot` is not zero. -/ +theorem loadIndex_boolMap {ρ : Val} {fields : List StorageField} {ctx : Context} {rt : Runtime} + {S : SymState} (hrel : ExprRel ρ fields ctx rt S) {x : String} {k : Nat} + (hk : boolMapOf? fields x = some k) {w : Nat} (hw : w < wordSize) : + rt.loadStorageIndex ctx x (.word w) = + .ok (.word (if Writes.store ρ S.writes (solHash w k % wordSize) % 256 = 0 then 0 else 1)) := by + obtain ⟨f, hf, rfl⟩ := boolMapOf?_spec hrel.fields hk + have hsl : rt.state.loadSlot (solHash w f.slot) = Writes.store ρ S.writes (solHash w f.slot % wordSize) := by + rw [← loadSlot_mod, hrel.store _ (Nat.mod_lt _ (by decide))] + have hlt : Writes.store ρ S.writes (solHash w f.slot % wordSize) < wordSize := + Writes.store_word hrel.ok _ _ + rcases hf.layout with hl | hl <;> + simp [Runtime.loadStorageIndex, hf.find, hl, mappingStorageSlotForKey, coerceMappingKeyWordAs, + Value.forceAbiLazy, Ty.coerceValue?, Value.asStorageWord?, norm_lt hw, bind, Except.bind, + State.loadStorageLayoutAt, State.loadStorageLayoutAtFuel, loadStorageWordAs, + Ty.storageValueFromWord?, mappingStorageSlot_eq, hsl, StorageLayout.depth, norm_lt hlt] + +/-- What the fragment knows of an `address` field it reads. -/ +structure AddrFieldOk (ctx : Context) (x : String) (f : StorageField) : Prop where + find : ctx.storageField? x = some f + layout : f.layout? = some (.scalar .address) + transient : f.transient = false + bytes : f.packedBytes = 20 + fits : f.packedOffset + 20 ≤ 32 + slot : f.slot < wordSize + +theorem addrFieldOf?_spec {fields : List StorageField} {ctx : Context} (hf : ctx.storageFields = fields) + {x : String} {k off : Nat} (h : addrFieldOf? fields x = some (k, off)) : + ∃ f, AddrFieldOk ctx x f ∧ f.slot = k ∧ f.packedOffset = off := by + unfold addrFieldOf? at h + split at h + · rename_i f hfind + split at h + · rename_i hs + simp only [Option.some.injEq, Prod.mk.injEq] at h + obtain ⟨rfl, rfl⟩ := h + unfold addrFieldOk at hs + simp only [Bool.and_eq_true, Bool.not_eq_true', decide_eq_true_eq] at hs + obtain ⟨⟨⟨⟨hl, ht⟩, hb⟩, ho⟩, hsl⟩ := hs + refine ⟨f, ⟨by simp [Context.storageField?, hf, hfind], ?_, ht, hb, ho, hsl⟩, rfl, rfl⟩ + split at hl + · rename_i h; exact h + · simp at hl + · simp at h + · simp at h + +theorem load_addrField {ctx : Context} {rt : Runtime} {x : String} {f : StorageField} + (hf : AddrFieldOk ctx x f) (hw : rt.state.loadSlot f.slot < wordSize) : + rt.loadStorageField ctx x = + .ok (.word (fieldValue (rt.state.loadSlot f.slot) f.packedOffset 20)) := by + have := hf.fits + have hv : fieldValue (rt.state.loadSlot f.slot) f.packedOffset 20 < 2 ^ 160 := by + unfold fieldValue + simp only [show ¬ (f.packedOffset = 0 ∧ (20 : Nat) = 32) by omega, ↓reduceIte] + exact Nat.mod_lt _ (by decide) + simp [Runtime.loadStorageField, hf.find, hf.layout, StorageField.storageValueFromWord?, + Ty.storageValueFromWord?, State.loadFieldWord, StorageField.isPacked, + SolidCore.Solidity.Source.wordBytes, State.loadFieldSlot, hf.transient, fieldValue, wordBitRange, + StorageField.packedBitWidth, StorageField.packedBitOffset, norm_lt hw, hf.bytes, + SolidCore.Solidity.Shared.Account.addressWord] + have hx : rt.state.loadSlot f.slot / 2 ^ (f.packedOffset * 8) % + 1461501637330902918203684832716283019655932542976 < wordSize := + Nat.lt_of_lt_of_le (Nat.mod_lt _ (by decide)) (by decide) + rw [norm_lt hx, norm_lt hx, SolidCore.Solidity.Shared.Account.addressModulus, + show (2 : Nat) ^ 160 = 1461501637330902918203684832716283019655932542976 from rfl, Nat.mod_mod] + +theorem loadHeader_addrField {ctx : Context} {rt : Runtime} {x : String} {f : StorageField} + (hf : AddrFieldOk ctx x f) (hw : rt.state.loadSlot f.slot < wordSize) : + rt.loadStorageFieldHeader ctx x = + .ok (.word (fieldValue (rt.state.loadSlot f.slot) f.packedOffset 20)) := by + simp only [Runtime.loadStorageFieldHeader, hf.find, hf.layout] + exact load_addrField hf hw + + 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) → @@ -688,10 +985,10 @@ theorem eval_erase (ρ : Val) (fields : List StorageField) (ctx : Context) (rt : 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 + | none => cases op <;> simp [eraseExpr, hl, binOf, negOf] at h | some pl => cases hr : eraseExpr fields S r with - | none => cases op <;> simp [eraseExpr, hl, hr, binOf] at h + | none => cases op <;> simp [eraseExpr, hl, hr, binOf, negOf] at h | some pr => obtain ⟨gl, vl⟩ := pl obtain ⟨gr, vr⟩ := pr @@ -701,7 +998,7 @@ theorem eval_erase (ρ : Val) (fields : List StorageField) (ctx : Context) (rt : 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, + cases op <;> simp only [eraseExpr, hl, hr, binOf, negOf, overflow, Option.bind_eq_bind, Option.bind_some, Option.some.injEq, Prod.mk.injEq, reduceCtorEq, Option.bind_none] at h all_goals first | (simp at h; done) @@ -722,12 +1019,36 @@ theorem eval_erase (ρ : Val) (fields : List StorageField) (ctx : Context) (rt : 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] + apply_bitOr _ _ hal har, apply_bitXor _ _ hal har, apply_ge _ _ hal har, + apply_le _ _ hal har, apply_ne _ _ hal har] + split <;> simp_all [SolI.ofExcept, WExpr.eval, BinOp.eval, UnOp.eval, Nat.mod_mod] all_goals first | exact add_wrap_lt hal har (by assumption) | exact add_nowrap_le (by assumption) | (split <;> simp_all <;> omega) + | (split <;> simp_all) + | unary op e => + cases op + case logicalNot => + cases he : eraseExpr fields S e with + | none => simp [eraseExpr, he] at h + | some p => + obtain ⟨gs0, v0⟩ := p + simp only [eraseExpr, he, Option.bind_eq_bind, Option.bind_some, Option.some.injEq, + Prod.mk.injEq] at h + obtain ⟨rfl, rfl⟩ := h + have ih := eval_erase ρ fields ctx rt S hrel e gs0 v0 n he + (by simp [Expr.orderFuel] at hf; omega) + simp only [Expr.evalFuel, ih, bind_exprResult, hrel.checked] + unfold exprResult + split + · rfl + · simp only [bind, EvmCompiler.Simulation.Interaction.bind, liftM, monadLift, + MonadLift.monadLift, apply_not _ (v0.eval_lt ρ), SolI.ofExcept, pure, + EvmCompiler.Simulation.Interaction.pure] + simp only [WExpr.eval, UnOp.eval] + split <;> rfl + all_goals simp [eraseExpr] at h | caller => simp only [eraseExpr, Option.some.injEq, Prod.mk.injEq] at h obtain ⟨rfl, rfl⟩ := h @@ -739,35 +1060,107 @@ theorem eval_erase (ρ : Val) (fields : List StorageField) (ctx : Context) (rt : 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 + cases hk : mapOf? fields x with + | some k => + simp only [eraseExpr, hk, Option.bind_eq_bind, Option.bind_eq_some_iff, Option.some.injEq, + Prod.mk.injEq] at h + obtain ⟨⟨gs0, v0⟩, hi, rfl, rfl⟩ := h + have ih := eval_erase ρ fields ctx rt S hrel i gs0 v0 n hi + (by simp [Expr.orderFuel, Expr.listEvalFuel] at hf; omega) + simp only [Expr.evalFuel, ih, bind_exprResult] + unfold exprResult + split + · rfl + · obtain ⟨f, hf, rfl⟩ := mapOf?_spec hrel.fields hk + rw [loadIndex_map hrel hk (v0.eval_lt ρ), Writes.eval_read hrel.ok] + simp only [WExpr.eval, hrel.hash, Nat.mod_eq_of_lt hf.slot] + rfl + | none => + simp only [eraseExpr, hk, Option.bind_eq_bind, Option.bind_eq_some_iff, Option.some.injEq, + Prod.mk.injEq] at h + obtain ⟨k, hk', ⟨gs0, v0⟩, hi, rfl, rfl⟩ := h + have ih := eval_erase ρ fields ctx rt S hrel i gs0 v0 n hi + (by simp [Expr.orderFuel, Expr.listEvalFuel] at hf; omega) + simp only [Expr.evalFuel, ih, bind_exprResult] + unfold exprResult + split + · rfl + · obtain ⟨f, hf, rfl⟩ := boolMapOf?_spec hrel.fields hk' + rw [loadIndex_boolMap hrel hk' (v0.eval_lt ρ), boolOfWord_eval, Writes.eval_read hrel.ok] + simp only [WExpr.eval, hrel.hash, Nat.mod_eq_of_lt hf.slot] + rfl all_goals - cases idx <;> simp only [eraseExpr, Option.map_eq_some_iff, Prod.mk.injEq] at h + cases idx <;> simp only [eraseExpr] 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 + cases hk : fieldOf? fields x with + | some p => + obtain ⟨k, off, bytes⟩ := p + simp only [hk, Option.some.injEq, Prod.mk.injEq] at h + obtain ⟨rfl, rfl⟩ := h + obtain ⟨f, hfx, rfl, rfl, rfl⟩ := fieldOf?_spec hrel.fields hk + have hsl := slot_read hrel hfx.slot + have hw : rt.state.loadSlot f.slot < wordSize := by + rw [hsl]; exact WExpr.eval_lt _ _ + simp only [Expr.evalFuel, loadHeader_field hfx hw, load_field hfx hw, bind, + EvmCompiler.Simulation.Interaction.bind, liftM, monadLift, MonadLift.monadLift, SolI.ofExcept, + exprResult, List.any_nil, Bool.false_eq_true, ↓reduceIte, hsl, + readField_eval ρ _ hfx.fits hfx.bytes] + try rfl + | none => + simp only [hk, Option.map_eq_some_iff, Prod.mk.injEq] at h + obtain ⟨⟨k, off⟩, hk', rfl, rfl⟩ := h + obtain ⟨f, hfx, rfl, rfl⟩ := addrFieldOf?_spec hrel.fields hk' + have hsl := slot_read hrel hfx.slot + have hw : rt.state.loadSlot f.slot < wordSize := by + rw [hsl]; exact WExpr.eval_lt _ _ + simp only [Expr.evalFuel, loadHeader_addrField hfx hw, load_addrField hfx hw, bind, + EvmCompiler.Simulation.Interaction.bind, liftM, monadLift, MonadLift.monadLift, SolI.ofExcept, + exprResult, List.any_nil, Bool.false_eq_true, ↓reduceIte, hsl, + readField_eval ρ _ hfx.fits (by decide)] + try rfl + | index base i2 => + cases base + case storageRead m x idx => + cases m + case element => + rcases idx with _ | ⟨i1, _ | ⟨_, _⟩⟩ + · simp [eraseExpr] at h + · simp only [eraseExpr, Option.bind_eq_bind, Option.bind_eq_some_iff, Option.some.injEq, + Prod.mk.injEq] at h + obtain ⟨k, hk, ⟨g1, v1⟩, h1, ⟨g2, v2⟩, h2, rfl, rfl⟩ := h + obtain ⟨m, rfl⟩ : ∃ m, n = m + 1 := + ⟨n - 1, by simp [Expr.orderFuel, Expr.listEvalFuel] at hf; omega⟩ + have ih1 := eval_erase ρ fields ctx rt S hrel i1 g1 v1 m h1 + (by simp [Expr.orderFuel, Expr.listEvalFuel] at hf; omega) + have ih2 := eval_erase ρ fields ctx rt S hrel i2 g2 v2 (m + 1) h2 + (by simp [Expr.orderFuel, Expr.listEvalFuel] at hf; omega) + rw [Expr.evalFuel] + rotate_left + · intro _ h; cases h + simp only [Expr.hasStorageRoot, ↓reduceIte, Expr.resolveLValueFuel, ih1, bind_exprResult] + unfold exprResult + by_cases hg1 : g1.any (fun g => g.eval ρ != 0) = true + · simp only [hg1, any_append, Bool.true_or, ↓reduceIte] + rfl + · simp only [hg1, Bool.false_eq_true, ↓reduceIte, bind_done_ok', pure, + EvmCompiler.Simulation.Interaction.pure, ResolvedLValue.asStoragePath?, ih2, + bind_exprResult] + by_cases hg2 : g2.any (fun g => g.eval ρ != 0) = true + · simp only [hg2, any_append, Bool.or_true, ↓reduceIte] + · simp only [hg2, Bool.false_eq_true, ↓reduceIte, any_append, hg1, Bool.false_or, + List.cons_append, List.nil_append] + obtain ⟨f, hf, rfl⟩ := map2Of?_spec hrel.fields hk + simp only [bind, EvmCompiler.Simulation.Interaction.bind, liftM, monadLift, + MonadLift.monadLift, SolI.ofExcept, + loadPath_map2 hrel hk (v1.eval_lt ρ) (v2.eval_lt ρ)] + rw [Writes.eval_read hrel.ok] + simp only [WExpr.eval, hrel.hash, Nat.mod_eq_of_lt hf.slot] + · simp [eraseExpr] at h + all_goals simp [eraseExpr] at h + all_goals simp [eraseExpr] at h | _ => simp [eraseExpr] at h end SolidCore.Refinement.Generic diff --git a/SolidCore/Refinement/Generic/SourceCall.lean b/SolidCore/Refinement/Generic/SourceCall.lean index 671f0136..a144a8df 100644 --- a/SolidCore/Refinement/Generic/SourceCall.lean +++ b/SolidCore/Refinement/Generic/SourceCall.lean @@ -6,20 +6,30 @@ import SolidCore.Refinement.Generic.SourceStmt `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. +width (`paramWidth`: `b`, or 160 for an address). Its returns are `uint256`, `address` or `bool` +words, and none of its bindings is a storage reference. The tree is the argument checks +(`paramGuards`: a word at or above `2 ^ w` for a parameter of width `w < 256` reverts with empty +data, as SolidCore's decoder, its address check or its `uint b` cleanup, and solar's `lower-abi` +do), then the body's branch tree run from `initState`, with each leaf turned into the call's end +by `leafTree`: the returned words ABI-encoded with the body's storage writes and logs, or a +revert's data (empty, `Panic(code)` or `Error(msg)`) with neither. + +Past the argument checks every argument word fits its width, which the facts `argFacts` record +(`gt (arg i) (2 ^ w - 1)` taken as zero). The erasure reads them through the `EraseEnv`'s +`facts` and `leafTree` through its own: a returned `address` word must be below `2 ^ 160` and a +`bool` word at most 1 on every call (`retOk`: its `bound` on the facts), as SolidCore's encoder +asks, so an `address` parameter, `msg.sender`, a masked storage read or a comparison returns +as it is. -/ namespace SolidCore.Refinement.Generic open SolidCore.Solidity.Source -/-- A binding of the fragment: a `uint256`, not a storage reference. -/ +/-- A return binding of the fragment: a `uint256`, an `address` or a `bool`, not a storage +reference. -/ def wordBinding (b : BindingDecl) : Bool := - (match b.ty with | .uint256 => true | _ => false) && !b.isStorageRef + (match b.ty with | .uint256 => true | .address => true | .bool => true | _ => false) && + !b.isStorageRef /-- The width of the argument word of a parameter of the fragment, from its binding and its ABI cleanup: `b` for a `uint256` with the cleanup `uint b`, `0 < b ≤ 256`, and 160 for an `address` with @@ -50,6 +60,14 @@ def paramGuards : List Nat → Nat → Tree → Tree .ite (.bin .gt (.arg i) (.lit (2 ^ w - 1))) (.halt false [] [] []) (paramGuards ws (i + 1) t) else paramGuards ws (i + 1) t +/-- What the argument checks from parameter `i` on leave known: each word of a parameter of +width `w < 256` is at most `2 ^ w - 1`. -/ +def argFacts : List Nat → Nat → Facts + | [], _ => [] + | w :: ws, i => + if w < 256 then (.bin .gt (.arg i) (.lit (2 ^ w - 1)), false) :: argFacts ws (i + 1) + else argFacts ws (i + 1) + /-- The parameters as locals: parameter `i` holds argument word `i`. -/ def paramLocals : List BindingDecl → Nat → Locals | [], _ => [] @@ -62,40 +80,67 @@ def initState (fn : FunctionDef) : SymState := writes := [] logs := [] } +/-- A returned word SolidCore's encoder takes for its type on every call the facts hold on: any +word for a `uint256`, one below `2 ^ 160` for an `address`, at most 1 for a `bool`. -/ +def retOk (K : Facts) (ty : Ty) (w : WExpr) : Bool := + match ty with + | .uint256 => true + | .address => decide (bound K w < 2 ^ 160) + | .bool => decide (bound K w ≤ 1) + | _ => false + +/-- Every returned word is one SolidCore's encoder takes for its return's type. -/ +def retsOk (K : Facts) : List BindingDecl → List WExpr → Bool + | [], [] => true + | r :: rs, w :: ws => retOk K r.ty w && retsOk K rs ws + | _, _ => false + +/-- The bytes of SolidCore's `Error(msg)` revert data: the selector `0x08c379a0` and the ABI +encoding of the message, when every byte is one. -/ +def errorBytes (msg : String) : Option (List OByte) := + match ABI.encodeValues? [.bytesCalldata] [.bytes (ABI.stringBytes msg)] with + | some p => + let bs := ABI.encodeSelector ABI.errorSelector ++ p + if bs.all (· < 256) then some (bs.map .lit) else none + | none => none + /-- How a call ends, from how its body ends: the returned words, ABI-encoded, or the named returns when the body falls through or returns nothing, with the body's writes and logs; a revert's data, with no writes and no logs. -/ -def leafTree (fn : FunctionDef) : Leaf → Option Tree +def leafTree (fn : FunctionDef) (K : Facts) : Leaf → Option Tree | .normal S => do let ws ← fn.returns.mapM fun r => Scopes.get? S.scopes r.name - some (.halt true (ws.flatMap wordOBytes) S.writes S.logs) + if retsOk K fn.returns ws then some (.halt true (ws.flatMap wordOBytes) S.writes S.logs) + else none | .returned S vs => if vs = [] then do let ws ← fn.returns.mapM fun r => Scopes.get? S.scopes r.name - some (.halt true (ws.flatMap wordOBytes) S.writes S.logs) - else if vs.length = fn.returns.length then + if retsOk K fn.returns ws then some (.halt true (ws.flatMap wordOBytes) S.writes S.logs) + else none + else if retsOk K fn.returns vs then some (.halt true (vs.flatMap wordOBytes) S.writes S.logs) else none - | .reverted none => some (.halt false [] [] []) - | .reverted (some c) => some (.halt false (panicBytes c) [] []) + | .reverted .empty => some (.halt false [] [] []) + | .reverted (.panic c) => some (.halt false (panicBytes c) [] []) + | .reverted (.error m) => (errorBytes m).map fun bs => .halt false bs [] [] /-- The call's tree from its body's branch tree. -/ -def brTree (fn : FunctionDef) : Br → Option Tree - | .leaf l => leafTree fn l +def brTree (fn : FunctionDef) (K : Facts) : Br → Option Tree + | .leaf l => leafTree fn K l | .ite c t e => do - let t' ← brTree fn t - let e' ← brTree fn e + let t' ← brTree fn K t + let e' ← brTree fn K e some (.ite c t' e') /-- The erasure of an external call of `fn` in the contract `E` describes: its argument checks, -then its body run with fuel `fuel`. -/ +then its body run with fuel `fuel`, knowing the facts the checks leave. -/ def eraseFn (E : EraseEnv) (fuel : Nat) (fn : FunctionDef) : Option Tree := match widthsOf fn.params fn.paramAbiCleanups with | none => none | some ws => if fn.returns.all wordBinding then do - let b ← eraseStmt E fuel fn.body (initState fn) - let t ← brTree fn b + let b ← eraseStmt { E with facts := argFacts ws 0 } fuel fn.body (initState fn) + let t ← brTree fn (argFacts ws 0) b some (paramGuards ws 0 t) else none diff --git a/SolidCore/Refinement/Generic/SourceRun.lean b/SolidCore/Refinement/Generic/SourceRun.lean index e9cb4abd..843dcb80 100644 --- a/SolidCore/Refinement/Generic/SourceRun.lean +++ b/SolidCore/Refinement/Generic/SourceRun.lean @@ -34,7 +34,8 @@ 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⟩ +def envOf (core : Contract) : EraseEnv := + { fields := core.storageFields, events := core.eventDecls, tbl := core.table } /-! ## The shape of the parameters -/ @@ -286,8 +287,11 @@ theorem bindArgs_words (ρ : Val) (hρ : ∀ a ∈ ρ.args, a < wordSize) : bind, Option.bind, paramLocals, frameOf, List.map_cons, WExpr.eval, List.getD_eq_getElem?_getD, List.getElem?_eq_getElem hi, Option.getD_some, Nat.mod_eq_of_lt hlt] +/-- A return the fragment encodes: a `uint256`, `address` or `bool`. -/ +abbrev RetTy (ty : Source.Ty) : Prop := ty = .uint256 ∨ ty = .address ∨ ty = .bool + theorem defaults_words (ρ : Val) (rs : List BindingDecl) - (hrs : ∀ r ∈ rs, r.ty = .uint256 ∧ r.isStorageRef = false) : + (hrs : ∀ r ∈ rs, RetTy r.ty ∧ r.isStorageRef = false) : rs.map BindingDecl.defaultBinding = frameOf ρ (rs.map fun r => (r.name, WExpr.lit 0)) := by induction rs with | nil => rfl @@ -295,16 +299,49 @@ theorem defaults_words (ρ : Val) (rs : List BindingDecl) 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] + rcases h.1 with h1 | h1 | h1 <;> + simp [BindingDecl.defaultBinding, h1, h.2, Source.Ty.defaultValue, WExpr.eval] + +/-- A word `retOk` accepts is one SolidCore coerces to its return's type and encodes as its +32-byte word. -/ +theorem retOk_spec {ρ : Val} {K : Facts} (hK : K.Hold ρ) {ty : Source.Ty} {w : WExpr} + (h : retOk K ty w = true) : + ty.coerceValue? (.word (w.eval ρ)) = some (.word (w.eval ρ)) ∧ + ABI.Ty.isDynamicAbi ty = false ∧ ABI.Ty.staticAbiHeadWords? ty = some 1 ∧ + ABI.encodeStaticValue? ty (.word (w.eval ρ)) = some (ABI.encodeWord (w.eval ρ)) := by + have hlt := w.eval_lt ρ + unfold retOk at h + split at h + · exact ⟨by simp [Source.Ty.coerceValue?], rfl, rfl, rfl⟩ + · simp only [decide_eq_true_eq] at h + have hn : w.eval ρ < 1461501637330902918203684832716283019655932542976 := + Nat.lt_of_le_of_lt (bound_sound hK w) h + exact ⟨by simp [Source.Ty.coerceValue?], rfl, rfl, + by simp [ABI.encodeStaticValue?, ABI.addressFits, norm_lt hlt, hn]⟩ + · simp only [decide_eq_true_eq] at h + have hn : w.eval ρ ≤ 1 := Nat.le_trans (bound_sound hK w) h + have hv : w.eval ρ = 0 ∨ w.eval ρ = 1 := by omega + rcases hv with hv | hv <;> + exact ⟨by simp [Source.Ty.coerceValue?, wordEq, hv], rfl, rfl, + by simp [ABI.encodeStaticValue?, wordEq, hv]⟩ + · simp at h + +theorem retsOk_length {K : Facts} : ∀ {rs : List BindingDecl} {ws : List WExpr}, + retsOk K rs ws = true → ws.length = rs.length + | [], [], _ => rfl + | _ :: rs, _ :: ws, h => by + simp only [retsOk, Bool.and_eq_true] at h + simp [retsOk_length h.2] + | [], _ :: _, h | _ :: _, [], h => by simp [retsOk] at h /-! ## Reading the returned words -/ theorem deref_word (rt : Runtime) (v : Nat) : rt.derefMemoryValueDeep (.word v) = .ok (.word v) := by simp [Runtime.derefMemoryValueDeep, Runtime.derefMemoryValueWithFuel] -theorem collect_words (ρ : Val) (rt : Runtime) (S : SymState) +theorem collect_words (ρ : Val) (rt : Runtime) (S : SymState) {K : Facts} (hK : K.Hold ρ) (hl : ∀ x e, Scopes.get? S.scopes x = some e → rt.lookupLocal? x = some (.word (e.eval ρ))) : - ∀ (rs : List BindingDecl) (ws : List WExpr), (∀ r ∈ rs, r.ty = .uint256) → + ∀ (rs : List BindingDecl) (ws : List WExpr), retsOk K rs ws = true → rs.mapM (fun r => Scopes.get? S.scopes r.name) = some ws → collectReturnBindings.collect rt rs = .ok (ws.map fun e => .word (e.eval ρ)) | [], ws, _, h => by @@ -314,23 +351,23 @@ theorem collect_words (ρ : Val) (rt : Runtime) (S : SymState) 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] + simp only [retsOk, Bool.and_eq_true] at hrs + have ih := collect_words ρ rt S hK hl rs ws' hrs.2 hws' + simp [collectReturnBindings.collect, hl _ _ he, deref_word, (retOk_spec hK hrs.1).1, ih, bind, + Except.bind, pure, Except.pure] -theorem coerce_words (ρ : Val) (rt : Runtime) : - ∀ (rs : List BindingDecl) (ws : List WExpr), (∀ r ∈ rs, r.ty = .uint256) → - ws.length = rs.length → +theorem coerce_words (ρ : Val) (rt : Runtime) {K : Facts} (hK : K.Hold ρ) : + ∀ (rs : List BindingDecl) (ws : List WExpr), retsOk K rs ws = true → coerceReturnBindings.coerce rt rs (ws.map fun e => .word (e.eval ρ)) = .ok (ws.map fun e => .word (e.eval ρ)) - | [], [], _, _ => rfl - | r :: rs, e :: ws, hrs, hl => by - have ih := coerce_words ρ rt rs ws (fun q hq => hrs q (List.mem_cons_of_mem _ hq)) - (by simpa using hl) + | [], [], _ => rfl + | r :: rs, e :: ws, hrs => by + simp only [retsOk, Bool.and_eq_true] at hrs + have ih := coerce_words ρ rt hK rs ws hrs.2 simp only [List.map_cons] at ih ⊢ - simp [coerceReturnBindings.coerce, deref_word, hrs r List.mem_cons_self, coerce_word, ih, + simp [coerceReturnBindings.coerce, deref_word, (retOk_spec hK hrs.1).1, ih, bind, Except.bind, pure, Except.pure] - | [], _ :: _, _, hl | _ :: _, [], _, hl => by simp at hl + | [], _ :: _, h | _ :: _, [], h => by simp [retsOk] at h /-! ## Encoding the output -/ @@ -374,35 +411,37 @@ theorem litBytes_eval (ρ : Val) (n : Nat) : 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 → +theorem encodeAux_words (ρ : Val) {K : Facts} (hK : K.Hold ρ) : + ∀ (rs : List BindingDecl) (ws : List WExpr) (off : Nat), retsOk K rs ws = true → ABI.encodeValuesAux? (rs.map BindingDecl.ty) (ws.map fun e => .word (e.eval ρ)) off = some ((ws.flatMap wordOBytes).map (OByte.eval ρ), [], off) - | [], [], _, _, _ => rfl - | r :: rs, e :: ws, off, hrs, 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 + | [], [], _, _ => rfl + | r :: rs, e :: ws, off, hrs => by + simp only [retsOk, Bool.and_eq_true] at hrs + have ih := encodeAux_words ρ hK rs ws off hrs.2 + obtain ⟨-, hd, -, he⟩ := retOk_spec hK hrs.1 + simp only [List.map_cons, ABI.encodeValuesAux?, hd, he, ih, Bool.false_eq_true, ↓reduceIte, + List.flatMap_cons, List.map_append, encodeWord_eval] + | [], _ :: _, _, h | _ :: _, [], _, h => by simp [retsOk] at h -theorem encode_words (ρ : Val) (rs : List BindingDecl) (ws : List WExpr) - (hrs : ∀ r ∈ rs, r.ty = .uint256) (hl : ws.length = rs.length) : +theorem encode_words (ρ : Val) {K : Facts} (hK : K.Hold ρ) (rs : List BindingDecl) (ws : List WExpr) + (hrs : retsOk K rs ws = true) : ABI.encodeValues? (rs.map BindingDecl.ty) (ws.map fun e => .word (e.eval ρ)) = some ((ws.flatMap wordOBytes).map (OByte.eval ρ)) := by - have hhw : ∀ (rs : List BindingDecl), (∀ r ∈ rs, r.ty = .uint256) → + have hhw : ∀ (rs : List BindingDecl) (ws : List WExpr), retsOk K rs ws = true → ABI.Ty.listAbiHeadWords? (rs.map BindingDecl.ty) = some rs.length := by - intro rs hrs + intro rs induction rs with - | nil => rfl + | nil => intro ws _; 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] + intro ws h + cases ws with + | nil => simp [retsOk] at h + | cons w ws => + simp only [retsOk, Bool.and_eq_true] at h + obtain ⟨-, hd, hw, -⟩ := retOk_spec (ρ := ρ) hK h.1 + simp [ABI.Ty.listAbiHeadWords?, ABI.Ty.abiHeadWords?, hd, hw, ih ws h.2, Nat.add_comm] + simp [ABI.encodeValues?, hhw rs ws hrs, encodeAux_words ρ hK rs ws _ hrs, bind, Option.bind] theorem encode_panic (ρ : Val) (core : Contract) (c : Nat) : ABI.Contract.encodeRevertData? core (.panic c) = some ((panicBytes c).map (OByte.eval ρ)) := by @@ -414,19 +453,41 @@ theorem encode_panic (ρ : Val) (core : Contract) (c : Nat) : simp only [ABI.Contract.encodeRevertData?, h2, panicBytes, List.map_append] congr 2 +/-- SolidCore's `Error(msg)` revert data are `errorBytes msg`. -/ +theorem encode_error (ρ : Val) (core : Contract) {m : String} {bs : List OByte} + (h : errorBytes m = some bs) : + ABI.Contract.encodeRevertData? core (.error m) = some (bs.map (OByte.eval ρ)) := by + unfold errorBytes at h + split at h + · rename_i p hp + dsimp only at h + split at h + · rename_i hall + simp only [Option.some.injEq] at h + subst h + simp only [ABI.Contract.encodeRevertData?, hp, List.map_map, Option.some.injEq] + symm + have hid : ∀ b ∈ ABI.encodeSelector ABI.errorSelector ++ p, (OByte.eval ρ ∘ OByte.lit) b = id b := + fun b hb => by + simp only [Function.comp, OByte.eval, id] + exact Nat.mod_eq_of_lt (by simpa using List.all_eq_true.mp hall b hb) + rw [List.map_congr_left hid, List.map_id] + · simp at h + · simp at h + /-! ## The call -/ -theorem brTree_eval (fn : FunctionDef) (ρ : Val) : - ∀ (b : Br) (T : Tree), brTree fn b = some T → - ∃ T', leafTree fn (b.eval ρ) = some T' ∧ T'.eval ρ = T.eval ρ +theorem brTree_eval (fn : FunctionDef) (K : Facts) (ρ : Val) : + ∀ (b : Br) (T : Tree), brTree fn K b = some T → + ∃ T', leafTree fn K (b.eval ρ) = some T' ∧ T'.eval ρ = T.eval ρ | .leaf l, T, h => ⟨T, h, rfl⟩ | .ite c t e, T, h => by simp only [brTree, Option.bind_eq_bind, Option.bind_eq_some_iff, Option.some.injEq] at h obtain ⟨t', ht, e', he, rfl⟩ := h simp only [Br.eval, Tree.eval] split - · exact brTree_eval fn ρ e e' he - · exact brTree_eval fn ρ t t' ht + · exact brTree_eval fn K ρ e e' he + · exact brTree_eval fn K ρ t t' ht theorem slotValue_lt (σ : List (Nat × Nat)) (k : Nat) : slotValue σ k < wordSize := by unfold slotValue @@ -591,6 +652,51 @@ theorem paramGuards_eval (ρ : Val) (t : Tree) (hρ : ∀ a ∈ ρ.args, a < wor have : a < 2 ^ w := Nat.lt_of_lt_of_le halt (Nat.pow_le_pow_right (by decide) (by omega)) simp [ih, this] +/-- Past the argument checks, the facts they leave hold. -/ +theorem argFacts_hold (ρ : Val) (hρ : ∀ a ∈ ρ.args, a < wordSize) : + ∀ (ws : List Nat) (i : Nat), argsClean ws (ρ.args.drop i) = true → (argFacts ws i).Hold ρ + | [], _, _ => by simp [argFacts, Facts.Hold] + | w :: ws, i, h => by + have key : ∀ a, (WExpr.arg i).eval ρ = a → a < 2 ^ w → argsClean ws (ρ.args.drop (i + 1)) = true → + (argFacts (w :: ws) i).Hold ρ := by + intro a ha haw hrest + have ih := argFacts_hold ρ hρ ws (i + 1) hrest + simp only [argFacts] + split + · rename_i hw256 + refine Facts.Hold.cons ih ?_ + have hpos := Nat.two_pow_pos w + have hm : (2 ^ w - 1) % wordSize = 2 ^ w - 1 := + Nat.mod_eq_of_lt (Nat.lt_of_lt_of_le (Nat.sub_lt hpos (by decide)) + (Nat.pow_le_pow_right (by decide) (by omega))) + have : ¬ 2 ^ w - 1 < a := by omega + simp only [eval_bin, eval_lit, ha, hm, BinOp.eval] + simp [this] + · exact ih + cases hdrop : ρ.args.drop i with + | nil => + have hge : ρ.args.length ≤ i := by simpa using hdrop + have hd1 : ρ.args.drop (i + 1) = [] := by simp; omega + have harg : (WExpr.arg i).eval ρ = 0 := by + simp [WExpr.eval, List.getD_eq_getElem?_getD, List.getElem?_eq_none hge] + refine key 0 harg (Nat.two_pow_pos w) ?_ + rw [hd1]; cases ws <;> rfl + | cons a as => + have hi : i < ρ.args.length := by + have := congrArg List.length hdrop; simp at this; omega + have ha : ρ.args.getD i 0 = a := by + rw [List.getD_eq_getElem?_getD, ← List.head?_drop, hdrop]; rfl + have hd1 : ρ.args.drop (i + 1) = as := by + rw [← List.drop_drop, hdrop]; rfl + have halt : a < wordSize := by + rw [← ha, List.getD_eq_getElem?_getD, List.getElem?_eq_getElem hi] + exact hρ _ (List.getElem_mem hi) + rw [hdrop] at h + simp only [argsClean, Bool.and_eq_true, decide_eq_true_eq] at h + refine key a ?_ h.1 (by rw [hd1]; exact h.2) + have ha' : ρ.args[i]?.getD 0 = a := by rw [← List.getD_eq_getElem?_getD]; exact ha + simp [WExpr.eval, ha', Nat.mod_eq_of_lt halt] + /-- **SolidCore rejects dirty argument words**: a call whose argument words SolidCore's decoder rejects with empty data reverts with empty output and keeps the call's storage. -/ theorem run_rejected {fuel : Nat} {c : TypeCheck.CheckedContract} {d : Source.State} @@ -620,13 +726,15 @@ theorem run_rejected {fuel : Nat} {c : TypeCheck.CheckedContract} {d : Source.St /-! ## The call -/ theorem wordBinding_ty {b : BindingDecl} (h : wordBinding b = true) : - b.ty = .uint256 ∧ b.isStorageRef = false := by + RetTy b.ty ∧ b.isStorageRef = false := by unfold wordBinding at h simp only [Bool.and_eq_true, Bool.not_eq_true'] at h refine ⟨?_, h.2⟩ have := h.1 split at this - · rename_i h'; exact h' + · rename_i h'; exact .inl h' + · rename_i h'; exact .inr (.inl h') + · rename_i h'; exact .inr (.inr h') · simp at this /-- The parameter widths of a function the erasure accepts. -/ @@ -646,9 +754,10 @@ theorem source_run_clean {fuel : Nat} {c : TypeCheck.CheckedContract} {d : Sourc (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) + (hb : eraseStmt { envOf c.core with facts := argFacts ws 0 } fuel fn.body (initState fn) = some b) + {T : Tree} (hT : brTree fn (argFacts ws 0) b = some T) (args : List Nat) (hlen : args.length = fn.params.length) (hargs : ∀ a ∈ args, a < 2 ^ 256) + (hclean : argsClean ws args = true) (hdec : ABI.decodeFunctionArgs? fn (Dirty.argBytes args) = .ok (args.map .word)) : Source.run fuel c { calldata := Abi.calldata sel args, callvalue := 0, storage := σ } = some (T.eval ⟨args, slotValue σ, solHash⟩).obs := by @@ -660,7 +769,7 @@ theorem source_run_clean {fuel : Nat} {c : TypeCheck.CheckedContract} {d : Sourc 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 := + have hr : ∀ r ∈ fn.returns, RetTy r.ty ∧ r.isStorageRef = false := fun r hr => wordBinding_ty (List.all_eq_true.mp hret r hr) generalize hctx : ABI.Contract.callContextAtWithBase c.core (Wide.ctxOf c) selfAddress callerAddress 0 ((EthLib.Base.natToBytes 4 sel).map (·.toNat) ++ Dirty.argBytes args) = ctx @@ -672,6 +781,9 @@ theorem source_run_clean {fuel : Nat} {c : TypeCheck.CheckedContract} {d : Sourc subst hctx; simp [ABI.Contract.callContextAtWithBase, SolidCore.Solidity.Shared.norm] set ρ : Val := ⟨args, slotValue σ, solHash⟩ with hρ have hρok : ρ.Ok := slotValue_store σ + set K := argFacts ws 0 with hK + have hKρ : K.Hold ρ := argFacts_hold ρ hargs ws 0 (by simpa [hρ] using hclean) + set E : EraseEnv := { envOf c.core with facts := K } with hE have hframe : fn.initialFrame? (args.map .word) = some (frameOf ρ (paramLocals fn.params 0 ++ fn.returns.map fun r => (r.name, .lit 0))) := by have h0 : BindingDecl.bindArgs? fn.params (args.map .word) = @@ -679,7 +791,7 @@ theorem source_run_clean {fuel : Nat} {c : TypeCheck.CheckedContract} {d : Sourc 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 + have hrel : StmtRel ρ E ctx { state := { st0 with selfBalance := SolidCore.Solidity.Shared.addWord (SolidCore.Solidity.Shared.Account.balanceAt ctx.accountBalances ctx.self) ctx.value @@ -701,31 +813,33 @@ theorem source_run_clean {fuel : Nat} {c : TypeCheck.CheckedContract} {d : Sourc 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 + logs := by subst hst; simp [hd.events, initState] + facts := hKρ } + obtain ⟨r, hrun, hleaf⟩ := eval_stmt ρ E ctx fuel fn.body (initState fn) b hb _ hrel have hcall : fn.call? fuel c.core.table ctx st0 (args.map .word) = some (fn.callBodyResult st0 r) := by have hacc' : fn.acceptsValue ctx.value = true := hctxv ▸ hacc simp only [FunctionDef.call?, FunctionDef.call, FunctionDef.evalBodyEntry, hacc', hframe, if_true, Option.map_some, Option.bind_some] - rw [show c.core.table = (envOf c.core).tbl from rfl, hrun] + rw [show c.core.table = E.tbl from rfl, hrun] rfl - obtain ⟨T', hT', hTe⟩ := brTree_eval fn ρ b T hT + obtain ⟨T', hT', hTe⟩ := brTree_eval fn K ρ 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 [leafTree, Option.bind_eq_bind, Option.bind_eq_some_iff] at hT' + obtain ⟨ws, hws, hT'⟩ := hT' + split at hT' + case isFalse => simp at hT' + rename_i hok + simp only [Option.some.injEq] at hT' + subst hT' simp only [FunctionDef.callBodyResult, FunctionDef.collectReturns, collectReturnBindings, - collect_words ρ rt S 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] + collect_words ρ rt S hKρ hleaf.expr.locals fn.returns ws hok hws, untag_words, + encode_words ρ hKρ fn.returns ws hok, bind, Option.bind, Option.map_some] simp only [Source.observe, Tree.eval, Res.obs, if_true, ↓reduceIte, logEntries_map, hleaf.logs, Option.some.injEq, Observable.mk.injEq, true_and] funext slot @@ -736,14 +850,17 @@ theorem source_run_clean {fuel : Nat} {c : TypeCheck.CheckedContract} {d : Sourc 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 [leafTree, if_true, Option.bind_eq_bind, Option.bind_eq_some_iff] at hT' + obtain ⟨ws, hws, hT'⟩ := hT' + split at hT' + case isFalse => simp at hT' + rename_i hok + simp only [Option.some.injEq] at hT' + subst hT' simp only [FunctionDef.callBodyResult, List.map_nil, List.isEmpty_nil, if_true, FunctionDef.collectReturns, collectReturnBindings, - collect_words ρ rt S 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] + collect_words ρ rt S hKρ hst'.expr.locals fn.returns ws hok hws, untag_words, + encode_words ρ hKρ fn.returns ws hok, bind, Option.bind, Option.map_some] simp only [Source.observe, Tree.eval, Res.obs, if_true, ↓reduceIte, logEntries_map, hst'.logs, Option.some.injEq, Observable.mk.injEq, true_and] funext slot @@ -751,7 +868,7 @@ theorem source_run_clean {fuel : Nat} {c : TypeCheck.CheckedContract} {d : Sourc · simp only [leafTree, hv, if_false] at hT' split at hT' case isFalse => simp at hT' - rename_i hlen' + rename_i hok simp only [Option.some.injEq] at hT' subst hT' have hne : (vs.map fun e => Value.word (e.eval ρ)).isEmpty = false := by @@ -760,24 +877,31 @@ theorem source_run_clean {fuel : Nat} {c : TypeCheck.CheckedContract} {d : Sourc | 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] + coerce_words ρ rt hKρ fn.returns vs hok, untag_words, + encode_words ρ hKρ fn.returns vs hok, bind, Option.bind, Option.map_some] simp only [Source.observe, Tree.eval, Res.obs, if_true, ↓reduceIte, logEntries_map, hst'.logs, Option.some.injEq, Observable.mk.injEq, true_and] funext slot exact loadSlot_eq _ S.writes ρ hρok hst'.store slot | reverted p => - cases p <;> cases r <;> simp only [LeafRel] at hleaf - · subst hleaf + cases r <;> simp only [LeafRel] at hleaf + subst hleaf + cases p with + | empty => simp only [leafTree, Option.some.injEq] at hT' subst hT' - simp [FunctionDef.callBodyResult, RevertData.untagFixedBytes, + simp [FunctionDef.callBodyResult, RevertData.untagFixedBytes, Fail.data, ABI.Contract.encodeRevertData?, Source.observe, Tree.eval, Res.obs, hρ, SolidCore.Refinement.Evm.Wide.callAt] - · subst hleaf + | panic c => simp only [leafTree, Option.some.injEq] at hT' subst hT' - simp [FunctionDef.callBodyResult, RevertData.untagFixedBytes, encode_panic ρ, + simp [FunctionDef.callBodyResult, RevertData.untagFixedBytes, Fail.data, encode_panic ρ, + Source.observe, Tree.eval, Res.obs, hρ, SolidCore.Refinement.Evm.Wide.callAt] + | error m => + simp only [leafTree, Option.map_eq_some_iff] at hT' + obtain ⟨bs, hbs, rfl⟩ := hT' + simp [FunctionDef.callBodyResult, RevertData.untagFixedBytes, Fail.data, encode_error ρ _ hbs, Source.observe, Tree.eval, Res.obs, hρ, SolidCore.Refinement.Evm.Wide.callAt] /-- **SolidCore runs a call of a function of the fragment as its erased tree**, from any storage @@ -805,7 +929,7 @@ theorem source_run {fuel : Nat} {c : TypeCheck.CheckedContract} {d : Source.Stat 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 hd hcov hsel hfind hw hret hb ht args hlen hargs hclean hdec · rw [if_neg hclean] rw [if_neg hclean] at hdec rw [run_rejected hd hsel hfind args hdec σ] diff --git a/SolidCore/Refinement/Generic/SourceStmt.lean b/SolidCore/Refinement/Generic/SourceStmt.lean index 94882736..2972f78c 100644 --- a/SolidCore/Refinement/Generic/SourceStmt.lean +++ b/SolidCore/Refinement/Generic/SourceStmt.lean @@ -18,11 +18,30 @@ table of internal functions, which the relation asks to be the context's and the namespace SolidCore.Refinement.Generic open SolidCore.Solidity.Source +/-- Why a statement of the fragment reverts: with empty data, with `Panic(code)`, or with +`Error(msg)`, as `require(c, msg)` and `revert(msg)` do. -/ +inductive Fail where + | empty + | panic (code : Nat) + | error (msg : String) + deriving DecidableEq, Repr + +/-- SolidCore's revert data of a revert. -/ +def Fail.data : Fail → RevertData + | .empty => .empty + | .panic c => .panic c + | .error m => .error m + +/-- The revert of a `require` or `revert` with the reason `r`, if any. -/ +def failOf : Option String → Fail + | none => .empty + | some m => .error m + /-- How a statement of the fragment ends. -/ inductive Leaf where | normal (S : SymState) | returned (S : SymState) (vals : List WExpr) - | reverted (panic : Option Nat) + | reverted (f : Fail) deriving DecidableEq, Repr /-- A statement's outcome as a tree of branches on words. -/ @@ -37,11 +56,11 @@ def Br.eval (ρ : Val) : Br → Leaf /-- 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 + gs.foldr (fun g acc => .ite g (.leaf (.reverted (.panic 0x11))) acc) rest theorem guards_eval (ρ : Val) (gs : List WExpr) (rest : Br) : (guards gs rest).eval ρ = - if gs.any (fun g => g.eval ρ != 0) then .reverted (some 0x11) else rest.eval ρ := by + if gs.any (fun g => g.eval ρ != 0) then .reverted (.panic 0x11) else rest.eval ρ := by induction gs with | nil => rfl | cons g gs ih => @@ -134,11 +153,13 @@ theorem wordTy_coerce {ty : Ty} (h : wordTy ty = true) (v : Nat) : 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. -/ +internal functions, with the facts that hold of every call it erases (`facts`: the argument +checks of the external function, which bound its `address` words for logs). -/ structure EraseEnv where fields : List StorageField events : List EventDecl tbl : FunctionTable + facts : Facts := [] /-- The erasure of a list of expressions: their overflow conditions and their words. -/ def eraseExprs (fields : List StorageField) (S : SymState) : List Expr → Option (List WExpr × List WExpr) @@ -298,7 +319,30 @@ def eraseStmt (E : EraseEnv) : Nat → Stmt → SymState → Option Br 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))) + | .panic code => some (.leaf (.reverted (.panic code))) + | .requireStmt c r => do + let (gs, v) ← eraseExpr E.fields S c + some (guards gs (.ite v (.leaf (.normal S)) (.leaf (.reverted (failOf r))))) + | .revertError r => some (.leaf (.reverted (failOf r))) + | .assign (.storageIndex x i) e => do + let (gs, v) ← eraseExpr E.fields S e + let (gi, key) ← eraseExpr E.fields S i + match mapOf? E.fields x with + | some k => + some (guards (gs ++ gi) (.leaf (.normal { S with writes := S.writes.set (.hash key (.lit k)) v }))) + | none => do + let k ← boolMapOf? E.fields x + if bound E.facts v ≤ 1 then + some (guards (gs ++ gi) + (.leaf (.normal { S with writes := S.writes.set (.hash key (.lit k)) v }))) + else none + | .assign (.index (.storageIndex x i1) i2) e => do + let k ← map2Of? E.fields x + let (gs, v) ← eraseExpr E.fields S e + let (g1, k1) ← eraseExpr E.fields S i1 + let (g2, k2) ← eraseExpr E.fields S i2 + some (guards (gs ++ g1 ++ g2) + (.leaf (.normal { S with writes := S.writes.set (.hash k2 (.hash k1 (.lit k))) v }))) | .internalCall targets callee args => do let fn ← E.tbl.lookup? callee if fn.params.all wordDecl && fn.returns.all wordDecl && args.length = fn.params.length then @@ -316,7 +360,7 @@ def eraseStmt (E : EraseEnv) : Nat → Stmt → SymState → Option Br 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 + if evOk E.facts decl.fields ws then some (guards gs (.leaf (.normal { S with logs := S.logs ++ [⟨.lit t :: evTopics decl.fields ws, (evData decl.fields ws).flatMap wordOBytes⟩] }))) else none @@ -347,6 +391,7 @@ structure StmtRel (ρ : Val) (E : EraseEnv) (ctx : Context) (rt : Runtime) (S : frames : rt.locals = S.scopes.map (frameOf ρ) store : ∀ k, k < wordSize → rt.state.loadSlot k = Writes.store ρ S.writes k logs : rt.state.events.map logOf = S.logs.map (Log.eval ρ) + facts : E.facts.Hold ρ theorem frame_lookup (ρ : Val) (L : Locals) (x : String) : Frame.lookup? (frameOf ρ L) x = (L.get? x).map fun e => Value.word (e.eval ρ) := by @@ -473,7 +518,8 @@ theorem StmtRel.write {ρ : Val} {E : EraseEnv} {ctx : Context} {rt : Runtime} { by_cases h : q = k.eval ρ · simp [h] · simp [h, Ne.symm h] - logs := by simp [State.storeSlot, hrel.logs] } + logs := by simp [State.storeSlot, hrel.logs] + facts := hrel.facts } /-- Writing a field keeps the relation, with the field's slot set to `writeField`. -/ theorem StmtRel.writeField {ρ : Val} {E : EraseEnv} {ctx : Context} @@ -495,8 +541,7 @@ 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 + | .reverted _ r, .reverted f => r = f.data | _, _ => False theorem caught_exprResult (ρ : Val) (gs : List WExpr) (v : WExpr) (rt : Runtime) : @@ -824,6 +869,82 @@ theorem eval_mapAssign (ρ : Val) (E : EraseEnv) (ctx : Context) (rt : Runtime) · simp only [hc, decide_false, Bool.not_false, ↓reduceIte] exact ⟨.reverted rt (.panic 0x11), rfl, rfl⟩ + +/-- A plain write of a `bool` word to a mapping to `bool`'s entry stores the word in the entry's +slot. -/ +theorem storeIndex_boolMap {ρ : Val} {E : EraseEnv} {ctx : Context} {rt : Runtime} {S : SymState} + (hrel : StmtRel ρ E ctx rt S) {x : String} {k : Nat} + (hk : boolMapOf? E.fields x = some k) {w v : Nat} (hw : w < wordSize) (hv : v ≤ 1) : + rt.storeStorageIndexWithDeepClear ctx x (.word w) (.word v) = + .ok { rt with state := rt.state.storeSlot (solHash w k) v } := by + obtain ⟨f, hf, rfl⟩ := boolMapOf?_spec hrel.fields hk + have hv' : v = 0 ∨ v = 1 := by omega + rcases hf.layout with hl | hl <;> rcases hv' with rfl | rfl <;> + simp [Runtime.storeStorageIndexWithDeepClear, hf.find, hl, mappingStorageSlotForKey, + coerceMappingKeyWordAs, Value.forceAbiLazy, Ty.coerceValue?, Value.asStorageWord?, norm_lt hw, + bind, Except.bind, State.storeStorageLayoutAtWithDeepClear, + State.storeStorageLayoutAtWithDeepClearFuelMode, State.storeStorageLayoutAt, coerceStorageWordAs, + Runtime.storageMaterializedValue, Runtime.derefMemoryValueDeep, Runtime.derefMemoryValueWithFuel, + StorageLayout.clearDepth, mappingStorageSlot_eq, pure, Except.pure, wordEq, + SolidCore.Solidity.Shared.norm, modulus_eq, Nat.mod_eq_of_lt hw] + +/-- A plain write of a word to a nested mapping's entry stores the word in the entry's slot. -/ +theorem storePath_map2 {ρ : Val} {E : EraseEnv} {ctx : Context} {rt : Runtime} {S : SymState} + (hrel : StmtRel ρ E ctx rt S) {x : String} {k : Nat} + (hk : map2Of? E.fields x = some k) {w1 w2 v : Nat} (h1 : w1 < wordSize) (h2 : w2 < wordSize) + (hv : v < wordSize) : + rt.storeStoragePathWithDeepClear ctx x [.word w1, .word w2] (.word v) = + .ok { rt with state := rt.state.storeSlot (solHash w2 (solHash w1 k)) v } := by + obtain ⟨f, hf, rfl⟩ := map2Of?_spec hrel.fields hk + rw [Runtime.storeStoragePathWithDeepClear, Runtime.storeStorageBasePathWithDeepClear] + simp only [Runtime.storageMaterializedValue, Runtime.derefMemoryValueDeep, + Runtime.derefMemoryValueWithFuel, bind, Except.bind, pure, Except.pure] + rw [resolve_map2 hf h1 h2] + simp [State.storeStorageLayoutAtWithDeepClear, State.storeStorageLayoutAtWithDeepClearFuelMode, + State.storeStorageLayoutAt, coerceStorageWordAs, Value.forceAbiLazy, Ty.coerceValue?, + Value.asStorageWord?, norm_lt hv, StorageLayout.clearDepth, bind, Except.bind, pure, Except.pure] + +/-- SolidCore resolves the target `m[i]` to the entry at `i`'s word, after `i`'s overflow +checks. -/ +theorem resolve_storageIndex (ρ : Val) (fields : List StorageField) (ctx : Context) (rt : Runtime) + (S : SymState) (hrel : ExprRel ρ fields ctx rt S) (x : String) {i : Expr} {gi : List WExpr} + {key : WExpr} (hi : eraseExpr fields S i = some (gi, key)) : + (LValue.resolveWithRuntime (.storageIndex x i) ctx rt).caught = + .done (.ok (if gi.any (fun g => g.eval ρ != 0) then .error (.panic 0x11) + else .ok (.storageIndex x (.word (key.eval ρ)), rt))) := by + simp only [LValue.resolveWithRuntime, Expr.resolveLValue, LValue.toExpr, Expr.storageIndex, + Expr.orderFuel, Expr.listEvalFuel] + rw [Expr.resolveLValueFuel] + rw [eval_erase ρ fields ctx rt S hrel i gi key _ hi (by omega)] + unfold exprResult + split <;> rfl + +/-- SolidCore resolves the target `m[i1][i2]` to the path of the two keys' words, after their +overflow checks. -/ +theorem resolve_index2 (ρ : Val) (fields : List StorageField) (ctx : Context) (rt : Runtime) + (S : SymState) (hrel : ExprRel ρ fields ctx rt S) (x : String) {i1 i2 : Expr} + {g1 g2 : List WExpr} {k1 k2 : WExpr} (h1 : eraseExpr fields S i1 = some (g1, k1)) + (h2 : eraseExpr fields S i2 = some (g2, k2)) : + (LValue.resolveWithRuntime (.index (.storageIndex x i1) i2) ctx rt).caught = + .done (.ok (if (g1 ++ g2).any (fun g => g.eval ρ != 0) then .error (.panic 0x11) + else .ok (.storagePath x [.word (k1.eval ρ), .word (k2.eval ρ)], rt))) := by + simp only [LValue.resolveWithRuntime, Expr.resolveLValue, LValue.toExpr, Expr.storageIndex, + Expr.orderFuel, Expr.listEvalFuel] + rw [Expr.resolveLValueFuel] + rw [Expr.resolveLValueFuel] + rw [eval_erase ρ fields ctx rt S hrel i1 g1 k1 _ h1 (by omega), bind_exprResult] + by_cases hg1 : g1.any (fun g => g.eval ρ != 0) = true + · simp only [hg1, any_append, Bool.true_or, ↓reduceIte] + rfl + · simp only [hg1, Bool.false_eq_true, ↓reduceIte, bind_done_ok, pure, + EvmCompiler.Simulation.Interaction.pure] + rw [eval_erase ρ fields ctx rt S hrel i2 g2 k2 _ h2 (by omega), bind_exprResult] + by_cases hg2 : g2.any (fun g => g.eval ρ != 0) = true + · simp only [hg2, any_append, Bool.or_true, ↓reduceIte] + rfl + · simp only [hg2, any_append, hg1, Bool.or_false, Bool.false_eq_true, ↓reduceIte] + rfl + theorem eval_exprList (ρ : Val) (fields : List StorageField) (ctx : Context) (rt : Runtime) (S : SymState) (hrel : ExprRel ρ fields ctx rt S) : ∀ (es : List Expr) (gs vs : List WExpr) (fuel : Nat), eraseExprs fields S es = some (gs, vs) → @@ -872,13 +993,13 @@ theorem materialize_words (ctx : Context) (rt : Runtime) (ρ : Val) : ∀ ws : L /-- 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) : + {K : Facts} (hK : K.Hold ρ) {ws : List WExpr} (hok : evOk K decl.fields ws = true) : ∃ ev rt', rt.emitEvent ctx name (ws.map fun e => Value.word (e.eval ρ)) = .ok rt' ∧ rt'.state.events = rt.state.events ++ [ev] ∧ rt'.locals = rt.locals ∧ rt'.state.storage = rt.state.storage ∧ logOf ev = Log.eval ρ ⟨.lit t :: evTopics decl.fields ws, (evData decl.fields ws).flatMap wordOBytes⟩ := by - obtain ⟨a, b, henc⟩ := encode_ok ρ decl.fields ws hok - have hdata := encodeValues_ok ρ decl.fields ws hok + obtain ⟨a, b, henc⟩ := encode_ok ρ hK decl.fields ws hok + have hdata := encodeValues_ok ρ hK decl.fields ws hok have hun : (ws.map fun e => Value.word (e.eval ρ)).map Value.untagFixedBytes = ws.map fun e => Value.word (e.eval ρ) := by simp [Value.untagFixedBytes] @@ -1240,7 +1361,7 @@ theorem eval_stmt (ρ : Val) (E : EraseEnv) (ctx : Context) : 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 hlog := emit_words ρ ctx rt hfind ht hrel.facts hok have heq : Stmt.eval (n + 1) E.tbl ctx rt (.emitEvent name es) = (do match ← (Expr.evalList ctx rt @@ -1322,6 +1443,37 @@ theorem eval_stmt (ρ : Val) (E : EraseEnv) (ctx : Context) : simp only [eraseStmt, Option.some.injEq] at h subst h exact ⟨.reverted rt (.panic code), by rw [Stmt.eval]; rfl, rfl⟩ + case requireStmt c r => + simp only [eraseStmt, Option.bind_eq_bind, Option.bind_eq_some_iff, Option.some.injEq] at h + obtain ⟨⟨gs, v⟩, hc, rfl⟩ := h + have heval := eval_eq ρ E.fields ctx rt S hrel.expr hc + rw [Stmt.eval] + simp only [heval, caught_exprResult, guards_eval] + by_cases hg : gs.any (fun g => g.eval ρ != 0) = true + · simp only [hg, ↓reduceIte] + exact ⟨.reverted rt (.panic 0x11), rfl, rfl⟩ + · simp only [hg, Bool.false_eq_true, ↓reduceIte, bind_done_ok, Value.expectWord, + norm_lt (v.eval_lt ρ), Br.eval, wordTruthy] + by_cases hv : v.eval ρ = 0 + · cases r + case none => + refine ⟨.reverted rt .empty, ?_, by simp only [hv, ↓reduceIte, LeafRel]; rfl⟩ + simp [hv] + rfl + case some m => + refine ⟨.reverted rt (.error m), ?_, by simp only [hv, ↓reduceIte, LeafRel]; rfl⟩ + simp [hv] + rfl + · refine ⟨.normal rt, ?_, by simp only [hv, ↓reduceIte, LeafRel]; exact hrel⟩ + simp [hv, SolidCore.Solidity.Shared.norm, modulus_eq, Nat.mod_eq_of_lt (v.eval_lt ρ)] + rfl + case revertError r => + simp only [eraseStmt, Option.some.injEq] at h + subst h + cases r + case none => exact ⟨.reverted rt .empty, by rw [Stmt.eval]; rfl, rfl⟩ + case some m => exact ⟨.reverted rt (.error m), by rw [Stmt.eval]; rfl, rfl⟩ + case assign target e => cases target case var x => @@ -1358,6 +1510,80 @@ theorem eval_stmt (ρ : Val) (E : EraseEnv) (ctx : Context) : rfl · simp only [bind_done_ok, hres, caught_done_ok, ite_self, ResolvedLValue.write, hassign] rfl + case storageIndex x i => + simp only [eraseStmt, Option.bind_eq_bind, Option.bind_eq_some_iff] at h + obtain ⟨⟨gs, v⟩, he, ⟨gi, key⟩, hi, h⟩ := h + obtain ⟨k, hk, hst, rfl⟩ : ∃ k, k < wordSize ∧ + rt.storeStorageIndexWithDeepClear ctx x (.word (key.eval ρ)) (.word (v.eval ρ)) = + .ok { rt with state := rt.state.storeSlot (solHash (key.eval ρ) k) (v.eval ρ) } ∧ + b = guards (gs ++ gi) + (.leaf (.normal { S with writes := S.writes.set (.hash key (.lit k)) v })) := by + split at h + · rename_i k hk + simp only [Option.some.injEq] at h + obtain ⟨f, hf, rfl⟩ := mapOf?_spec hrel.fields hk + exact ⟨f.slot, hf.slot, storeIndex_map hrel hk (key.eval_lt ρ) (v.eval_lt ρ), h.symm⟩ + · simp only [Option.bind_eq_bind, Option.bind_eq_some_iff] at h + obtain ⟨k, hk, h⟩ := h + split at h + · rename_i hb + simp only [Option.some.injEq] at h + obtain ⟨f, hf, rfl⟩ := boolMapOf?_spec hrel.fields hk + exact ⟨f.slot, hf.slot, storeIndex_boolMap hrel hk (key.eval_lt ρ) + (Nat.le_trans (bound_sound hrel.facts v) hb), h.symm⟩ + · simp at h + have heval := eval_eq ρ E.fields ctx rt S hrel.expr he + have hres := resolve_storageIndex ρ E.fields ctx rt S hrel.expr x hi + have hsl : (WExpr.hash key (.lit k)).eval ρ = solHash (key.eval ρ) k % wordSize := by + simp only [WExpr.eval, hrel.hash, Nat.mod_eq_of_lt hk] + have hw := hrel.write (.hash key (.lit k)) v + rw [hsl, storeSlot_mod] at hw + rw [Stmt.eval] + simp only [LValue.wantsMemoryRefRhs, Bool.false_eq_true, ↓reduceIte, heval, caught_exprResult] + rw [guards_eval] + simp only [any_append] + by_cases hg : gs.any (fun g => g.eval ρ != 0) = true + · simp only [hg, Bool.true_or, ↓reduceIte] + exact ⟨.reverted rt (.panic 0x11), rfl, rfl⟩ + · simp only [hg, Bool.false_or, Bool.false_eq_true, ↓reduceIte, bind_done_ok, hres] + by_cases hgi : gi.any (fun g => g.eval ρ != 0) = true + · simp only [hgi, ↓reduceIte] + exact ⟨.reverted rt (.panic 0x11), rfl, rfl⟩ + · simp only [hgi, Bool.false_eq_true, ↓reduceIte, bind_done_ok, ResolvedLValue.write, hst, + ite_self] + exact ⟨_, rfl, hw⟩ + case index base i2 => + cases base + case storageIndex x i1 => + simp only [eraseStmt, Option.bind_eq_bind, Option.bind_eq_some_iff, Option.some.injEq] at h + obtain ⟨k, hk, ⟨gs, v⟩, he, ⟨g1, k1⟩, h1, ⟨g2, k2⟩, h2, rfl⟩ := h + obtain ⟨f, hf, rfl⟩ := map2Of?_spec hrel.fields hk + have heval := eval_eq ρ E.fields ctx rt S hrel.expr he + have hres := resolve_index2 ρ E.fields ctx rt S hrel.expr x h1 h2 + simp only [any_append] at hres + have hsl : (WExpr.hash k2 (.hash k1 (.lit f.slot))).eval ρ = + solHash (k2.eval ρ) (solHash (k1.eval ρ) f.slot) % wordSize := by + simp only [WExpr.eval, hrel.hash, Nat.mod_eq_of_lt hf.slot, + Nat.mod_eq_of_lt (solHash_lt _ _)] + have hw := hrel.write (.hash k2 (.hash k1 (.lit f.slot))) v + rw [hsl, storeSlot_mod] at hw + have hst := storePath_map2 hrel hk (k1.eval_lt ρ) (k2.eval_lt ρ) (v.eval_lt ρ) + rw [Stmt.eval] + simp only [LValue.wantsMemoryRefRhs, LValue.toExpr, Expr.hasStorageRoot, Bool.true_or, + Bool.not_true, Bool.false_eq_true, ↓reduceIte, heval, caught_exprResult] + rw [guards_eval] + simp only [any_append] + by_cases hg : gs.any (fun g => g.eval ρ != 0) = true + · simp only [hg, Bool.true_or, ↓reduceIte] + exact ⟨.reverted rt (.panic 0x11), rfl, rfl⟩ + · simp only [hg, Bool.false_or, Bool.false_eq_true, ↓reduceIte, bind_done_ok, hres] + by_cases hgi : (g1.any (fun g => g.eval ρ != 0) || g2.any (fun g => g.eval ρ != 0)) = true + · simp only [hgi, ↓reduceIte, Bool.or_assoc] + exact ⟨.reverted rt (.panic 0x11), rfl, rfl⟩ + · simp only [hgi, Bool.or_assoc, Bool.false_eq_true, ↓reduceIte, bind_done_ok, + ResolvedLValue.write, hst, ite_self] + exact ⟨_, rfl, hw⟩ + all_goals simp [eraseStmt] at h case storage x => simp only [eraseStmt, Option.bind_eq_bind, Option.bind_eq_some_iff, Option.some.injEq] at h obtain ⟨⟨k, off, bytes⟩, hk, ⟨gs, v⟩, he, rfl⟩ := h diff --git a/SolidCore/Refinement/Generic/Stage.lean b/SolidCore/Refinement/Generic/Stage.lean index 0caac7bb..8a975f86 100644 --- a/SolidCore/Refinement/Generic/Stage.lean +++ b/SolidCore/Refinement/Generic/Stage.lean @@ -30,15 +30,19 @@ module that reads the caller and hashes nothing, under every oracle with SolidCo 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 +`0 < b ≤ 256` bits or addresses (a dirty argument word reverts), `uint256`, `address` and `bool` +returns, checked `+`, `-`, `*` with narrow cleanups, truncating casts such as `uint256(a)`, +bitwise `&`, `|`, `^`, comparisons and `!`, scoped locals, `msg.sender`, unsigned storage fields +alone in their slot or packed with others and mappings to `uint256` (reads, writes and compound +assignments such as `v += x` and `w ^= x`), `address` fields (reads), mappings to `bool` and +nested mappings `m[k1][k2]` to `uint256` (reads and writes), `if` and `else if`, blocks, +returns, `require(c)`, `require(c, msg)`, `revert(msg)` and reverts with `Panic`, logs with +indexed `address` topics, and the other statements `eraseStmt` erases, dispatched by selector +with static call data. `check` asks, for each function of `fns`, that its selector fits in four +bytes, that SolidCore dispatches it to a function with that many parameters, and that the two trees agree: the erasure of the SolidCore function in the contract's `envOf` and the symbolic run of -the MIR module on its selector, compared by `=` on their canonical forms (`Tree.canon`). +the MIR module on its selector, compared by `Tree.beq` (equality) on their canonical forms +(`Tree.canon`). The proof joins the two halves: `source_run` (SolidCore runs the call as the erased tree, with the call's argument words, storage and `solHash`) and `symTree_sound` (the module runs the call as @@ -168,7 +172,7 @@ theorem SourceAsk.envAsk {env : EnvFlags} {o : Oracle} (h : SourceAsk env o) (ar /-- 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. -/ +canonical form (`Tree.beq`). -/ def checkFn (fuel mirFuel : Nat) (core : Contract) (m : Module) (env : EnvFlags) (f : Fn) : Bool := decide (f.sel < 2 ^ 32) && match core.findFunctionBySelector? f.sel with @@ -176,7 +180,7 @@ def checkFn (fuel mirFuel : Nat) (core : Contract) (m : Module) (env : EnvFlags) | 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) + | some t1, some t2 => t1.canon.beq t2.canon | _, _ => false /-- Whether every function of `fns` lowers to `m`, with the environment flag `env` (off by @@ -206,6 +210,7 @@ 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 hcf := Tree.eq_of_beq hcf have hsrc := source_run hd hcov hsel hfind ht1 args (by rw [hlen, hpl]) hargs change Source.run fuel c _ = some obs at hrun rw [hsrc] at hrun diff --git a/SolidCore/Refinement/Generic/Tree.lean b/SolidCore/Refinement/Generic/Tree.lean index 41bbf7d1..9eea4d5a 100644 --- a/SolidCore/Refinement/Generic/Tree.lean +++ b/SolidCore/Refinement/Generic/Tree.lean @@ -31,7 +31,8 @@ the slot words otherwise, since a computed slot may be any slot (`Writes.eval_re 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. +`Tree.canon` (Simp.lean, after `Tree.norm` here) and `Tree.beq`, equality as a `Bool`, which the +kernel evaluates. -/ namespace SolidCore.Refinement.Generic @@ -307,6 +308,25 @@ inductive Tree where | ite (c : WExpr) (t e : Tree) deriving DecidableEq, Repr +/-- Equality of trees as a `Bool`, by structural recursion on both: the kernel evaluates it on the +large trees of a call where it gets stuck on the derived `DecidableEq Tree`. -/ +def Tree.beq : Tree → Tree → Bool + | .halt s o w l, .halt s' o' w' l' => s == s' && decide (o = o') && decide (w = w') && decide (l = l') + | .ite c t e, .ite c' t' e' => decide (c = c') && Tree.beq t t' && Tree.beq e e' + | _, _ => false + +theorem Tree.eq_of_beq : ∀ {a b : Tree}, Tree.beq a b = true → a = b + | .halt _ _ _ _, .halt _ _ _ _, h => by + simp only [Tree.beq, Bool.and_eq_true, beq_iff_eq, decide_eq_true_eq] at h + obtain ⟨⟨⟨rfl, rfl⟩, rfl⟩, rfl⟩ := h + rfl + | .ite _ _ _, .ite _ _ _, h => by + simp only [Tree.beq, Bool.and_eq_true, decide_eq_true_eq] at h + obtain ⟨⟨rfl, ht⟩, he⟩ := h + rw [Tree.eq_of_beq ht, Tree.eq_of_beq he] + | .halt _ _ _ _, .ite _ _ _, h => by simp [Tree.beq] at h + | .ite _ _ _, .halt _ _ _ _, h => by simp [Tree.beq] at h + /-- What a call shows: whether it succeeded, its output, its logs and the storage after it. -/ structure Res where success : Bool diff --git a/SolidCore/Refinement/Solar/Assemble.lean b/SolidCore/Refinement/Solar/Assemble.lean index d9b4338c..0ffd56ee 100644 --- a/SolidCore/Refinement/Solar/Assemble.lean +++ b/SolidCore/Refinement/Solar/Assemble.lean @@ -24,7 +24,8 @@ whose hash is EthLib's KECCAK256 (`OracleOk`, `stage_of_check_eth`). 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 + REVERT) has a constant offset and size (pushed, or a DUP of a pushed one) below the + certificate's memory bound, and the code is below 2^32 bytes. Each block has a potential, a bound on the items its runs execute (the certificate's, or by default the items from it to the end of the layout): each item takes one unit, and a jump or a fall goes to a block whose potential is at most what is left, so a run @@ -242,6 +243,13 @@ def fallOk (p : Program) (c : Cert) (b h : Nat) (ty : List Ty) (k : Nat) : Bool /-- A memory range of constant offset and size within the certificate's bound. -/ def rangeOk (c : Cert) (o s : Word) : Bool := decide (s.toNat = 0) || decide (o.toNat + s.toNat ≤ c.top) +/-- The constants on top of the stack after DUP of the word at depth `i`, from the constants +`known` on top before it: that word, when it is one of them, on top of the constant below it. -/ +def dupKnown (known : List Word) (i : Nat) : List Word := + match known[i]? with + | some v => v :: known.take 1 + | none => [] + /-- The check of one instruction from a stack of at least `h` words whose top words are `known`, constants just pushed, typed `ty`, with potential `k`, and `ok` for the rest of the block: each item takes one unit of potential, each instruction finds the words it reads, as data @@ -253,7 +261,8 @@ def blockStep (p : Program) (c : Cert) (ok : Nat → List Word → List Ty → N | 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) + | .dup i => decide (1 ≤ k) && decide (i.val + 1 ≤ h) && + ok (h + 1) (dupKnown known i.val) (tyAt ty i.val :: ty) (k - 1) | .swap i => decide (1 ≤ k) && decide (i.val + 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 => diff --git a/SolidCore/Refinement/Solar/AssembleSim.lean b/SolidCore/Refinement/Solar/AssembleSim.lean index 7b466576..121b1d1b 100644 --- a/SolidCore/Refinement/Solar/AssembleSim.lean +++ b/SolidCore/Refinement/Solar/AssembleSim.lean @@ -205,6 +205,20 @@ theorem SR.dup {c : Cert} {ty : List Ty} {S T : List Word} (h : SR c ty S T) {i SR c (tyAt ty i :: ty) (S[i] :: S) (T[i] :: T) := SR.cons (h.2 i hi hi') h +/-- DUP of a word keeps the known constants a prefix of the stack. -/ +theorem dupKnown_prefix {known S : List Word} (hk : known <+: S) {i : Nat} (hi : i < S.length) : + dupKnown known i <+: S[i] :: S := by + unfold dupKnown + split + · rename_i v hv + have hS : S[i]? = some v := by + obtain ⟨t, rfl⟩ := hk + rw [List.getElem?_append_left (List.getElem?_eq_some_iff.1 hv).1, hv] + rw [List.getElem?_eq_getElem hi, Option.some.injEq] at hS + rw [hS] + exact (List.prefix_cons_inj v).2 ((List.take_prefix 1 known).trans hk) + · exact List.nil_prefix + theorem tyAt_tySwap (ty : List Ty) (i j : Nat) : tyAt (tySwap ty i) j = if j = 0 then tyAt ty (i + 1) else if j = i + 1 then tyAt ty 0 else tyAt ty j := by @@ -460,24 +474,26 @@ theorem stack_sim {p : Program} {c : Cert} {ok : Nat → List Word → List Ty {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) : + (hk : known <+: S) (hR : SR c ty S T) : 1 ≤ k ∧ ∃ byte, opByte op = some byte ∧ ∃ h' ty' S' T', SolarTV.EVM.step ctx op S = some S' ∧ SolarTV.EVM.step ctx op T = some T' ∧ - SR c ty' S' T' ∧ h' ≤ S'.length ∧ S'.length ≤ S.length + 1 ∧ ok h' [] ty' (k - 1) = true := by + SR c ty' S' T' ∧ h' ≤ S'.length ∧ S'.length ≤ S.length + 1 ∧ + ∃ known', known' <+: S' ∧ ok h' known' ty' (k - 1) = true := by have hL := hR.length by_cases hd : ∃ i, op = .dup i · obtain ⟨i, rfl⟩ := hd simp only [blockStep, Bool.and_eq_true, decide_eq_true_eq] at hok - obtain ⟨⟨hk, hi⟩, hok⟩ := hok + obtain ⟨⟨hk1, 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⟩ + refine ⟨hk1, _, rfl, h + 1, _, _, _, ?_, ?_, SR.dup hR hiS hiT, by simp; omega, by simp, _, + dupKnown_prefix hk hiS, hok⟩ · simp [SolarTV.EVM.step, List.getElem?_eq_getElem hiS] · simp [SolarTV.EVM.step, List.getElem?_eq_getElem hiT] by_cases hs : ∃ i, op = .swap i · obtain ⟨i, rfl⟩ := hs simp only [blockStep, Bool.and_eq_true, decide_eq_true_eq] at hok - obtain ⟨⟨hk, hi⟩, hok⟩ := hok + obtain ⟨⟨hk1, hi⟩, hok⟩ := hok rcases S with _ | ⟨a, S⟩ · simp at hh; omega rcases T with _ | ⟨b, T⟩ @@ -485,26 +501,27 @@ theorem stack_sim {p : Program} {c : Cert} {ok : Nat → List Word → List Ty 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⟩ + refine ⟨hk1, _, rfl, h, _, _, _, ?_, ?_, SR.swap hR hiS hiT, by simp; omega, by simp, [], + List.nil_prefix, hok⟩ · simp [SolarTV.EVM.step, List.getElem?_eq_getElem hiS] · simp [SolarTV.EVM.step, List.getElem?_eq_getElem hiT] by_cases hp : op = .pop · subst hp simp only [blockStep, Bool.and_eq_true, decide_eq_true_eq] at hok - obtain ⟨⟨hk, h1⟩, hok⟩ := hok + obtain ⟨⟨hk1, 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⟩ + refine ⟨hk1, _, rfl, h - 1, _, _, _, rfl, rfl, (SR.uncons.1 hR).2, by simp at hh; omega, + by simp only [List.length_cons]; omega, [], List.nil_prefix, hok⟩ have hd' : ∀ i, op ≠ .dup i := fun i e => hd ⟨i, e⟩ have hs' : ∀ i, op ≠ .swap i := fun i e => hs ⟨i, e⟩ rw [blockStep_stack hne hd' hs' hp] at hok split at hok · rename_i need d hn simp only [Bool.and_eq_true, decide_eq_true_eq] at hok - obtain ⟨⟨⟨hk, hneed⟩, hdata⟩, hok⟩ := hok + obtain ⟨⟨⟨hk1, hneed⟩, hdata⟩, hok⟩ := hok obtain ⟨byte, hbyte⟩ := opByte_of_stackNeed hn have hS' : ∃ S', SolarTV.EVM.step ctx op S = some S' := by cases op <;> simp only [stackNeed, reduceCtorEq, Option.some.injEq, Prod.mk.injEq] at hn @@ -519,8 +536,8 @@ theorem stack_sim {p : Program} {c : Cert} {ok : Nat → List Word → List Ty 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⟩ + refine ⟨hk1, byte, hbyte, (h + d).toNat, _, _, _, hstep, hstepT, + SR.cons (τ := some false) rfl (SR.drop need hR), ?_, ?_, [], List.nil_prefix, hok⟩ · simp only [List.length_cons, List.length_drop]; omega · simp only [List.length_cons, List.length_drop]; omega · cases hok @@ -895,8 +912,8 @@ theorem exec_sim {p : Program} {c : Cert} {code : ByteArray} (G : Glob p c code) ((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 + obtain ⟨hk1, byte, hbyte, h', ty', S', T', hstep, hstepT, hR', hh', hlen', known', hkn, + hok⟩ := stack_sim (ctx := context o call s) hne hok' hh hk hR rw [lowerInstr_stack hne, hbyte] at I' simp only [Option.getD_some, List.singleton_append] at I' obtain ⟨next, hd, hseg⟩ := I'.seg.head @@ -907,8 +924,8 @@ theorem exec_sim {p : Program} {c : Cert} {code : ByteArray} (G : Glob p c code) 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) + exact SimOut.pre hrule (IH h' known' ty' S' T' (k - 1) s (pc + 1) M g1 st ss hok (by omega) + hkn hR' (I'.next hk1 hseg (by omega) (by omega)) R) · simp [blockStep] at hok' · -- MSTORE. rcases known with _ | ⟨ow, known'⟩ diff --git a/SolidCore/Refinement/Solar/Token/Assembly.lean b/SolidCore/Refinement/Solar/Token/Assembly.lean new file mode 100644 index 00000000..390b02ac --- /dev/null +++ b/SolidCore/Refinement/Solar/Token/Assembly.lean @@ -0,0 +1,103 @@ +import SolidCore.Refinement.Solar.AssembleSim +import SolidCore.Refinement.Solar.AssembleFast +import token.gen.Token.Evm11 +import token.gen.Token.Bytecode +import token.Proofs.Stages + +/-! +# token: the final EVM IR to solar's bytecode + +solar-tv/milestone/token/token.sol (an ERC-20 token: balances, nested allowances and a frozen flag +in mappings, a total and an owner; balanceOf, allowance, getOwner, isFrozen, freeze, transfer, +approve and transferFrom, which emit the indexed Transfer and Approval events, revert with +"balance" and "allowance" and skip the allowance's update when it is unlimited) compiles with +solar 3ca8f483 (-Zcheck-analyses=false -Ogas --evm-version osaka) to the final EVM IR evm11 (after +late-word) and to 761 bytes of runtime bytecode (sha256 +b6f1c3ab69651bb080d1ac406be62499ca6ba82de76bb1d203a7619404b2c799), both exported by +-Zemit-lean-stages into solar's solar-tv/milestone/token and imported from there. Solar's +milestone proves the stages from the first lowered MIR to evm11 +(SolarTV.Milestone.Token.token_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, nested for the allowances, it reads CALLER, logs with LOG3, and its two +revert strings share one block that stores the string's offset with PUSH 32; DUP1, a constant the +check follows through the DUP (Assemble.dupKnown). Two jumps go back in the layout (to the shared +tail that logs Transfer, and to the shared revert block), so the certificate gives each block's +potential. + +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 bytecode. +-/ + +namespace SolidCore.Refinement.Solar.Token + +open SolarTV.Assembly SolarTV.Export.Token + +/-- The runtime bytecode solar exported. -/ +def code : ByteArray := ⟨(bytecode.map UInt8.ofNat).toArray⟩ + +/-- The certificate: each block's offset in the code (every block but the first is a jump +target), the stack height each block needs on entry (the dispatcher's selector for the second +half of the dispatch, the string's words for the shared revert block, the transfer's sender and +recipient for its shared tail), all of it data, the bound on memory (the reverts' 128 bytes), each +block's potential, and that the program reads the caller and hashes. -/ +def cert : Assemble.Cert := + { offsets := [0, 0x3d, 0x41, 0x53, 0x81, 0xa4, 0xdb, 0xeb, 0x114, 0x143, 0x19e, 0x1cc, 0x1da, + 0x1f1, 0x24e, 0x2aa, 0x2e5], + needs := [0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 2, 0, 2, 0, 0, 3, 0], top := 128, + costs := [155, 4, 10, 143, 27, 41, 12, 31, 34, 85, 11, 19, 14, 47, 132, 62, 21], + types := [[], [], [], [some false], [], [], [], [], [], [], [some false, some false], [], + [some false, some false], [], [], [some false, some false, 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 evm11 code cert = true := by + rw [Assemble.check_eq_checkFast] + decide +kernel + +/-- EVM IR to bytecode is a stage for token 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.Token.token_mir_to_evmir o call trivial) (stageOk o ho scope) + +/-- info: 'SolidCore.Refinement.Solar.Token.check_ok' depends on axioms: [propext, Quot.sound] -/ +#guard_msgs in +#print axioms check_ok + +/-- info: 'SolidCore.Refinement.Solar.Token.stageOk' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms stageOk + +/-- info: 'SolidCore.Refinement.Solar.Token.backend' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms backend + +end SolidCore.Refinement.Solar.Token + diff --git a/SolidCore/Refinement/Solar/Token/Lowering.lean b/SolidCore/Refinement/Solar/Token/Lowering.lean new file mode 100644 index 00000000..3c48be63 --- /dev/null +++ b/SolidCore/Refinement/Solar/Token/Lowering.lean @@ -0,0 +1,1143 @@ +import SolidCore.Refinement.Generic.Value +import SolidCore.Refinement.KernelCopies +import SolidCore.Refinement.KernelRfl +import SolidCore.Refinement.Source.Token +import token.gen.Token.Stage0 + +/-! +# token: the generic source stage on an ERC-20-like token + +scripts/refinement/token/token.sol, + + contract Token { + mapping(address => uint256) balances; + mapping(address => mapping(address => uint256)) allowances; + mapping(address => bool) frozen; + uint256 totalSupply; address owner; + event Transfer(address indexed from, address indexed to, uint256 value); + event Approval(address indexed owner, address indexed spender, uint256 value); + function balanceOf(address who) external view returns (uint256); + function allowance(address holder, address spender) external view returns (uint256); + function getOwner() external view returns (address); + function isFrozen(address who) external view returns (bool); + function freeze(address who) external; // require(msg.sender == owner) + function transfer(address to, uint256 value) external returns (bool); + function approve(address spender, uint256 value) external returns (bool); + function transferFrom(address from, address to, uint256 value) external returns (bool); } + +has a nested mapping (an allowance at `keccak256(spender, keccak256(holder, 1))`), a mapping to +`bool` (read as the low byte of its word not zero), an `address` field (`owner`, slot 4), view +functions returning a `uint256`, an `address` and a `bool`, `require(c)` (empty revert data), +`require(c, "balance")` and `revert("allowance")` (`Error(string)` revert data), an +`if`/`else if` on a `uint256` local against `type(uint256).max`, and logs with two indexed +address topics taken from `msg.sender` and from parameters. + +`SolarTV.Export.Token.stage0` is solar's first lowered MIR module for it after +`lower-evm-shaped`: solar's own `-Zemit-lean-stages` export (solar 0.8.38+commit.3ca8f483, +-Zcheck-analyses=false -Ogas, osaka; sha256 ee5ac4da…3dae) in solar's solar-tv/milestone/token, +imported from there: the one definition both this source stage and solar-tv's backend stages +(`SolarTV.Milestone.Token.token_mir_to_evmir`) are about, so the stages compose. + +SolidCore's core (`coreLit`, solc 0.8.35's AST through scripts/solc_ast_to_lean_source.py into +Source/Token.lean and `TypeCheck.CheckedInput.contract`, printed and copied) is erased by +`Generic.eraseFn`; the module is run symbolically with the environment flag +(`Generic.symTree … .all`): the caller is `callerWord`, a mapping slot the word +`hash key slot`. Both trees agree in canonical form for every function. + +* `shape_eq`: `Token` type checks, its core is `coreLit`, its constructor leaves no storage; +* `check_stage0`, `checkValue_stage0`: the generic check accepts stage0 for the eight + external functions, at no value and at any value (`decide +kernel`); +* `check_rejects_map2`, `check_rejects_frozen`, `check_rejects_approval`: it rejects stage0 + with `allowance`'s two keys hashed in the other order, with `transfer`'s `frozen` check + dropped, and with `approve`'s `Approval` topic changed; +* `lowering`, `loweringValue`: the stage from SolidCore to stage0 on every call of the eight + 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.Token + +open SolidCore.Refinement SolidCore.Refinement.Abi SolidCore.Solidity SolidCore.Solidity.Source +open SolarTV.Export.Token (stage0) + +/-- 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 `Token`. -/ +def contract? : Except TypeCheck.TypeError TypeCheck.CheckedContract := + TypeCheck.CheckedInput.contract Source.Token.importedSourceUnit "Token" + +/-- The selector of `balanceOf(address)`. -/ +abbrev balanceOfSel : Nat := 0x70a08231 + +/-- The selector of `allowance(address,address)`. -/ +abbrev allowanceSel : Nat := 0xdd62ed3e + +/-- The selector of `getOwner()`. -/ +abbrev getOwnerSel : Nat := 0x893d20e8 + +/-- The selector of `isFrozen(address)`. -/ +abbrev isFrozenSel : Nat := 0xe5839836 + +/-- The selector of `freeze(address)`. -/ +abbrev freezeSel : Nat := 0x8d1fdf2f + +/-- The selector of `transfer(address,uint256)`. -/ +abbrev transferSel : Nat := 0xa9059cbb + +/-- The selector of `approve(address,uint256)`. -/ +abbrev approveSel : Nat := 0x095ea7b3 + +/-- The selector of `transferFrom(address,address,uint256)`. -/ +abbrev transferFromSel : Nat := 0x23b872dd + +/-- `balanceOf` and its parameters (an address is a word of 160 bits). -/ +def fnBalanceOf : Fn := ⟨balanceOfSel, [.uint 160]⟩ + +/-- `allowance` and its parameters (an address is a word of 160 bits). -/ +def fnAllowance : Fn := ⟨allowanceSel, [.uint 160, .uint 160]⟩ + +/-- `getOwner` and its parameters (an address is a word of 160 bits). -/ +def fnGetOwner : Fn := ⟨getOwnerSel, []⟩ + +/-- `isFrozen` and its parameters (an address is a word of 160 bits). -/ +def fnIsFrozen : Fn := ⟨isFrozenSel, [.uint 160]⟩ + +/-- `freeze` and its parameters (an address is a word of 160 bits). -/ +def fnFreeze : Fn := ⟨freezeSel, [.uint 160]⟩ + +/-- `transfer` and its parameters (an address is a word of 160 bits). -/ +def fnTransfer : Fn := ⟨transferSel, [.uint 160, .uint 256]⟩ + +/-- `approve` and its parameters (an address is a word of 160 bits). -/ +def fnApprove : Fn := ⟨approveSel, [.uint 160, .uint 256]⟩ + +/-- `transferFrom` and its parameters (an address is a word of 160 bits). -/ +def fnTransferFrom : Fn := ⟨transferFromSel, [.uint 160, .uint 160, .uint 256]⟩ + +/-- The external functions of `Token`. -/ +def fns : List Fn := + [fnBalanceOf, fnAllowance, fnGetOwner, fnIsFrozen, fnFreeze, fnTransfer, fnApprove, fnTransferFrom] + +/-- SolidCore's core contract of `Token`, 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 := "allowances", + slot := 1, + ty? := none, + layout? := some (SolidCore.Solidity.Source.StorageLayout.mapping + (SolidCore.Solidity.Source.Ty.address) + (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 := "frozen", + slot := 2, + ty? := none, + layout? := some (SolidCore.Solidity.Source.StorageLayout.mapping + (SolidCore.Solidity.Source.Ty.address) + (SolidCore.Solidity.Source.StorageLayout.scalar + (SolidCore.Solidity.Source.Ty.bool))), + transient := false, + packedOffset := 0, + packedBytes := 32, + packedSigned := false }, + { name := "totalSupply", + slot := 3, + 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 }, + { name := "owner", + slot := 4, + ty? := some (SolidCore.Solidity.Source.Ty.address), + layout? := some (SolidCore.Solidity.Source.StorageLayout.scalar + (SolidCore.Solidity.Source.Ty.address)), + transient := false, + packedOffset := 0, + packedBytes := 20, + packedSigned := false }], + immutableFields := [], + eventDecls := [{ name := "Transfer", + indexedCount := 2, + topic? := some 100389287136786176327247604509743168900146139575972864366142685224231313322991, + fields := [{ ty := SolidCore.Solidity.Source.Ty.address, indexed := true }, + { ty := SolidCore.Solidity.Source.Ty.address, indexed := true }, + { ty := SolidCore.Solidity.Source.Ty.uint256, indexed := false }] }, + { name := "Approval", + indexedCount := 2, + topic? := some 63486140976153616755203102783360879283472101686154884697241723088393386309925, + fields := [{ ty := SolidCore.Solidity.Source.Ty.address, indexed := true }, + { ty := SolidCore.Solidity.Source.Ty.address, indexed := true }, + { ty := SolidCore.Solidity.Source.Ty.uint256, indexed := false }] }, + { name := "Token.Transfer", + indexedCount := 2, + topic? := some 100389287136786176327247604509743168900146139575972864366142685224231313322991, + fields := [{ ty := SolidCore.Solidity.Source.Ty.address, indexed := true }, + { ty := SolidCore.Solidity.Source.Ty.address, indexed := true }, + { ty := SolidCore.Solidity.Source.Ty.uint256, indexed := false }] }, + { name := "Token.Approval", + indexedCount := 2, + topic? := some 63486140976153616755203102783360879283472101686154884697241723088393386309925, + fields := [{ ty := SolidCore.Solidity.Source.Ty.address, indexed := true }, + { ty := SolidCore.Solidity.Source.Ty.address, indexed := true }, + { ty := SolidCore.Solidity.Source.Ty.uint256, indexed := false }] }], + errorDecls := [], + functions := [{ 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 := "allowance", + selector? := some 3714247998, + payable := false, + params := [{ name := "holder", ty := SolidCore.Solidity.Source.Ty.address, isStorageRef := false }, + { name := "spender", ty := SolidCore.Solidity.Source.Ty.address, isStorageRef := false }], + paramAbiCleanups := [SolidCore.Solidity.Source.AbiCleanup.none, + 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.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.index + (SolidCore.Solidity.Source.Expr.storageRead + (SolidCore.Solidity.Source.StorageReadMode.element) + "allowances" + [SolidCore.Solidity.Source.Expr.var "holder"]) + (SolidCore.Solidity.Source.Expr.var "spender"))]]], + dispatchId? := none }, + { name := "getOwner", + selector? := some 2302484712, + payable := false, + params := [], + paramAbiCleanups := [], + returns := [{ name := "_ret0", ty := SolidCore.Solidity.Source.Ty.address, 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.storageRead + (SolidCore.Solidity.Source.StorageReadMode.ref) + "owner" + []]]], + dispatchId? := none }, + { name := "isFrozen", + selector? := some 3850606646, + 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.bool, 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.storageRead + (SolidCore.Solidity.Source.StorageReadMode.element) + "frozen" + [SolidCore.Solidity.Source.Expr.var "who"]]]], + dispatchId? := none }, + { name := "freeze", + selector? := some 2367676207, + payable := false, + params := [{ name := "who", ty := SolidCore.Solidity.Source.Ty.address, isStorageRef := false }], + paramAbiCleanups := [SolidCore.Solidity.Source.AbiCleanup.none], + returns := [], + body := SolidCore.Solidity.Source.Stmt.block + [SolidCore.Solidity.Source.Stmt.skip, + SolidCore.Solidity.Source.Stmt.block + [SolidCore.Solidity.Source.Stmt.requireStmt + (SolidCore.Solidity.Source.Expr.binary + (SolidCore.Solidity.Source.BinaryOp.eq) + (SolidCore.Solidity.Source.Expr.caller) + (SolidCore.Solidity.Source.Expr.storageRead + (SolidCore.Solidity.Source.StorageReadMode.ref) + "owner" + [])) + none, + SolidCore.Solidity.Source.Stmt.assign + (SolidCore.Solidity.Source.LValue.storageIndex + "frozen" + (SolidCore.Solidity.Source.Expr.var "who")) + (SolidCore.Solidity.Source.Expr.word 1)]], + dispatchId? := none }, + { name := "transfer", + selector? := some 2835717307, + payable := false, + params := [{ name := "to", ty := SolidCore.Solidity.Source.Ty.address, isStorageRef := false }, + { name := "value", 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.bool, isStorageRef := false }], + body := SolidCore.Solidity.Source.Stmt.block + [SolidCore.Solidity.Source.Stmt.skip, + 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.skip, + SolidCore.Solidity.Source.Stmt.block + [SolidCore.Solidity.Source.Stmt.requireStmt + (SolidCore.Solidity.Source.Expr.unary + (SolidCore.Solidity.Source.UnaryOp.logicalNot) + (SolidCore.Solidity.Source.Expr.storageRead + (SolidCore.Solidity.Source.StorageReadMode.element) + "frozen" + [SolidCore.Solidity.Source.Expr.caller])) + none, + SolidCore.Solidity.Source.Stmt.requireStmt + (SolidCore.Solidity.Source.Expr.binary + (SolidCore.Solidity.Source.BinaryOp.ge) + (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.caller])) + (SolidCore.Solidity.Source.Expr.castOp + (SolidCore.Solidity.Source.CastKind.uintCleanup) + 256 + (SolidCore.Solidity.Source.Expr.var "value"))) + (some "balance"), + SolidCore.Solidity.Source.Stmt.exprStmt + (SolidCore.Solidity.Source.Expr.assignment + (some (SolidCore.Solidity.Source.BinaryOp.sub)) + (some (SolidCore.Solidity.Source.ValueCleanup.uint 256)) + (SolidCore.Solidity.Source.Expr.storageRead + (SolidCore.Solidity.Source.StorageReadMode.element) + "balances" + [SolidCore.Solidity.Source.Expr.caller]) + (SolidCore.Solidity.Source.Expr.var "value")), + 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 "to"]) + (SolidCore.Solidity.Source.Expr.var "value")), + SolidCore.Solidity.Source.Stmt.emitEvent + "Transfer" + [SolidCore.Solidity.Source.Expr.caller, + SolidCore.Solidity.Source.Expr.var "to", + SolidCore.Solidity.Source.Expr.var "value"], + SolidCore.Solidity.Source.Stmt.returnValues [SolidCore.Solidity.Source.Expr.word 1]]], + dispatchId? := none }, + { name := "approve", + selector? := some 157198259, + payable := false, + params := [{ name := "spender", ty := SolidCore.Solidity.Source.Ty.address, isStorageRef := false }, + { name := "value", 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.bool, isStorageRef := false }], + body := SolidCore.Solidity.Source.Stmt.block + [SolidCore.Solidity.Source.Stmt.skip, + 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.skip, + SolidCore.Solidity.Source.Stmt.block + [SolidCore.Solidity.Source.Stmt.assign + (SolidCore.Solidity.Source.LValue.index + (SolidCore.Solidity.Source.LValue.storageIndex + "allowances" + (SolidCore.Solidity.Source.Expr.caller)) + (SolidCore.Solidity.Source.Expr.var "spender")) + (SolidCore.Solidity.Source.Expr.castOp + (SolidCore.Solidity.Source.CastKind.uintCleanup) + 256 + (SolidCore.Solidity.Source.Expr.var "value")), + SolidCore.Solidity.Source.Stmt.emitEvent + "Approval" + [SolidCore.Solidity.Source.Expr.caller, + SolidCore.Solidity.Source.Expr.var "spender", + SolidCore.Solidity.Source.Expr.var "value"], + SolidCore.Solidity.Source.Stmt.returnValues [SolidCore.Solidity.Source.Expr.word 1]]], + dispatchId? := none }, + { name := "transferFrom", + selector? := some 599290589, + payable := false, + params := [{ name := "from", ty := SolidCore.Solidity.Source.Ty.address, isStorageRef := false }, + { name := "to", ty := SolidCore.Solidity.Source.Ty.address, isStorageRef := false }, + { name := "value", ty := SolidCore.Solidity.Source.Ty.uint256, isStorageRef := false }], + paramAbiCleanups := [SolidCore.Solidity.Source.AbiCleanup.none, + SolidCore.Solidity.Source.AbiCleanup.none, + SolidCore.Solidity.Source.AbiCleanup.uint 256], + returns := [{ name := "_ret0", ty := SolidCore.Solidity.Source.Ty.bool, isStorageRef := false }], + body := SolidCore.Solidity.Source.Stmt.block + [SolidCore.Solidity.Source.Stmt.skip, + SolidCore.Solidity.Source.Stmt.skip, + 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.skip, + SolidCore.Solidity.Source.Stmt.block + [SolidCore.Solidity.Source.Stmt.varDecl + (SolidCore.Solidity.Source.Ty.uint256) + "a" + (some (SolidCore.Solidity.Source.Expr.castOp + (SolidCore.Solidity.Source.CastKind.uintCleanup) + 256 + (SolidCore.Solidity.Source.Expr.index + (SolidCore.Solidity.Source.Expr.storageRead + (SolidCore.Solidity.Source.StorageReadMode.element) + "allowances" + [SolidCore.Solidity.Source.Expr.var "from"]) + (SolidCore.Solidity.Source.Expr.caller)))), + SolidCore.Solidity.Source.Stmt.ifElse + (SolidCore.Solidity.Source.Expr.binary + (SolidCore.Solidity.Source.BinaryOp.lt) + (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 "value"))) + (SolidCore.Solidity.Source.Stmt.block + [SolidCore.Solidity.Source.Stmt.revertError (some "allowance")]) + (SolidCore.Solidity.Source.Stmt.ifElse + (SolidCore.Solidity.Source.Expr.binary + (SolidCore.Solidity.Source.BinaryOp.ne) + (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.word + 115792089237316195423570985008687907853269984665640564039457584007913129639935))) + (SolidCore.Solidity.Source.Stmt.block + [SolidCore.Solidity.Source.Stmt.assign + (SolidCore.Solidity.Source.LValue.index + (SolidCore.Solidity.Source.LValue.storageIndex + "allowances" + (SolidCore.Solidity.Source.Expr.var "from")) + (SolidCore.Solidity.Source.Expr.caller)) + (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 "value")))))]) + (SolidCore.Solidity.Source.Stmt.skip)), + SolidCore.Solidity.Source.Stmt.requireStmt + (SolidCore.Solidity.Source.Expr.binary + (SolidCore.Solidity.Source.BinaryOp.ge) + (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 "from"])) + (SolidCore.Solidity.Source.Expr.castOp + (SolidCore.Solidity.Source.CastKind.uintCleanup) + 256 + (SolidCore.Solidity.Source.Expr.var "value"))) + none, + SolidCore.Solidity.Source.Stmt.exprStmt + (SolidCore.Solidity.Source.Expr.assignment + (some (SolidCore.Solidity.Source.BinaryOp.sub)) + (some (SolidCore.Solidity.Source.ValueCleanup.uint 256)) + (SolidCore.Solidity.Source.Expr.storageRead + (SolidCore.Solidity.Source.StorageReadMode.element) + "balances" + [SolidCore.Solidity.Source.Expr.var "from"]) + (SolidCore.Solidity.Source.Expr.var "value")), + 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 "to"]) + (SolidCore.Solidity.Source.Expr.var "value")), + SolidCore.Solidity.Source.Stmt.emitEvent + "Transfer" + [SolidCore.Solidity.Source.Expr.var "from", + SolidCore.Solidity.Source.Expr.var "to", + SolidCore.Solidity.Source.Expr.var "value"], + SolidCore.Solidity.Source.Stmt.returnValues [SolidCore.Solidity.Source.Expr.word 1]]], + 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 }, + { name := "__internal_allowance(address,address)#[SolidCore.Solidity.Ty.address false, SolidCore.Solidity.Ty.address false]", + selector? := none, + payable := false, + params := [{ name := "holder", ty := SolidCore.Solidity.Source.Ty.address, isStorageRef := false }, + { name := "spender", ty := SolidCore.Solidity.Source.Ty.address, isStorageRef := false }], + paramAbiCleanups := [SolidCore.Solidity.Source.AbiCleanup.none, + 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.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.index + (SolidCore.Solidity.Source.Expr.storageRead + (SolidCore.Solidity.Source.StorageReadMode.element) + "allowances" + [SolidCore.Solidity.Source.Expr.var "holder"]) + (SolidCore.Solidity.Source.Expr.var "spender"))]]], + dispatchId? := none }, + { name := "__internal_getOwner()#[]", + selector? := none, + payable := false, + params := [], + paramAbiCleanups := [], + returns := [{ name := "_ret0", ty := SolidCore.Solidity.Source.Ty.address, 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.storageRead + (SolidCore.Solidity.Source.StorageReadMode.ref) + "owner" + []]]], + dispatchId? := none }, + { name := "__internal_isFrozen(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.bool, 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.storageRead + (SolidCore.Solidity.Source.StorageReadMode.element) + "frozen" + [SolidCore.Solidity.Source.Expr.var "who"]]]], + dispatchId? := none }, + { name := "__internal_freeze(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 := [], + body := SolidCore.Solidity.Source.Stmt.block + [SolidCore.Solidity.Source.Stmt.skip, + SolidCore.Solidity.Source.Stmt.block + [SolidCore.Solidity.Source.Stmt.requireStmt + (SolidCore.Solidity.Source.Expr.binary + (SolidCore.Solidity.Source.BinaryOp.eq) + (SolidCore.Solidity.Source.Expr.caller) + (SolidCore.Solidity.Source.Expr.storageRead + (SolidCore.Solidity.Source.StorageReadMode.ref) + "owner" + [])) + none, + SolidCore.Solidity.Source.Stmt.assign + (SolidCore.Solidity.Source.LValue.storageIndex + "frozen" + (SolidCore.Solidity.Source.Expr.var "who")) + (SolidCore.Solidity.Source.Expr.word 1)]], + dispatchId? := none }, + { name := "__internal_transfer(address,uint256)#[SolidCore.Solidity.Ty.address false, SolidCore.Solidity.Ty.uint 256]", + selector? := none, + payable := false, + params := [{ name := "to", ty := SolidCore.Solidity.Source.Ty.address, isStorageRef := false }, + { name := "value", 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.bool, isStorageRef := false }], + body := SolidCore.Solidity.Source.Stmt.block + [SolidCore.Solidity.Source.Stmt.skip, + 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.skip, + SolidCore.Solidity.Source.Stmt.block + [SolidCore.Solidity.Source.Stmt.requireStmt + (SolidCore.Solidity.Source.Expr.unary + (SolidCore.Solidity.Source.UnaryOp.logicalNot) + (SolidCore.Solidity.Source.Expr.storageRead + (SolidCore.Solidity.Source.StorageReadMode.element) + "frozen" + [SolidCore.Solidity.Source.Expr.caller])) + none, + SolidCore.Solidity.Source.Stmt.requireStmt + (SolidCore.Solidity.Source.Expr.binary + (SolidCore.Solidity.Source.BinaryOp.ge) + (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.caller])) + (SolidCore.Solidity.Source.Expr.castOp + (SolidCore.Solidity.Source.CastKind.uintCleanup) + 256 + (SolidCore.Solidity.Source.Expr.var "value"))) + (some "balance"), + SolidCore.Solidity.Source.Stmt.exprStmt + (SolidCore.Solidity.Source.Expr.assignment + (some (SolidCore.Solidity.Source.BinaryOp.sub)) + (some (SolidCore.Solidity.Source.ValueCleanup.uint 256)) + (SolidCore.Solidity.Source.Expr.storageRead + (SolidCore.Solidity.Source.StorageReadMode.element) + "balances" + [SolidCore.Solidity.Source.Expr.caller]) + (SolidCore.Solidity.Source.Expr.var "value")), + 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 "to"]) + (SolidCore.Solidity.Source.Expr.var "value")), + SolidCore.Solidity.Source.Stmt.emitEvent + "Transfer" + [SolidCore.Solidity.Source.Expr.caller, + SolidCore.Solidity.Source.Expr.var "to", + SolidCore.Solidity.Source.Expr.var "value"], + SolidCore.Solidity.Source.Stmt.returnValues [SolidCore.Solidity.Source.Expr.word 1]]], + dispatchId? := none }, + { name := "__internal_approve(address,uint256)#[SolidCore.Solidity.Ty.address false, SolidCore.Solidity.Ty.uint 256]", + selector? := none, + payable := false, + params := [{ name := "spender", ty := SolidCore.Solidity.Source.Ty.address, isStorageRef := false }, + { name := "value", 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.bool, isStorageRef := false }], + body := SolidCore.Solidity.Source.Stmt.block + [SolidCore.Solidity.Source.Stmt.skip, + 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.skip, + SolidCore.Solidity.Source.Stmt.block + [SolidCore.Solidity.Source.Stmt.assign + (SolidCore.Solidity.Source.LValue.index + (SolidCore.Solidity.Source.LValue.storageIndex + "allowances" + (SolidCore.Solidity.Source.Expr.caller)) + (SolidCore.Solidity.Source.Expr.var "spender")) + (SolidCore.Solidity.Source.Expr.castOp + (SolidCore.Solidity.Source.CastKind.uintCleanup) + 256 + (SolidCore.Solidity.Source.Expr.var "value")), + SolidCore.Solidity.Source.Stmt.emitEvent + "Approval" + [SolidCore.Solidity.Source.Expr.caller, + SolidCore.Solidity.Source.Expr.var "spender", + SolidCore.Solidity.Source.Expr.var "value"], + SolidCore.Solidity.Source.Stmt.returnValues [SolidCore.Solidity.Source.Expr.word 1]]], + dispatchId? := none }, + { name := "__internal_transferFrom(address,address,uint256)#[SolidCore.Solidity.Ty.address false, SolidCore.Solidity.Ty.address false, SolidCore.Solidity.Ty.uint 256]", + selector? := none, + payable := false, + params := [{ name := "from", ty := SolidCore.Solidity.Source.Ty.address, isStorageRef := false }, + { name := "to", ty := SolidCore.Solidity.Source.Ty.address, isStorageRef := false }, + { name := "value", ty := SolidCore.Solidity.Source.Ty.uint256, isStorageRef := false }], + paramAbiCleanups := [SolidCore.Solidity.Source.AbiCleanup.none, + SolidCore.Solidity.Source.AbiCleanup.none, + SolidCore.Solidity.Source.AbiCleanup.uint 256], + returns := [{ name := "_ret0", ty := SolidCore.Solidity.Source.Ty.bool, isStorageRef := false }], + body := SolidCore.Solidity.Source.Stmt.block + [SolidCore.Solidity.Source.Stmt.skip, + SolidCore.Solidity.Source.Stmt.skip, + 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.skip, + SolidCore.Solidity.Source.Stmt.block + [SolidCore.Solidity.Source.Stmt.varDecl + (SolidCore.Solidity.Source.Ty.uint256) + "a" + (some (SolidCore.Solidity.Source.Expr.castOp + (SolidCore.Solidity.Source.CastKind.uintCleanup) + 256 + (SolidCore.Solidity.Source.Expr.index + (SolidCore.Solidity.Source.Expr.storageRead + (SolidCore.Solidity.Source.StorageReadMode.element) + "allowances" + [SolidCore.Solidity.Source.Expr.var "from"]) + (SolidCore.Solidity.Source.Expr.caller)))), + SolidCore.Solidity.Source.Stmt.ifElse + (SolidCore.Solidity.Source.Expr.binary + (SolidCore.Solidity.Source.BinaryOp.lt) + (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 "value"))) + (SolidCore.Solidity.Source.Stmt.block + [SolidCore.Solidity.Source.Stmt.revertError (some "allowance")]) + (SolidCore.Solidity.Source.Stmt.ifElse + (SolidCore.Solidity.Source.Expr.binary + (SolidCore.Solidity.Source.BinaryOp.ne) + (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.word + 115792089237316195423570985008687907853269984665640564039457584007913129639935))) + (SolidCore.Solidity.Source.Stmt.block + [SolidCore.Solidity.Source.Stmt.assign + (SolidCore.Solidity.Source.LValue.index + (SolidCore.Solidity.Source.LValue.storageIndex + "allowances" + (SolidCore.Solidity.Source.Expr.var "from")) + (SolidCore.Solidity.Source.Expr.caller)) + (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 "value")))))]) + (SolidCore.Solidity.Source.Stmt.skip)), + SolidCore.Solidity.Source.Stmt.requireStmt + (SolidCore.Solidity.Source.Expr.binary + (SolidCore.Solidity.Source.BinaryOp.ge) + (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 "from"])) + (SolidCore.Solidity.Source.Expr.castOp + (SolidCore.Solidity.Source.CastKind.uintCleanup) + 256 + (SolidCore.Solidity.Source.Expr.var "value"))) + none, + SolidCore.Solidity.Source.Stmt.exprStmt + (SolidCore.Solidity.Source.Expr.assignment + (some (SolidCore.Solidity.Source.BinaryOp.sub)) + (some (SolidCore.Solidity.Source.ValueCleanup.uint 256)) + (SolidCore.Solidity.Source.Expr.storageRead + (SolidCore.Solidity.Source.StorageReadMode.element) + "balances" + [SolidCore.Solidity.Source.Expr.var "from"]) + (SolidCore.Solidity.Source.Expr.var "value")), + 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 "to"]) + (SolidCore.Solidity.Source.Expr.var "value")), + SolidCore.Solidity.Source.Stmt.emitEvent + "Transfer" + [SolidCore.Solidity.Source.Expr.var "from", + SolidCore.Solidity.Source.Expr.var "to", + SolidCore.Solidity.Source.Expr.var "value"], + SolidCore.Solidity.Source.Stmt.returnValues [SolidCore.Solidity.Source.Expr.word 1]]], + dispatchId? := none }] } + +/-! ## The selectors and the events' signature topics + +The type checker computes each external function's selector and each 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 `balanceOf(address)`, by Keccak-256 of its signature. -/ +def selBalanceOf : SolidCore.Solidity.Shared.Word := + SolidCore.Solidity.Source.ABI.selectorFromSignature "balanceOf(address)" + +kernel_rfl selBalanceOf_eq selBalanceOf balanceOfSel + +/-- The selector of `allowance(address,address)`, by Keccak-256 of its signature. -/ +def selAllowance : SolidCore.Solidity.Shared.Word := + SolidCore.Solidity.Source.ABI.selectorFromSignature "allowance(address,address)" + +kernel_rfl selAllowance_eq selAllowance allowanceSel + +/-- The selector of `getOwner()`, by Keccak-256 of its signature. -/ +def selGetOwner : SolidCore.Solidity.Shared.Word := + SolidCore.Solidity.Source.ABI.selectorFromSignature "getOwner()" + +kernel_rfl selGetOwner_eq selGetOwner getOwnerSel + +/-- The selector of `isFrozen(address)`, by Keccak-256 of its signature. -/ +def selIsFrozen : SolidCore.Solidity.Shared.Word := + SolidCore.Solidity.Source.ABI.selectorFromSignature "isFrozen(address)" + +kernel_rfl selIsFrozen_eq selIsFrozen isFrozenSel + +/-- The selector of `freeze(address)`, by Keccak-256 of its signature. -/ +def selFreeze : SolidCore.Solidity.Shared.Word := + SolidCore.Solidity.Source.ABI.selectorFromSignature "freeze(address)" + +kernel_rfl selFreeze_eq selFreeze freezeSel + +/-- The selector of `transfer(address,uint256)`, by Keccak-256 of its signature. -/ +def selTransfer : SolidCore.Solidity.Shared.Word := + SolidCore.Solidity.Source.ABI.selectorFromSignature "transfer(address,uint256)" + +kernel_rfl selTransfer_eq selTransfer transferSel + +/-- The selector of `approve(address,uint256)`, by Keccak-256 of its signature. -/ +def selApprove : SolidCore.Solidity.Shared.Word := + SolidCore.Solidity.Source.ABI.selectorFromSignature "approve(address,uint256)" + +kernel_rfl selApprove_eq selApprove approveSel + +/-- The selector of `transferFrom(address,address,uint256)`, by Keccak-256 of its signature. -/ +def selTransferFrom : SolidCore.Solidity.Shared.Word := + SolidCore.Solidity.Source.ABI.selectorFromSignature "transferFrom(address,address,uint256)" + +kernel_rfl selTransferFrom_eq selTransferFrom transferFromSel + +/-- The topic of `Transfer(address,address,uint256)`, by Keccak-256 of its signature. -/ +def topicTransfer : Nat := SolidCore.Solidity.Source.Keccak.digestWord "Transfer(address,address,uint256)" + +kernel_rfl topicTransfer_eq topicTransfer 0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef + +/-- The topic of `Approval(address,address,uint256)`, by Keccak-256 of its signature. -/ +def topicApproval : Nat := SolidCore.Solidity.Source.Keccak.digestWord "Approval(address,address,uint256)" + +kernel_rfl topicApproval_eq topicApproval 0x8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925 + +/-- `ABI.selectorFromSignature`, with `Token`'s signatures by table. -/ +def selectorTable (s : String) : SolidCore.Solidity.Shared.Word := + if s = "balanceOf(address)" then balanceOfSel + else if s = "allowance(address,address)" then allowanceSel + else if s = "getOwner()" then getOwnerSel + else if s = "isFrozen(address)" then isFrozenSel + else if s = "freeze(address)" then freezeSel + else if s = "transfer(address,uint256)" then transferSel + else if s = "approve(address,uint256)" then approveSel + else if s = "transferFrom(address,address,uint256)" then transferFromSel + 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 selBalanceOf_eq + · split + · next h => subst h; exact selAllowance_eq + · split + · next h => subst h; exact selGetOwner_eq + · split + · next h => subst h; exact selIsFrozen_eq + · split + · next h => subst h; exact selFreeze_eq + · split + · next h => subst h; exact selTransfer_eq + · split + · next h => subst h; exact selApprove_eq + · split + · next h => subst h; exact selTransferFrom_eq + · rfl + +/-- `Keccak.digestWord`, with the events' signatures by table. -/ +def digestTable (s : String) : Nat := + if s = "Transfer(address,address,uint256)" then 0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef + else if s = "Approval(address,address,uint256)" then 0x8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925 + 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 topicTransfer_eq + · split + · next h => subst h; exact topicApproval_eq + · rfl + +/-- SolidCore's checked core of `Token`, and whether its constructor leaves no storage and no +logs, when `Token` 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)`: `Token` 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 topics 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 `balanceOf`. -/ +theorem check_balanceOf : + Generic.check fuel mirFuel coreLit stage0 [fnBalanceOf] .all = true := by + decide +kernel + +set_option maxRecDepth 100000 in +/-- The kernel's evaluation: the generic check accepts stage0 for `allowance`. -/ +theorem check_allowance : + Generic.check fuel mirFuel coreLit stage0 [fnAllowance] .all = true := by + decide +kernel + +set_option maxRecDepth 100000 in +/-- The kernel's evaluation: the generic check accepts stage0 for `getOwner`. -/ +theorem check_getOwner : + Generic.check fuel mirFuel coreLit stage0 [fnGetOwner] .all = true := by + decide +kernel + +set_option maxRecDepth 100000 in +/-- The kernel's evaluation: the generic check accepts stage0 for `isFrozen`. -/ +theorem check_isFrozen : + Generic.check fuel mirFuel coreLit stage0 [fnIsFrozen] .all = true := by + decide +kernel + +set_option maxRecDepth 100000 in +/-- The kernel's evaluation: the generic check accepts stage0 for `freeze`. -/ +theorem check_freeze : + Generic.check fuel mirFuel coreLit stage0 [fnFreeze] .all = true := by + decide +kernel + +set_option maxRecDepth 100000 in +/-- The kernel's evaluation: the generic check accepts stage0 for `transfer`. -/ +theorem check_transfer : + Generic.check fuel mirFuel coreLit stage0 [fnTransfer] .all = true := by + decide +kernel + +set_option maxRecDepth 100000 in +/-- The kernel's evaluation: the generic check accepts stage0 for `approve`. -/ +theorem check_approve : + Generic.check fuel mirFuel coreLit stage0 [fnApprove] .all = true := by + decide +kernel + +set_option maxRecDepth 100000 in +/-- The kernel's evaluation: the generic check accepts stage0 for `transferFrom`. -/ +theorem check_transferFrom : + Generic.check fuel mirFuel coreLit stage0 [fnTransferFrom] .all = true := by + decide +kernel + +/-- The generic check accepts stage0 for every external function. -/ +theorem check_stage0 : + Generic.check fuel mirFuel coreLit stage0 fns .all = true := by + have h0 := check_balanceOf + have h1 := check_allowance + have h2 := check_getOwner + have h3 := check_isFrozen + have h4 := check_freeze + have h5 := check_transfer + have h6 := check_approve + have h7 := check_transferFrom + simp only [Generic.check, List.all_cons, List.all_nil, Bool.and_true] at h0 h1 h2 h3 h4 h5 h6 h7 + simp only [Generic.check, fns, List.all_cons, List.all_nil, Bool.and_true, h0, h1, h2, h3, h4, h5, h6, h7] + +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 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 := + { stage0 with + functions := stage0.functions.mapIdx fun j fn => + if j = i then { fn with blocks := fn.blocks.map fun b => { b with insts := b.insts.map f } } + else fn } + +/-- `allowance` hashing its two keys in the other order: the entry at +`keccak256(holder, keccak256(spender, 1))`, not `keccak256(spender, keccak256(holder, 1))`. -/ +def swapKeys : SolarTV.MIR.Lowered.Inst → SolarTV.MIR.Lowered.Inst + | .effect none .mstore [.const 0, .value 14] => .effect none .mstore [.const 0, .value 18] + | .effect none .mstore [.const 0, .value 18] => .effect none .mstore [.const 0, .value 14] + | i => i + +/-- `transfer` without its `require(!frozen[msg.sender])`: the frozen flag read as zero. -/ +def noFrozen : SolarTV.MIR.Lowered.Inst → SolarTV.MIR.Lowered.Inst + | .ne d (.value 90) b => .ne d (.const 0) b + | i => i + +/-- `approve`'s log with another first topic. -/ +def wrongApproval : 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 + +set_option maxRecDepth 100000 in +/-- The kernel's evaluation: the check rejects `allowance` with its keys hashed in the other +order. -/ +theorem check_rejects_map2 : + Generic.check fuel mirFuel coreLit (mapFn 1 swapKeys) [fnAllowance] .all = false := by + decide +kernel + +set_option maxRecDepth 100000 in +/-- The kernel's evaluation: the check rejects `transfer` without its `frozen` check. -/ +theorem check_rejects_frozen : + Generic.check fuel mirFuel coreLit (mapFn 5 noFrozen) [fnTransfer] .all = false := by + decide +kernel + +set_option maxRecDepth 100000 in +/-- The kernel's evaluation: the check rejects `approve` with the wrong `Approval` topic. -/ +theorem check_rejects_approval : + Generic.check fuel mirFuel coreLit (mapFn 6 wrongApproval) [fnApprove] .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 `Token`**: every call of its eight external functions 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 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 `Token` 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 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_map2 + +#print axioms check_rejects_frozen + +#print axioms check_rejects_approval + +#print axioms lowering + +#print axioms loweringValue + +end SolidCore.Refinement.Solar.Token diff --git a/SolidCore/Refinement/Solar/Token/Mutants.lean b/SolidCore/Refinement/Solar/Token/Mutants.lean new file mode 100644 index 00000000..3a0d8a24 --- /dev/null +++ b/SolidCore/Refinement/Solar/Token/Mutants.lean @@ -0,0 +1,91 @@ +import SolidCore.Refinement.Solar.Token.Assembly + +/-! +# token: one-byte mutants of the bytecode + +The assembler check rejects the bytecode with one byte changed where the token's behaviour +turns on it: the transfer's balance test, the caller it debits, the Transfer event's log and +signature, a mapping slot's hash, the allowances' slot, the shared revert block's string offset +(a constant the check follows through a DUP), the unlimited allowance's test and the frozen +check's jump. Each rejection is the kernel's evaluation of the check's one-pass form +(Assemble.checkFast). +-/ + +namespace SolidCore.Refinement.Solar.Token + +open SolarTV.Assembly SolarTV.Export.Token + +/-- 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: transfer's LT of the balance and the value (0x177), its CALLER +for the frozen flag's key (0x152), its LOG3 (0x1c3), the first byte of the Transfer signature +(0x1a0), balanceOf's KECCAK256 (0x9c), allowance's slot 1 (0xc0), the revert block's DUP1 of the +string offset 32 (0x1dd), transferFrom's ISZERO of the allowance's NOT (0x28a) and the frozen +check's JUMPI (0x164). -/ +theorem mutated_bytes : bytecode[0x177]? = some 0x10 ∧ bytecode[0x152]? = some 0x33 ∧ + bytecode[0x1c3]? = some 0xa3 ∧ bytecode[0x1a0]? = some 0xdd ∧ bytecode[0x9c]? = some 0x20 ∧ + bytecode[0xc0]? = some 0x01 ∧ bytecode[0x1dd]? = some 0x80 ∧ bytecode[0x28a]? = some 0x15 ∧ + bytecode[0x164]? = some 0x57 := by decide + +set_option maxRecDepth 100000 in +/-- GT for the balance test's LT: rejected. -/ +theorem mutantLt_check : Assemble.check evm11 (mutant 0x177 0x11) 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 0x152 0x32) cert = false := by + rw [Assemble.check_eq_checkFast] + decide +kernel + +set_option maxRecDepth 100000 in +/-- LOG2 for the Transfer event's LOG3: rejected. -/ +theorem mutantLog_check : Assemble.check evm11 (mutant 0x1c3 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 evm11 (mutant 0x1a0 0xde) cert = false := by + rw [Assemble.check_eq_checkFast] + decide +kernel + +set_option maxRecDepth 100000 in +/-- ADD for the hash of the mapping slot: rejected. -/ +theorem mutantKeccak_check : Assemble.check evm11 (mutant 0x9c 0x01) cert = false := by + rw [Assemble.check_eq_checkFast] + decide +kernel + +set_option maxRecDepth 100000 in +/-- The frozen flags' slot 2 for the allowances' slot 1: rejected. -/ +theorem mutantSlot_check : Assemble.check evm11 (mutant 0xc0 0x02) cert = false := by + rw [Assemble.check_eq_checkFast] + decide +kernel + +set_option maxRecDepth 100000 in +/-- DUP2 for the DUP1 of the revert string's offset, an MSTORE at an offset the check does not +know: rejected. -/ +theorem mutantDup_check : Assemble.check evm11 (mutant 0x1dd 0x81) cert = false := by + rw [Assemble.check_eq_checkFast] + decide +kernel + +set_option maxRecDepth 100000 in +/-- POP for the ISZERO of the unlimited allowance's test: rejected. -/ +theorem mutantAllOnes_check : Assemble.check evm11 (mutant 0x28a 0x50) cert = false := by + rw [Assemble.check_eq_checkFast] + decide +kernel + +set_option maxRecDepth 100000 in +/-- JUMP for the frozen check's JUMPI: rejected. -/ +theorem mutantFrozen_check : Assemble.check evm11 (mutant 0x164 0x56) cert = false := by + rw [Assemble.check_eq_checkFast] + decide +kernel + +/-- info: 'SolidCore.Refinement.Solar.Token.mutantDup_check' depends on axioms: [propext, Quot.sound] -/ +#guard_msgs in +#print axioms mutantDup_check + +end SolidCore.Refinement.Solar.Token + diff --git a/SolidCore/Refinement/Source/Token.lean b/SolidCore/Refinement/Source/Token.lean new file mode 100644 index 00000000..ad92fbe9 --- /dev/null +++ b/SolidCore/Refinement/Source/Token.lean @@ -0,0 +1,152 @@ +-- Generated from scripts/refinement/token/token.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 Token + +def importedSourceName : String := "scripts/refinement/token/token.sol" + +def importedContractDecl0 : ContractDecl := +{ kind := ContractKind.contract + name := "Token" + 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 := "allowances", + ty := Ty.mapping (Ty.address false) (Ty.mapping (Ty.address false) (Ty.uint 256)), + visibility := some Visibility.internal_, + mutability := VarMutability.mutable, + override? := none, + init := none }), (ContractItem.stateVar + { name := "frozen", + ty := Ty.mapping (Ty.address false) (Ty.bool), + visibility := some Visibility.internal_, + mutability := VarMutability.mutable, + override? := none, + init := none }), (ContractItem.stateVar + { name := "totalSupply", + ty := Ty.uint 256, + visibility := some Visibility.internal_, + mutability := VarMutability.mutable, + override? := none, + init := none }), (ContractItem.stateVar + { name := "owner", + ty := Ty.address false, + visibility := some Visibility.internal_, + mutability := VarMutability.mutable, + override? := none, + init := none }), (ContractItem.eventDecl + { name := "Transfer", + params := [{ name := some "from", ty := Ty.address false, indexed := true }, { name := some "to", ty := Ty.address false, indexed := true }, { name := some "value", ty := Ty.uint 256, indexed := false }], + anonymous := false }), (ContractItem.eventDecl + { name := "Approval", + params := [{ name := some "owner", ty := Ty.address false, indexed := true }, { name := some "spender", ty := Ty.address false, indexed := true }, { name := some "value", ty := Ty.uint 256, indexed := false }], + anonymous := false }), (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")))]) }), (ContractItem.function + { kind := FunctionKind.function, + name := some "allowance", + visibility := some Visibility.external_, + mutability := StateMutability.view, + params := [{ name := some "holder", ty := Ty.address false, location := none }, { name := some "spender", 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.index (Expr.ident "allowances") (Expr.ident "holder")) (Expr.ident "spender")))]) }), (ContractItem.function + { kind := FunctionKind.function, + name := some "getOwner", + visibility := some Visibility.external_, + mutability := StateMutability.view, + params := [], + returns := [{ name := none, ty := Ty.address false, location := none }], + virtual := false, + override? := none, + modifiers := [], + body := some (Stmt.block [Stmt.returnValues (some (Expr.ident "owner"))]) }), (ContractItem.function + { kind := FunctionKind.function, + name := some "isFrozen", + visibility := some Visibility.external_, + mutability := StateMutability.view, + params := [{ name := some "who", ty := Ty.address false, location := none }], + returns := [{ name := none, ty := Ty.bool, location := none }], + virtual := false, + override? := none, + modifiers := [], + body := some (Stmt.block [Stmt.returnValues (some (Expr.index (Expr.ident "frozen") (Expr.ident "who")))]) }), (ContractItem.function + { kind := FunctionKind.function, + name := some "freeze", + visibility := some Visibility.external_, + mutability := StateMutability.nonpayable, + params := [{ name := some "who", ty := Ty.address false, location := none }], + returns := [], + virtual := false, + override? := none, + modifiers := [], + body := some (Stmt.block [Stmt.expr (Expr.call (Expr.ident "require") [Arg.positional (Expr.binary BinaryOp.eq (Expr.member (Expr.ident "msg") "sender") (Expr.ident "owner"))]), Stmt.expr (Expr.assign (Expr.index (Expr.ident "frozen") (Expr.ident "who")) AssignOp.assign (Expr.literal (Literal.bool true)))]) }), (ContractItem.function + { kind := FunctionKind.function, + name := some "transfer", + visibility := some Visibility.external_, + mutability := StateMutability.nonpayable, + params := [{ name := some "to", ty := Ty.address false, location := none }, { name := some "value", ty := Ty.uint 256, location := none }], + returns := [{ name := none, ty := Ty.bool, location := none }], + virtual := false, + override? := none, + modifiers := [], + body := some (Stmt.block [Stmt.expr (Expr.call (Expr.ident "require") [Arg.positional (Expr.unary UnaryOp.logicalNot (Expr.index (Expr.ident "frozen") (Expr.member (Expr.ident "msg") "sender")))]), Stmt.expr (Expr.call (Expr.ident "require") [Arg.positional (Expr.binary BinaryOp.ge (Expr.index (Expr.ident "balances") (Expr.member (Expr.ident "msg") "sender")) (Expr.ident "value")), Arg.positional (Expr.literal (Literal.string "balance"))]), Stmt.expr (Expr.assign (Expr.index (Expr.ident "balances") (Expr.member (Expr.ident "msg") "sender")) AssignOp.subAssign (Expr.ident "value")), Stmt.expr (Expr.assign (Expr.index (Expr.ident "balances") (Expr.ident "to")) AssignOp.addAssign (Expr.ident "value")), Stmt.emitEvent (Expr.call (Expr.ident "Transfer") [Arg.positional (Expr.member (Expr.ident "msg") "sender"), Arg.positional (Expr.ident "to"), Arg.positional (Expr.ident "value")]), Stmt.returnValues (some (Expr.literal (Literal.bool true)))]) }), (ContractItem.function + { kind := FunctionKind.function, + name := some "approve", + visibility := some Visibility.external_, + mutability := StateMutability.nonpayable, + params := [{ name := some "spender", ty := Ty.address false, location := none }, { name := some "value", ty := Ty.uint 256, location := none }], + returns := [{ name := none, ty := Ty.bool, location := none }], + virtual := false, + override? := none, + modifiers := [], + body := some (Stmt.block [Stmt.expr (Expr.assign (Expr.index (Expr.index (Expr.ident "allowances") (Expr.member (Expr.ident "msg") "sender")) (Expr.ident "spender")) AssignOp.assign (Expr.ident "value")), Stmt.emitEvent (Expr.call (Expr.ident "Approval") [Arg.positional (Expr.member (Expr.ident "msg") "sender"), Arg.positional (Expr.ident "spender"), Arg.positional (Expr.ident "value")]), Stmt.returnValues (some (Expr.literal (Literal.bool true)))]) }), (ContractItem.function + { kind := FunctionKind.function, + name := some "transferFrom", + visibility := some Visibility.external_, + mutability := StateMutability.nonpayable, + params := [{ name := some "from", ty := Ty.address false, location := none }, { name := some "to", ty := Ty.address false, location := none }, { name := some "value", ty := Ty.uint 256, location := none }], + returns := [{ name := none, ty := Ty.bool, location := none }], + virtual := false, + override? := none, + modifiers := [], + body := some (Stmt.block [Stmt.varDecl [{ name := some "a", ty := Ty.uint 256, location := none }] (some (Expr.index (Expr.index (Expr.ident "allowances") (Expr.ident "from")) (Expr.member (Expr.ident "msg") "sender"))), Stmt.ifElse (Expr.binary BinaryOp.lt (Expr.ident "a") (Expr.ident "value")) (Stmt.block [Stmt.expr (Expr.call (Expr.ident "revert") [Arg.positional (Expr.literal (Literal.string "allowance"))])]) (some (Stmt.ifElse (Expr.binary BinaryOp.ne (Expr.ident "a") (Expr.member (Expr.typeName (Ty.uint 256)) "max")) (Stmt.block [Stmt.expr (Expr.assign (Expr.index (Expr.index (Expr.ident "allowances") (Expr.ident "from")) (Expr.member (Expr.ident "msg") "sender")) AssignOp.assign (Expr.binary BinaryOp.sub (Expr.ident "a") (Expr.ident "value")))]) none)), Stmt.expr (Expr.call (Expr.ident "require") [Arg.positional (Expr.binary BinaryOp.ge (Expr.index (Expr.ident "balances") (Expr.ident "from")) (Expr.ident "value"))]), Stmt.expr (Expr.assign (Expr.index (Expr.ident "balances") (Expr.ident "from")) AssignOp.subAssign (Expr.ident "value")), Stmt.expr (Expr.assign (Expr.index (Expr.ident "balances") (Expr.ident "to")) AssignOp.addAssign (Expr.ident "value")), Stmt.emitEvent (Expr.call (Expr.ident "Transfer") [Arg.positional (Expr.ident "from"), Arg.positional (Expr.ident "to"), Arg.positional (Expr.ident "value")]), Stmt.returnValues (some (Expr.literal (Literal.bool true)))]) })] } + +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 Token +end Source +end Refinement +end SolidCore diff --git a/SolidCore/Solidity/Ast.lean b/SolidCore/Solidity/Ast.lean index a7c60cea..662c5a95 100644 --- a/SolidCore/Solidity/Ast.lean +++ b/SolidCore/Solidity/Ast.lean @@ -217,10 +217,11 @@ def Ty.reprFlatItems : List Ty -> String 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. -/ +(`Std.Format.defWidth` is 120 columns) and so is the derived print itself: up to 120 +characters, which the kernel evaluates, as it cannot `Std.Format`'s `partial` printer. -/ def Ty.reprListString (ts : List Ty) : String := let s := Ty.reprFlatList ts - if s.length < 100 then s else toString (repr ts) + if s.length ≤ 120 then s else toString (repr ts) def Ty.function (params returns : List Ty) (mutability : StateMutability) (visibility : Visibility) : Ty := diff --git a/lakefile.lean b/lakefile.lean index 2ddbf64f..0ec14fa1 100644 --- a/lakefile.lean +++ b/lakefile.lean @@ -149,3 +149,15 @@ lean_lib SolidCoreSolarBank where 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] + +-- token (solar-tv/milestone/token/token.sol at solar 3ca8f483, copied to +-- scripts/refinement/token/token.sol: an ERC-20 with a nested allowance mapping, a mapping to +-- bool, an address field, require and revert with Error(string) and two indexed address topics): +-- the generic source stage against solar's own first lowered MIR (token.gen.Token.Stage0, the +-- module solar-tv's backend stages start from), the generic assembler check under an oracle whose +-- caller and hash are EthLib's, the composition from SolidCore to the bytecode bound to the +-- export's manifest, and one-byte mutants. Outside the default root: the export shares solar-tv's +-- milestone libraries. +lean_lib SolidCoreSolarToken where + roots := #[`SolidCore.Refinement.Solar.Token.Lowering, `SolidCore.Refinement.Solar.Token.Assembly, + `SolidCore.Refinement.Solar.Token.Mutants, `SolidCore.Refinement.Solar.Token.Certified] diff --git a/scripts/refinement/token/mir_to_lean.py b/scripts/refinement/token/mir_to_lean.py new file mode 100644 index 00000000..70230c70 --- /dev/null +++ b/scripts/refinement/token/mir_to_lean.py @@ -0,0 +1,168 @@ +#!/usr/bin/env python3 +"""Transcribe solar's printed lowered MIR (after lower-evm-shaped) into a SolarTV Lean module. + + scripts/refinement/token/mir_to_lean.py STAGE.mir NAMESPACE > Stage0.lean + +The input is one module as solar -Zprint-after-each prints it after lower-evm-shaped. The +output follows the layout of solar's -Zemit-lean-stages: the functions in the printed order +with the dispatch entry last, blocks by their bbN number, EVM operand order for shifts, each +function's parameters as fresh value numbers past the module's largest, and !metadata dropped. +An instruction it does not know stops it with an error rather than a guess. +""" +import re +import sys + +PURE = {"add", "sub", "mul", "div", "lt", "gt", "eq", "and", "or", "xor", "byte", "iszero", "not"} +SHIFT = {"shl", "shr"} +EFFECT0 = {"calldatasize", "callvalue", "caller"} + + +def die(msg): + sys.exit(f"error: {msg}") + + +def parse(text): + fns = [] + cur = None + blk = None + for raw in text.splitlines(): + line = raw.split(";", 1)[0].rstrip() + line = re.sub(r"\s*!metadata\((?:[^()]|\([^()]*\))*\)", "", line) + if not line.strip() or line.startswith("@"): + continue + m = re.match(r"fn @(\w+)\((.*?)\)(?:\s*->\s*[^\s\[{]+)?(\s*\[[^\]]*\])?\s*\{", line) + if m: + params = [p.split(":")[0].strip() for p in m.group(2).split(",") if p.strip()] + cur = {"name": m.group(1), "params": params, "blocks": {}, "entry": "entry" in (m.group(3) or "")} + fns.append(cur) + continue + if line.strip() == "}": + cur = None + continue + m = re.match(r"\s*bb(\d+)(?:\s*\[[^\]]*\])?:", line) + if m: + blk = {"insts": []} + cur["blocks"][int(m.group(1))] = blk + continue + blk["insts"].append(line.strip()) + return fns + + +def main(): + text = open(sys.argv[1]).read() + ns = sys.argv[2] + fns = parse(text) + order = [f for f in fns if not f["entry"]] + [f for f in fns if f["entry"]] + index = {f["name"]: i for i, f in enumerate(order)} + top = max(int(v) for v in re.findall(r"\bv(\d+)\b", text)) + nxt = top + 1 + out = [] + for f in order: + argmap = {} + for p in f["params"]: + argmap[p] = nxt + nxt += 1 + + def opd(tok): + tok = tok.strip() + if re.fullmatch(r"v\d+", tok): + return f".value {tok[1:]}" + if tok in argmap: + return f".value {argmap[tok]}" + if re.fullmatch(r"0x[0-9a-fA-F]+|\d+", tok): + return f".const {tok}" + die(f"operand {tok}") + + def dst(tok): + tok = tok.split(":")[0].strip() + if not re.fullmatch(r"v\d+", tok): + die(f"destination {tok}") + return tok[1:] + + nums = sorted(f["blocks"]) + if nums != list(range(len(nums))): + die(f"the blocks of @{f['name']} are not bb0..bbN") + blocks = [] + for b in nums: + insts, term = [], None + for ins in f["blocks"][b]["insts"]: + if term is not None: + die(f"an instruction after the terminator in @{f['name']} bb{b}: {ins}") + m = re.fullmatch(r"(v\d+(?::\s*\w+)?)\s*=\s*(.*)", ins) + if m: + d, rhs = dst(m.group(1)), m.group(2) + mz = re.fullmatch(r"zext i\d+ (\S+) to i256", rhs) + if mz: + insts.append(f".word {d} ({opd(mz.group(1))})") + continue + op, _, rest = rhs.partition(" ") + args = [a for a in rest.split(",") if a.strip()] + if op == "ne": + insts.append(f".ne {d} ({opd(args[0])}) ({opd(args[1])})") + elif op in PURE: + insts.append(f".pure {d} .{op} [{', '.join(opd(a) for a in args)}]") + elif op in SHIFT: + insts.append(f".pure {d} .{op} [{opd(args[1])}, {opd(args[0])}]") + elif op in EFFECT0 and not args: + insts.append(f".effect (some {d}) .{op} []") + elif op in ("calldataload", "sload", "keccak256"): + insts.append(f".effect (some {d}) .{op} [{', '.join(opd(a) for a in args)}]") + elif op == "icall": + callee = args[0].strip().lstrip("@") + insts.append(f".call (some {d}) {index[callee]} [{', '.join(opd(a) for a in args[1:])}]") + else: + die(f"the instruction {ins}") + continue + op, _, rest = ins.partition(" ") + args = [a for a in rest.split(",") if a.strip()] + if op in ("mstore", "sstore"): + insts.append(f".effect none .{op} [{', '.join(opd(a) for a in args)}]") + elif op == "log": + insts.append(f".effect none (.log {len(args) - 2}) [{', '.join(opd(a) for a in args)}]") + elif op == "jumpi": + term = f".branch ({opd(args[0])}) {args[1].strip()[2:]} {args[2].strip()[2:]}" + elif op == "jump": + term = f".jump {args[0].strip()[2:]}" + elif op == "returndata": + term = f".ret ({opd(args[0])}) ({opd(args[1])})" + elif op == "revert": + term = f".revert ({opd(args[0])}) ({opd(args[1])})" + elif op == "stop": + term = ".stop" + elif op == "tail_call": + callee = args[0].strip().lstrip("@") + term = f".tailCall {index[callee]} [{', '.join(opd(a) for a in args[1:])}]" + elif op == "switch": + m = re.fullmatch(r"switch (\S+), default bb(\d+), \[(.*)\]", ins) + cases = [c.split("=>") for c in m.group(3).split(",")] + cs = ", ".join(f"({opd(k)}, {t.strip()[2:]})" for k, t in cases) + term = f".switch ({opd(m.group(1))}) {m.group(2)} [{cs}]" + else: + die(f"the instruction {ins}") + if term is None: + die(f"@{f['name']} bb{b} has no terminator") + body = ",\n ".join(insts) + blocks.append(f" -- bb{b}\n ⟨[],\n [{body}],\n {term}⟩") + params = ", ".join(str(argmap[p]) for p in f["params"]) + out.append(f" -- @{f['name']}\n {{ params := [{params}],\n blocks := [\n" + + ",\n".join(blocks) + "] }") + bt = chr(96) + print("import SolarTV.MIR.Program") + print() + print("/-! Transcribed by scripts/refinement/token/mir_to_lean.py from solar's lowered MIR after") + print(f"{bt}lower-evm-shaped{bt} (scripts/refinement/token/stage0.mir); do not edit. -/") + print() + print(f"namespace {ns}") + print() + print("open SolarTV") + print() + print(f"/-- The first lowered MIR module, after {bt}lower-evm-shaped{bt} advanced the phase. -/") + print("def stage0 : MIR.Lowered.Module :=") + print(f" {{ entry := {len(order) - 1},") + print(" functions := [") + print(",\n".join(out) + "] }") + print() + print(f"end {ns}") + + +main() diff --git a/scripts/refinement/token/stage0.mir b/scripts/refinement/token/stage0.mir new file mode 100644 index 00000000..f54da09a --- /dev/null +++ b/scripts/refinement/token/stage0.mir @@ -0,0 +1,283 @@ +@module Token +@phase lowered +; runtime dispatch entry +fn @entry() [entry] { + bb0: + v0 = callvalue + v1 = ne v0, 0 + jumpi v1, bb10, bb1 + bb1: ; preds = bb0 + v2 = calldataload 0 + v3 = shr v2, 224 + switch v3, default bb10, [0x95ea7b3 => bb2, 0x23b872dd => bb3, 0x70a08231 => bb4, 0x893d20e8 => bb5, 0x8d1fdf2f => bb6, 0xa9059cbb => bb7, 0xdd62ed3e => bb8, 0xe5839836 => bb9] + bb9: ; preds = bb1 + tail_call @isFrozen + bb8: ; preds = bb1 + tail_call @allowance + bb7: ; preds = bb1 + tail_call @transfer + bb6: ; preds = bb1 + tail_call @freeze + bb5: ; preds = bb1 + tail_call @getOwner + bb4: ; preds = bb1 + tail_call @balanceOf + bb3: ; preds = bb1 + tail_call @transferFrom + bb2: ; preds = bb1 + tail_call @approve + bb10 [cold]: ; preds = bb0, bb1 + revert 0, 0 +} + +fn @balanceOf() { + bb0: + v3 = calldatasize + v4 = lt v3, 36 + v5 = calldataload 4 + v6 = gt v5, 0xffffffffffffffffffffffffffffffffffffffff + v10 = or v4, v6 + jumpi v10, bb1, bb2 + bb2: ; preds = bb0 + mstore 0, v5 + mstore 32, 0 !metadata(memory=scratch) + v8 = keccak256 0, 64 !metadata(memory=scratch) + v2 = sload v8 + mstore 0, v2 !metadata(memory=scratch) + returndata 0, 32 + bb1 [cold]: ; preds = bb0 + revert 0, 0 +} + +fn @allowance() { + bb0: + v5 = calldatasize + v6 = lt v5, 68 + v7 = calldataload 4 + v8 = gt v7, 0xffffffffffffffffffffffffffffffffffffffff + v17 = or v6, v8 + v9 = calldataload 36 + v10 = gt v9, 0xffffffffffffffffffffffffffffffffffffffff + v18 = or v17, v10 + jumpi v18, bb1, bb2 + bb2: ; preds = bb0 + mstore 0, v7 + mstore 32, 1 !metadata(memory=scratch) + v13 = keccak256 0, 64 !metadata(memory=scratch) + mstore 0, v9 + mstore 32, v13 + v14 = keccak256 0, 64 !metadata(memory=scratch) + v4 = sload v14 + mstore 0, v4 !metadata(memory=scratch) + returndata 0, 32 + bb1 [cold]: ; preds = bb0 + revert 0, 0 +} + +fn @getOwner() { + bb0: + v0 = sload 4 !metadata(storage=slot(4)) + v3 = and v0, 0xffffffffffffffffffffffffffffffffffffffff + mstore 0, v3 + returndata 0, 32 +} + +fn @isFrozen() { + bb0: + v5 = calldatasize + v6 = lt v5, 36 + v7 = calldataload 4 + v8 = gt v7, 0xffffffffffffffffffffffffffffffffffffffff + v15 = or v6, v8 + jumpi v15, bb1, bb2 + bb2: ; preds = bb0 + mstore 0, v7 + mstore 32, 2 !metadata(memory=scratch) + v12 = keccak256 0, 64 !metadata(memory=scratch) + v2 = sload v12 + v14 = and v2, 255 + v4 = ne v14, 0 + v11 = zext i1 v4 to i256 + mstore 0, v11 !metadata(memory=scratch) + returndata 0, 32 + bb1 [cold]: ; preds = bb0 + revert 0, 0 +} + +fn @freeze() { + bb0: + v7 = calldatasize + v8 = lt v7, 36 + v9 = calldataload 4 + v10 = gt v9, 0xffffffffffffffffffffffffffffffffffffffff + v15 = or v8, v10 + jumpi v15, bb1, bb3 + bb3: ; preds = bb0 + v0: i256 = caller + v1 = sload 4 !metadata(storage=slot(4)) + v14 = and v1, 0xffffffffffffffffffffffffffffffffffffffff + v3 = eq v0, v14 + jumpi v3, bb2, bb1 + bb2: ; preds = bb3 + mstore 0, v9 + mstore 32, 2 !metadata(memory=scratch) + v12 = keccak256 0, 64 !metadata(memory=scratch) + sstore v12, 1 + stop + bb1 [cold]: ; preds = bb0, bb3 + revert 0, 0 +} + +fn @transfer() { + bb0: + v28 = calldatasize + v29 = lt v28, 68 + v30 = calldataload 4 + v31 = gt v30, 0xffffffffffffffffffffffffffffffffffffffff + v41 = or v29, v31 + jumpi v41, bb1, bb7 + bb7: ; preds = bb0 + v32 = calldataload 36 + v0: i256 = caller + mstore 0, v0 + mstore 32, 2 !metadata(memory=scratch) + v38 = keccak256 0, 64 !metadata(memory=scratch) + v3 = sload v38 + v40 = and v3, 255 + v5 = ne v40, 0 + jumpi v5, bb1, bb2 + bb2: ; preds = bb7 + mstore 0, v0 + mstore 32, 0 !metadata(memory=scratch) + v36 = keccak256 0, 64 !metadata(memory=scratch) + v11 = sload v36 + v12 = lt v11, v32 + jumpi v12, bb3, bb4 + bb4: ; preds = bb2 + v18 = sub v11, v32 + sstore v36, v18 + mstore 0, v30 + v37 = keccak256 0, 64 !metadata(memory=scratch) + v21 = sload v37 + v26 = add v21, v32 + v27 = lt v26, v21 + jumpi v27, bb5, bb6 + bb6: ; preds = bb4 + sstore v37, v26 + mstore 0, v32 + log 0, 32, 0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef, v0, v30 + mstore 0, 1 + returndata 0, 32 + bb5 [cold]: ; preds = bb4 + mstore 32, 17 !metadata(memory=scratch) + mstore 0, 0x4e487b71 !metadata(memory=scratch) + revert 28, 36 + bb3 [cold]: ; preds = bb2 + tail_call @revert_error, 7, 0x62616c616e636500000000000000000000000000000000000000000000000000 + bb1 [cold]: ; preds = bb0, bb7 + revert 0, 0 +} + +fn @approve() { + bb0: + v8 = calldatasize + v9 = lt v8, 68 + v10 = calldataload 4 + v11 = gt v10, 0xffffffffffffffffffffffffffffffffffffffff + v19 = or v9, v11 + jumpi v19, bb1, bb2 + bb2: ; preds = bb0 + v12 = calldataload 36 + v0: i256 = caller + mstore 0, v0 + mstore 32, 1 !metadata(memory=scratch) + v16 = keccak256 0, 64 !metadata(memory=scratch) + mstore 0, v10 + mstore 32, v16 + v17 = keccak256 0, 64 !metadata(memory=scratch) + sstore v17, v12 + mstore 0, v12 + log 0, 32, 0x8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925, v0, v10 + mstore 0, 1 + returndata 0, 32 + bb1 [cold]: ; preds = bb0 + revert 0, 0 +} + +fn @transferFrom() { + bb0: + v32 = calldatasize + v33 = lt v32, 100 + v34 = calldataload 4 + v35 = gt v34, 0xffffffffffffffffffffffffffffffffffffffff + v53 = or v33, v35 + v36 = calldataload 36 + v37 = gt v36, 0xffffffffffffffffffffffffffffffffffffffff + v54 = or v53, v37 + jumpi v54, bb5, bb9 + bb9: ; preds = bb0 + v38 = calldataload 68 + mstore 0, v34 + mstore 32, 1 !metadata(memory=scratch) + v49 = keccak256 0, 64 !metadata(memory=scratch) + v2: i256 = caller + mstore 0, v2 + mstore 32, v49 + v50 = keccak256 0, 64 !metadata(memory=scratch) + v5 = sload v50 + v6 = lt v5, v38 + jumpi v6, bb4, bb1 + bb1: ; preds = bb9 + v43 = not v5 + v7 = ne v43, 0 + jumpi v7, bb3, bb2 + bb3: ; preds = bb1 + v8 = sub v5, v38 + mstore 0, v34 + mstore 32, 1 !metadata(memory=scratch) + v46 = keccak256 0, 64 !metadata(memory=scratch) + mstore 0, v2 + mstore 32, v46 + v47 = keccak256 0, 64 !metadata(memory=scratch) + sstore v47, v8 + jump bb2 + bb2: ; preds = bb1, bb3 + mstore 0, v34 + mstore 32, 0 !metadata(memory=scratch) + v45 = keccak256 0, 64 !metadata(memory=scratch) + v16 = sload v45 + v17 = lt v16, v38 + jumpi v17, bb5, bb6 + bb6: ; preds = bb2 + v23 = sub v16, v38 + sstore v45, v23 + mstore 0, v36 + v48 = keccak256 0, 64 !metadata(memory=scratch) + v26 = sload v48 + v30 = add v26, v38 + v31 = lt v30, v26 + jumpi v31, bb7, bb8 + bb8: ; preds = bb6 + sstore v48, v30 + mstore 0, v38 + log 0, 32, 0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef, v34, v36 + mstore 0, 1 + returndata 0, 32 + bb7 [cold]: ; preds = bb6 + mstore 32, 17 !metadata(memory=scratch) + mstore 0, 0x4e487b71 !metadata(memory=scratch) + revert 28, 36 + bb4 [cold]: ; preds = bb9 + tail_call @revert_error, 9, 0x616c6c6f77616e63650000000000000000000000000000000000000000000000 + bb5 [cold]: ; preds = bb2, bb0 + revert 0, 0 +} + +fn @revert_error(arg0: i256, arg1: i256) [cold] { + bb0 [cold]: + mstore 32, 32 !metadata(memory=scratch) + mstore 64, arg0 !metadata(memory=scratch) + mstore 96, arg1 !metadata(memory=scratch) + mstore 0, 0x8c379a0 !metadata(memory=scratch) + revert 28, 100 +} diff --git a/scripts/refinement/token/token.sol b/scripts/refinement/token/token.sol new file mode 100644 index 00000000..cb5efea6 --- /dev/null +++ b/scripts/refinement/token/token.sol @@ -0,0 +1,60 @@ +contract Token { + mapping(address => uint256) balances; + mapping(address => mapping(address => uint256)) allowances; + mapping(address => bool) frozen; + uint256 totalSupply; + address owner; + + event Transfer(address indexed from, address indexed to, uint256 value); + event Approval(address indexed owner, address indexed spender, uint256 value); + + function balanceOf(address who) external view returns (uint256) { + return balances[who]; + } + + function allowance(address holder, address spender) external view returns (uint256) { + return allowances[holder][spender]; + } + + function getOwner() external view returns (address) { + return owner; + } + + function isFrozen(address who) external view returns (bool) { + return frozen[who]; + } + + function freeze(address who) external { + require(msg.sender == owner); + frozen[who] = true; + } + + function transfer(address to, uint256 value) external returns (bool) { + require(!frozen[msg.sender]); + require(balances[msg.sender] >= value, "balance"); + balances[msg.sender] -= value; + balances[to] += value; + emit Transfer(msg.sender, to, value); + return true; + } + + function approve(address spender, uint256 value) external returns (bool) { + allowances[msg.sender][spender] = value; + emit Approval(msg.sender, spender, value); + return true; + } + + function transferFrom(address from, address to, uint256 value) external returns (bool) { + uint256 a = allowances[from][msg.sender]; + if (a < value) { + revert("allowance"); + } else if (a != type(uint256).max) { + allowances[from][msg.sender] = a - value; + } + require(balances[from] >= value); + balances[from] -= value; + balances[to] += value; + emit Transfer(from, to, value); + return true; + } +} From f78b7f5b6663667c4eae55bd29db7b08429cbeb4 Mon Sep 17 00:00:00 2001 From: alpharush <0xalpharush@protonmail.com> Date: Thu, 12 Nov 2026 21:25:34 -0600 Subject: [PATCH 4/8] fix(evmyul): track the vendored FFI source --- .gitignore | 1 + vendor/evmyul/EvmYul/FFI/ffi.c | 161 +++++++++++++++++++++++++++++++++ 2 files changed, 162 insertions(+) create mode 100644 vendor/evmyul/EvmYul/FFI/ffi.c diff --git a/.gitignore b/.gitignore index 7172907b..d800f98f 100644 --- a/.gitignore +++ b/.gitignore @@ -7,6 +7,7 @@ tests/.foundry-suites/ *.olean *.ilean *.c +!vendor/evmyul/EvmYul/FFI/ffi.c *.o *.so *.dylib diff --git a/vendor/evmyul/EvmYul/FFI/ffi.c b/vendor/evmyul/EvmYul/FFI/ffi.c new file mode 100644 index 00000000..9b9991f7 --- /dev/null +++ b/vendor/evmyul/EvmYul/FFI/ffi.c @@ -0,0 +1,161 @@ +#include +#include "lean/lean.h" +#include "sha-256.h" +#include +#include +#include "sha3.h" + +#define SHA256_OUTPUT_SIZE 32 +#define KECCAK256_OUTPUT_SIZE 32 + +// #define BLAKE2B_OUTPUT_SIZE 64 +#define BLAKE2B_COMPRESS_SIZE 8 +#define BLAKE2B_KEY_LENGTH 8 + +extern lean_obj_res sha256(b_lean_obj_arg input, size_t len) { + uint8_t hash[SHA256_OUTPUT_SIZE]; + calc_sha_256(hash, lean_sarray_cptr(input), len); + lean_obj_res res = lean_mk_empty_byte_array(lean_box(SHA256_OUTPUT_SIZE)); + for (int i = 0; i < SHA256_OUTPUT_SIZE; ++i) + lean_byte_array_push(res, hash[i]); + return res; +} + +// Implementation based on https://github.com/BLAKE2/BLAKE2/ +// with # of rounds parameterised from 12 (BLAKE2) to k < 2^32. + +uint64_t rotr64(const uint64_t w, const unsigned int c) { + return (w >> c) | (w << (64 - c)); +} + +#define G(a, b, c, d, e, f) \ + do { \ + v[a] = v[a] + v[b] + e; \ + v[d] = rotr64(v[d] ^ v[a], 32); \ + v[c] = v[c] + v[d]; \ + v[b] = rotr64(v[b] ^ v[c], 24); \ + v[a] = v[a] + v[b] + f; \ + v[d] = rotr64(v[d] ^ v[a], 16); \ + v[c] = v[c] + v[d]; \ + v[b] = rotr64(v[b] ^ v[c], 63); \ + } while(0) + +const uint64_t blake2b_IV[8] = { + 0x6A09E667F3BCC908ULL, 0xBB67AE8584CAA73BULL, + 0x3C6EF372FE94F82BULL, 0xA54FF53A5F1D36F1ULL, + 0x510E527FADE682D1ULL, 0x9B05688C2B3E6C1FULL, + 0x1F83D9ABFB41BD6BULL, 0x5BE0CD19137E2179ULL +}; + +// Do not repeat the last two rows, we'll be MOD 10, +// as we are going 12 -> k rounds. +const uint8_t blake2b_sigma[10][16] = { + {0 , 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10, 11, 12, 13, 14, 15}, + {14, 10, 4 , 8 , 9 , 15, 13, 6 , 1 , 12, 0 , 2 , 11, 7 , 5 , 3 }, + {11, 8 , 12, 0 , 5 , 2 , 15, 13, 10, 14, 3 , 6 , 7 , 1 , 9 , 4 }, + {7 , 9 , 3 , 1 , 13, 12, 11, 14, 2 , 6 , 5 , 10, 4 , 0 , 15, 8 }, + {9 , 0 , 5 , 7 , 2 , 4 , 10, 15, 14, 1 , 11, 12, 6 , 8 , 3 , 13}, + {2 , 12, 6 , 10, 0 , 11, 8 , 3 , 4 , 13, 7 , 5 , 15, 14, 1 , 9 }, + {12, 5 , 1 , 15, 14, 13, 4 , 10, 0 , 7 , 6 , 3 , 9 , 2 , 8 , 11}, + {13, 11, 7 , 14, 12, 1 , 3 , 9 , 5 , 0 , 15, 4 , 8 , 6 , 2 , 10}, + {6 , 15, 14, 9 , 11, 3 , 0 , 8 , 12, 2 , 13, 7 , 1 , 4 , 10, 5 }, + {10, 2 , 8 , 4 , 7 , 6 , 1 , 5 , 15, 11, 9 , 14, 3 , 12, 13, 0 } +}; + +static void blake2b_compress_any( + uint32_t rounds, + uint64_t* h, + const uint64_t* const m, + const uint64_t* const t, + bool f +) { + uint64_t v[16]; + for (int i = 0; i < 8; ++i) { + v[i] = h[i]; + v[i + 8] = blake2b_IV[i]; + } + v[12] ^= t[0]; + v[13] ^= t[1]; + if (f) v[14] = ~v[14]; + + for (unsigned int i = 0U; i < rounds; ++i) { + G(0, 4, 8 , 12, m[blake2b_sigma[i % 10][0 ]], m[blake2b_sigma[i % 10][1 ]]); + G(1, 5, 9 , 13, m[blake2b_sigma[i % 10][2 ]], m[blake2b_sigma[i % 10][3 ]]); + G(2, 6, 10, 14, m[blake2b_sigma[i % 10][4 ]], m[blake2b_sigma[i % 10][5 ]]); + G(3, 7, 11, 15, m[blake2b_sigma[i % 10][6 ]], m[blake2b_sigma[i % 10][7 ]]); + G(0, 5, 10, 15, m[blake2b_sigma[i % 10][8 ]], m[blake2b_sigma[i % 10][9 ]]); + G(1, 6, 11, 12, m[blake2b_sigma[i % 10][10]], m[blake2b_sigma[i % 10][11]]); + G(2, 7, 8 , 13, m[blake2b_sigma[i % 10][12]], m[blake2b_sigma[i % 10][13]]); + G(3, 4, 9 , 14, m[blake2b_sigma[i % 10][14]], m[blake2b_sigma[i % 10][15]]); + } + + for (int i = 0; i < 8; ++i) + h[i] ^= v[i] ^ v[i + 8]; +} + +extern lean_obj_arg blake2compressb64(b_lean_obj_arg input) { + uint8_t* in = lean_sarray_cptr(input); + + // [0; 3] (4 bytes) - big endian, 4 bytes + uint32_t rounds = (in[3] << 0 * 8) | (in[2] << 1 * 8) | + (in[1] << 2 * 8) | ((uint32_t)in[0] << 3 * 8); + in += 4; + + // [4; 67] (64 bytes) - small endian, 8 bytes, 8 times + uint64_t h[8]; + for (int i = 0; i < 8; ++i) { + h[i] = ((uint64_t)in[0] << (0 * 8)) | ((uint64_t)in[1] << (1 * 8)) | + ((uint64_t)in[2] << (2 * 8)) | ((uint64_t)in[3] << (3 * 8)) | + ((uint64_t)in[4] << (4 * 8)) | ((uint64_t)in[5] << (5 * 8)) | + ((uint64_t)in[6] << (6 * 8)) | ((uint64_t)in[7] << (7 * 8)); + in += sizeof(uint64_t); + } + + // [68; 195] (128 bytes) - small endian, 8 bytes, 16 times + uint64_t m[16]; + for (int i = 0; i < 16; ++i) { + m[i] = ((uint64_t)in[0] << (0 * 8)) | ((uint64_t)in[1] << (1 * 8)) | + ((uint64_t)in[2] << (2 * 8)) | ((uint64_t)in[3] << (3 * 8)) | + ((uint64_t)in[4] << (4 * 8)) | ((uint64_t)in[5] << (5 * 8)) | + ((uint64_t)in[6] << (6 * 8)) | ((uint64_t)in[7] << (7 * 8)); + in += sizeof(uint64_t); + } + + // [196; 211] (16 bytes) - small endian, 8 bytes, 2 times + uint64_t t[2]; + for (int i = 0; i < 2; ++i) { + t[i] = ((uint64_t)in[0] << (0 * 8)) | ((uint64_t)in[1] << (1 * 8)) | + ((uint64_t)in[2] << (2 * 8)) | ((uint64_t)in[3] << (3 * 8)) | + ((uint64_t)in[4] << (4 * 8)) | ((uint64_t)in[5] << (5 * 8)) | + ((uint64_t)in[6] << (6 * 8)) | ((uint64_t)in[7] << (7 * 8)); + in += sizeof(uint64_t); + } + + // [212; 212] (1 bytes) - 0 is false, 1 is true + bool f = *in; + + blake2b_compress_any(rounds, h, m, t, f); + + lean_obj_res res = lean_mk_empty_byte_array(lean_box(BLAKE2B_COMPRESS_SIZE * sizeof(uint64_t))); + + for (int i = 0; i < BLAKE2B_COMPRESS_SIZE * sizeof(uint64_t); ++i) + lean_byte_array_push(res, *(((uint8_t*)h) + i)); + + return res; +} + +extern lean_obj_arg memset_zero(size_t n) { + lean_object* res = lean_alloc_sarray(1, n, n); + uint8_t* it = lean_sarray_cptr(res); + memset(it, 0, n); + return res; +} + +extern lean_obj_arg keccak256(b_lean_obj_arg input, size_t inBytes) { + uint8_t hash[KECCAK256_OUTPUT_SIZE]; + sha3_HashBuffer(256, SHA3_FLAGS_KECCAK, lean_sarray_cptr(input), inBytes, hash, KECCAK256_OUTPUT_SIZE); + lean_obj_res res = lean_mk_empty_byte_array(lean_box(KECCAK256_OUTPUT_SIZE)); + for (int i = 0; i < KECCAK256_OUTPUT_SIZE; ++i) + lean_byte_array_push(res, hash[i]); + return res; +} From 31abe93a977389df2234027e5f5b8b9673687169 Mon Sep 17 00:00:00 2001 From: alpharush <0xalpharush@protonmail.com> Date: Thu, 12 Nov 2026 22:58:30 -0600 Subject: [PATCH 5/8] feat(tv): move the SolarTV library into solidity-lean --- Certified/README.md | 12 + Certified/bank/Proofs.lean | 3 + Certified/bank/Proofs/Assembly.lean | 42 + Certified/bank/Proofs/Runs/Evm1.lean | 22 + Certified/bank/Proofs/Runs/Evm10.lean | 22 + Certified/bank/Proofs/Runs/Evm11.lean | 22 + Certified/bank/Proofs/Runs/Evm2.lean | 22 + Certified/bank/Proofs/Runs/Evm3.lean | 22 + Certified/bank/Proofs/Runs/Evm4.lean | 22 + Certified/bank/Proofs/Runs/Evm5.lean | 22 + Certified/bank/Proofs/Runs/Evm6.lean | 22 + Certified/bank/Proofs/Runs/Evm7.lean | 22 + Certified/bank/Proofs/Runs/Evm8.lean | 22 + Certified/bank/Proofs/Runs/Evm9.lean | 22 + Certified/bank/Proofs/Runs/Mir1.lean | 22 + Certified/bank/Proofs/Runs/Mir2.lean | 22 + Certified/bank/Proofs/Runs/Mir3.lean | 22 + Certified/bank/Proofs/Runs/Mir4.lean | 22 + Certified/bank/Proofs/Runs/Sched.lean | 22 + Certified/bank/Proofs/Runs/Stage0.lean | 21 + Certified/bank/Proofs/Stages.lean | 275 ++++ Certified/bank/bank.sol | 26 + Certified/bank/bytecode.hex | 1 + Certified/bank/gen/Bank/Bytecode.lean | 42 + Certified/bank/gen/Bank/Evm1.lean | 319 +++++ Certified/bank/gen/Bank/Evm10.lean | 265 ++++ Certified/bank/gen/Bank/Evm11.lean | 263 ++++ Certified/bank/gen/Bank/Evm2.lean | 285 +++++ Certified/bank/gen/Bank/Evm3.lean | 319 +++++ Certified/bank/gen/Bank/Evm4.lean | 319 +++++ Certified/bank/gen/Bank/Evm5.lean | 305 +++++ Certified/bank/gen/Bank/Evm6.lean | 295 +++++ Certified/bank/gen/Bank/Evm7.lean | 268 ++++ Certified/bank/gen/Bank/Evm8.lean | 266 ++++ Certified/bank/gen/Bank/Evm9.lean | 265 ++++ Certified/bank/gen/Bank/Manifest.lean | 52 + Certified/bank/gen/Bank/Mir1.lean | 146 +++ Certified/bank/gen/Bank/Mir2.lean | 150 +++ Certified/bank/gen/Bank/Mir3.lean | 224 ++++ Certified/bank/gen/Bank/Mir4.lean | 224 ++++ Certified/bank/gen/Bank/Sched.lean | 321 +++++ Certified/bank/gen/Bank/Stage0.lean | 144 +++ Certified/bank/gen/Bank/manifest.json | 169 +++ Certified/bank/options | 3 + Certified/c4/Proofs.lean | 3 + Certified/c4/Proofs/Assembly.lean | 42 + Certified/c4/Proofs/Runs/Evm1.lean | 22 + Certified/c4/Proofs/Runs/Evm2.lean | 22 + Certified/c4/Proofs/Runs/Evm3.lean | 22 + Certified/c4/Proofs/Runs/Evm4.lean | 22 + Certified/c4/Proofs/Runs/Evm5.lean | 22 + Certified/c4/Proofs/Runs/Mir1.lean | 22 + Certified/c4/Proofs/Runs/Mir2.lean | 22 + Certified/c4/Proofs/Runs/Sched.lean | 22 + Certified/c4/Proofs/Runs/Stage0.lean | 21 + Certified/c4/Proofs/Stages.lean | 147 +++ Certified/c4/bytecode.hex | 1 + Certified/c4/c4.sol | 3 + Certified/c4/gen/Main/Bytecode.lean | 20 + Certified/c4/gen/Main/Evm1.lean | 90 ++ Certified/c4/gen/Main/Evm2.lean | 92 ++ Certified/c4/gen/Main/Evm3.lean | 92 ++ Certified/c4/gen/Main/Evm4.lean | 90 ++ Certified/c4/gen/Main/Evm5.lean | 86 ++ Certified/c4/gen/Main/Manifest.lean | 42 + Certified/c4/gen/Main/Mir1.lean | 77 ++ Certified/c4/gen/Main/Mir2.lean | 77 ++ Certified/c4/gen/Main/Sched.lean | 98 ++ Certified/c4/gen/Main/Stage0.lean | 76 ++ Certified/c4/gen/Main/manifest.json | 103 ++ Certified/c4/options | 1 + Certified/counter/Proofs.lean | 3 + Certified/counter/Proofs/Assembly.lean | 42 + Certified/counter/Proofs/Runs/Evm1.lean | 22 + Certified/counter/Proofs/Runs/Evm2.lean | 22 + Certified/counter/Proofs/Runs/Evm3.lean | 22 + Certified/counter/Proofs/Runs/Evm4.lean | 22 + Certified/counter/Proofs/Runs/Evm5.lean | 22 + Certified/counter/Proofs/Runs/Sched.lean | 22 + Certified/counter/Proofs/Runs/Stage0.lean | 21 + Certified/counter/Proofs/Stages.lean | 115 ++ Certified/counter/bytecode.hex | 1 + Certified/counter/counter.sol | 7 + Certified/counter/gen/Counter/Bytecode.lean | 19 + Certified/counter/gen/Counter/Evm1.lean | 72 ++ Certified/counter/gen/Counter/Evm2.lean | 72 ++ Certified/counter/gen/Counter/Evm3.lean | 72 ++ Certified/counter/gen/Counter/Evm4.lean | 70 ++ Certified/counter/gen/Counter/Evm5.lean | 66 + Certified/counter/gen/Counter/Manifest.lean | 42 + Certified/counter/gen/Counter/Sched.lean | 82 ++ Certified/counter/gen/Counter/Stage0.lean | 74 ++ Certified/counter/gen/Counter/manifest.json | 89 ++ Certified/counter/options | 3 + Certified/events/Proofs.lean | 3 + Certified/events/Proofs/Assembly.lean | 42 + Certified/events/Proofs/Runs/Evm1.lean | 22 + Certified/events/Proofs/Runs/Evm2.lean | 22 + Certified/events/Proofs/Runs/Evm3.lean | 22 + Certified/events/Proofs/Runs/Evm4.lean | 22 + Certified/events/Proofs/Runs/Evm5.lean | 22 + Certified/events/Proofs/Runs/Mir1.lean | 22 + Certified/events/Proofs/Runs/Sched.lean | 22 + Certified/events/Proofs/Runs/Stage0.lean | 21 + Certified/events/Proofs/Stages.lean | 131 ++ Certified/events/bytecode.hex | 1 + Certified/events/events.sol | 7 + Certified/events/gen/Events/Bytecode.lean | 22 + Certified/events/gen/Events/Evm1.lean | 70 ++ Certified/events/gen/Events/Evm2.lean | 78 ++ Certified/events/gen/Events/Evm3.lean | 78 ++ Certified/events/gen/Events/Evm4.lean | 76 ++ Certified/events/gen/Events/Evm5.lean | 72 ++ Certified/events/gen/Events/Manifest.lean | 43 + Certified/events/gen/Events/Mir1.lean | 70 ++ Certified/events/gen/Events/Sched.lean | 80 ++ Certified/events/gen/Events/Stage0.lean | 55 + Certified/events/gen/Events/manifest.json | 97 ++ Certified/events/options | 3 + Certified/masks/Proofs.lean | 3 + Certified/masks/Proofs/Assembly.lean | 42 + Certified/masks/Proofs/Runs/Evm1.lean | 22 + Certified/masks/Proofs/Runs/Evm2.lean | 22 + Certified/masks/Proofs/Runs/Evm3.lean | 22 + Certified/masks/Proofs/Runs/Evm4.lean | 22 + Certified/masks/Proofs/Runs/Evm5.lean | 22 + Certified/masks/Proofs/Runs/Evm6.lean | 22 + Certified/masks/Proofs/Runs/Mir1.lean | 22 + Certified/masks/Proofs/Runs/Mir2.lean | 22 + Certified/masks/Proofs/Runs/Sched.lean | 22 + Certified/masks/Proofs/Runs/Stage0.lean | 21 + Certified/masks/Proofs/Stages.lean | 163 +++ Certified/masks/bytecode.hex | 1 + Certified/masks/gen/Masks/Bytecode.lean | 24 + Certified/masks/gen/Masks/Evm1.lean | 139 +++ Certified/masks/gen/Masks/Evm2.lean | 121 ++ Certified/masks/gen/Masks/Evm3.lean | 121 ++ Certified/masks/gen/Masks/Evm4.lean | 121 ++ Certified/masks/gen/Masks/Evm5.lean | 117 ++ Certified/masks/gen/Masks/Evm6.lean | 111 ++ Certified/masks/gen/Masks/Manifest.lean | 45 + Certified/masks/gen/Masks/Mir1.lean | 101 ++ Certified/masks/gen/Masks/Mir2.lean | 116 ++ Certified/masks/gen/Masks/Sched.lean | 140 +++ Certified/masks/gen/Masks/Stage0.lean | 100 ++ Certified/masks/gen/Masks/manifest.json | 113 ++ Certified/masks/masks.sol | 14 + Certified/masks/options | 3 + Certified/mulx/Proofs.lean | 3 + Certified/mulx/Proofs/Assembly.lean | 42 + Certified/mulx/Proofs/Runs/Evm1.lean | 22 + Certified/mulx/Proofs/Runs/Evm2.lean | 22 + Certified/mulx/Proofs/Runs/Evm3.lean | 22 + Certified/mulx/Proofs/Runs/Evm4.lean | 22 + Certified/mulx/Proofs/Runs/Evm5.lean | 22 + Certified/mulx/Proofs/Runs/Evm6.lean | 22 + Certified/mulx/Proofs/Runs/Evm7.lean | 22 + Certified/mulx/Proofs/Runs/Evm8.lean | 22 + Certified/mulx/Proofs/Runs/Mir1.lean | 22 + Certified/mulx/Proofs/Runs/Mir2.lean | 22 + Certified/mulx/Proofs/Runs/Mir3.lean | 22 + Certified/mulx/Proofs/Runs/Sched.lean | 22 + Certified/mulx/Proofs/Runs/Stage0.lean | 21 + Certified/mulx/Proofs/Stages.lean | 211 ++++ Certified/mulx/bytecode.hex | 1 + Certified/mulx/gen/Main/Bytecode.lean | 25 + Certified/mulx/gen/Main/Evm1.lean | 159 +++ Certified/mulx/gen/Main/Evm2.lean | 161 +++ Certified/mulx/gen/Main/Evm3.lean | 161 +++ Certified/mulx/gen/Main/Evm4.lean | 149 +++ Certified/mulx/gen/Main/Evm5.lean | 143 +++ Certified/mulx/gen/Main/Evm6.lean | 143 +++ Certified/mulx/gen/Main/Evm7.lean | 142 +++ Certified/mulx/gen/Main/Evm8.lean | 142 +++ Certified/mulx/gen/Main/Manifest.lean | 46 + Certified/mulx/gen/Main/Mir1.lean | 126 ++ Certified/mulx/gen/Main/Mir2.lean | 132 ++ Certified/mulx/gen/Main/Mir3.lean | 132 ++ Certified/mulx/gen/Main/Sched.lean | 173 +++ Certified/mulx/gen/Main/Stage0.lean | 122 ++ Certified/mulx/gen/Main/manifest.json | 135 ++ Certified/mulx/mulx.sol | 9 + Certified/mulx/options | 1 + Certified/reader/Proofs.lean | 3 + Certified/reader/Proofs/Assembly.lean | 42 + Certified/reader/Proofs/Runs/Evm1.lean | 22 + Certified/reader/Proofs/Runs/Evm2.lean | 22 + Certified/reader/Proofs/Runs/Evm3.lean | 22 + Certified/reader/Proofs/Runs/Evm4.lean | 22 + Certified/reader/Proofs/Runs/Evm5.lean | 22 + Certified/reader/Proofs/Runs/Evm6.lean | 22 + Certified/reader/Proofs/Runs/Evm7.lean | 22 + Certified/reader/Proofs/Runs/Mir1.lean | 22 + Certified/reader/Proofs/Runs/Mir2.lean | 22 + Certified/reader/Proofs/Runs/Mir3.lean | 22 + Certified/reader/Proofs/Runs/Sched.lean | 22 + Certified/reader/Proofs/Runs/Stage0.lean | 21 + Certified/reader/Proofs/Stages.lean | 195 +++ Certified/reader/bytecode.hex | 1 + Certified/reader/gen/Reader/Bytecode.lean | 21 + Certified/reader/gen/Reader/Evm1.lean | 92 ++ Certified/reader/gen/Reader/Evm2.lean | 92 ++ Certified/reader/gen/Reader/Evm3.lean | 90 ++ Certified/reader/gen/Reader/Evm4.lean | 88 ++ Certified/reader/gen/Reader/Evm5.lean | 88 ++ Certified/reader/gen/Reader/Evm6.lean | 88 ++ Certified/reader/gen/Reader/Evm7.lean | 86 ++ Certified/reader/gen/Reader/Manifest.lean | 47 + Certified/reader/gen/Reader/Mir1.lean | 83 ++ Certified/reader/gen/Reader/Mir2.lean | 85 ++ Certified/reader/gen/Reader/Mir3.lean | 85 ++ Certified/reader/gen/Reader/Sched.lean | 104 ++ Certified/reader/gen/Reader/Stage0.lean | 82 ++ Certified/reader/gen/Reader/manifest.json | 129 ++ Certified/reader/options | 3 + Certified/reader/reader.sol | 13 + Certified/token/Proofs.lean | 3 + Certified/token/Proofs/Assembly.lean | 42 + Certified/token/Proofs/Runs/Evm1.lean | 23 + Certified/token/Proofs/Runs/Evm10.lean | 23 + Certified/token/Proofs/Runs/Evm11.lean | 23 + Certified/token/Proofs/Runs/Evm2.lean | 23 + Certified/token/Proofs/Runs/Evm3.lean | 23 + Certified/token/Proofs/Runs/Evm4.lean | 23 + Certified/token/Proofs/Runs/Evm5.lean | 23 + Certified/token/Proofs/Runs/Evm6.lean | 23 + Certified/token/Proofs/Runs/Evm7.lean | 23 + Certified/token/Proofs/Runs/Evm8.lean | 23 + Certified/token/Proofs/Runs/Evm9.lean | 23 + Certified/token/Proofs/Runs/Mir1.lean | 23 + Certified/token/Proofs/Runs/Mir2.lean | 23 + Certified/token/Proofs/Runs/Mir3.lean | 23 + Certified/token/Proofs/Runs/Mir4.lean | 23 + Certified/token/Proofs/Runs/Sched.lean | 23 + Certified/token/Proofs/Runs/Stage0.lean | 22 + Certified/token/Proofs/Stages.lean | 275 ++++ Certified/token/bytecode.hex | 1 + Certified/token/gen/Token/Bytecode.lean | 61 + Certified/token/gen/Token/Evm1.lean | 567 +++++++++ Certified/token/gen/Token/Evm10.lean | 486 ++++++++ Certified/token/gen/Token/Evm11.lean | 484 +++++++ Certified/token/gen/Token/Evm2.lean | 519 ++++++++ Certified/token/gen/Token/Evm3.lean | 529 ++++++++ Certified/token/gen/Token/Evm4.lean | 529 ++++++++ Certified/token/gen/Token/Evm5.lean | 507 ++++++++ Certified/token/gen/Token/Evm6.lean | 491 ++++++++ Certified/token/gen/Token/Evm7.lean | 484 +++++++ Certified/token/gen/Token/Evm8.lean | 484 +++++++ Certified/token/gen/Token/Evm9.lean | 484 +++++++ Certified/token/gen/Token/Manifest.lean | 53 + Certified/token/gen/Token/Mir1.lean | 369 ++++++ Certified/token/gen/Token/Mir2.lean | 368 ++++++ Certified/token/gen/Token/Mir3.lean | 382 ++++++ Certified/token/gen/Token/Mir4.lean | 382 ++++++ Certified/token/gen/Token/Sched.lean | 568 +++++++++ Certified/token/gen/Token/Stage0.lean | 359 ++++++ Certified/token/gen/Token/manifest.json | 170 +++ Certified/token/options | 4 + Certified/token/token.sol | 60 + Certified/w1/W1.lean | 2 + Certified/w1/W1/Sanity.lean | 110 ++ Certified/w1/gen/Main/Bytecode.lean | 18 + Certified/w1/gen/Main/Evm1.lean | 62 + Certified/w1/gen/Main/Evm2.lean | 62 + Certified/w1/gen/Main/Evm3.lean | 60 + Certified/w1/gen/Main/Evm4.lean | 56 + Certified/w1/gen/Main/Manifest.lean | 41 + Certified/w1/gen/Main/Sched.lean | 70 ++ Certified/w1/gen/Main/Stage0.lean | 62 + Certified/w1/gen/Main/manifest.json | 81 ++ Certified/w1/gen/Stages.lean | 9 + Certified/w1/w1.sol | 3 + Certified/w4/Proofs.lean | 3 + Certified/w4/Proofs/Assembly.lean | 42 + Certified/w4/Proofs/Runs/Evm1.lean | 22 + Certified/w4/Proofs/Runs/Evm2.lean | 22 + Certified/w4/Proofs/Runs/Evm3.lean | 22 + Certified/w4/Proofs/Runs/Evm4.lean | 22 + Certified/w4/Proofs/Runs/Sched.lean | 22 + Certified/w4/Proofs/Runs/Stage0.lean | 21 + Certified/w4/Proofs/Stages.lean | 99 ++ Certified/w4/bytecode.hex | 1 + Certified/w4/gen/Main/Bytecode.lean | 16 + Certified/w4/gen/Main/Evm1.lean | 42 + Certified/w4/gen/Main/Evm2.lean | 42 + Certified/w4/gen/Main/Evm3.lean | 40 + Certified/w4/gen/Main/Evm4.lean | 36 + Certified/w4/gen/Main/Manifest.lean | 41 + Certified/w4/gen/Main/Sched.lean | 48 + Certified/w4/gen/Main/Stage0.lean | 51 + Certified/w4/gen/Main/manifest.json | 81 ++ Certified/w4/options | 3 + Certified/w4/w4.sol | 8 + SolidCore/Refinement/Solar/Assemble.lean | 44 +- SolidCore/Refinement/Solar/AssembleSim.lean | 8 +- lake-manifest.json | 127 +- lakefile.lean | 118 +- scripts/check-evm-rules-vendor.sh | 9 + tv/SolarTV.lean | 255 ++++ tv/SolarTV/Agreement/Encoder.lean | 768 ++++++++++++ tv/SolarTV/Agreement/Tactic.lean | 552 ++++++++ tv/SolarTV/Composition.lean | 112 ++ tv/SolarTV/CutPoint.lean | 533 ++++++++ tv/SolarTV/CutPointExamples.lean | 190 +++ tv/SolarTV/EVMIR/Gas.lean | 143 +++ tv/SolarTV/EVMIR/GasSafety.lean | 42 + tv/SolarTV/EVMIR/Memory.lean | 87 ++ tv/SolarTV/EVMIR/Ops.lean | 159 +++ tv/SolarTV/EVMIR/Precompiles/BLS12381.lean | 89 ++ tv/SolarTV/EVMIR/Precompiles/BN254.lean | 51 + tv/SolarTV/EVMIR/Precompiles/Blake2F.lean | 51 + tv/SolarTV/EVMIR/Precompiles/Bytes.lean | 31 + tv/SolarTV/EVMIR/Precompiles/Curve.lean | 66 + tv/SolarTV/EVMIR/Precompiles/Execute.lean | 81 ++ tv/SolarTV/EVMIR/Precompiles/Field.lean | 79 ++ tv/SolarTV/EVMIR/Precompiles/Gas.lean | 74 ++ tv/SolarTV/EVMIR/Precompiles/KZG.lean | 63 + .../EVMIR/Precompiles/MapConstants.lean | 98 ++ tv/SolarTV/EVMIR/Precompiles/Maps.lean | 58 + tv/SolarTV/EVMIR/Precompiles/Observe.lean | 24 + tv/SolarTV/EVMIR/Precompiles/Pairing.lean | 81 ++ tv/SolarTV/EVMIR/Precompiles/RIPEMD160.lean | 72 ++ tv/SolarTV/EVMIR/Precompiles/SHA256.lean | 52 + tv/SolarTV/EVMIR/Precompiles/Safety.lean | 22 + tv/SolarTV/EVMIR/Precompiles/Signatures.lean | 56 + tv/SolarTV/EVMIR/Program.lean | 196 +++ tv/SolarTV/EVMIR/StackSafety.lean | 75 ++ tv/SolarTV/EVMIR/State/Create.lean | 42 + tv/SolarTV/EVMIR/State/Decode.lean | 52 + tv/SolarTV/EVMIR/State/Delegation.lean | 36 + tv/SolarTV/EVMIR/State/Environment.lean | 22 + tv/SolarTV/EVMIR/State/Interpreter.lean | 314 +++++ tv/SolarTV/EVMIR/State/Messages.lean | 87 ++ tv/SolarTV/EVMIR/State/Normalize.lean | 35 + tv/SolarTV/EVMIR/State/Observe.lean | 81 ++ tv/SolarTV/EVMIR/State/Safety.lean | 60 + tv/SolarTV/EVMIR/State/Selfdestruct.lean | 35 + tv/SolarTV/EVMIR/State/Types.lean | 70 ++ .../EVMIR/Transforms/EqIszeroJumpi.lean | 21 + tv/SolarTV/EVMIR/Transforms/GasSwapAdd.lean | 25 + .../EVMIR/Transforms/StackPeephole.lean | 19 + tv/SolarTV/Keccak.lean | 70 ++ tv/SolarTV/KeccakSafety.lean | 33 + tv/SolarTV/MIR/Ops.lean | 149 +++ tv/SolarTV/MIR/Program.lean | 434 +++++++ tv/SolarTV/MIR/State/Aggregates.lean | 54 + tv/SolarTV/MIR/State/Allocation.lean | 34 + tv/SolarTV/MIR/State/IR.lean | 192 +++ tv/SolarTV/MIR/State/Interpreter.lean | 199 +++ tv/SolarTV/MIR/State/Messages.lean | 64 + tv/SolarTV/MIR/State/Normalize.lean | 42 + tv/SolarTV/MIR/State/Observe.lean | 80 ++ tv/SolarTV/MIR/State/Ops.lean | 162 +++ tv/SolarTV/MIR/State/Safety.lean | 59 + tv/SolarTV/MIR/State/Values.lean | 121 ++ tv/SolarTV/MIR/Transforms/Casts.lean | 42 + tv/SolarTV/MIR/Transforms/CheckElim.lean | 19 + tv/SolarTV/MIR/Transforms/DCE.lean | 18 + tv/SolarTV/MIR/Transforms/DeadStore.lean | 18 + .../MIR/Transforms/RenamePhiPredecessors.lean | 22 + .../MIR/Transforms/TrimSwitchDefaults.lean | 47 + tv/SolarTV/MIR/Validation/AddZero.lean | 107 ++ tv/SolarTV/Machine.lean | 672 ++++++++++ tv/SolarTV/Memory.lean | 116 ++ tv/SolarTV/MemorySafety.lean | 19 + tv/SolarTV/MemorySymbolic.lean | 264 ++++ tv/SolarTV/MemorySymbolicSafety.lean | 183 +++ tv/SolarTV/Outcome.lean | 116 ++ tv/SolarTV/Sem.lean | 64 + tv/SolarTV/Stages/Assembly.lean | 248 ++++ tv/SolarTV/Stages/AssemblyCheck.lean | 74 ++ tv/SolarTV/Stages/Entries.lean | 93 ++ tv/SolarTV/Stages/Link.lean | 351 ++++++ tv/SolarTV/State/ByteMemory.lean | 34 + tv/SolarTV/State/Calls.lean | 142 +++ tv/SolarTV/State/Context.lean | 46 + tv/SolarTV/State/Fork.lean | 22 + tv/SolarTV/State/Journal.lean | 88 ++ tv/SolarTV/State/MemoryLaws.lean | 76 ++ tv/SolarTV/State/Storage.lean | 123 ++ tv/SolarTV/State/StorageSafety.lean | 32 + tv/SolarTV/State/World.lean | 87 ++ tv/SolarTV/Word.lean | 56 + tv/SolarTV/WordSafety.lean | 37 + tv/W1Proofs.lean | 3 + tv/W1Proofs/Assembly.lean | 42 + tv/W1Proofs/Axioms.lean | 25 + tv/W1Proofs/Items.lean | 268 ++++ tv/W1Proofs/Runs/Evm1.lean | 22 + tv/W1Proofs/Runs/Evm2.lean | 22 + tv/W1Proofs/Runs/Evm3.lean | 22 + tv/W1Proofs/Runs/Evm4.lean | 22 + tv/W1Proofs/Runs/Sched.lean | 22 + tv/W1Proofs/Runs/Stage0.lean | 21 + tv/W1Proofs/Segment.lean | 154 +++ tv/W1Proofs/Stage.lean | 41 + tv/W1Proofs/Stages.lean | 99 ++ tv/W1Proofs/Tactic.lean | 1108 +++++++++++++++++ vendor/evm-rules/EvmRules.lean | 10 + vendor/evm-rules/EvmRules/Arith.lean | 244 ++++ vendor/evm-rules/EvmRules/ArithTactic.lean | 112 ++ vendor/evm-rules/EvmRules/Bitblast.lean | 42 + vendor/evm-rules/EvmRules/Bits.lean | 133 ++ vendor/evm-rules/EvmRules/Casts.lean | 173 +++ vendor/evm-rules/EvmRules/Lemmas.lean | 130 ++ vendor/evm-rules/EvmRules/Reference.lean | 207 +++ vendor/evm-rules/EvmRules/Simp.lean | 234 ++++ vendor/evm-rules/EvmRules/Tactic.lean | 101 ++ vendor/evm-rules/EvmRules/Word.lean | 141 +++ vendor/evm-rules/README.md | 10 + 410 files changed, 39005 insertions(+), 83 deletions(-) create mode 100644 Certified/README.md create mode 100644 Certified/bank/Proofs.lean create mode 100644 Certified/bank/Proofs/Assembly.lean create mode 100644 Certified/bank/Proofs/Runs/Evm1.lean create mode 100644 Certified/bank/Proofs/Runs/Evm10.lean create mode 100644 Certified/bank/Proofs/Runs/Evm11.lean create mode 100644 Certified/bank/Proofs/Runs/Evm2.lean create mode 100644 Certified/bank/Proofs/Runs/Evm3.lean create mode 100644 Certified/bank/Proofs/Runs/Evm4.lean create mode 100644 Certified/bank/Proofs/Runs/Evm5.lean create mode 100644 Certified/bank/Proofs/Runs/Evm6.lean create mode 100644 Certified/bank/Proofs/Runs/Evm7.lean create mode 100644 Certified/bank/Proofs/Runs/Evm8.lean create mode 100644 Certified/bank/Proofs/Runs/Evm9.lean create mode 100644 Certified/bank/Proofs/Runs/Mir1.lean create mode 100644 Certified/bank/Proofs/Runs/Mir2.lean create mode 100644 Certified/bank/Proofs/Runs/Mir3.lean create mode 100644 Certified/bank/Proofs/Runs/Mir4.lean create mode 100644 Certified/bank/Proofs/Runs/Sched.lean create mode 100644 Certified/bank/Proofs/Runs/Stage0.lean create mode 100644 Certified/bank/Proofs/Stages.lean create mode 100644 Certified/bank/bank.sol create mode 100644 Certified/bank/bytecode.hex create mode 100644 Certified/bank/gen/Bank/Bytecode.lean create mode 100644 Certified/bank/gen/Bank/Evm1.lean create mode 100644 Certified/bank/gen/Bank/Evm10.lean create mode 100644 Certified/bank/gen/Bank/Evm11.lean create mode 100644 Certified/bank/gen/Bank/Evm2.lean create mode 100644 Certified/bank/gen/Bank/Evm3.lean create mode 100644 Certified/bank/gen/Bank/Evm4.lean create mode 100644 Certified/bank/gen/Bank/Evm5.lean create mode 100644 Certified/bank/gen/Bank/Evm6.lean create mode 100644 Certified/bank/gen/Bank/Evm7.lean create mode 100644 Certified/bank/gen/Bank/Evm8.lean create mode 100644 Certified/bank/gen/Bank/Evm9.lean create mode 100644 Certified/bank/gen/Bank/Manifest.lean create mode 100644 Certified/bank/gen/Bank/Mir1.lean create mode 100644 Certified/bank/gen/Bank/Mir2.lean create mode 100644 Certified/bank/gen/Bank/Mir3.lean create mode 100644 Certified/bank/gen/Bank/Mir4.lean create mode 100644 Certified/bank/gen/Bank/Sched.lean create mode 100644 Certified/bank/gen/Bank/Stage0.lean create mode 100644 Certified/bank/gen/Bank/manifest.json create mode 100644 Certified/bank/options create mode 100644 Certified/c4/Proofs.lean create mode 100644 Certified/c4/Proofs/Assembly.lean create mode 100644 Certified/c4/Proofs/Runs/Evm1.lean create mode 100644 Certified/c4/Proofs/Runs/Evm2.lean create mode 100644 Certified/c4/Proofs/Runs/Evm3.lean create mode 100644 Certified/c4/Proofs/Runs/Evm4.lean create mode 100644 Certified/c4/Proofs/Runs/Evm5.lean create mode 100644 Certified/c4/Proofs/Runs/Mir1.lean create mode 100644 Certified/c4/Proofs/Runs/Mir2.lean create mode 100644 Certified/c4/Proofs/Runs/Sched.lean create mode 100644 Certified/c4/Proofs/Runs/Stage0.lean create mode 100644 Certified/c4/Proofs/Stages.lean create mode 100644 Certified/c4/bytecode.hex create mode 100644 Certified/c4/c4.sol create mode 100644 Certified/c4/gen/Main/Bytecode.lean create mode 100644 Certified/c4/gen/Main/Evm1.lean create mode 100644 Certified/c4/gen/Main/Evm2.lean create mode 100644 Certified/c4/gen/Main/Evm3.lean create mode 100644 Certified/c4/gen/Main/Evm4.lean create mode 100644 Certified/c4/gen/Main/Evm5.lean create mode 100644 Certified/c4/gen/Main/Manifest.lean create mode 100644 Certified/c4/gen/Main/Mir1.lean create mode 100644 Certified/c4/gen/Main/Mir2.lean create mode 100644 Certified/c4/gen/Main/Sched.lean create mode 100644 Certified/c4/gen/Main/Stage0.lean create mode 100644 Certified/c4/gen/Main/manifest.json create mode 100644 Certified/c4/options create mode 100644 Certified/counter/Proofs.lean create mode 100644 Certified/counter/Proofs/Assembly.lean create mode 100644 Certified/counter/Proofs/Runs/Evm1.lean create mode 100644 Certified/counter/Proofs/Runs/Evm2.lean create mode 100644 Certified/counter/Proofs/Runs/Evm3.lean create mode 100644 Certified/counter/Proofs/Runs/Evm4.lean create mode 100644 Certified/counter/Proofs/Runs/Evm5.lean create mode 100644 Certified/counter/Proofs/Runs/Sched.lean create mode 100644 Certified/counter/Proofs/Runs/Stage0.lean create mode 100644 Certified/counter/Proofs/Stages.lean create mode 100644 Certified/counter/bytecode.hex create mode 100644 Certified/counter/counter.sol create mode 100644 Certified/counter/gen/Counter/Bytecode.lean create mode 100644 Certified/counter/gen/Counter/Evm1.lean create mode 100644 Certified/counter/gen/Counter/Evm2.lean create mode 100644 Certified/counter/gen/Counter/Evm3.lean create mode 100644 Certified/counter/gen/Counter/Evm4.lean create mode 100644 Certified/counter/gen/Counter/Evm5.lean create mode 100644 Certified/counter/gen/Counter/Manifest.lean create mode 100644 Certified/counter/gen/Counter/Sched.lean create mode 100644 Certified/counter/gen/Counter/Stage0.lean create mode 100644 Certified/counter/gen/Counter/manifest.json create mode 100644 Certified/counter/options create mode 100644 Certified/events/Proofs.lean create mode 100644 Certified/events/Proofs/Assembly.lean create mode 100644 Certified/events/Proofs/Runs/Evm1.lean create mode 100644 Certified/events/Proofs/Runs/Evm2.lean create mode 100644 Certified/events/Proofs/Runs/Evm3.lean create mode 100644 Certified/events/Proofs/Runs/Evm4.lean create mode 100644 Certified/events/Proofs/Runs/Evm5.lean create mode 100644 Certified/events/Proofs/Runs/Mir1.lean create mode 100644 Certified/events/Proofs/Runs/Sched.lean create mode 100644 Certified/events/Proofs/Runs/Stage0.lean create mode 100644 Certified/events/Proofs/Stages.lean create mode 100644 Certified/events/bytecode.hex create mode 100644 Certified/events/events.sol create mode 100644 Certified/events/gen/Events/Bytecode.lean create mode 100644 Certified/events/gen/Events/Evm1.lean create mode 100644 Certified/events/gen/Events/Evm2.lean create mode 100644 Certified/events/gen/Events/Evm3.lean create mode 100644 Certified/events/gen/Events/Evm4.lean create mode 100644 Certified/events/gen/Events/Evm5.lean create mode 100644 Certified/events/gen/Events/Manifest.lean create mode 100644 Certified/events/gen/Events/Mir1.lean create mode 100644 Certified/events/gen/Events/Sched.lean create mode 100644 Certified/events/gen/Events/Stage0.lean create mode 100644 Certified/events/gen/Events/manifest.json create mode 100644 Certified/events/options create mode 100644 Certified/masks/Proofs.lean create mode 100644 Certified/masks/Proofs/Assembly.lean create mode 100644 Certified/masks/Proofs/Runs/Evm1.lean create mode 100644 Certified/masks/Proofs/Runs/Evm2.lean create mode 100644 Certified/masks/Proofs/Runs/Evm3.lean create mode 100644 Certified/masks/Proofs/Runs/Evm4.lean create mode 100644 Certified/masks/Proofs/Runs/Evm5.lean create mode 100644 Certified/masks/Proofs/Runs/Evm6.lean create mode 100644 Certified/masks/Proofs/Runs/Mir1.lean create mode 100644 Certified/masks/Proofs/Runs/Mir2.lean create mode 100644 Certified/masks/Proofs/Runs/Sched.lean create mode 100644 Certified/masks/Proofs/Runs/Stage0.lean create mode 100644 Certified/masks/Proofs/Stages.lean create mode 100644 Certified/masks/bytecode.hex create mode 100644 Certified/masks/gen/Masks/Bytecode.lean create mode 100644 Certified/masks/gen/Masks/Evm1.lean create mode 100644 Certified/masks/gen/Masks/Evm2.lean create mode 100644 Certified/masks/gen/Masks/Evm3.lean create mode 100644 Certified/masks/gen/Masks/Evm4.lean create mode 100644 Certified/masks/gen/Masks/Evm5.lean create mode 100644 Certified/masks/gen/Masks/Evm6.lean create mode 100644 Certified/masks/gen/Masks/Manifest.lean create mode 100644 Certified/masks/gen/Masks/Mir1.lean create mode 100644 Certified/masks/gen/Masks/Mir2.lean create mode 100644 Certified/masks/gen/Masks/Sched.lean create mode 100644 Certified/masks/gen/Masks/Stage0.lean create mode 100644 Certified/masks/gen/Masks/manifest.json create mode 100644 Certified/masks/masks.sol create mode 100644 Certified/masks/options create mode 100644 Certified/mulx/Proofs.lean create mode 100644 Certified/mulx/Proofs/Assembly.lean create mode 100644 Certified/mulx/Proofs/Runs/Evm1.lean create mode 100644 Certified/mulx/Proofs/Runs/Evm2.lean create mode 100644 Certified/mulx/Proofs/Runs/Evm3.lean create mode 100644 Certified/mulx/Proofs/Runs/Evm4.lean create mode 100644 Certified/mulx/Proofs/Runs/Evm5.lean create mode 100644 Certified/mulx/Proofs/Runs/Evm6.lean create mode 100644 Certified/mulx/Proofs/Runs/Evm7.lean create mode 100644 Certified/mulx/Proofs/Runs/Evm8.lean create mode 100644 Certified/mulx/Proofs/Runs/Mir1.lean create mode 100644 Certified/mulx/Proofs/Runs/Mir2.lean create mode 100644 Certified/mulx/Proofs/Runs/Mir3.lean create mode 100644 Certified/mulx/Proofs/Runs/Sched.lean create mode 100644 Certified/mulx/Proofs/Runs/Stage0.lean create mode 100644 Certified/mulx/Proofs/Stages.lean create mode 100644 Certified/mulx/bytecode.hex create mode 100644 Certified/mulx/gen/Main/Bytecode.lean create mode 100644 Certified/mulx/gen/Main/Evm1.lean create mode 100644 Certified/mulx/gen/Main/Evm2.lean create mode 100644 Certified/mulx/gen/Main/Evm3.lean create mode 100644 Certified/mulx/gen/Main/Evm4.lean create mode 100644 Certified/mulx/gen/Main/Evm5.lean create mode 100644 Certified/mulx/gen/Main/Evm6.lean create mode 100644 Certified/mulx/gen/Main/Evm7.lean create mode 100644 Certified/mulx/gen/Main/Evm8.lean create mode 100644 Certified/mulx/gen/Main/Manifest.lean create mode 100644 Certified/mulx/gen/Main/Mir1.lean create mode 100644 Certified/mulx/gen/Main/Mir2.lean create mode 100644 Certified/mulx/gen/Main/Mir3.lean create mode 100644 Certified/mulx/gen/Main/Sched.lean create mode 100644 Certified/mulx/gen/Main/Stage0.lean create mode 100644 Certified/mulx/gen/Main/manifest.json create mode 100644 Certified/mulx/mulx.sol create mode 100644 Certified/mulx/options create mode 100644 Certified/reader/Proofs.lean create mode 100644 Certified/reader/Proofs/Assembly.lean create mode 100644 Certified/reader/Proofs/Runs/Evm1.lean create mode 100644 Certified/reader/Proofs/Runs/Evm2.lean create mode 100644 Certified/reader/Proofs/Runs/Evm3.lean create mode 100644 Certified/reader/Proofs/Runs/Evm4.lean create mode 100644 Certified/reader/Proofs/Runs/Evm5.lean create mode 100644 Certified/reader/Proofs/Runs/Evm6.lean create mode 100644 Certified/reader/Proofs/Runs/Evm7.lean create mode 100644 Certified/reader/Proofs/Runs/Mir1.lean create mode 100644 Certified/reader/Proofs/Runs/Mir2.lean create mode 100644 Certified/reader/Proofs/Runs/Mir3.lean create mode 100644 Certified/reader/Proofs/Runs/Sched.lean create mode 100644 Certified/reader/Proofs/Runs/Stage0.lean create mode 100644 Certified/reader/Proofs/Stages.lean create mode 100644 Certified/reader/bytecode.hex create mode 100644 Certified/reader/gen/Reader/Bytecode.lean create mode 100644 Certified/reader/gen/Reader/Evm1.lean create mode 100644 Certified/reader/gen/Reader/Evm2.lean create mode 100644 Certified/reader/gen/Reader/Evm3.lean create mode 100644 Certified/reader/gen/Reader/Evm4.lean create mode 100644 Certified/reader/gen/Reader/Evm5.lean create mode 100644 Certified/reader/gen/Reader/Evm6.lean create mode 100644 Certified/reader/gen/Reader/Evm7.lean create mode 100644 Certified/reader/gen/Reader/Manifest.lean create mode 100644 Certified/reader/gen/Reader/Mir1.lean create mode 100644 Certified/reader/gen/Reader/Mir2.lean create mode 100644 Certified/reader/gen/Reader/Mir3.lean create mode 100644 Certified/reader/gen/Reader/Sched.lean create mode 100644 Certified/reader/gen/Reader/Stage0.lean create mode 100644 Certified/reader/gen/Reader/manifest.json create mode 100644 Certified/reader/options create mode 100644 Certified/reader/reader.sol create mode 100644 Certified/token/Proofs.lean create mode 100644 Certified/token/Proofs/Assembly.lean create mode 100644 Certified/token/Proofs/Runs/Evm1.lean create mode 100644 Certified/token/Proofs/Runs/Evm10.lean create mode 100644 Certified/token/Proofs/Runs/Evm11.lean create mode 100644 Certified/token/Proofs/Runs/Evm2.lean create mode 100644 Certified/token/Proofs/Runs/Evm3.lean create mode 100644 Certified/token/Proofs/Runs/Evm4.lean create mode 100644 Certified/token/Proofs/Runs/Evm5.lean create mode 100644 Certified/token/Proofs/Runs/Evm6.lean create mode 100644 Certified/token/Proofs/Runs/Evm7.lean create mode 100644 Certified/token/Proofs/Runs/Evm8.lean create mode 100644 Certified/token/Proofs/Runs/Evm9.lean create mode 100644 Certified/token/Proofs/Runs/Mir1.lean create mode 100644 Certified/token/Proofs/Runs/Mir2.lean create mode 100644 Certified/token/Proofs/Runs/Mir3.lean create mode 100644 Certified/token/Proofs/Runs/Mir4.lean create mode 100644 Certified/token/Proofs/Runs/Sched.lean create mode 100644 Certified/token/Proofs/Runs/Stage0.lean create mode 100644 Certified/token/Proofs/Stages.lean create mode 100644 Certified/token/bytecode.hex create mode 100644 Certified/token/gen/Token/Bytecode.lean create mode 100644 Certified/token/gen/Token/Evm1.lean create mode 100644 Certified/token/gen/Token/Evm10.lean create mode 100644 Certified/token/gen/Token/Evm11.lean create mode 100644 Certified/token/gen/Token/Evm2.lean create mode 100644 Certified/token/gen/Token/Evm3.lean create mode 100644 Certified/token/gen/Token/Evm4.lean create mode 100644 Certified/token/gen/Token/Evm5.lean create mode 100644 Certified/token/gen/Token/Evm6.lean create mode 100644 Certified/token/gen/Token/Evm7.lean create mode 100644 Certified/token/gen/Token/Evm8.lean create mode 100644 Certified/token/gen/Token/Evm9.lean create mode 100644 Certified/token/gen/Token/Manifest.lean create mode 100644 Certified/token/gen/Token/Mir1.lean create mode 100644 Certified/token/gen/Token/Mir2.lean create mode 100644 Certified/token/gen/Token/Mir3.lean create mode 100644 Certified/token/gen/Token/Mir4.lean create mode 100644 Certified/token/gen/Token/Sched.lean create mode 100644 Certified/token/gen/Token/Stage0.lean create mode 100644 Certified/token/gen/Token/manifest.json create mode 100644 Certified/token/options create mode 100644 Certified/token/token.sol create mode 100644 Certified/w1/W1.lean create mode 100644 Certified/w1/W1/Sanity.lean create mode 100644 Certified/w1/gen/Main/Bytecode.lean create mode 100644 Certified/w1/gen/Main/Evm1.lean create mode 100644 Certified/w1/gen/Main/Evm2.lean create mode 100644 Certified/w1/gen/Main/Evm3.lean create mode 100644 Certified/w1/gen/Main/Evm4.lean create mode 100644 Certified/w1/gen/Main/Manifest.lean create mode 100644 Certified/w1/gen/Main/Sched.lean create mode 100644 Certified/w1/gen/Main/Stage0.lean create mode 100644 Certified/w1/gen/Main/manifest.json create mode 100644 Certified/w1/gen/Stages.lean create mode 100644 Certified/w1/w1.sol create mode 100644 Certified/w4/Proofs.lean create mode 100644 Certified/w4/Proofs/Assembly.lean create mode 100644 Certified/w4/Proofs/Runs/Evm1.lean create mode 100644 Certified/w4/Proofs/Runs/Evm2.lean create mode 100644 Certified/w4/Proofs/Runs/Evm3.lean create mode 100644 Certified/w4/Proofs/Runs/Evm4.lean create mode 100644 Certified/w4/Proofs/Runs/Sched.lean create mode 100644 Certified/w4/Proofs/Runs/Stage0.lean create mode 100644 Certified/w4/Proofs/Stages.lean create mode 100644 Certified/w4/bytecode.hex create mode 100644 Certified/w4/gen/Main/Bytecode.lean create mode 100644 Certified/w4/gen/Main/Evm1.lean create mode 100644 Certified/w4/gen/Main/Evm2.lean create mode 100644 Certified/w4/gen/Main/Evm3.lean create mode 100644 Certified/w4/gen/Main/Evm4.lean create mode 100644 Certified/w4/gen/Main/Manifest.lean create mode 100644 Certified/w4/gen/Main/Sched.lean create mode 100644 Certified/w4/gen/Main/Stage0.lean create mode 100644 Certified/w4/gen/Main/manifest.json create mode 100644 Certified/w4/options create mode 100644 Certified/w4/w4.sol create mode 100755 scripts/check-evm-rules-vendor.sh create mode 100644 tv/SolarTV.lean create mode 100644 tv/SolarTV/Agreement/Encoder.lean create mode 100644 tv/SolarTV/Agreement/Tactic.lean create mode 100644 tv/SolarTV/Composition.lean create mode 100644 tv/SolarTV/CutPoint.lean create mode 100644 tv/SolarTV/CutPointExamples.lean create mode 100644 tv/SolarTV/EVMIR/Gas.lean create mode 100644 tv/SolarTV/EVMIR/GasSafety.lean create mode 100644 tv/SolarTV/EVMIR/Memory.lean create mode 100644 tv/SolarTV/EVMIR/Ops.lean create mode 100644 tv/SolarTV/EVMIR/Precompiles/BLS12381.lean create mode 100644 tv/SolarTV/EVMIR/Precompiles/BN254.lean create mode 100644 tv/SolarTV/EVMIR/Precompiles/Blake2F.lean create mode 100644 tv/SolarTV/EVMIR/Precompiles/Bytes.lean create mode 100644 tv/SolarTV/EVMIR/Precompiles/Curve.lean create mode 100644 tv/SolarTV/EVMIR/Precompiles/Execute.lean create mode 100644 tv/SolarTV/EVMIR/Precompiles/Field.lean create mode 100644 tv/SolarTV/EVMIR/Precompiles/Gas.lean create mode 100644 tv/SolarTV/EVMIR/Precompiles/KZG.lean create mode 100644 tv/SolarTV/EVMIR/Precompiles/MapConstants.lean create mode 100644 tv/SolarTV/EVMIR/Precompiles/Maps.lean create mode 100644 tv/SolarTV/EVMIR/Precompiles/Observe.lean create mode 100644 tv/SolarTV/EVMIR/Precompiles/Pairing.lean create mode 100644 tv/SolarTV/EVMIR/Precompiles/RIPEMD160.lean create mode 100644 tv/SolarTV/EVMIR/Precompiles/SHA256.lean create mode 100644 tv/SolarTV/EVMIR/Precompiles/Safety.lean create mode 100644 tv/SolarTV/EVMIR/Precompiles/Signatures.lean create mode 100644 tv/SolarTV/EVMIR/Program.lean create mode 100644 tv/SolarTV/EVMIR/StackSafety.lean create mode 100644 tv/SolarTV/EVMIR/State/Create.lean create mode 100644 tv/SolarTV/EVMIR/State/Decode.lean create mode 100644 tv/SolarTV/EVMIR/State/Delegation.lean create mode 100644 tv/SolarTV/EVMIR/State/Environment.lean create mode 100644 tv/SolarTV/EVMIR/State/Interpreter.lean create mode 100644 tv/SolarTV/EVMIR/State/Messages.lean create mode 100644 tv/SolarTV/EVMIR/State/Normalize.lean create mode 100644 tv/SolarTV/EVMIR/State/Observe.lean create mode 100644 tv/SolarTV/EVMIR/State/Safety.lean create mode 100644 tv/SolarTV/EVMIR/State/Selfdestruct.lean create mode 100644 tv/SolarTV/EVMIR/State/Types.lean create mode 100644 tv/SolarTV/EVMIR/Transforms/EqIszeroJumpi.lean create mode 100644 tv/SolarTV/EVMIR/Transforms/GasSwapAdd.lean create mode 100644 tv/SolarTV/EVMIR/Transforms/StackPeephole.lean create mode 100644 tv/SolarTV/Keccak.lean create mode 100644 tv/SolarTV/KeccakSafety.lean create mode 100644 tv/SolarTV/MIR/Ops.lean create mode 100644 tv/SolarTV/MIR/Program.lean create mode 100644 tv/SolarTV/MIR/State/Aggregates.lean create mode 100644 tv/SolarTV/MIR/State/Allocation.lean create mode 100644 tv/SolarTV/MIR/State/IR.lean create mode 100644 tv/SolarTV/MIR/State/Interpreter.lean create mode 100644 tv/SolarTV/MIR/State/Messages.lean create mode 100644 tv/SolarTV/MIR/State/Normalize.lean create mode 100644 tv/SolarTV/MIR/State/Observe.lean create mode 100644 tv/SolarTV/MIR/State/Ops.lean create mode 100644 tv/SolarTV/MIR/State/Safety.lean create mode 100644 tv/SolarTV/MIR/State/Values.lean create mode 100644 tv/SolarTV/MIR/Transforms/Casts.lean create mode 100644 tv/SolarTV/MIR/Transforms/CheckElim.lean create mode 100644 tv/SolarTV/MIR/Transforms/DCE.lean create mode 100644 tv/SolarTV/MIR/Transforms/DeadStore.lean create mode 100644 tv/SolarTV/MIR/Transforms/RenamePhiPredecessors.lean create mode 100644 tv/SolarTV/MIR/Transforms/TrimSwitchDefaults.lean create mode 100644 tv/SolarTV/MIR/Validation/AddZero.lean create mode 100644 tv/SolarTV/Machine.lean create mode 100644 tv/SolarTV/Memory.lean create mode 100644 tv/SolarTV/MemorySafety.lean create mode 100644 tv/SolarTV/MemorySymbolic.lean create mode 100644 tv/SolarTV/MemorySymbolicSafety.lean create mode 100644 tv/SolarTV/Outcome.lean create mode 100644 tv/SolarTV/Sem.lean create mode 100644 tv/SolarTV/Stages/Assembly.lean create mode 100644 tv/SolarTV/Stages/AssemblyCheck.lean create mode 100644 tv/SolarTV/Stages/Entries.lean create mode 100644 tv/SolarTV/Stages/Link.lean create mode 100644 tv/SolarTV/State/ByteMemory.lean create mode 100644 tv/SolarTV/State/Calls.lean create mode 100644 tv/SolarTV/State/Context.lean create mode 100644 tv/SolarTV/State/Fork.lean create mode 100644 tv/SolarTV/State/Journal.lean create mode 100644 tv/SolarTV/State/MemoryLaws.lean create mode 100644 tv/SolarTV/State/Storage.lean create mode 100644 tv/SolarTV/State/StorageSafety.lean create mode 100644 tv/SolarTV/State/World.lean create mode 100644 tv/SolarTV/Word.lean create mode 100644 tv/SolarTV/WordSafety.lean create mode 100644 tv/W1Proofs.lean create mode 100644 tv/W1Proofs/Assembly.lean create mode 100644 tv/W1Proofs/Axioms.lean create mode 100644 tv/W1Proofs/Items.lean create mode 100644 tv/W1Proofs/Runs/Evm1.lean create mode 100644 tv/W1Proofs/Runs/Evm2.lean create mode 100644 tv/W1Proofs/Runs/Evm3.lean create mode 100644 tv/W1Proofs/Runs/Evm4.lean create mode 100644 tv/W1Proofs/Runs/Sched.lean create mode 100644 tv/W1Proofs/Runs/Stage0.lean create mode 100644 tv/W1Proofs/Segment.lean create mode 100644 tv/W1Proofs/Stage.lean create mode 100644 tv/W1Proofs/Stages.lean create mode 100644 tv/W1Proofs/Tactic.lean create mode 100644 vendor/evm-rules/EvmRules.lean create mode 100644 vendor/evm-rules/EvmRules/Arith.lean create mode 100644 vendor/evm-rules/EvmRules/ArithTactic.lean create mode 100644 vendor/evm-rules/EvmRules/Bitblast.lean create mode 100644 vendor/evm-rules/EvmRules/Bits.lean create mode 100644 vendor/evm-rules/EvmRules/Casts.lean create mode 100644 vendor/evm-rules/EvmRules/Lemmas.lean create mode 100644 vendor/evm-rules/EvmRules/Reference.lean create mode 100644 vendor/evm-rules/EvmRules/Simp.lean create mode 100644 vendor/evm-rules/EvmRules/Tactic.lean create mode 100644 vendor/evm-rules/EvmRules/Word.lean create mode 100644 vendor/evm-rules/README.md diff --git a/Certified/README.md b/Certified/README.md new file mode 100644 index 00000000..f4f37fe5 --- /dev/null +++ b/Certified/README.md @@ -0,0 +1,12 @@ +# Certified: generated per-contract stages and proofs + +Each directory is one contract that solar's certify driver exported and proved, laid out as the +driver writes it: `/.sol` (the source), `options` (the compiler options), +`bytecode.hex`, `gen//*.lean` (the exported stages, modules `.gen..*`) +and `Proofs.lean`, `Proofs/**` (the backend proofs, modules `.Proofs.*`). `w1/` also holds +the `W1` checks of w1's stages. The `srcDir` of each library is `Certified`, so module names carry +no `Certified` prefix, as the solidity-lean refinement proofs import them. + +Only the contracts a headline theorem or milestone check here imports are committed: w1, w4, +counter, masks, c4, mulx, bank, events, reader and token. Regenerate one with solar's certify +driver against this commit (solar's pin file names it); it rewrites the directory in place. diff --git a/Certified/bank/Proofs.lean b/Certified/bank/Proofs.lean new file mode 100644 index 00000000..b3f5f79b --- /dev/null +++ b/Certified/bank/Proofs.lean @@ -0,0 +1,3 @@ +-- Generated by solar-tv/milestone/certify.py; do not edit. +import bank.Proofs.Stages +import bank.Proofs.Assembly diff --git a/Certified/bank/Proofs/Assembly.lean b/Certified/bank/Proofs/Assembly.lean new file mode 100644 index 00000000..ecd79b90 --- /dev/null +++ b/Certified/bank/Proofs/Assembly.lean @@ -0,0 +1,42 @@ +-- Generated by solar-tv/milestone/certify.py; do not edit. +import W1Proofs.Items +import bank.gen.Bank.Evm11 +import bank.gen.Bank.Bytecode + +/-! The final EVM IR of `Bank` against its bytecode, by the assembly checker's walk: the bytecode decodes, linearly from offset 0, to exactly the program's instructions, each jumped-to block at its `JUMPDEST`. -/ + +namespace SolarTV.Milestone.Bank + +open SolarTV.Assembly SolarTV.Export.Bank SolarTV.Milestone.W1 + +set_option maxRecDepth 100000 + +/-- The items of the final EVM IR. -/ +def items : List Item := (itemsOf evm11).getD [] + +theorem items_eq : itemsOf evm11 = some items := by decide + +/-- The layout: each jumped-to block at the bytecode's next `JUMPDEST`. The walk checks it. -/ +def offset (label : Nat) : Nat := if label = 1 then 0x28 else if label = 2 then 0x2c else if label = 3 then 0x3e else if label = 4 then 0x4d else if label = 5 then 0x87 else if label = 6 then 0xcb else if label = 7 then 0xe1 else if label = 8 then 0xe5 else if label = 9 then 0xf8 else if label = 10 then 0x11b else if label = 11 then 0x134 else if label = 12 then 0x147 else if label = 13 then 0x161 else if label = 14 then 0x193 else if label = 15 then 0x1a6 else 0 + +/-- The instructions the walk reaches, each at its offset. -/ +def stream : List (Nat × Instr) := (walk bytecode offset 0 items).getD [] + +/-- The checker's walk accepts the exported bytecode against the final EVM IR. -/ +theorem walk_eq : walk bytecode offset 0 items = some stream := by decide +kernel + +theorem checked : Walk bytecode offset 0 items stream := walk_sound walk_eq + +/-- The bytecode's linear decoding is the final EVM IR's instructions at the layout. -/ +theorem decodes : decodeFrom bytecode (bytecode.length + 1) 0 = stream := + walk_decodes checked _ (by have := walk_length checked; omega) + +/-- info: 'SolarTV.Milestone.Bank.walk_eq' depends on axioms: [propext, Quot.sound] -/ +#guard_msgs in +#print axioms walk_eq + +/-- info: 'SolarTV.Milestone.Bank.decodes' depends on axioms: [propext, Quot.sound] -/ +#guard_msgs in +#print axioms decodes + +end SolarTV.Milestone.Bank diff --git a/Certified/bank/Proofs/Runs/Evm1.lean b/Certified/bank/Proofs/Runs/Evm1.lean new file mode 100644 index 00000000..730c801b --- /dev/null +++ b/Certified/bank/Proofs/Runs/Evm1.lean @@ -0,0 +1,22 @@ +-- Generated by solar-tv/milestone/certify.py; do not edit. +import W1Proofs.Tactic +import W1Proofs.Axioms +import bank.gen.Bank.Evm1 +import bank.gen.Bank.Sched + +/-! `peephole-early`: its input and output end in the same result on every call. -/ + +namespace SolarTV.Milestone.Bank + +open Machine SolarTV.Export.Bank SolarTV.Milestone.W1 + +set_option maxHeartbeats 8000000 in +theorem evm1_run (o : Oracle) (call : Call) : + EVM.Program.run o sched call 333 = EVM.Program.run o evm1 call 333 := by + sym_exec + +/-- info: 'SolarTV.Milestone.Bank.evm1_run' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within evm1_run + +end SolarTV.Milestone.Bank diff --git a/Certified/bank/Proofs/Runs/Evm10.lean b/Certified/bank/Proofs/Runs/Evm10.lean new file mode 100644 index 00000000..fcc2d70b --- /dev/null +++ b/Certified/bank/Proofs/Runs/Evm10.lean @@ -0,0 +1,22 @@ +-- Generated by solar-tv/milestone/certify.py; do not edit. +import W1Proofs.Tactic +import W1Proofs.Axioms +import bank.gen.Bank.Evm10 +import bank.gen.Bank.Evm9 + +/-! `block-layout`: its input and output end in the same result on every call. -/ + +namespace SolarTV.Milestone.Bank + +open Machine SolarTV.Export.Bank SolarTV.Milestone.W1 + +set_option maxHeartbeats 8000000 in +theorem evm10_run (o : Oracle) (call : Call) : + EVM.Program.run o evm9 call 144 = EVM.Program.run o evm10 call 144 := by + sym_exec + +/-- info: 'SolarTV.Milestone.Bank.evm10_run' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within evm10_run + +end SolarTV.Milestone.Bank diff --git a/Certified/bank/Proofs/Runs/Evm11.lean b/Certified/bank/Proofs/Runs/Evm11.lean new file mode 100644 index 00000000..87302e0d --- /dev/null +++ b/Certified/bank/Proofs/Runs/Evm11.lean @@ -0,0 +1,22 @@ +-- Generated by solar-tv/milestone/certify.py; do not edit. +import W1Proofs.Tactic +import W1Proofs.Axioms +import bank.gen.Bank.Evm11 +import bank.gen.Bank.Evm10 + +/-! `stack-reschedule`: its input and output end in the same result on every call. -/ + +namespace SolarTV.Milestone.Bank + +open Machine SolarTV.Export.Bank SolarTV.Milestone.W1 + +set_option maxHeartbeats 8000000 in +theorem evm11_run (o : Oracle) (call : Call) : + EVM.Program.run o evm10 call 144 = EVM.Program.run o evm11 call 144 := by + sym_exec + +/-- info: 'SolarTV.Milestone.Bank.evm11_run' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within evm11_run + +end SolarTV.Milestone.Bank diff --git a/Certified/bank/Proofs/Runs/Evm2.lean b/Certified/bank/Proofs/Runs/Evm2.lean new file mode 100644 index 00000000..ec8a5797 --- /dev/null +++ b/Certified/bank/Proofs/Runs/Evm2.lean @@ -0,0 +1,22 @@ +-- Generated by solar-tv/milestone/certify.py; do not edit. +import W1Proofs.Tactic +import W1Proofs.Axioms +import bank.gen.Bank.Evm2 +import bank.gen.Bank.Evm1 + +/-! `cfg-simplify-early`: its input and output end in the same result on every call. -/ + +namespace SolarTV.Milestone.Bank + +open Machine SolarTV.Export.Bank SolarTV.Milestone.W1 + +set_option maxHeartbeats 8000000 in +theorem evm2_run (o : Oracle) (call : Call) : + EVM.Program.run o evm1 call 333 = EVM.Program.run o evm2 call 180 := by + sym_exec + +/-- info: 'SolarTV.Milestone.Bank.evm2_run' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within evm2_run + +end SolarTV.Milestone.Bank diff --git a/Certified/bank/Proofs/Runs/Evm3.lean b/Certified/bank/Proofs/Runs/Evm3.lean new file mode 100644 index 00000000..bbf5841d --- /dev/null +++ b/Certified/bank/Proofs/Runs/Evm3.lean @@ -0,0 +1,22 @@ +-- Generated by solar-tv/milestone/certify.py; do not edit. +import W1Proofs.Tactic +import W1Proofs.Axioms +import bank.gen.Bank.Evm3 +import bank.gen.Bank.Evm2 + +/-! `compact-pushes`: its input and output end in the same result on every call. -/ + +namespace SolarTV.Milestone.Bank + +open Machine SolarTV.Export.Bank SolarTV.Milestone.W1 + +set_option maxHeartbeats 8000000 in +theorem evm3_run (o : Oracle) (call : Call) : + EVM.Program.run o evm2 call 180 = EVM.Program.run o evm3 call 180 := by + sym_exec + +/-- info: 'SolarTV.Milestone.Bank.evm3_run' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within evm3_run + +end SolarTV.Milestone.Bank diff --git a/Certified/bank/Proofs/Runs/Evm4.lean b/Certified/bank/Proofs/Runs/Evm4.lean new file mode 100644 index 00000000..1f15c4de --- /dev/null +++ b/Certified/bank/Proofs/Runs/Evm4.lean @@ -0,0 +1,22 @@ +-- Generated by solar-tv/milestone/certify.py; do not edit. +import W1Proofs.Tactic +import W1Proofs.Axioms +import bank.gen.Bank.Evm4 +import bank.gen.Bank.Evm3 + +/-! `block-layout`: its input and output end in the same result on every call. -/ + +namespace SolarTV.Milestone.Bank + +open Machine SolarTV.Export.Bank SolarTV.Milestone.W1 + +set_option maxHeartbeats 8000000 in +theorem evm4_run (o : Oracle) (call : Call) : + EVM.Program.run o evm3 call 180 = EVM.Program.run o evm4 call 180 := by + sym_exec + +/-- info: 'SolarTV.Milestone.Bank.evm4_run' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within evm4_run + +end SolarTV.Milestone.Bank diff --git a/Certified/bank/Proofs/Runs/Evm5.lean b/Certified/bank/Proofs/Runs/Evm5.lean new file mode 100644 index 00000000..74ded001 --- /dev/null +++ b/Certified/bank/Proofs/Runs/Evm5.lean @@ -0,0 +1,22 @@ +-- Generated by solar-tv/milestone/certify.py; do not edit. +import W1Proofs.Tactic +import W1Proofs.Axioms +import bank.gen.Bank.Evm5 +import bank.gen.Bank.Evm4 + +/-! `terminal-dedup`: its input and output end in the same result on every call. -/ + +namespace SolarTV.Milestone.Bank + +open Machine SolarTV.Export.Bank SolarTV.Milestone.W1 + +set_option maxHeartbeats 8000000 in +theorem evm5_run (o : Oracle) (call : Call) : + EVM.Program.run o evm4 call 180 = EVM.Program.run o evm5 call 180 := by + sym_exec + +/-- info: 'SolarTV.Milestone.Bank.evm5_run' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within evm5_run + +end SolarTV.Milestone.Bank diff --git a/Certified/bank/Proofs/Runs/Evm6.lean b/Certified/bank/Proofs/Runs/Evm6.lean new file mode 100644 index 00000000..26b6757d --- /dev/null +++ b/Certified/bank/Proofs/Runs/Evm6.lean @@ -0,0 +1,22 @@ +-- Generated by solar-tv/milestone/certify.py; do not edit. +import W1Proofs.Tactic +import W1Proofs.Axioms +import bank.gen.Bank.Evm6 +import bank.gen.Bank.Evm5 + +/-! `cfg-simplify-early`: its input and output end in the same result on every call. -/ + +namespace SolarTV.Milestone.Bank + +open Machine SolarTV.Export.Bank SolarTV.Milestone.W1 + +set_option maxHeartbeats 8000000 in +theorem evm6_run (o : Oracle) (call : Call) : + EVM.Program.run o evm5 call 180 = EVM.Program.run o evm6 call 135 := by + sym_exec + +/-- info: 'SolarTV.Milestone.Bank.evm6_run' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within evm6_run + +end SolarTV.Milestone.Bank diff --git a/Certified/bank/Proofs/Runs/Evm7.lean b/Certified/bank/Proofs/Runs/Evm7.lean new file mode 100644 index 00000000..7affbe1d --- /dev/null +++ b/Certified/bank/Proofs/Runs/Evm7.lean @@ -0,0 +1,22 @@ +-- Generated by solar-tv/milestone/certify.py; do not edit. +import W1Proofs.Tactic +import W1Proofs.Axioms +import bank.gen.Bank.Evm7 +import bank.gen.Bank.Evm6 + +/-! `tail-merge`: its input and output end in the same result on every call. -/ + +namespace SolarTV.Milestone.Bank + +open Machine SolarTV.Export.Bank SolarTV.Milestone.W1 + +set_option maxHeartbeats 8000000 in +theorem evm7_run (o : Oracle) (call : Call) : + EVM.Program.run o evm6 call 135 = EVM.Program.run o evm7 call 153 := by + sym_exec + +/-- info: 'SolarTV.Milestone.Bank.evm7_run' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within evm7_run + +end SolarTV.Milestone.Bank diff --git a/Certified/bank/Proofs/Runs/Evm8.lean b/Certified/bank/Proofs/Runs/Evm8.lean new file mode 100644 index 00000000..793328db --- /dev/null +++ b/Certified/bank/Proofs/Runs/Evm8.lean @@ -0,0 +1,22 @@ +-- Generated by solar-tv/milestone/certify.py; do not edit. +import W1Proofs.Tactic +import W1Proofs.Axioms +import bank.gen.Bank.Evm8 +import bank.gen.Bank.Evm7 + +/-! `cfg-simplify-early`: its input and output end in the same result on every call. -/ + +namespace SolarTV.Milestone.Bank + +open Machine SolarTV.Export.Bank SolarTV.Milestone.W1 + +set_option maxHeartbeats 8000000 in +theorem evm8_run (o : Oracle) (call : Call) : + EVM.Program.run o evm7 call 153 = EVM.Program.run o evm8 call 144 := by + sym_exec + +/-- info: 'SolarTV.Milestone.Bank.evm8_run' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within evm8_run + +end SolarTV.Milestone.Bank diff --git a/Certified/bank/Proofs/Runs/Evm9.lean b/Certified/bank/Proofs/Runs/Evm9.lean new file mode 100644 index 00000000..52c307e7 --- /dev/null +++ b/Certified/bank/Proofs/Runs/Evm9.lean @@ -0,0 +1,22 @@ +-- Generated by solar-tv/milestone/certify.py; do not edit. +import W1Proofs.Tactic +import W1Proofs.Axioms +import bank.gen.Bank.Evm9 +import bank.gen.Bank.Evm8 + +/-! `reorder-pushes`: its input and output end in the same result on every call. -/ + +namespace SolarTV.Milestone.Bank + +open Machine SolarTV.Export.Bank SolarTV.Milestone.W1 + +set_option maxHeartbeats 8000000 in +theorem evm9_run (o : Oracle) (call : Call) : + EVM.Program.run o evm8 call 144 = EVM.Program.run o evm9 call 144 := by + sym_exec + +/-- info: 'SolarTV.Milestone.Bank.evm9_run' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within evm9_run + +end SolarTV.Milestone.Bank diff --git a/Certified/bank/Proofs/Runs/Mir1.lean b/Certified/bank/Proofs/Runs/Mir1.lean new file mode 100644 index 00000000..1d7e3dc8 --- /dev/null +++ b/Certified/bank/Proofs/Runs/Mir1.lean @@ -0,0 +1,22 @@ +-- Generated by solar-tv/milestone/certify.py; do not edit. +import W1Proofs.Tactic +import W1Proofs.Axioms +import bank.gen.Bank.Mir1 +import bank.gen.Bank.Stage0 + +/-! `place-reads`: its input and output end in the same result on every call. -/ + +namespace SolarTV.Milestone.Bank + +open Machine SolarTV.Export.Bank SolarTV.Milestone.W1 + +set_option maxHeartbeats 8000000 in +theorem mir1_run (o : Oracle) (call : Call) : + MIR.Lowered.Module.run o stage0 call 171 = MIR.Lowered.Module.run o mir1 call 171 := by + sym_exec + +/-- info: 'SolarTV.Milestone.Bank.mir1_run' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within mir1_run + +end SolarTV.Milestone.Bank diff --git a/Certified/bank/Proofs/Runs/Mir2.lean b/Certified/bank/Proofs/Runs/Mir2.lean new file mode 100644 index 00000000..652758b4 --- /dev/null +++ b/Certified/bank/Proofs/Runs/Mir2.lean @@ -0,0 +1,22 @@ +-- Generated by solar-tv/milestone/certify.py; do not edit. +import W1Proofs.Tactic +import W1Proofs.Axioms +import bank.gen.Bank.Mir2 +import bank.gen.Bank.Mir1 + +/-! `spell-width-tests`: its input and output end in the same result on every call. -/ + +namespace SolarTV.Milestone.Bank + +open Machine SolarTV.Export.Bank SolarTV.Milestone.W1 + +set_option maxHeartbeats 8000000 in +theorem mir2_run (o : Oracle) (call : Call) : + MIR.Lowered.Module.run o mir1 call 171 = MIR.Lowered.Module.run o mir2 call 171 := by + sym_exec + +/-- info: 'SolarTV.Milestone.Bank.mir2_run' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within mir2_run + +end SolarTV.Milestone.Bank diff --git a/Certified/bank/Proofs/Runs/Mir3.lean b/Certified/bank/Proofs/Runs/Mir3.lean new file mode 100644 index 00000000..d7680337 --- /dev/null +++ b/Certified/bank/Proofs/Runs/Mir3.lean @@ -0,0 +1,22 @@ +-- Generated by solar-tv/milestone/certify.py; do not edit. +import W1Proofs.Tactic +import W1Proofs.Axioms +import bank.gen.Bank.Mir3 +import bank.gen.Bank.Mir2 + +/-! `lower-assumes`: its input and output end in the same result on every call. -/ + +namespace SolarTV.Milestone.Bank + +open Machine SolarTV.Export.Bank SolarTV.Milestone.W1 + +set_option maxHeartbeats 8000000 in +theorem mir3_run (o : Oracle) (call : Call) : + MIR.Lowered.Module.run o mir2 call 171 = MIR.Lowered.Module.run o mir3 call 315 := by + sym_exec + +/-- info: 'SolarTV.Milestone.Bank.mir3_run' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within mir3_run + +end SolarTV.Milestone.Bank diff --git a/Certified/bank/Proofs/Runs/Mir4.lean b/Certified/bank/Proofs/Runs/Mir4.lean new file mode 100644 index 00000000..0c4a23d9 --- /dev/null +++ b/Certified/bank/Proofs/Runs/Mir4.lean @@ -0,0 +1,22 @@ +-- Generated by solar-tv/milestone/certify.py; do not edit. +import W1Proofs.Tactic +import W1Proofs.Axioms +import bank.gen.Bank.Mir4 +import bank.gen.Bank.Mir3 + +/-! `evm-inst-schedule`: its input and output end in the same result on every call. -/ + +namespace SolarTV.Milestone.Bank + +open Machine SolarTV.Export.Bank SolarTV.Milestone.W1 + +set_option maxHeartbeats 8000000 in +theorem mir4_run (o : Oracle) (call : Call) : + MIR.Lowered.Module.run o mir3 call 315 = MIR.Lowered.Module.run o mir4 call 315 := by + sym_exec + +/-- info: 'SolarTV.Milestone.Bank.mir4_run' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within mir4_run + +end SolarTV.Milestone.Bank diff --git a/Certified/bank/Proofs/Runs/Sched.lean b/Certified/bank/Proofs/Runs/Sched.lean new file mode 100644 index 00000000..60b04044 --- /dev/null +++ b/Certified/bank/Proofs/Runs/Sched.lean @@ -0,0 +1,22 @@ +-- Generated by solar-tv/milestone/certify.py; do not edit. +import W1Proofs.Tactic +import W1Proofs.Axioms +import bank.gen.Bank.Sched +import bank.gen.Bank.Mir4 + +/-! Stack scheduling: the last lowered MIR and the scheduled EVM IR end in the same result on every call. -/ + +namespace SolarTV.Milestone.Bank + +open Machine SolarTV.Export.Bank SolarTV.Milestone.W1 + +set_option maxHeartbeats 8000000 in +theorem sched_run (o : Oracle) (call : Call) : + MIR.Lowered.Module.run o mir4 call 315 = EVM.Program.run o sched call 333 := by + sym_exec + +/-- info: 'SolarTV.Milestone.Bank.sched_run' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within sched_run + +end SolarTV.Milestone.Bank diff --git a/Certified/bank/Proofs/Runs/Stage0.lean b/Certified/bank/Proofs/Runs/Stage0.lean new file mode 100644 index 00000000..b583b1ca --- /dev/null +++ b/Certified/bank/Proofs/Runs/Stage0.lean @@ -0,0 +1,21 @@ +-- Generated by solar-tv/milestone/certify.py; do not edit. +import W1Proofs.Tactic +import W1Proofs.Axioms +import bank.gen.Bank.Stage0 + +/-! The first lowered MIR ends on every call within 171 blocks, its block count times the square of one more than its call sites. -/ + +namespace SolarTV.Milestone.Bank + +open Machine SolarTV.Export.Bank SolarTV.Milestone.W1 + +set_option maxHeartbeats 8000000 in +theorem stage0_ends (o : Oracle) (call : Call) : + (MIR.Lowered.Module.run o stage0 call 171).isSome = true := by + sym_exec + +/-- info: 'SolarTV.Milestone.Bank.stage0_ends' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within stage0_ends + +end SolarTV.Milestone.Bank diff --git a/Certified/bank/Proofs/Stages.lean b/Certified/bank/Proofs/Stages.lean new file mode 100644 index 00000000..cf1368d4 --- /dev/null +++ b/Certified/bank/Proofs/Stages.lean @@ -0,0 +1,275 @@ +-- Generated by solar-tv/milestone/certify.py; do not edit. +import bank.Proofs.Runs.Stage0 +import bank.Proofs.Runs.Mir1 +import bank.Proofs.Runs.Mir2 +import bank.Proofs.Runs.Mir3 +import bank.Proofs.Runs.Mir4 +import bank.Proofs.Runs.Sched +import bank.Proofs.Runs.Evm1 +import bank.Proofs.Runs.Evm2 +import bank.Proofs.Runs.Evm3 +import bank.Proofs.Runs.Evm4 +import bank.Proofs.Runs.Evm5 +import bank.Proofs.Runs.Evm6 +import bank.Proofs.Runs.Evm7 +import bank.Proofs.Runs.Evm8 +import bank.Proofs.Runs.Evm9 +import bank.Proofs.Runs.Evm10 +import bank.Proofs.Runs.Evm11 +import W1Proofs.Stage +import SolarTV.Composition + +/-! The backend stages of `Bank`, each proved on every call (`anyCall`: any calldata, call value and storage) under every oracle, and chained from the first lowered MIR `stage0` to the final EVM IR `evm11`. Fuels are the programs' block counts times the square of one more than their call sites. -/ + +namespace SolarTV.Milestone.Bank + +open Machine SolarTV.Export.Bank SolarTV.Milestone.W1 + +/-- `place-reads`: stage0 to mir1. -/ +theorem stage_mir1 (o : Oracle) : Stage (mirSem o) (mirSem o) stage0 mir1 anyCall := + stage_of_runs (A := MIR.Lowered.moduleLayer) (B := MIR.Lowered.moduleLayer) 171 171 (fun call _ => stage0_ends o call) + (fun call _ => mir1_run o call) + +theorem mir1_ends (o : Oracle) : ∀ call, anyCall call → + (MIR.Lowered.Module.run o mir1 call 171).isSome = true := + ends_of_runs (A := MIR.Lowered.moduleLayer) (B := MIR.Lowered.moduleLayer) + (o := o) (p := stage0) (q := mir1) (n := 171) (m := 171) (fun call _ => stage0_ends o call) + (fun call _ => mir1_run o call) + +/-- `spell-width-tests`: mir1 to mir2. -/ +theorem stage_mir2 (o : Oracle) : Stage (mirSem o) (mirSem o) mir1 mir2 anyCall := + stage_of_runs (A := MIR.Lowered.moduleLayer) (B := MIR.Lowered.moduleLayer) 171 171 (mir1_ends o) + (fun call _ => mir2_run o call) + +theorem mir2_ends (o : Oracle) : ∀ call, anyCall call → + (MIR.Lowered.Module.run o mir2 call 171).isSome = true := + ends_of_runs (A := MIR.Lowered.moduleLayer) (B := MIR.Lowered.moduleLayer) + (o := o) (p := mir1) (q := mir2) (n := 171) (m := 171) (mir1_ends o) + (fun call _ => mir2_run o call) + +/-- `lower-assumes`: mir2 to mir3. -/ +theorem stage_mir3 (o : Oracle) : Stage (mirSem o) (mirSem o) mir2 mir3 anyCall := + stage_of_runs (A := MIR.Lowered.moduleLayer) (B := MIR.Lowered.moduleLayer) 171 315 (mir2_ends o) + (fun call _ => mir3_run o call) + +theorem mir3_ends (o : Oracle) : ∀ call, anyCall call → + (MIR.Lowered.Module.run o mir3 call 315).isSome = true := + ends_of_runs (A := MIR.Lowered.moduleLayer) (B := MIR.Lowered.moduleLayer) + (o := o) (p := mir2) (q := mir3) (n := 171) (m := 315) (mir2_ends o) + (fun call _ => mir3_run o call) + +/-- `evm-inst-schedule`: mir3 to mir4. -/ +theorem stage_mir4 (o : Oracle) : Stage (mirSem o) (mirSem o) mir3 mir4 anyCall := + stage_of_runs (A := MIR.Lowered.moduleLayer) (B := MIR.Lowered.moduleLayer) 315 315 (mir3_ends o) + (fun call _ => mir4_run o call) + +theorem mir4_ends (o : Oracle) : ∀ call, anyCall call → + (MIR.Lowered.Module.run o mir4 call 315).isSome = true := + ends_of_runs (A := MIR.Lowered.moduleLayer) (B := MIR.Lowered.moduleLayer) + (o := o) (p := mir3) (q := mir4) (n := 315) (m := 315) (mir3_ends o) + (fun call _ => mir4_run o call) + +/-- `stack-schedule`: mir4 to sched. -/ +theorem stage_sched (o : Oracle) : Stage (mirSem o) (evmirSem o) mir4 sched anyCall := + stage_of_runs (A := MIR.Lowered.moduleLayer) (B := EVM.Program.layer) 315 333 (mir4_ends o) + (fun call _ => sched_run o call) + +theorem sched_ends (o : Oracle) : ∀ call, anyCall call → + (EVM.Program.run o sched call 333).isSome = true := + ends_of_runs (A := MIR.Lowered.moduleLayer) (B := EVM.Program.layer) + (o := o) (p := mir4) (q := sched) (n := 315) (m := 333) (mir4_ends o) + (fun call _ => sched_run o call) + +/-- `peephole-early`: sched to evm1. -/ +theorem stage_evm1 (o : Oracle) : Stage (evmirSem o) (evmirSem o) sched evm1 anyCall := + stage_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) 333 333 (sched_ends o) + (fun call _ => evm1_run o call) + +theorem evm1_ends (o : Oracle) : ∀ call, anyCall call → + (EVM.Program.run o evm1 call 333).isSome = true := + ends_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) + (o := o) (p := sched) (q := evm1) (n := 333) (m := 333) (sched_ends o) + (fun call _ => evm1_run o call) + +/-- `cfg-simplify-early`: evm1 to evm2. -/ +theorem stage_evm2 (o : Oracle) : Stage (evmirSem o) (evmirSem o) evm1 evm2 anyCall := + stage_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) 333 180 (evm1_ends o) + (fun call _ => evm2_run o call) + +theorem evm2_ends (o : Oracle) : ∀ call, anyCall call → + (EVM.Program.run o evm2 call 180).isSome = true := + ends_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) + (o := o) (p := evm1) (q := evm2) (n := 333) (m := 180) (evm1_ends o) + (fun call _ => evm2_run o call) + +/-- `compact-pushes`: evm2 to evm3. -/ +theorem stage_evm3 (o : Oracle) : Stage (evmirSem o) (evmirSem o) evm2 evm3 anyCall := + stage_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) 180 180 (evm2_ends o) + (fun call _ => evm3_run o call) + +theorem evm3_ends (o : Oracle) : ∀ call, anyCall call → + (EVM.Program.run o evm3 call 180).isSome = true := + ends_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) + (o := o) (p := evm2) (q := evm3) (n := 180) (m := 180) (evm2_ends o) + (fun call _ => evm3_run o call) + +/-- `block-layout`: evm3 to evm4. -/ +theorem stage_evm4 (o : Oracle) : Stage (evmirSem o) (evmirSem o) evm3 evm4 anyCall := + stage_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) 180 180 (evm3_ends o) + (fun call _ => evm4_run o call) + +theorem evm4_ends (o : Oracle) : ∀ call, anyCall call → + (EVM.Program.run o evm4 call 180).isSome = true := + ends_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) + (o := o) (p := evm3) (q := evm4) (n := 180) (m := 180) (evm3_ends o) + (fun call _ => evm4_run o call) + +/-- `terminal-dedup`: evm4 to evm5. -/ +theorem stage_evm5 (o : Oracle) : Stage (evmirSem o) (evmirSem o) evm4 evm5 anyCall := + stage_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) 180 180 (evm4_ends o) + (fun call _ => evm5_run o call) + +theorem evm5_ends (o : Oracle) : ∀ call, anyCall call → + (EVM.Program.run o evm5 call 180).isSome = true := + ends_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) + (o := o) (p := evm4) (q := evm5) (n := 180) (m := 180) (evm4_ends o) + (fun call _ => evm5_run o call) + +/-- `cfg-simplify-early`: evm5 to evm6. -/ +theorem stage_evm6 (o : Oracle) : Stage (evmirSem o) (evmirSem o) evm5 evm6 anyCall := + stage_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) 180 135 (evm5_ends o) + (fun call _ => evm6_run o call) + +theorem evm6_ends (o : Oracle) : ∀ call, anyCall call → + (EVM.Program.run o evm6 call 135).isSome = true := + ends_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) + (o := o) (p := evm5) (q := evm6) (n := 180) (m := 135) (evm5_ends o) + (fun call _ => evm6_run o call) + +/-- `tail-merge`: evm6 to evm7. -/ +theorem stage_evm7 (o : Oracle) : Stage (evmirSem o) (evmirSem o) evm6 evm7 anyCall := + stage_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) 135 153 (evm6_ends o) + (fun call _ => evm7_run o call) + +theorem evm7_ends (o : Oracle) : ∀ call, anyCall call → + (EVM.Program.run o evm7 call 153).isSome = true := + ends_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) + (o := o) (p := evm6) (q := evm7) (n := 135) (m := 153) (evm6_ends o) + (fun call _ => evm7_run o call) + +/-- `cfg-simplify-early`: evm7 to evm8. -/ +theorem stage_evm8 (o : Oracle) : Stage (evmirSem o) (evmirSem o) evm7 evm8 anyCall := + stage_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) 153 144 (evm7_ends o) + (fun call _ => evm8_run o call) + +theorem evm8_ends (o : Oracle) : ∀ call, anyCall call → + (EVM.Program.run o evm8 call 144).isSome = true := + ends_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) + (o := o) (p := evm7) (q := evm8) (n := 153) (m := 144) (evm7_ends o) + (fun call _ => evm8_run o call) + +/-- `reorder-pushes`: evm8 to evm9. -/ +theorem stage_evm9 (o : Oracle) : Stage (evmirSem o) (evmirSem o) evm8 evm9 anyCall := + stage_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) 144 144 (evm8_ends o) + (fun call _ => evm9_run o call) + +theorem evm9_ends (o : Oracle) : ∀ call, anyCall call → + (EVM.Program.run o evm9 call 144).isSome = true := + ends_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) + (o := o) (p := evm8) (q := evm9) (n := 144) (m := 144) (evm8_ends o) + (fun call _ => evm9_run o call) + +/-- `block-layout`: evm9 to evm10. -/ +theorem stage_evm10 (o : Oracle) : Stage (evmirSem o) (evmirSem o) evm9 evm10 anyCall := + stage_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) 144 144 (evm9_ends o) + (fun call _ => evm10_run o call) + +theorem evm10_ends (o : Oracle) : ∀ call, anyCall call → + (EVM.Program.run o evm10 call 144).isSome = true := + ends_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) + (o := o) (p := evm9) (q := evm10) (n := 144) (m := 144) (evm9_ends o) + (fun call _ => evm10_run o call) + +/-- `stack-reschedule`: evm10 to evm11. -/ +theorem stage_evm11 (o : Oracle) : Stage (evmirSem o) (evmirSem o) evm10 evm11 anyCall := + stage_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) 144 144 (evm10_ends o) + (fun call _ => evm11_run o call) + +/-- The compilation from the first lowered MIR to the final EVM IR. -/ +def compilation : Compilation := + ⟨stage0, [mir1, mir2, mir3, mir4], sched, [evm1, evm2, evm3, evm4, evm5, evm6, evm7, evm8, evm9, evm10, evm11]⟩ + +/-- Every stage from the first lowered MIR to the final EVM IR, chained by the library's composition, on every call. -/ +theorem bank_mir_to_evmir (o : Oracle) : Stage (mirSem o) (evmirSem o) stage0 evm11 anyCall := + mir_to_evmir o anyCall compilation ⟨stage_mir1 o, stage_mir2 o, stage_mir3 o, stage_mir4 o, trivial⟩ (stage_sched o) + ⟨stage_evm1 o, stage_evm2 o, stage_evm3 o, stage_evm4 o, stage_evm5 o, stage_evm6 o, stage_evm7 o, stage_evm8 o, stage_evm9 o, stage_evm10 o, stage_evm11 o, trivial⟩ + +/-- info: 'SolarTV.Milestone.Bank.stage_mir1' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms stage_mir1 + +/-- info: 'SolarTV.Milestone.Bank.stage_mir2' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms stage_mir2 + +/-- info: 'SolarTV.Milestone.Bank.stage_mir3' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms stage_mir3 + +/-- info: 'SolarTV.Milestone.Bank.stage_mir4' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms stage_mir4 + +/-- info: 'SolarTV.Milestone.Bank.stage_sched' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms stage_sched + +/-- info: 'SolarTV.Milestone.Bank.stage_evm1' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms stage_evm1 + +/-- info: 'SolarTV.Milestone.Bank.stage_evm2' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms stage_evm2 + +/-- info: 'SolarTV.Milestone.Bank.stage_evm3' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms stage_evm3 + +/-- info: 'SolarTV.Milestone.Bank.stage_evm4' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms stage_evm4 + +/-- info: 'SolarTV.Milestone.Bank.stage_evm5' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms stage_evm5 + +/-- info: 'SolarTV.Milestone.Bank.stage_evm6' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms stage_evm6 + +/-- info: 'SolarTV.Milestone.Bank.stage_evm7' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms stage_evm7 + +/-- info: 'SolarTV.Milestone.Bank.stage_evm8' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms stage_evm8 + +/-- info: 'SolarTV.Milestone.Bank.stage_evm9' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms stage_evm9 + +/-- info: 'SolarTV.Milestone.Bank.stage_evm10' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms stage_evm10 + +/-- info: 'SolarTV.Milestone.Bank.stage_evm11' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms stage_evm11 + +/-- info: 'SolarTV.Milestone.Bank.bank_mir_to_evmir' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms bank_mir_to_evmir + +end SolarTV.Milestone.Bank diff --git a/Certified/bank/bank.sol b/Certified/bank/bank.sol new file mode 100644 index 00000000..be8994d3 --- /dev/null +++ b/Certified/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/Certified/bank/bytecode.hex b/Certified/bank/bytecode.hex new file mode 100644 index 00000000..6c899e5b --- /dev/null +++ b/Certified/bank/bytecode.hex @@ -0,0 +1 @@ +346028575f3560e01c80632f4f21e21460f857806370a0823114610161578063b6b55f2514603e575b5f5ffd5b6011602052634e487b715f526024601cfd5b60243610602857600435803360875b815f525f60205260405f2080548481019081105f1960601c85116101a657602c578155600154938401938410602c57926001559154905090565b905f52337fe1fffcc4923d04b559f4d29a8bfc6cda04eb5b0d3c460751c2402c5c5cc9109c60205fa25f525f1960601c331160cb575f1960601c331160cb5760205ff35b690417000000010000000260201b335f1960601c915b6020525b60405260605263ed572b275f526064601cfd5b60043560a01c60443610176028576004355f1960601c81166024358261011b604d565b5f525f1960601c8211610147578181036101345760205ff35b6d010200000002000000020000000760e1565b505f1960601c906d041700000002000000020000000960e1565b60043560a01c60243610176028576004355f1960601c8116815f525f60205260405f20545f528181036101935760205ff35b6d010200000003000000020000000960e1565b505050505f1960601c6d04170000000000000000800000006020529060e556 diff --git a/Certified/bank/gen/Bank/Bytecode.lean b/Certified/bank/gen/Bank/Bytecode.lean new file mode 100644 index 00000000..1ae1df5e --- /dev/null +++ b/Certified/bank/gen/Bank/Bytecode.lean @@ -0,0 +1,42 @@ +-- solar-lean-stage: kind=bytecode index=0 pass=assemble +/-! Generated by `solar -Zemit-lean-stages` for `Bank`; do not edit. -/ + +namespace SolarTV.Export.Bank + +/-- The runtime bytecode, byte by byte. -/ +def bytecode : List Nat := + [0x34, 0x60, 0x28, 0x57, 0x5f, 0x35, 0x60, 0xe0, 0x1c, 0x80, 0x63, 0x2f, 0x4f, 0x21, 0xe2, 0x14, + 0x60, 0xf8, 0x57, 0x80, 0x63, 0x70, 0xa0, 0x82, 0x31, 0x14, 0x61, 0x01, 0x61, 0x57, 0x80, 0x63, + 0xb6, 0xb5, 0x5f, 0x25, 0x14, 0x60, 0x3e, 0x57, 0x5b, 0x5f, 0x5f, 0xfd, 0x5b, 0x60, 0x11, 0x60, + 0x20, 0x52, 0x63, 0x4e, 0x48, 0x7b, 0x71, 0x5f, 0x52, 0x60, 0x24, 0x60, 0x1c, 0xfd, 0x5b, 0x60, + 0x24, 0x36, 0x10, 0x60, 0x28, 0x57, 0x60, 0x04, 0x35, 0x80, 0x33, 0x60, 0x87, 0x5b, 0x81, 0x5f, + 0x52, 0x5f, 0x60, 0x20, 0x52, 0x60, 0x40, 0x5f, 0x20, 0x80, 0x54, 0x84, 0x81, 0x01, 0x90, 0x81, + 0x10, 0x5f, 0x19, 0x60, 0x60, 0x1c, 0x85, 0x11, 0x61, 0x01, 0xa6, 0x57, 0x60, 0x2c, 0x57, 0x81, + 0x55, 0x60, 0x01, 0x54, 0x93, 0x84, 0x01, 0x93, 0x84, 0x10, 0x60, 0x2c, 0x57, 0x92, 0x60, 0x01, + 0x55, 0x91, 0x54, 0x90, 0x50, 0x90, 0x56, 0x5b, 0x90, 0x5f, 0x52, 0x33, 0x7f, 0xe1, 0xff, 0xfc, + 0xc4, 0x92, 0x3d, 0x04, 0xb5, 0x59, 0xf4, 0xd2, 0x9a, 0x8b, 0xfc, 0x6c, 0xda, 0x04, 0xeb, 0x5b, + 0x0d, 0x3c, 0x46, 0x07, 0x51, 0xc2, 0x40, 0x2c, 0x5c, 0x5c, 0xc9, 0x10, 0x9c, 0x60, 0x20, 0x5f, + 0xa2, 0x5f, 0x52, 0x5f, 0x19, 0x60, 0x60, 0x1c, 0x33, 0x11, 0x60, 0xcb, 0x57, 0x5f, 0x19, 0x60, + 0x60, 0x1c, 0x33, 0x11, 0x60, 0xcb, 0x57, 0x60, 0x20, 0x5f, 0xf3, 0x5b, 0x69, 0x04, 0x17, 0x00, + 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x02, 0x60, 0x20, 0x1b, 0x33, 0x5f, 0x19, 0x60, 0x60, 0x1c, + 0x91, 0x5b, 0x60, 0x20, 0x52, 0x5b, 0x60, 0x40, 0x52, 0x60, 0x60, 0x52, 0x63, 0xed, 0x57, 0x2b, + 0x27, 0x5f, 0x52, 0x60, 0x64, 0x60, 0x1c, 0xfd, 0x5b, 0x60, 0x04, 0x35, 0x60, 0xa0, 0x1c, 0x60, + 0x44, 0x36, 0x10, 0x17, 0x60, 0x28, 0x57, 0x60, 0x04, 0x35, 0x5f, 0x19, 0x60, 0x60, 0x1c, 0x81, + 0x16, 0x60, 0x24, 0x35, 0x82, 0x61, 0x01, 0x1b, 0x60, 0x4d, 0x56, 0x5b, 0x5f, 0x52, 0x5f, 0x19, + 0x60, 0x60, 0x1c, 0x82, 0x11, 0x61, 0x01, 0x47, 0x57, 0x81, 0x81, 0x03, 0x61, 0x01, 0x34, 0x57, + 0x60, 0x20, 0x5f, 0xf3, 0x5b, 0x6d, 0x01, 0x02, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x02, + 0x00, 0x00, 0x00, 0x07, 0x60, 0xe1, 0x56, 0x5b, 0x50, 0x5f, 0x19, 0x60, 0x60, 0x1c, 0x90, 0x6d, + 0x04, 0x17, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x09, 0x60, 0xe1, + 0x56, 0x5b, 0x60, 0x04, 0x35, 0x60, 0xa0, 0x1c, 0x60, 0x24, 0x36, 0x10, 0x17, 0x60, 0x28, 0x57, + 0x60, 0x04, 0x35, 0x5f, 0x19, 0x60, 0x60, 0x1c, 0x81, 0x16, 0x81, 0x5f, 0x52, 0x5f, 0x60, 0x20, + 0x52, 0x60, 0x40, 0x5f, 0x20, 0x54, 0x5f, 0x52, 0x81, 0x81, 0x03, 0x61, 0x01, 0x93, 0x57, 0x60, + 0x20, 0x5f, 0xf3, 0x5b, 0x6d, 0x01, 0x02, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x02, 0x00, + 0x00, 0x00, 0x09, 0x60, 0xe1, 0x56, 0x5b, 0x50, 0x50, 0x50, 0x50, 0x5f, 0x19, 0x60, 0x60, 0x1c, + 0x6d, 0x04, 0x17, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x00, 0x00, 0x00, 0x60, + 0x20, 0x52, 0x90, 0x60, 0xe5, 0x56] + +/-- The runtime bytecode in hex, as `--emit=bin-runtime` prints it. -/ +def bytecodeHex : String := + "346028575f3560e01c80632f4f21e21460f857806370a0823114610161578063b6b55f2514603e575b5f5ffd5b6011602052634e487b715f526024601cfd5b60243610602857600435803360875b815f525f60205260405f2080548481019081105f1960601c85116101a657602c578155600154938401938410602c57926001559154905090565b905f52337fe1fffcc4923d04b559f4d29a8bfc6cda04eb5b0d3c460751c2402c5c5cc9109c60205fa25f525f1960601c331160cb575f1960601c331160cb5760205ff35b690417000000010000000260201b335f1960601c915b6020525b60405260605263ed572b275f526064601cfd5b60043560a01c60443610176028576004355f1960601c81166024358261011b604d565b5f525f1960601c8211610147578181036101345760205ff35b6d010200000002000000020000000760e1565b505f1960601c906d041700000002000000020000000960e1565b60043560a01c60243610176028576004355f1960601c8116815f525f60205260405f20545f528181036101935760205ff35b6d010200000003000000020000000960e1565b505050505f1960601c6d04170000000000000000800000006020529060e556" + +end SolarTV.Export.Bank diff --git a/Certified/bank/gen/Bank/Evm1.lean b/Certified/bank/gen/Bank/Evm1.lean new file mode 100644 index 00000000..dd2044f5 --- /dev/null +++ b/Certified/bank/gen/Bank/Evm1.lean @@ -0,0 +1,319 @@ +-- solar-lean-stage: kind=evm index=1 pass=peephole-early +import SolarTV.EVMIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `Bank`; do not edit. -/ + +namespace SolarTV.Export.Bank + +/-- The runtime EVM IR after `peephole-early`. -/ +def evm1 : EVM.Program.Program := + { blocks := [ + -- bb0 + [.effect .callvalue 0, + .jumpi 5, + .jump 1], + -- bb1 + [.op (.stack (.push 0)), + .effect .calldataload 1, + .op (.stack (.push 224)), + .op (.stack .shr), + .op (.stack (.dup 0)), + .op (.stack (.push 0x2f4f21e2)), + .op (.stack .eq), + .jumpi 4, + .op (.stack (.dup 0)), + .op (.stack (.push 0x70a08231)), + .op (.stack .eq), + .jumpi 3, + .op (.stack (.dup 0)), + .op (.stack (.push 0xb6b55f25)), + .op (.stack .eq), + .jumpi 2, + .jump 5], + -- bb2 + [.jump 6], + -- bb3 + [.jump 24], + -- bb4 + [.jump 15], + -- bb5 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb6 + [.op (.stack (.push 36)), + .op (.stack .calldatasize), + .op (.stack .lt), + .jumpi 14, + .jump 7], + -- bb7 + [.op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.dup 0)), + .effect .caller 0, + .pushLabel 8, + .jump 30], + -- bb8 + [.op (.stack (.swap 0)), + .op (.stack (.push 0)), + .op .store, + .effect .caller 0, + .op (.stack (.push 0xe1fffcc4923d04b559f4d29a8bfc6cda04eb5b0d3c460751c2402c5c5cc9109c)), + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .effect (.log 2) 4, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 0xffffffffffffffffffffffffffffffffffffffff)), + .effect .caller 0, + .op (.stack .gt), + .jumpi 12, + .jump 9], + -- bb9 + [.op (.stack (.push 0xffffffffffffffffffffffffffffffffffffffff)), + .effect .caller 0, + .op (.stack .gt), + .jumpi 11, + .jump 10], + -- bb10 + [.op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb11 + [.op (.stack (.push 0x417000000010000000200000000)), + .effect .caller 0, + .op (.stack (.push 0xffffffffffffffffffffffffffffffffffffffff)), + .jump 13], + -- bb12 + [.op (.stack (.push 0x417000000010000000200000000)), + .effect .caller 0, + .op (.stack (.push 0xffffffffffffffffffffffffffffffffffffffff)), + .jump 13], + -- bb13 + [.op (.stack (.swap 1)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op .store, + .op (.stack (.push 96)), + .op .store, + .op (.stack (.push 0xed572b27)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 100)), + .op (.stack (.push 28)), + .revert], + -- bb14 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb15 + [.op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 160)), + .op (.stack .shr), + .op (.stack (.push 68)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack .or), + .jumpi 23, + .jump 16], + -- bb16 + [.op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 0xffffffffffffffffffffffffffffffffffffffff)), + .op (.stack (.dup 1)), + .op (.stack .and), + .op (.stack (.push 36)), + .effect .calldataload 1, + .op (.stack (.dup 2)), + .pushLabel 17, + .jump 30], + -- bb17 + [.op (.stack (.push 0)), + .op .store, + .op (.stack (.push 0xffffffffffffffffffffffffffffffffffffffff)), + .op (.stack (.dup 2)), + .op (.stack .gt), + .jumpi 21, + .jump 18], + -- bb18 + [.op (.stack (.dup 1)), + .op (.stack (.dup 1)), + .op (.stack .sub), + .jumpi 20, + .jump 19], + -- bb19 + [.op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb20 + [.op (.stack (.push 0x102000000020000000200000007)), + .jump 22], + -- bb21 + [.op (.stack .pop), + .op (.stack (.push 0xffffffffffffffffffffffffffffffffffffffff)), + .op (.stack (.push 0x417000000020000000200000009)), + .op (.stack (.swap 1)), + .op (.stack (.swap 0)), + .op (.stack (.swap 1)), + .jump 22], + -- bb22 + [.op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op .store, + .op (.stack (.push 96)), + .op .store, + .op (.stack (.push 0xed572b27)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 100)), + .op (.stack (.push 28)), + .revert], + -- bb23 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb24 + [.op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 160)), + .op (.stack .shr), + .op (.stack (.push 36)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack .or), + .jumpi 29, + .jump 25], + -- bb25 + [.op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 0xffffffffffffffffffffffffffffffffffffffff)), + .op (.stack (.dup 1)), + .op (.stack .and), + .op (.stack (.dup 1)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 0)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .effect .sload 1, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.dup 1)), + .op (.stack (.dup 1)), + .op (.stack .sub), + .jumpi 27, + .jump 26], + -- bb26 + [.op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb27 + [.op (.stack (.push 0x102000000030000000200000009)), + .jump 28], + -- bb28 + [.op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op .store, + .op (.stack (.push 96)), + .op .store, + .op (.stack (.push 0xed572b27)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 100)), + .op (.stack (.push 28)), + .revert], + -- bb29 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb30 + [.op (.stack (.dup 1)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 0)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .op (.stack (.dup 0)), + .effect .sload 1, + .op (.stack (.dup 4)), + .op (.stack (.dup 1)), + .op (.stack .add), + .op (.stack (.swap 0)), + .op (.stack (.dup 1)), + .op (.stack .lt), + .op (.stack (.push 0xffffffffffffffffffffffffffffffffffffffff)), + .op (.stack (.dup 5)), + .op (.stack .gt), + .jumpi 35, + .jump 31], + -- bb31 + [.jumpi 34, + .jump 32], + -- bb32 + [.op (.stack (.dup 1)), + .effect .sstore 2, + .op (.stack (.push 1)), + .effect .sload 1, + .op (.stack (.swap 3)), + .op (.stack (.dup 4)), + .op (.stack .add), + .op (.stack (.swap 3)), + .op (.stack (.dup 4)), + .op (.stack .lt), + .jumpi 34, + .jump 33], + -- bb33 + [.op (.stack (.swap 2)), + .op (.stack (.push 1)), + .effect .sstore 2, + .op (.stack (.swap 1)), + .effect .sload 1, + .op (.stack (.swap 0)), + .op (.stack .pop), + .op (.stack (.swap 0)), + .jumpDyn], + -- bb34 + [.op (.stack (.push 17)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 0x4e487b71)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 36)), + .op (.stack (.push 28)), + .revert], + -- bb35 + [.op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack (.push 0x417000000000000000080000000)), + .op (.stack (.push 0xffffffffffffffffffffffffffffffffffffffff)), + .jump 36], + -- bb36 + [.op (.stack (.swap 0)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.swap 0)), + .op (.stack (.push 64)), + .op .store, + .op (.stack (.push 96)), + .op .store, + .op (.stack (.push 0xed572b27)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 100)), + .op (.stack (.push 28)), + .revert]] } + +end SolarTV.Export.Bank diff --git a/Certified/bank/gen/Bank/Evm10.lean b/Certified/bank/gen/Bank/Evm10.lean new file mode 100644 index 00000000..d52d203a --- /dev/null +++ b/Certified/bank/gen/Bank/Evm10.lean @@ -0,0 +1,265 @@ +-- solar-lean-stage: kind=evm index=10 pass=block-layout +import SolarTV.EVMIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `Bank`; do not edit. -/ + +namespace SolarTV.Export.Bank + +/-- The runtime EVM IR after `block-layout`. -/ +def evm10 : EVM.Program.Program := + { blocks := [ + -- bb0 + [.effect .callvalue 0, + .jumpi 1, + .op (.stack (.push 0)), + .effect .calldataload 1, + .op (.stack (.push 224)), + .op (.stack .shr), + .op (.stack (.dup 0)), + .op (.stack (.push 0x2f4f21e2)), + .op (.stack .eq), + .jumpi 9, + .op (.stack (.dup 0)), + .op (.stack (.push 0x70a08231)), + .op (.stack .eq), + .jumpi 13, + .op (.stack (.dup 0)), + .op (.stack (.push 0xb6b55f25)), + .op (.stack .eq), + .jumpi 3, + .jump 1], + -- bb5 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb34 + [.op (.stack (.push 17)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 0x4e487b71)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 36)), + .op (.stack (.push 28)), + .revert], + -- bb6 + [.op (.stack (.push 36)), + .op (.stack .calldatasize), + .op (.stack .lt), + .jumpi 1, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.dup 0)), + .effect .caller 0, + .pushLabel 5, + .jump 4], + -- bb30 + [.op (.stack (.dup 1)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 0)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .op (.stack (.dup 0)), + .effect .sload 1, + .op (.stack (.dup 4)), + .op (.stack (.dup 1)), + .op (.stack .add), + .op (.stack (.swap 0)), + .op (.stack (.dup 1)), + .op (.stack .lt), + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .op (.stack (.dup 5)), + .op (.stack .gt), + .jumpi 15, + .jumpi 2, + .op (.stack (.dup 1)), + .effect .sstore 2, + .op (.stack (.push 1)), + .effect .sload 1, + .op (.stack (.swap 3)), + .op (.stack (.dup 4)), + .op (.stack .add), + .op (.stack (.swap 3)), + .op (.stack (.dup 4)), + .op (.stack .lt), + .jumpi 2, + .op (.stack (.swap 2)), + .op (.stack (.push 1)), + .effect .sstore 2, + .op (.stack (.swap 1)), + .effect .sload 1, + .op (.stack (.swap 0)), + .op (.stack .pop), + .op (.stack (.swap 0)), + .jumpDyn], + -- bb8 + [.op (.stack (.swap 0)), + .op (.stack (.push 0)), + .op .store, + .effect .caller 0, + .op (.stack (.push 0xe1fffcc4923d04b559f4d29a8bfc6cda04eb5b0d3c460751c2402c5c5cc9109c)), + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .effect (.log 2) 4, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .effect .caller 0, + .op (.stack .gt), + .jumpi 6, + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .effect .caller 0, + .op (.stack .gt), + .jumpi 6, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb11 + [.op (.stack (.push 0x4170000000100000002)), + .op (.stack (.push 32)), + .op (.stack .shl), + .effect .caller 0, + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .op (.stack (.swap 1)), + .jump 7], + -- bb37 + [.op (.stack (.push 32)), + .op .store, + .jump 8], + -- bb36 + [.op (.stack (.push 64)), + .op .store, + .op (.stack (.push 96)), + .op .store, + .op (.stack (.push 0xed572b27)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 100)), + .op (.stack (.push 28)), + .revert], + -- bb15 + [.op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 160)), + .op (.stack .shr), + .op (.stack (.push 68)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack .or), + .jumpi 1, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .op (.stack (.dup 1)), + .op (.stack .and), + .op (.stack (.push 36)), + .effect .calldataload 1, + .op (.stack (.dup 2)), + .pushLabel 10, + .jump 4], + -- bb17 + [.op (.stack (.push 0)), + .op .store, + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .op (.stack (.dup 2)), + .op (.stack .gt), + .jumpi 12, + .op (.stack (.dup 1)), + .op (.stack (.dup 1)), + .op (.stack .sub), + .jumpi 11, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb20 + [.op (.stack (.push 0x102000000020000000200000007)), + .jump 7], + -- bb21 + [.op (.stack .pop), + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .op (.stack (.push 0x417000000020000000200000009)), + .op (.stack (.swap 1)), + .op (.stack (.swap 0)), + .op (.stack (.swap 1)), + .jump 7], + -- bb24 + [.op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 160)), + .op (.stack .shr), + .op (.stack (.push 36)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack .or), + .jumpi 1, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .op (.stack (.dup 1)), + .op (.stack .and), + .op (.stack (.dup 1)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 0)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .effect .sload 1, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.dup 1)), + .op (.stack (.dup 1)), + .op (.stack .sub), + .jumpi 14, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb27 + [.op (.stack (.push 0x102000000030000000200000009)), + .jump 7], + -- bb35 + [.op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .op (.stack (.push 0x417000000000000000080000000)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.swap 0)), + .jump 8]] } + +end SolarTV.Export.Bank diff --git a/Certified/bank/gen/Bank/Evm11.lean b/Certified/bank/gen/Bank/Evm11.lean new file mode 100644 index 00000000..00f7ad58 --- /dev/null +++ b/Certified/bank/gen/Bank/Evm11.lean @@ -0,0 +1,263 @@ +-- solar-lean-stage: kind=evm index=11 pass=stack-reschedule +import SolarTV.EVMIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `Bank`; do not edit. -/ + +namespace SolarTV.Export.Bank + +/-- The runtime EVM IR after `stack-reschedule`. -/ +def evm11 : EVM.Program.Program := + { blocks := [ + -- bb0 + [.effect .callvalue 0, + .jumpi 1, + .op (.stack (.push 0)), + .effect .calldataload 1, + .op (.stack (.push 224)), + .op (.stack .shr), + .op (.stack (.dup 0)), + .op (.stack (.push 0x2f4f21e2)), + .op (.stack .eq), + .jumpi 9, + .op (.stack (.dup 0)), + .op (.stack (.push 0x70a08231)), + .op (.stack .eq), + .jumpi 13, + .op (.stack (.dup 0)), + .op (.stack (.push 0xb6b55f25)), + .op (.stack .eq), + .jumpi 3, + .jump 1], + -- bb5 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb34 + [.op (.stack (.push 17)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 0x4e487b71)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 36)), + .op (.stack (.push 28)), + .revert], + -- bb6 + [.op (.stack (.push 36)), + .op (.stack .calldatasize), + .op (.stack .lt), + .jumpi 1, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.dup 0)), + .effect .caller 0, + .pushLabel 5, + .jump 4], + -- bb30 + [.op (.stack (.dup 1)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 0)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .op (.stack (.dup 0)), + .effect .sload 1, + .op (.stack (.dup 4)), + .op (.stack (.dup 1)), + .op (.stack .add), + .op (.stack (.swap 0)), + .op (.stack (.dup 1)), + .op (.stack .lt), + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .op (.stack (.dup 5)), + .op (.stack .gt), + .jumpi 15, + .jumpi 2, + .op (.stack (.dup 1)), + .effect .sstore 2, + .op (.stack (.push 1)), + .effect .sload 1, + .op (.stack (.swap 3)), + .op (.stack (.dup 4)), + .op (.stack .add), + .op (.stack (.swap 3)), + .op (.stack (.dup 4)), + .op (.stack .lt), + .jumpi 2, + .op (.stack (.swap 2)), + .op (.stack (.push 1)), + .effect .sstore 2, + .op (.stack (.swap 1)), + .effect .sload 1, + .op (.stack (.swap 0)), + .op (.stack .pop), + .op (.stack (.swap 0)), + .jumpDyn], + -- bb8 + [.op (.stack (.swap 0)), + .op (.stack (.push 0)), + .op .store, + .effect .caller 0, + .op (.stack (.push 0xe1fffcc4923d04b559f4d29a8bfc6cda04eb5b0d3c460751c2402c5c5cc9109c)), + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .effect (.log 2) 4, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .effect .caller 0, + .op (.stack .gt), + .jumpi 6, + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .effect .caller 0, + .op (.stack .gt), + .jumpi 6, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb11 + [.op (.stack (.push 0x4170000000100000002)), + .op (.stack (.push 32)), + .op (.stack .shl), + .effect .caller 0, + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .op (.stack (.swap 1)), + .jump 7], + -- bb37 + [.op (.stack (.push 32)), + .op .store, + .jump 8], + -- bb36 + [.op (.stack (.push 64)), + .op .store, + .op (.stack (.push 96)), + .op .store, + .op (.stack (.push 0xed572b27)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 100)), + .op (.stack (.push 28)), + .revert], + -- bb15 + [.op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 160)), + .op (.stack .shr), + .op (.stack (.push 68)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack .or), + .jumpi 1, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .op (.stack (.dup 1)), + .op (.stack .and), + .op (.stack (.push 36)), + .effect .calldataload 1, + .op (.stack (.dup 2)), + .pushLabel 10, + .jump 4], + -- bb17 + [.op (.stack (.push 0)), + .op .store, + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .op (.stack (.dup 2)), + .op (.stack .gt), + .jumpi 12, + .op (.stack (.dup 1)), + .op (.stack (.dup 1)), + .op (.stack .sub), + .jumpi 11, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb20 + [.op (.stack (.push 0x102000000020000000200000007)), + .jump 7], + -- bb21 + [.op (.stack .pop), + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .op (.stack (.swap 0)), + .op (.stack (.push 0x417000000020000000200000009)), + .jump 7], + -- bb24 + [.op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 160)), + .op (.stack .shr), + .op (.stack (.push 36)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack .or), + .jumpi 1, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .op (.stack (.dup 1)), + .op (.stack .and), + .op (.stack (.dup 1)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 0)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .effect .sload 1, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.dup 1)), + .op (.stack (.dup 1)), + .op (.stack .sub), + .jumpi 14, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb27 + [.op (.stack (.push 0x102000000030000000200000009)), + .jump 7], + -- bb35 + [.op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .op (.stack (.push 0x417000000000000000080000000)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.swap 0)), + .jump 8]] } + +end SolarTV.Export.Bank diff --git a/Certified/bank/gen/Bank/Evm2.lean b/Certified/bank/gen/Bank/Evm2.lean new file mode 100644 index 00000000..986c3065 --- /dev/null +++ b/Certified/bank/gen/Bank/Evm2.lean @@ -0,0 +1,285 @@ +-- solar-lean-stage: kind=evm index=2 pass=cfg-simplify-early +import SolarTV.EVMIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `Bank`; do not edit. -/ + +namespace SolarTV.Export.Bank + +/-- The runtime EVM IR after `cfg-simplify-early`. -/ +def evm2 : EVM.Program.Program := + { blocks := [ + -- bb0 + [.effect .callvalue 0, + .jumpi 1, + .op (.stack (.push 0)), + .effect .calldataload 1, + .op (.stack (.push 224)), + .op (.stack .shr), + .op (.stack (.dup 0)), + .op (.stack (.push 0x2f4f21e2)), + .op (.stack .eq), + .jumpi 8, + .op (.stack (.dup 0)), + .op (.stack (.push 0x70a08231)), + .op (.stack .eq), + .jumpi 14, + .op (.stack (.dup 0)), + .op (.stack (.push 0xb6b55f25)), + .op (.stack .eq), + .jumpi 2, + .jump 1], + -- bb5 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb6 + [.op (.stack (.push 36)), + .op (.stack .calldatasize), + .op (.stack .lt), + .jumpi 7, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.dup 0)), + .effect .caller 0, + .pushLabel 3, + .jump 17], + -- bb8 + [.op (.stack (.swap 0)), + .op (.stack (.push 0)), + .op .store, + .effect .caller 0, + .op (.stack (.push 0xe1fffcc4923d04b559f4d29a8bfc6cda04eb5b0d3c460751c2402c5c5cc9109c)), + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .effect (.log 2) 4, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 0xffffffffffffffffffffffffffffffffffffffff)), + .effect .caller 0, + .op (.stack .gt), + .jumpi 5, + .op (.stack (.push 0xffffffffffffffffffffffffffffffffffffffff)), + .effect .caller 0, + .op (.stack .gt), + .jumpi 4, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb11 + [.op (.stack (.push 0x417000000010000000200000000)), + .effect .caller 0, + .op (.stack (.push 0xffffffffffffffffffffffffffffffffffffffff)), + .jump 6], + -- bb12 + [.op (.stack (.push 0x417000000010000000200000000)), + .effect .caller 0, + .op (.stack (.push 0xffffffffffffffffffffffffffffffffffffffff)), + .jump 6], + -- bb13 + [.op (.stack (.swap 1)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op .store, + .op (.stack (.push 96)), + .op .store, + .op (.stack (.push 0xed572b27)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 100)), + .op (.stack (.push 28)), + .revert], + -- bb14 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb15 + [.op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 160)), + .op (.stack .shr), + .op (.stack (.push 68)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack .or), + .jumpi 13, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 0xffffffffffffffffffffffffffffffffffffffff)), + .op (.stack (.dup 1)), + .op (.stack .and), + .op (.stack (.push 36)), + .effect .calldataload 1, + .op (.stack (.dup 2)), + .pushLabel 9, + .jump 17], + -- bb17 + [.op (.stack (.push 0)), + .op .store, + .op (.stack (.push 0xffffffffffffffffffffffffffffffffffffffff)), + .op (.stack (.dup 2)), + .op (.stack .gt), + .jumpi 11, + .op (.stack (.dup 1)), + .op (.stack (.dup 1)), + .op (.stack .sub), + .jumpi 10, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb20 + [.op (.stack (.push 0x102000000020000000200000007)), + .jump 12], + -- bb21 + [.op (.stack .pop), + .op (.stack (.push 0xffffffffffffffffffffffffffffffffffffffff)), + .op (.stack (.push 0x417000000020000000200000009)), + .op (.stack (.swap 1)), + .op (.stack (.swap 0)), + .op (.stack (.swap 1)), + .jump 12], + -- bb22 + [.op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op .store, + .op (.stack (.push 96)), + .op .store, + .op (.stack (.push 0xed572b27)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 100)), + .op (.stack (.push 28)), + .revert], + -- bb23 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb24 + [.op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 160)), + .op (.stack .shr), + .op (.stack (.push 36)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack .or), + .jumpi 16, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 0xffffffffffffffffffffffffffffffffffffffff)), + .op (.stack (.dup 1)), + .op (.stack .and), + .op (.stack (.dup 1)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 0)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .effect .sload 1, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.dup 1)), + .op (.stack (.dup 1)), + .op (.stack .sub), + .jumpi 15, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb27 + [.op (.stack (.push 0x102000000030000000200000009)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op .store, + .op (.stack (.push 96)), + .op .store, + .op (.stack (.push 0xed572b27)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 100)), + .op (.stack (.push 28)), + .revert], + -- bb29 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb30 + [.op (.stack (.dup 1)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 0)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .op (.stack (.dup 0)), + .effect .sload 1, + .op (.stack (.dup 4)), + .op (.stack (.dup 1)), + .op (.stack .add), + .op (.stack (.swap 0)), + .op (.stack (.dup 1)), + .op (.stack .lt), + .op (.stack (.push 0xffffffffffffffffffffffffffffffffffffffff)), + .op (.stack (.dup 5)), + .op (.stack .gt), + .jumpi 19, + .jumpi 18, + .op (.stack (.dup 1)), + .effect .sstore 2, + .op (.stack (.push 1)), + .effect .sload 1, + .op (.stack (.swap 3)), + .op (.stack (.dup 4)), + .op (.stack .add), + .op (.stack (.swap 3)), + .op (.stack (.dup 4)), + .op (.stack .lt), + .jumpi 18, + .op (.stack (.swap 2)), + .op (.stack (.push 1)), + .effect .sstore 2, + .op (.stack (.swap 1)), + .effect .sload 1, + .op (.stack (.swap 0)), + .op (.stack .pop), + .op (.stack (.swap 0)), + .jumpDyn], + -- bb34 + [.op (.stack (.push 17)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 0x4e487b71)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 36)), + .op (.stack (.push 28)), + .revert], + -- bb35 + [.op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack (.push 0x417000000000000000080000000)), + .op (.stack (.push 0xffffffffffffffffffffffffffffffffffffffff)), + .op (.stack (.swap 0)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.swap 0)), + .op (.stack (.push 64)), + .op .store, + .op (.stack (.push 96)), + .op .store, + .op (.stack (.push 0xed572b27)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 100)), + .op (.stack (.push 28)), + .revert]] } + +end SolarTV.Export.Bank diff --git a/Certified/bank/gen/Bank/Evm3.lean b/Certified/bank/gen/Bank/Evm3.lean new file mode 100644 index 00000000..ca797f6d --- /dev/null +++ b/Certified/bank/gen/Bank/Evm3.lean @@ -0,0 +1,319 @@ +-- solar-lean-stage: kind=evm index=3 pass=compact-pushes +import SolarTV.EVMIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `Bank`; do not edit. -/ + +namespace SolarTV.Export.Bank + +/-- The runtime EVM IR after `compact-pushes`. -/ +def evm3 : EVM.Program.Program := + { blocks := [ + -- bb0 + [.effect .callvalue 0, + .jumpi 1, + .op (.stack (.push 0)), + .effect .calldataload 1, + .op (.stack (.push 224)), + .op (.stack .shr), + .op (.stack (.dup 0)), + .op (.stack (.push 0x2f4f21e2)), + .op (.stack .eq), + .jumpi 8, + .op (.stack (.dup 0)), + .op (.stack (.push 0x70a08231)), + .op (.stack .eq), + .jumpi 14, + .op (.stack (.dup 0)), + .op (.stack (.push 0xb6b55f25)), + .op (.stack .eq), + .jumpi 2, + .jump 1], + -- bb5 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb6 + [.op (.stack (.push 36)), + .op (.stack .calldatasize), + .op (.stack .lt), + .jumpi 7, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.dup 0)), + .effect .caller 0, + .pushLabel 3, + .jump 17], + -- bb8 + [.op (.stack (.swap 0)), + .op (.stack (.push 0)), + .op .store, + .effect .caller 0, + .op (.stack (.push 0xe1fffcc4923d04b559f4d29a8bfc6cda04eb5b0d3c460751c2402c5c5cc9109c)), + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .effect (.log 2) 4, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .effect .caller 0, + .op (.stack .gt), + .jumpi 5, + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .effect .caller 0, + .op (.stack .gt), + .jumpi 4, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb11 + [.op (.stack (.push 0x4170000000100000002)), + .op (.stack (.push 32)), + .op (.stack .shl), + .effect .caller 0, + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .jump 6], + -- bb12 + [.op (.stack (.push 0x4170000000100000002)), + .op (.stack (.push 32)), + .op (.stack .shl), + .effect .caller 0, + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .jump 6], + -- bb13 + [.op (.stack (.swap 1)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op .store, + .op (.stack (.push 96)), + .op .store, + .op (.stack (.push 0xed572b27)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 100)), + .op (.stack (.push 28)), + .revert], + -- bb14 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb15 + [.op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 160)), + .op (.stack .shr), + .op (.stack (.push 68)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack .or), + .jumpi 13, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .op (.stack (.dup 1)), + .op (.stack .and), + .op (.stack (.push 36)), + .effect .calldataload 1, + .op (.stack (.dup 2)), + .pushLabel 9, + .jump 17], + -- bb17 + [.op (.stack (.push 0)), + .op .store, + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .op (.stack (.dup 2)), + .op (.stack .gt), + .jumpi 11, + .op (.stack (.dup 1)), + .op (.stack (.dup 1)), + .op (.stack .sub), + .jumpi 10, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb20 + [.op (.stack (.push 0x102000000020000000200000007)), + .jump 12], + -- bb21 + [.op (.stack .pop), + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .op (.stack (.push 0x417000000020000000200000009)), + .op (.stack (.swap 1)), + .op (.stack (.swap 0)), + .op (.stack (.swap 1)), + .jump 12], + -- bb22 + [.op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op .store, + .op (.stack (.push 96)), + .op .store, + .op (.stack (.push 0xed572b27)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 100)), + .op (.stack (.push 28)), + .revert], + -- bb23 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb24 + [.op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 160)), + .op (.stack .shr), + .op (.stack (.push 36)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack .or), + .jumpi 16, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .op (.stack (.dup 1)), + .op (.stack .and), + .op (.stack (.dup 1)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 0)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .effect .sload 1, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.dup 1)), + .op (.stack (.dup 1)), + .op (.stack .sub), + .jumpi 15, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb27 + [.op (.stack (.push 0x102000000030000000200000009)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op .store, + .op (.stack (.push 96)), + .op .store, + .op (.stack (.push 0xed572b27)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 100)), + .op (.stack (.push 28)), + .revert], + -- bb29 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb30 + [.op (.stack (.dup 1)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 0)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .op (.stack (.dup 0)), + .effect .sload 1, + .op (.stack (.dup 4)), + .op (.stack (.dup 1)), + .op (.stack .add), + .op (.stack (.swap 0)), + .op (.stack (.dup 1)), + .op (.stack .lt), + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .op (.stack (.dup 5)), + .op (.stack .gt), + .jumpi 19, + .jumpi 18, + .op (.stack (.dup 1)), + .effect .sstore 2, + .op (.stack (.push 1)), + .effect .sload 1, + .op (.stack (.swap 3)), + .op (.stack (.dup 4)), + .op (.stack .add), + .op (.stack (.swap 3)), + .op (.stack (.dup 4)), + .op (.stack .lt), + .jumpi 18, + .op (.stack (.swap 2)), + .op (.stack (.push 1)), + .effect .sstore 2, + .op (.stack (.swap 1)), + .effect .sload 1, + .op (.stack (.swap 0)), + .op (.stack .pop), + .op (.stack (.swap 0)), + .jumpDyn], + -- bb34 + [.op (.stack (.push 17)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 0x4e487b71)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 36)), + .op (.stack (.push 28)), + .revert], + -- bb35 + [.op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack (.push 0x417000000000000000080000000)), + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .op (.stack (.swap 0)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.swap 0)), + .op (.stack (.push 64)), + .op .store, + .op (.stack (.push 96)), + .op .store, + .op (.stack (.push 0xed572b27)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 100)), + .op (.stack (.push 28)), + .revert]] } + +end SolarTV.Export.Bank diff --git a/Certified/bank/gen/Bank/Evm4.lean b/Certified/bank/gen/Bank/Evm4.lean new file mode 100644 index 00000000..3c4875ec --- /dev/null +++ b/Certified/bank/gen/Bank/Evm4.lean @@ -0,0 +1,319 @@ +-- solar-lean-stage: kind=evm index=4 pass=block-layout +import SolarTV.EVMIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `Bank`; do not edit. -/ + +namespace SolarTV.Export.Bank + +/-- The runtime EVM IR after `block-layout`. -/ +def evm4 : EVM.Program.Program := + { blocks := [ + -- bb0 + [.effect .callvalue 0, + .jumpi 1, + .op (.stack (.push 0)), + .effect .calldataload 1, + .op (.stack (.push 224)), + .op (.stack .shr), + .op (.stack (.dup 0)), + .op (.stack (.push 0x2f4f21e2)), + .op (.stack .eq), + .jumpi 9, + .op (.stack (.dup 0)), + .op (.stack (.push 0x70a08231)), + .op (.stack .eq), + .jumpi 14, + .op (.stack (.dup 0)), + .op (.stack (.push 0xb6b55f25)), + .op (.stack .eq), + .jumpi 3, + .jump 1], + -- bb5 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb34 + [.op (.stack (.push 17)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 0x4e487b71)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 36)), + .op (.stack (.push 28)), + .revert], + -- bb6 + [.op (.stack (.push 36)), + .op (.stack .calldatasize), + .op (.stack .lt), + .jumpi 15, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.dup 0)), + .effect .caller 0, + .pushLabel 5, + .jump 4], + -- bb30 + [.op (.stack (.dup 1)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 0)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .op (.stack (.dup 0)), + .effect .sload 1, + .op (.stack (.dup 4)), + .op (.stack (.dup 1)), + .op (.stack .add), + .op (.stack (.swap 0)), + .op (.stack (.dup 1)), + .op (.stack .lt), + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .op (.stack (.dup 5)), + .op (.stack .gt), + .jumpi 19, + .jumpi 2, + .op (.stack (.dup 1)), + .effect .sstore 2, + .op (.stack (.push 1)), + .effect .sload 1, + .op (.stack (.swap 3)), + .op (.stack (.dup 4)), + .op (.stack .add), + .op (.stack (.swap 3)), + .op (.stack (.dup 4)), + .op (.stack .lt), + .jumpi 2, + .op (.stack (.swap 2)), + .op (.stack (.push 1)), + .effect .sstore 2, + .op (.stack (.swap 1)), + .effect .sload 1, + .op (.stack (.swap 0)), + .op (.stack .pop), + .op (.stack (.swap 0)), + .jumpDyn], + -- bb8 + [.op (.stack (.swap 0)), + .op (.stack (.push 0)), + .op .store, + .effect .caller 0, + .op (.stack (.push 0xe1fffcc4923d04b559f4d29a8bfc6cda04eb5b0d3c460751c2402c5c5cc9109c)), + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .effect (.log 2) 4, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .effect .caller 0, + .op (.stack .gt), + .jumpi 8, + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .effect .caller 0, + .op (.stack .gt), + .jumpi 6, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb11 + [.op (.stack (.push 0x4170000000100000002)), + .op (.stack (.push 32)), + .op (.stack .shl), + .effect .caller 0, + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .jump 7], + -- bb13 + [.op (.stack (.swap 1)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op .store, + .op (.stack (.push 96)), + .op .store, + .op (.stack (.push 0xed572b27)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 100)), + .op (.stack (.push 28)), + .revert], + -- bb12 + [.op (.stack (.push 0x4170000000100000002)), + .op (.stack (.push 32)), + .op (.stack .shl), + .effect .caller 0, + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .jump 7], + -- bb15 + [.op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 160)), + .op (.stack .shr), + .op (.stack (.push 68)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack .or), + .jumpi 16, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .op (.stack (.dup 1)), + .op (.stack .and), + .op (.stack (.push 36)), + .effect .calldataload 1, + .op (.stack (.dup 2)), + .pushLabel 10, + .jump 4], + -- bb17 + [.op (.stack (.push 0)), + .op .store, + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .op (.stack (.dup 2)), + .op (.stack .gt), + .jumpi 13, + .op (.stack (.dup 1)), + .op (.stack (.dup 1)), + .op (.stack .sub), + .jumpi 11, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb20 + [.op (.stack (.push 0x102000000020000000200000007)), + .jump 12], + -- bb22 + [.op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op .store, + .op (.stack (.push 96)), + .op .store, + .op (.stack (.push 0xed572b27)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 100)), + .op (.stack (.push 28)), + .revert], + -- bb21 + [.op (.stack .pop), + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .op (.stack (.push 0x417000000020000000200000009)), + .op (.stack (.swap 1)), + .op (.stack (.swap 0)), + .op (.stack (.swap 1)), + .jump 12], + -- bb24 + [.op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 160)), + .op (.stack .shr), + .op (.stack (.push 36)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack .or), + .jumpi 18, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .op (.stack (.dup 1)), + .op (.stack .and), + .op (.stack (.dup 1)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 0)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .effect .sload 1, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.dup 1)), + .op (.stack (.dup 1)), + .op (.stack .sub), + .jumpi 17, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb14 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb23 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb27 + [.op (.stack (.push 0x102000000030000000200000009)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op .store, + .op (.stack (.push 96)), + .op .store, + .op (.stack (.push 0xed572b27)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 100)), + .op (.stack (.push 28)), + .revert], + -- bb29 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb35 + [.op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack (.push 0x417000000000000000080000000)), + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .op (.stack (.swap 0)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.swap 0)), + .op (.stack (.push 64)), + .op .store, + .op (.stack (.push 96)), + .op .store, + .op (.stack (.push 0xed572b27)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 100)), + .op (.stack (.push 28)), + .revert]] } + +end SolarTV.Export.Bank diff --git a/Certified/bank/gen/Bank/Evm5.lean b/Certified/bank/gen/Bank/Evm5.lean new file mode 100644 index 00000000..5423cb76 --- /dev/null +++ b/Certified/bank/gen/Bank/Evm5.lean @@ -0,0 +1,305 @@ +-- solar-lean-stage: kind=evm index=5 pass=terminal-dedup +import SolarTV.EVMIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `Bank`; do not edit. -/ + +namespace SolarTV.Export.Bank + +/-- The runtime EVM IR after `terminal-dedup`. -/ +def evm5 : EVM.Program.Program := + { blocks := [ + -- bb0 + [.effect .callvalue 0, + .jumpi 1, + .op (.stack (.push 0)), + .effect .calldataload 1, + .op (.stack (.push 224)), + .op (.stack .shr), + .op (.stack (.dup 0)), + .op (.stack (.push 0x2f4f21e2)), + .op (.stack .eq), + .jumpi 9, + .op (.stack (.dup 0)), + .op (.stack (.push 0x70a08231)), + .op (.stack .eq), + .jumpi 14, + .op (.stack (.dup 0)), + .op (.stack (.push 0xb6b55f25)), + .op (.stack .eq), + .jumpi 3, + .jump 1], + -- bb5 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb34 + [.op (.stack (.push 17)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 0x4e487b71)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 36)), + .op (.stack (.push 28)), + .revert], + -- bb6 + [.op (.stack (.push 36)), + .op (.stack .calldatasize), + .op (.stack .lt), + .jumpi 15, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.dup 0)), + .effect .caller 0, + .pushLabel 5, + .jump 4], + -- bb30 + [.op (.stack (.dup 1)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 0)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .op (.stack (.dup 0)), + .effect .sload 1, + .op (.stack (.dup 4)), + .op (.stack (.dup 1)), + .op (.stack .add), + .op (.stack (.swap 0)), + .op (.stack (.dup 1)), + .op (.stack .lt), + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .op (.stack (.dup 5)), + .op (.stack .gt), + .jumpi 19, + .jumpi 2, + .op (.stack (.dup 1)), + .effect .sstore 2, + .op (.stack (.push 1)), + .effect .sload 1, + .op (.stack (.swap 3)), + .op (.stack (.dup 4)), + .op (.stack .add), + .op (.stack (.swap 3)), + .op (.stack (.dup 4)), + .op (.stack .lt), + .jumpi 2, + .op (.stack (.swap 2)), + .op (.stack (.push 1)), + .effect .sstore 2, + .op (.stack (.swap 1)), + .effect .sload 1, + .op (.stack (.swap 0)), + .op (.stack .pop), + .op (.stack (.swap 0)), + .jumpDyn], + -- bb8 + [.op (.stack (.swap 0)), + .op (.stack (.push 0)), + .op .store, + .effect .caller 0, + .op (.stack (.push 0xe1fffcc4923d04b559f4d29a8bfc6cda04eb5b0d3c460751c2402c5c5cc9109c)), + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .effect (.log 2) 4, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .effect .caller 0, + .op (.stack .gt), + .jumpi 8, + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .effect .caller 0, + .op (.stack .gt), + .jumpi 6, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb11 + [.op (.stack (.push 0x4170000000100000002)), + .op (.stack (.push 32)), + .op (.stack .shl), + .effect .caller 0, + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .jump 7], + -- bb13 + [.op (.stack (.swap 1)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op .store, + .op (.stack (.push 96)), + .op .store, + .op (.stack (.push 0xed572b27)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 100)), + .op (.stack (.push 28)), + .revert], + -- bb12 + [.jump 6], + -- bb15 + [.op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 160)), + .op (.stack .shr), + .op (.stack (.push 68)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack .or), + .jumpi 16, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .op (.stack (.dup 1)), + .op (.stack .and), + .op (.stack (.push 36)), + .effect .calldataload 1, + .op (.stack (.dup 2)), + .pushLabel 10, + .jump 4], + -- bb17 + [.op (.stack (.push 0)), + .op .store, + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .op (.stack (.dup 2)), + .op (.stack .gt), + .jumpi 13, + .op (.stack (.dup 1)), + .op (.stack (.dup 1)), + .op (.stack .sub), + .jumpi 11, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb20 + [.op (.stack (.push 0x102000000020000000200000007)), + .jump 12], + -- bb22 + [.op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op .store, + .op (.stack (.push 96)), + .op .store, + .op (.stack (.push 0xed572b27)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 100)), + .op (.stack (.push 28)), + .revert], + -- bb21 + [.op (.stack .pop), + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .op (.stack (.push 0x417000000020000000200000009)), + .op (.stack (.swap 1)), + .op (.stack (.swap 0)), + .op (.stack (.swap 1)), + .jump 12], + -- bb24 + [.op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 160)), + .op (.stack .shr), + .op (.stack (.push 36)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack .or), + .jumpi 18, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .op (.stack (.dup 1)), + .op (.stack .and), + .op (.stack (.dup 1)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 0)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .effect .sload 1, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.dup 1)), + .op (.stack (.dup 1)), + .op (.stack .sub), + .jumpi 17, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb14 + [.jump 1], + -- bb23 + [.jump 1], + -- bb27 + [.op (.stack (.push 0x102000000030000000200000009)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op .store, + .op (.stack (.push 96)), + .op .store, + .op (.stack (.push 0xed572b27)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 100)), + .op (.stack (.push 28)), + .revert], + -- bb29 + [.jump 1], + -- bb35 + [.op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack (.push 0x417000000000000000080000000)), + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .op (.stack (.swap 0)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.swap 0)), + .op (.stack (.push 64)), + .op .store, + .op (.stack (.push 96)), + .op .store, + .op (.stack (.push 0xed572b27)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 100)), + .op (.stack (.push 28)), + .revert]] } + +end SolarTV.Export.Bank diff --git a/Certified/bank/gen/Bank/Evm6.lean b/Certified/bank/gen/Bank/Evm6.lean new file mode 100644 index 00000000..42377488 --- /dev/null +++ b/Certified/bank/gen/Bank/Evm6.lean @@ -0,0 +1,295 @@ +-- solar-lean-stage: kind=evm index=6 pass=cfg-simplify-early +import SolarTV.EVMIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `Bank`; do not edit. -/ + +namespace SolarTV.Export.Bank + +/-- The runtime EVM IR after `cfg-simplify-early`. -/ +def evm6 : EVM.Program.Program := + { blocks := [ + -- bb0 + [.effect .callvalue 0, + .jumpi 1, + .op (.stack (.push 0)), + .effect .calldataload 1, + .op (.stack (.push 224)), + .op (.stack .shr), + .op (.stack (.dup 0)), + .op (.stack (.push 0x2f4f21e2)), + .op (.stack .eq), + .jumpi 7, + .op (.stack (.dup 0)), + .op (.stack (.push 0x70a08231)), + .op (.stack .eq), + .jumpi 12, + .op (.stack (.dup 0)), + .op (.stack (.push 0xb6b55f25)), + .op (.stack .eq), + .jumpi 3, + .jump 1], + -- bb5 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb34 + [.op (.stack (.push 17)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 0x4e487b71)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 36)), + .op (.stack (.push 28)), + .revert], + -- bb6 + [.op (.stack (.push 36)), + .op (.stack .calldatasize), + .op (.stack .lt), + .jumpi 1, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.dup 0)), + .effect .caller 0, + .pushLabel 5, + .jump 4], + -- bb30 + [.op (.stack (.dup 1)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 0)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .op (.stack (.dup 0)), + .effect .sload 1, + .op (.stack (.dup 4)), + .op (.stack (.dup 1)), + .op (.stack .add), + .op (.stack (.swap 0)), + .op (.stack (.dup 1)), + .op (.stack .lt), + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .op (.stack (.dup 5)), + .op (.stack .gt), + .jumpi 14, + .jumpi 2, + .op (.stack (.dup 1)), + .effect .sstore 2, + .op (.stack (.push 1)), + .effect .sload 1, + .op (.stack (.swap 3)), + .op (.stack (.dup 4)), + .op (.stack .add), + .op (.stack (.swap 3)), + .op (.stack (.dup 4)), + .op (.stack .lt), + .jumpi 2, + .op (.stack (.swap 2)), + .op (.stack (.push 1)), + .effect .sstore 2, + .op (.stack (.swap 1)), + .effect .sload 1, + .op (.stack (.swap 0)), + .op (.stack .pop), + .op (.stack (.swap 0)), + .jumpDyn], + -- bb8 + [.op (.stack (.swap 0)), + .op (.stack (.push 0)), + .op .store, + .effect .caller 0, + .op (.stack (.push 0xe1fffcc4923d04b559f4d29a8bfc6cda04eb5b0d3c460751c2402c5c5cc9109c)), + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .effect (.log 2) 4, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .effect .caller 0, + .op (.stack .gt), + .jumpi 6, + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .effect .caller 0, + .op (.stack .gt), + .jumpi 6, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb11 + [.op (.stack (.push 0x4170000000100000002)), + .op (.stack (.push 32)), + .op (.stack .shl), + .effect .caller 0, + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .op (.stack (.swap 1)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op .store, + .op (.stack (.push 96)), + .op .store, + .op (.stack (.push 0xed572b27)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 100)), + .op (.stack (.push 28)), + .revert], + -- bb15 + [.op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 160)), + .op (.stack .shr), + .op (.stack (.push 68)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack .or), + .jumpi 1, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .op (.stack (.dup 1)), + .op (.stack .and), + .op (.stack (.push 36)), + .effect .calldataload 1, + .op (.stack (.dup 2)), + .pushLabel 8, + .jump 4], + -- bb17 + [.op (.stack (.push 0)), + .op .store, + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .op (.stack (.dup 2)), + .op (.stack .gt), + .jumpi 11, + .op (.stack (.dup 1)), + .op (.stack (.dup 1)), + .op (.stack .sub), + .jumpi 9, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb20 + [.op (.stack (.push 0x102000000020000000200000007)), + .jump 10], + -- bb22 + [.op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op .store, + .op (.stack (.push 96)), + .op .store, + .op (.stack (.push 0xed572b27)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 100)), + .op (.stack (.push 28)), + .revert], + -- bb21 + [.op (.stack .pop), + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .op (.stack (.push 0x417000000020000000200000009)), + .op (.stack (.swap 1)), + .op (.stack (.swap 0)), + .op (.stack (.swap 1)), + .jump 10], + -- bb24 + [.op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 160)), + .op (.stack .shr), + .op (.stack (.push 36)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack .or), + .jumpi 1, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .op (.stack (.dup 1)), + .op (.stack .and), + .op (.stack (.dup 1)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 0)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .effect .sload 1, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.dup 1)), + .op (.stack (.dup 1)), + .op (.stack .sub), + .jumpi 13, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb27 + [.op (.stack (.push 0x102000000030000000200000009)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op .store, + .op (.stack (.push 96)), + .op .store, + .op (.stack (.push 0xed572b27)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 100)), + .op (.stack (.push 28)), + .revert], + -- bb35 + [.op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack (.push 0x417000000000000000080000000)), + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .op (.stack (.swap 0)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.swap 0)), + .op (.stack (.push 64)), + .op .store, + .op (.stack (.push 96)), + .op .store, + .op (.stack (.push 0xed572b27)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 100)), + .op (.stack (.push 28)), + .revert]] } + +end SolarTV.Export.Bank diff --git a/Certified/bank/gen/Bank/Evm7.lean b/Certified/bank/gen/Bank/Evm7.lean new file mode 100644 index 00000000..7317023c --- /dev/null +++ b/Certified/bank/gen/Bank/Evm7.lean @@ -0,0 +1,268 @@ +-- solar-lean-stage: kind=evm index=7 pass=tail-merge +import SolarTV.EVMIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `Bank`; do not edit. -/ + +namespace SolarTV.Export.Bank + +/-- The runtime EVM IR after `tail-merge`. -/ +def evm7 : EVM.Program.Program := + { blocks := [ + -- bb0 + [.effect .callvalue 0, + .jumpi 1, + .op (.stack (.push 0)), + .effect .calldataload 1, + .op (.stack (.push 224)), + .op (.stack .shr), + .op (.stack (.dup 0)), + .op (.stack (.push 0x2f4f21e2)), + .op (.stack .eq), + .jumpi 7, + .op (.stack (.dup 0)), + .op (.stack (.push 0x70a08231)), + .op (.stack .eq), + .jumpi 12, + .op (.stack (.dup 0)), + .op (.stack (.push 0xb6b55f25)), + .op (.stack .eq), + .jumpi 3, + .jump 1], + -- bb5 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb34 + [.op (.stack (.push 17)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 0x4e487b71)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 36)), + .op (.stack (.push 28)), + .revert], + -- bb6 + [.op (.stack (.push 36)), + .op (.stack .calldatasize), + .op (.stack .lt), + .jumpi 1, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.dup 0)), + .effect .caller 0, + .pushLabel 5, + .jump 4], + -- bb30 + [.op (.stack (.dup 1)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 0)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .op (.stack (.dup 0)), + .effect .sload 1, + .op (.stack (.dup 4)), + .op (.stack (.dup 1)), + .op (.stack .add), + .op (.stack (.swap 0)), + .op (.stack (.dup 1)), + .op (.stack .lt), + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .op (.stack (.dup 5)), + .op (.stack .gt), + .jumpi 14, + .jumpi 2, + .op (.stack (.dup 1)), + .effect .sstore 2, + .op (.stack (.push 1)), + .effect .sload 1, + .op (.stack (.swap 3)), + .op (.stack (.dup 4)), + .op (.stack .add), + .op (.stack (.swap 3)), + .op (.stack (.dup 4)), + .op (.stack .lt), + .jumpi 2, + .op (.stack (.swap 2)), + .op (.stack (.push 1)), + .effect .sstore 2, + .op (.stack (.swap 1)), + .effect .sload 1, + .op (.stack (.swap 0)), + .op (.stack .pop), + .op (.stack (.swap 0)), + .jumpDyn], + -- bb8 + [.op (.stack (.swap 0)), + .op (.stack (.push 0)), + .op .store, + .effect .caller 0, + .op (.stack (.push 0xe1fffcc4923d04b559f4d29a8bfc6cda04eb5b0d3c460751c2402c5c5cc9109c)), + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .effect (.log 2) 4, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .effect .caller 0, + .op (.stack .gt), + .jumpi 6, + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .effect .caller 0, + .op (.stack .gt), + .jumpi 6, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb11 + [.op (.stack (.push 0x4170000000100000002)), + .op (.stack (.push 32)), + .op (.stack .shl), + .effect .caller 0, + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .op (.stack (.swap 1)), + .jump 16], + -- bb15 + [.op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 160)), + .op (.stack .shr), + .op (.stack (.push 68)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack .or), + .jumpi 1, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .op (.stack (.dup 1)), + .op (.stack .and), + .op (.stack (.push 36)), + .effect .calldataload 1, + .op (.stack (.dup 2)), + .pushLabel 8, + .jump 4], + -- bb17 + [.op (.stack (.push 0)), + .op .store, + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .op (.stack (.dup 2)), + .op (.stack .gt), + .jumpi 11, + .op (.stack (.dup 1)), + .op (.stack (.dup 1)), + .op (.stack .sub), + .jumpi 9, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb20 + [.op (.stack (.push 0x102000000020000000200000007)), + .jump 10], + -- bb22 + [.jump 16], + -- bb21 + [.op (.stack .pop), + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .op (.stack (.push 0x417000000020000000200000009)), + .op (.stack (.swap 1)), + .op (.stack (.swap 0)), + .op (.stack (.swap 1)), + .jump 10], + -- bb24 + [.op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 160)), + .op (.stack .shr), + .op (.stack (.push 36)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack .or), + .jumpi 1, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .op (.stack (.dup 1)), + .op (.stack .and), + .op (.stack (.dup 1)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 0)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .effect .sload 1, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.dup 1)), + .op (.stack (.dup 1)), + .op (.stack .sub), + .jumpi 13, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb27 + [.op (.stack (.push 0x102000000030000000200000009)), + .jump 16], + -- bb35 + [.op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack (.push 0x417000000000000000080000000)), + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .op (.stack (.swap 0)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.swap 0)), + .jump 15], + -- bb36 + [.op (.stack (.push 64)), + .op .store, + .op (.stack (.push 96)), + .op .store, + .op (.stack (.push 0xed572b27)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 100)), + .op (.stack (.push 28)), + .revert], + -- bb37 + [.op (.stack (.push 32)), + .op .store, + .jump 15]] } + +end SolarTV.Export.Bank diff --git a/Certified/bank/gen/Bank/Evm8.lean b/Certified/bank/gen/Bank/Evm8.lean new file mode 100644 index 00000000..7e222cff --- /dev/null +++ b/Certified/bank/gen/Bank/Evm8.lean @@ -0,0 +1,266 @@ +-- solar-lean-stage: kind=evm index=8 pass=cfg-simplify-early +import SolarTV.EVMIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `Bank`; do not edit. -/ + +namespace SolarTV.Export.Bank + +/-- The runtime EVM IR after `cfg-simplify-early`. -/ +def evm8 : EVM.Program.Program := + { blocks := [ + -- bb0 + [.effect .callvalue 0, + .jumpi 1, + .op (.stack (.push 0)), + .effect .calldataload 1, + .op (.stack (.push 224)), + .op (.stack .shr), + .op (.stack (.dup 0)), + .op (.stack (.push 0x2f4f21e2)), + .op (.stack .eq), + .jumpi 7, + .op (.stack (.dup 0)), + .op (.stack (.push 0x70a08231)), + .op (.stack .eq), + .jumpi 11, + .op (.stack (.dup 0)), + .op (.stack (.push 0xb6b55f25)), + .op (.stack .eq), + .jumpi 3, + .jump 1], + -- bb5 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb34 + [.op (.stack (.push 17)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 0x4e487b71)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 36)), + .op (.stack (.push 28)), + .revert], + -- bb6 + [.op (.stack (.push 36)), + .op (.stack .calldatasize), + .op (.stack .lt), + .jumpi 1, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.dup 0)), + .effect .caller 0, + .pushLabel 5, + .jump 4], + -- bb30 + [.op (.stack (.dup 1)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 0)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .op (.stack (.dup 0)), + .effect .sload 1, + .op (.stack (.dup 4)), + .op (.stack (.dup 1)), + .op (.stack .add), + .op (.stack (.swap 0)), + .op (.stack (.dup 1)), + .op (.stack .lt), + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .op (.stack (.dup 5)), + .op (.stack .gt), + .jumpi 13, + .jumpi 2, + .op (.stack (.dup 1)), + .effect .sstore 2, + .op (.stack (.push 1)), + .effect .sload 1, + .op (.stack (.swap 3)), + .op (.stack (.dup 4)), + .op (.stack .add), + .op (.stack (.swap 3)), + .op (.stack (.dup 4)), + .op (.stack .lt), + .jumpi 2, + .op (.stack (.swap 2)), + .op (.stack (.push 1)), + .effect .sstore 2, + .op (.stack (.swap 1)), + .effect .sload 1, + .op (.stack (.swap 0)), + .op (.stack .pop), + .op (.stack (.swap 0)), + .jumpDyn], + -- bb8 + [.op (.stack (.swap 0)), + .op (.stack (.push 0)), + .op .store, + .effect .caller 0, + .op (.stack (.push 0xe1fffcc4923d04b559f4d29a8bfc6cda04eb5b0d3c460751c2402c5c5cc9109c)), + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .effect (.log 2) 4, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .effect .caller 0, + .op (.stack .gt), + .jumpi 6, + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .effect .caller 0, + .op (.stack .gt), + .jumpi 6, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb11 + [.op (.stack (.push 0x4170000000100000002)), + .op (.stack (.push 32)), + .op (.stack .shl), + .effect .caller 0, + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .op (.stack (.swap 1)), + .jump 15], + -- bb15 + [.op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 160)), + .op (.stack .shr), + .op (.stack (.push 68)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack .or), + .jumpi 1, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .op (.stack (.dup 1)), + .op (.stack .and), + .op (.stack (.push 36)), + .effect .calldataload 1, + .op (.stack (.dup 2)), + .pushLabel 8, + .jump 4], + -- bb17 + [.op (.stack (.push 0)), + .op .store, + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .op (.stack (.dup 2)), + .op (.stack .gt), + .jumpi 10, + .op (.stack (.dup 1)), + .op (.stack (.dup 1)), + .op (.stack .sub), + .jumpi 9, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb20 + [.op (.stack (.push 0x102000000020000000200000007)), + .jump 15], + -- bb21 + [.op (.stack .pop), + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .op (.stack (.push 0x417000000020000000200000009)), + .op (.stack (.swap 1)), + .op (.stack (.swap 0)), + .op (.stack (.swap 1)), + .jump 15], + -- bb24 + [.op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 160)), + .op (.stack .shr), + .op (.stack (.push 36)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack .or), + .jumpi 1, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .op (.stack (.dup 1)), + .op (.stack .and), + .op (.stack (.dup 1)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 0)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .effect .sload 1, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.dup 1)), + .op (.stack (.dup 1)), + .op (.stack .sub), + .jumpi 12, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb27 + [.op (.stack (.push 0x102000000030000000200000009)), + .jump 15], + -- bb35 + [.op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack (.push 0x417000000000000000080000000)), + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .op (.stack (.swap 0)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.swap 0)), + .jump 14], + -- bb36 + [.op (.stack (.push 64)), + .op .store, + .op (.stack (.push 96)), + .op .store, + .op (.stack (.push 0xed572b27)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 100)), + .op (.stack (.push 28)), + .revert], + -- bb37 + [.op (.stack (.push 32)), + .op .store, + .jump 14]] } + +end SolarTV.Export.Bank diff --git a/Certified/bank/gen/Bank/Evm9.lean b/Certified/bank/gen/Bank/Evm9.lean new file mode 100644 index 00000000..b12b86ce --- /dev/null +++ b/Certified/bank/gen/Bank/Evm9.lean @@ -0,0 +1,265 @@ +-- solar-lean-stage: kind=evm index=9 pass=reorder-pushes +import SolarTV.EVMIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `Bank`; do not edit. -/ + +namespace SolarTV.Export.Bank + +/-- The runtime EVM IR after `reorder-pushes`. -/ +def evm9 : EVM.Program.Program := + { blocks := [ + -- bb0 + [.effect .callvalue 0, + .jumpi 1, + .op (.stack (.push 0)), + .effect .calldataload 1, + .op (.stack (.push 224)), + .op (.stack .shr), + .op (.stack (.dup 0)), + .op (.stack (.push 0x2f4f21e2)), + .op (.stack .eq), + .jumpi 7, + .op (.stack (.dup 0)), + .op (.stack (.push 0x70a08231)), + .op (.stack .eq), + .jumpi 11, + .op (.stack (.dup 0)), + .op (.stack (.push 0xb6b55f25)), + .op (.stack .eq), + .jumpi 3, + .jump 1], + -- bb5 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb34 + [.op (.stack (.push 17)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 0x4e487b71)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 36)), + .op (.stack (.push 28)), + .revert], + -- bb6 + [.op (.stack (.push 36)), + .op (.stack .calldatasize), + .op (.stack .lt), + .jumpi 1, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.dup 0)), + .effect .caller 0, + .pushLabel 5, + .jump 4], + -- bb30 + [.op (.stack (.dup 1)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 0)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .op (.stack (.dup 0)), + .effect .sload 1, + .op (.stack (.dup 4)), + .op (.stack (.dup 1)), + .op (.stack .add), + .op (.stack (.swap 0)), + .op (.stack (.dup 1)), + .op (.stack .lt), + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .op (.stack (.dup 5)), + .op (.stack .gt), + .jumpi 13, + .jumpi 2, + .op (.stack (.dup 1)), + .effect .sstore 2, + .op (.stack (.push 1)), + .effect .sload 1, + .op (.stack (.swap 3)), + .op (.stack (.dup 4)), + .op (.stack .add), + .op (.stack (.swap 3)), + .op (.stack (.dup 4)), + .op (.stack .lt), + .jumpi 2, + .op (.stack (.swap 2)), + .op (.stack (.push 1)), + .effect .sstore 2, + .op (.stack (.swap 1)), + .effect .sload 1, + .op (.stack (.swap 0)), + .op (.stack .pop), + .op (.stack (.swap 0)), + .jumpDyn], + -- bb8 + [.op (.stack (.swap 0)), + .op (.stack (.push 0)), + .op .store, + .effect .caller 0, + .op (.stack (.push 0xe1fffcc4923d04b559f4d29a8bfc6cda04eb5b0d3c460751c2402c5c5cc9109c)), + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .effect (.log 2) 4, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .effect .caller 0, + .op (.stack .gt), + .jumpi 6, + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .effect .caller 0, + .op (.stack .gt), + .jumpi 6, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb11 + [.op (.stack (.push 0x4170000000100000002)), + .op (.stack (.push 32)), + .op (.stack .shl), + .effect .caller 0, + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .op (.stack (.swap 1)), + .jump 15], + -- bb15 + [.op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 160)), + .op (.stack .shr), + .op (.stack (.push 68)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack .or), + .jumpi 1, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .op (.stack (.dup 1)), + .op (.stack .and), + .op (.stack (.push 36)), + .effect .calldataload 1, + .op (.stack (.dup 2)), + .pushLabel 8, + .jump 4], + -- bb17 + [.op (.stack (.push 0)), + .op .store, + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .op (.stack (.dup 2)), + .op (.stack .gt), + .jumpi 10, + .op (.stack (.dup 1)), + .op (.stack (.dup 1)), + .op (.stack .sub), + .jumpi 9, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb20 + [.op (.stack (.push 0x102000000020000000200000007)), + .jump 15], + -- bb21 + [.op (.stack .pop), + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .op (.stack (.push 0x417000000020000000200000009)), + .op (.stack (.swap 1)), + .op (.stack (.swap 0)), + .op (.stack (.swap 1)), + .jump 15], + -- bb24 + [.op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 160)), + .op (.stack .shr), + .op (.stack (.push 36)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack .or), + .jumpi 1, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .op (.stack (.dup 1)), + .op (.stack .and), + .op (.stack (.dup 1)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 0)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .effect .sload 1, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.dup 1)), + .op (.stack (.dup 1)), + .op (.stack .sub), + .jumpi 12, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb27 + [.op (.stack (.push 0x102000000030000000200000009)), + .jump 15], + -- bb35 + [.op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .op (.stack (.push 0x417000000000000000080000000)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.swap 0)), + .jump 14], + -- bb36 + [.op (.stack (.push 64)), + .op .store, + .op (.stack (.push 96)), + .op .store, + .op (.stack (.push 0xed572b27)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 100)), + .op (.stack (.push 28)), + .revert], + -- bb37 + [.op (.stack (.push 32)), + .op .store, + .jump 14]] } + +end SolarTV.Export.Bank diff --git a/Certified/bank/gen/Bank/Manifest.lean b/Certified/bank/gen/Bank/Manifest.lean new file mode 100644 index 00000000..fb9d324e --- /dev/null +++ b/Certified/bank/gen/Bank/Manifest.lean @@ -0,0 +1,52 @@ +-- solar-lean-stage: kind=manifest index=0 pass=none +/-! Generated by `solar -Zemit-lean-stages` for `Bank`; do not edit. + +What the stages of this directory were compiled from and by. `stages` lists each +stage's file, its definition, the pass whose output it is, and the SHA-256 of the file. +-/ + +namespace SolarTV.Export.Bank.Manifest + +def sources : List (String × String) := + [("solar-tv/milestone/bank/bank.sol", "513398d47335b204a6b047493dd86e9c05066e950ba1300ba5d25850a5f8cb1f")] + +def compiler : String := "0.8.38+commit.4a7d9ede.solar.0.3.0-dev" + +def arguments : List String := + ["solar-tv/milestone/bank/bank.sol", + "-Ogas", + "--evm-version", + "osaka", + "--emit=bin-runtime", + "-Zemit-lean-stages=solar-tv/milestone/bank/gen"] + +def evmVersion : String := "osaka" + +def optimization : String := "Gas" + +def stages : List (String × String × String × String) := + [("Stage0", "stage0", "lower-evm-shaped", "7d145b2998661cb5c4592a5374f9cc79d94794bba2f6f17b3dfdd0e2a87e0fcc"), + ("Mir1", "mir1", "place-reads", "fc18b9f9f61ef53c23dcf6f6799dee7c57a15ca47bb4da2255c633f82b1308ab"), + ("Mir2", "mir2", "spell-width-tests", "706bb5ac9ec0a0d67f08496e91c62af4ae17405eb912f83decf45e9a8292b2c0"), + ("Mir3", "mir3", "lower-assumes", "aedcd4a2b80c765f6e037a756d6db7b1fab1a2447bdf0ca62eda37ae64185e34"), + ("Mir4", "mir4", "evm-inst-schedule", "6f68722b113a0f8f2cda66280547c0601f97b443d416806a6803322a38ae51b9"), + ("Sched", "sched", "stack-schedule", "7867a2d8d7a8605c655c1bc038b5cee9a7e714d6c152c9e267afc6dcfd8f9586"), + ("Evm1", "evm1", "peephole-early", "92adb3e54ee739c60d8e69961ba9619245df9ae42f1dca9df06fa352fd35f652"), + ("Evm2", "evm2", "cfg-simplify-early", "357042975eaf869a3c7f3a65ee4fc68bf6ef1cbb39d2c129c7aa730ac4ce95c7"), + ("Evm3", "evm3", "compact-pushes", "95b583b99ae08080b2753dc74b9a3d0f0921e23147a0419959612ea9afb91025"), + ("Evm4", "evm4", "block-layout", "5c18eab01a900c5e39d0cac1415ad8339a52ba78c43649f4e3fbfb8cb380e6e1"), + ("Evm5", "evm5", "terminal-dedup", "6ebad5531b56a0b055f247364e211b2ed1882f40858c9d75ce5b15ffcd5d9ea2"), + ("Evm6", "evm6", "cfg-simplify-early", "5f9a29c13202ce893fa142487c112f530321e5ac8041c28597d23504b278b7f8"), + ("Evm7", "evm7", "tail-merge", "baa56a2fc6e55d128e88f34ce5e6bcfdf7e4cbb78a0a907bf7ddcea3a8502bfa"), + ("Evm8", "evm8", "cfg-simplify-early", "b954ed58f56daec2d604a03ac02aa0ef3e543767b4a5d0bb13f68ea7f74fead6"), + ("Evm9", "evm9", "reorder-pushes", "43597405f5bd81147174381637469732e796aa4056f192d37311c7b21f95b65c"), + ("Evm10", "evm10", "block-layout", "0153e265384d5fa0bb56bbcddac12cb7724b905dafbd698d03461bba22095730"), + ("Evm11", "evm11", "stack-reschedule", "d55f0c281937953166c7fe2d2176bcb62145f1e1a597546d95ae4e3d903329aa"), + ("Bytecode", "bytecode", "assemble", "48ec986cf2d82ee746b044677549cc626376293bd6701e44e04d9b1e8e93bd8a")] + +def bytecodeHex : String := + "346028575f3560e01c80632f4f21e21460f857806370a0823114610161578063b6b55f2514603e575b5f5ffd5b6011602052634e487b715f526024601cfd5b60243610602857600435803360875b815f525f60205260405f2080548481019081105f1960601c85116101a657602c578155600154938401938410602c57926001559154905090565b905f52337fe1fffcc4923d04b559f4d29a8bfc6cda04eb5b0d3c460751c2402c5c5cc9109c60205fa25f525f1960601c331160cb575f1960601c331160cb5760205ff35b690417000000010000000260201b335f1960601c915b6020525b60405260605263ed572b275f526064601cfd5b60043560a01c60443610176028576004355f1960601c81166024358261011b604d565b5f525f1960601c8211610147578181036101345760205ff35b6d010200000002000000020000000760e1565b505f1960601c906d041700000002000000020000000960e1565b60043560a01c60243610176028576004355f1960601c8116815f525f60205260405f20545f528181036101935760205ff35b6d010200000003000000020000000960e1565b505050505f1960601c6d04170000000000000000800000006020529060e556" + +def bytecodeSha256 : String := "bff0578068ce4ab4a041f226e4e960c13d358c8b430718fefe9ce3a22d760543" + +end SolarTV.Export.Bank.Manifest diff --git a/Certified/bank/gen/Bank/Mir1.lean b/Certified/bank/gen/Bank/Mir1.lean new file mode 100644 index 00000000..4c74b5a8 --- /dev/null +++ b/Certified/bank/gen/Bank/Mir1.lean @@ -0,0 +1,146 @@ +-- solar-lean-stage: kind=mir index=1 pass=place-reads +import SolarTV.MIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `Bank`; do not edit. -/ + +namespace SolarTV.Export.Bank + +/-- The lowered MIR module after `place-reads`. -/ +def mir1 : MIR.Lowered.Module := + { entry := 4, + functions := [ + -- @credit + { params := [0, 30, 1], + blocks := [ + -- bb0 + ⟨[], + [.effect none .mstore [.const 0, .value 0], + .effect none .mstore [.const 32, .const 0], + .effect (some 29) .keccak256 [.const 0, .const 64], + .effect (some 5) .sload [.value 29], + .pure 15 .add [.value 5, .value 1], + .pure 16 .lt [.value 15, .value 5], + .assume true .gt [.value 30, .const 0xffffffffffffffffffffffffffffffffffffffff]], + .branch (.value 16) 1 2⟩, + -- bb1 + ⟨[], + [.effect none .mstore [.const 32, .const 17], + .effect none .mstore [.const 0, .const 0x4e487b71]], + .revert (.const 28) (.const 36)⟩, + -- bb2 + ⟨[], + [.effect none .sstore [.value 29, .value 15], + .effect (some 8) .sload [.const 1], + .pure 23 .add [.value 8, .value 1], + .pure 24 .lt [.value 23, .value 8]], + .branch (.value 24) 1 3⟩, + -- bb3 + ⟨[], + [.effect none .sstore [.const 1, .value 23], + .effect (some 14) .sload [.value 29]], + .leave [.value 14]⟩] }, + -- @deposit + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 11) .calldatasize [], + .pure 13 .lt [.value 11, .const 36]], + .branch (.value 13) 1 2⟩, + -- bb1 + ⟨[], + [], + .revert (.const 0) (.const 0)⟩, + -- bb2 + ⟨[], + [.effect (some 15) .calldataload [.const 4], + .effect (some 1) .caller [], + .call (some 2) 0 [.value 1, .value 1, .value 15], + .effect none .mstore [.const 0, .value 15], + .effect none (.log 2) [.const 0, .const 32, .const 0xe1fffcc4923d04b559f4d29a8bfc6cda04eb5b0d3c460751c2402c5c5cc9109c, .value 1], + .effect none .mstore [.const 0, .value 2], + .assume true .gt [.value 1, .const 0xffffffffffffffffffffffffffffffffffffffff], + .assume true .gt [.value 1, .const 0xffffffffffffffffffffffffffffffffffffffff]], + .ret (.const 0) (.const 32)⟩] }, + -- @depositFor + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 5) .calldatasize [], + .pure 7 .lt [.value 5, .const 68], + .effect (some 9) .calldataload [.const 4], + .pure 11 .gt [.value 9, .const 0xffffffffffffffffffffffffffffffffffffffff], + .pure 21 .or [.value 7, .value 11]], + .branch (.value 21) 1 2⟩, + -- bb1 + ⟨[], + [], + .revert (.const 0) (.const 0)⟩, + -- bb2 + ⟨[], + [.effect (some 22) .calldataload [.const 4], + .effect (some 13) .calldataload [.const 36], + .pure 19 .and [.value 22, .const 0xffffffffffffffffffffffffffffffffffffffff], + .call (some 3) 0 [.value 22, .value 22, .value 13], + .effect none .mstore [.const 0, .value 3], + .assume true .gt [.value 22, .const 0xffffffffffffffffffffffffffffffffffffffff], + .assume false .eq [.value 19, .value 22]], + .ret (.const 0) (.const 32)⟩] }, + -- @balanceOf + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 7) .calldatasize [], + .pure 9 .lt [.value 7, .const 36], + .effect (some 11) .calldataload [.const 4], + .pure 13 .gt [.value 11, .const 0xffffffffffffffffffffffffffffffffffffffff], + .pure 25 .or [.value 9, .value 13]], + .branch (.value 25) 1 2⟩, + -- bb1 + ⟨[], + [], + .revert (.const 0) (.const 0)⟩, + -- bb2 + ⟨[], + [.effect (some 26) .calldataload [.const 4], + .pure 24 .and [.value 26, .const 0xffffffffffffffffffffffffffffffffffffffff], + .effect none .mstore [.const 0, .value 26], + .effect none .mstore [.const 32, .const 0], + .effect (some 22) .keccak256 [.const 0, .const 64], + .effect (some 5) .sload [.value 22], + .effect none .mstore [.const 0, .value 5], + .assume false .eq [.value 24, .value 26]], + .ret (.const 0) (.const 32)⟩] }, + -- @entry + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 0) .callvalue [], + .ne 2 (.value 0) (.const 0)], + .branch (.value 2) 5 1⟩, + -- bb1 + ⟨[], + [.effect (some 4) .calldataload [.const 0], + .pure 6 .shr [.const 224, .value 4]], + .switch (.value 6) 5 [(.const 0x2f4f21e2, 2), (.const 0x70a08231, 3), (.const 0xb6b55f25, 4)]⟩, + -- bb2 + ⟨[], + [], + .tailCall 2 []⟩, + -- bb3 + ⟨[], + [], + .tailCall 3 []⟩, + -- bb4 + ⟨[], + [], + .tailCall 1 []⟩, + -- bb5 + ⟨[], + [], + .revert (.const 0) (.const 0)⟩] }] } + +end SolarTV.Export.Bank diff --git a/Certified/bank/gen/Bank/Mir2.lean b/Certified/bank/gen/Bank/Mir2.lean new file mode 100644 index 00000000..4e159ef1 --- /dev/null +++ b/Certified/bank/gen/Bank/Mir2.lean @@ -0,0 +1,150 @@ +-- solar-lean-stage: kind=mir index=2 pass=spell-width-tests +import SolarTV.MIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `Bank`; do not edit. -/ + +namespace SolarTV.Export.Bank + +/-- The lowered MIR module after `spell-width-tests`. -/ +def mir2 : MIR.Lowered.Module := + { entry := 4, + functions := [ + -- @credit + { params := [0, 30, 1], + blocks := [ + -- bb0 + ⟨[], + [.effect none .mstore [.const 0, .value 0], + .effect none .mstore [.const 32, .const 0], + .effect (some 29) .keccak256 [.const 0, .const 64], + .effect (some 5) .sload [.value 29], + .pure 15 .add [.value 5, .value 1], + .pure 16 .lt [.value 15, .value 5], + .assume true .gt [.value 30, .const 0xffffffffffffffffffffffffffffffffffffffff]], + .branch (.value 16) 1 2⟩, + -- bb1 + ⟨[], + [.effect none .mstore [.const 32, .const 17], + .effect none .mstore [.const 0, .const 0x4e487b71]], + .revert (.const 28) (.const 36)⟩, + -- bb2 + ⟨[], + [.effect none .sstore [.value 29, .value 15], + .effect (some 8) .sload [.const 1], + .pure 23 .add [.value 8, .value 1], + .pure 24 .lt [.value 23, .value 8]], + .branch (.value 24) 1 3⟩, + -- bb3 + ⟨[], + [.effect none .sstore [.const 1, .value 23], + .effect (some 14) .sload [.value 29]], + .leave [.value 14]⟩] }, + -- @deposit + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 11) .calldatasize [], + .pure 13 .lt [.value 11, .const 36]], + .branch (.value 13) 1 2⟩, + -- bb1 + ⟨[], + [], + .revert (.const 0) (.const 0)⟩, + -- bb2 + ⟨[], + [.effect (some 15) .calldataload [.const 4], + .effect (some 1) .caller [], + .call (some 2) 0 [.value 1, .value 1, .value 15], + .effect none .mstore [.const 0, .value 15], + .effect none (.log 2) [.const 0, .const 32, .const 0xe1fffcc4923d04b559f4d29a8bfc6cda04eb5b0d3c460751c2402c5c5cc9109c, .value 1], + .effect none .mstore [.const 0, .value 2], + .assume true .gt [.value 1, .const 0xffffffffffffffffffffffffffffffffffffffff], + .assume true .gt [.value 1, .const 0xffffffffffffffffffffffffffffffffffffffff]], + .ret (.const 0) (.const 32)⟩] }, + -- @depositFor + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 5) .calldatasize [], + .pure 7 .lt [.value 5, .const 68], + .effect (some 9) .calldataload [.const 4], + .pure 24 .shr [.const 160, .value 9], + .word 27 (.value 7), + .pure 28 .or [.value 24, .value 27], + .ne 21 (.value 28) (.const 0)], + .branch (.value 21) 1 2⟩, + -- bb1 + ⟨[], + [], + .revert (.const 0) (.const 0)⟩, + -- bb2 + ⟨[], + [.effect (some 22) .calldataload [.const 4], + .effect (some 13) .calldataload [.const 36], + .pure 19 .and [.value 22, .const 0xffffffffffffffffffffffffffffffffffffffff], + .call (some 3) 0 [.value 22, .value 22, .value 13], + .effect none .mstore [.const 0, .value 3], + .assume true .gt [.value 22, .const 0xffffffffffffffffffffffffffffffffffffffff], + .assume false .eq [.value 19, .value 22]], + .ret (.const 0) (.const 32)⟩] }, + -- @balanceOf + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 7) .calldatasize [], + .pure 9 .lt [.value 7, .const 36], + .effect (some 11) .calldataload [.const 4], + .pure 28 .shr [.const 160, .value 11], + .word 31 (.value 9), + .pure 32 .or [.value 28, .value 31], + .ne 25 (.value 32) (.const 0)], + .branch (.value 25) 1 2⟩, + -- bb1 + ⟨[], + [], + .revert (.const 0) (.const 0)⟩, + -- bb2 + ⟨[], + [.effect (some 26) .calldataload [.const 4], + .pure 24 .and [.value 26, .const 0xffffffffffffffffffffffffffffffffffffffff], + .effect none .mstore [.const 0, .value 26], + .effect none .mstore [.const 32, .const 0], + .effect (some 22) .keccak256 [.const 0, .const 64], + .effect (some 5) .sload [.value 22], + .effect none .mstore [.const 0, .value 5], + .assume false .eq [.value 24, .value 26]], + .ret (.const 0) (.const 32)⟩] }, + -- @entry + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 0) .callvalue [], + .ne 2 (.value 0) (.const 0)], + .branch (.value 2) 5 1⟩, + -- bb1 + ⟨[], + [.effect (some 4) .calldataload [.const 0], + .pure 6 .shr [.const 224, .value 4]], + .switch (.value 6) 5 [(.const 0x2f4f21e2, 2), (.const 0x70a08231, 3), (.const 0xb6b55f25, 4)]⟩, + -- bb2 + ⟨[], + [], + .tailCall 2 []⟩, + -- bb3 + ⟨[], + [], + .tailCall 3 []⟩, + -- bb4 + ⟨[], + [], + .tailCall 1 []⟩, + -- bb5 + ⟨[], + [], + .revert (.const 0) (.const 0)⟩] }] } + +end SolarTV.Export.Bank diff --git a/Certified/bank/gen/Bank/Mir3.lean b/Certified/bank/gen/Bank/Mir3.lean new file mode 100644 index 00000000..6f8c95c5 --- /dev/null +++ b/Certified/bank/gen/Bank/Mir3.lean @@ -0,0 +1,224 @@ +-- solar-lean-stage: kind=mir index=3 pass=lower-assumes +import SolarTV.MIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `Bank`; do not edit. -/ + +namespace SolarTV.Export.Bank + +/-- The lowered MIR module after `lower-assumes`. -/ +def mir3 : MIR.Lowered.Module := + { entry := 4, + functions := [ + -- @credit + { params := [0, 1], + blocks := [ + -- bb0 + ⟨[], + [.effect none .mstore [.const 0, .value 0], + .effect none .mstore [.const 32, .const 0], + .effect (some 29) .keccak256 [.const 0, .const 64], + .effect (some 5) .sload [.value 29], + .pure 15 .add [.value 5, .value 1], + .pure 16 .lt [.value 15, .value 5], + .pure 32 .gt [.value 0, .const 0xffffffffffffffffffffffffffffffffffffffff]], + .branch (.value 32) 5 6⟩, + -- bb1 + ⟨[], + [.effect none .mstore [.const 32, .const 17], + .effect none .mstore [.const 0, .const 0x4e487b71]], + .revert (.const 28) (.const 36)⟩, + -- bb2 + ⟨[], + [.effect none .sstore [.value 29, .value 15], + .effect (some 8) .sload [.const 1], + .pure 23 .add [.value 8, .value 1], + .pure 24 .lt [.value 23, .value 8]], + .branch (.value 24) 1 3⟩, + -- bb3 + ⟨[], + [.effect none .sstore [.const 1, .value 23], + .effect (some 14) .sload [.value 29]], + .leave [.value 14]⟩, + -- bb4 + ⟨[(34, [(5, .const 0x417000000000000000080000000)]), (35, [(5, .value 0)]), (36, [(5, .const 0xffffffffffffffffffffffffffffffffffffffff)])], + [.effect none .mstore [.const 32, .value 34], + .effect none .mstore [.const 64, .value 35], + .effect none .mstore [.const 96, .value 36], + .effect none .mstore [.const 0, .const 0xed572b27]], + .revert (.const 28) (.const 100)⟩, + -- bb5 + ⟨[], + [], + .jump 4⟩, + -- bb6 + ⟨[], + [], + .branch (.value 16) 1 2⟩] }, + -- @deposit + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 11) .calldatasize [], + .pure 13 .lt [.value 11, .const 36]], + .branch (.value 13) 1 2⟩, + -- bb1 + ⟨[], + [], + .revert (.const 0) (.const 0)⟩, + -- bb2 + ⟨[], + [.effect (some 15) .calldataload [.const 4], + .effect (some 1) .caller [], + .call (some 2) 0 [.value 1, .value 15], + .effect none .mstore [.const 0, .value 15], + .effect none (.log 2) [.const 0, .const 32, .const 0xe1fffcc4923d04b559f4d29a8bfc6cda04eb5b0d3c460751c2402c5c5cc9109c, .value 1], + .effect none .mstore [.const 0, .value 2], + .pure 21 .gt [.value 1, .const 0xffffffffffffffffffffffffffffffffffffffff]], + .branch (.value 21) 4 5⟩, + -- bb3 + ⟨[(25, [(4, .const 0x417000000010000000200000000), (6, .const 0x417000000010000000200000000)]), (26, [(4, .value 1), (6, .value 1)]), (27, [(4, .const 0xffffffffffffffffffffffffffffffffffffffff), (6, .const 0xffffffffffffffffffffffffffffffffffffffff)])], + [.effect none .mstore [.const 32, .value 25], + .effect none .mstore [.const 64, .value 26], + .effect none .mstore [.const 96, .value 27], + .effect none .mstore [.const 0, .const 0xed572b27]], + .revert (.const 28) (.const 100)⟩, + -- bb4 + ⟨[], + [], + .jump 3⟩, + -- bb5 + ⟨[], + [.pure 23 .gt [.value 1, .const 0xffffffffffffffffffffffffffffffffffffffff]], + .branch (.value 23) 6 7⟩, + -- bb6 + ⟨[], + [], + .jump 3⟩, + -- bb7 + ⟨[], + [], + .ret (.const 0) (.const 32)⟩] }, + -- @depositFor + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 5) .calldatasize [], + .pure 7 .lt [.value 5, .const 68], + .effect (some 9) .calldataload [.const 4], + .pure 24 .shr [.const 160, .value 9], + .word 27 (.value 7), + .pure 28 .or [.value 24, .value 27], + .ne 21 (.value 28) (.const 0)], + .branch (.value 21) 1 2⟩, + -- bb1 + ⟨[], + [], + .revert (.const 0) (.const 0)⟩, + -- bb2 + ⟨[], + [.effect (some 22) .calldataload [.const 4], + .effect (some 13) .calldataload [.const 36], + .pure 19 .and [.value 22, .const 0xffffffffffffffffffffffffffffffffffffffff], + .call (some 3) 0 [.value 22, .value 13], + .effect none .mstore [.const 0, .value 3], + .pure 31 .gt [.value 22, .const 0xffffffffffffffffffffffffffffffffffffffff]], + .branch (.value 31) 4 5⟩, + -- bb3 + ⟨[(35, [(4, .const 0x417000000020000000200000009), (6, .const 0x102000000020000000200000007)]), (36, [(4, .value 22), (6, .value 19)]), (37, [(4, .const 0xffffffffffffffffffffffffffffffffffffffff), (6, .value 22)])], + [.effect none .mstore [.const 32, .value 35], + .effect none .mstore [.const 64, .value 36], + .effect none .mstore [.const 96, .value 37], + .effect none .mstore [.const 0, .const 0xed572b27]], + .revert (.const 28) (.const 100)⟩, + -- bb4 + ⟨[], + [], + .jump 3⟩, + -- bb5 + ⟨[], + [.ne 33 (.value 19) (.value 22)], + .branch (.value 33) 6 7⟩, + -- bb6 + ⟨[], + [], + .jump 3⟩, + -- bb7 + ⟨[], + [], + .ret (.const 0) (.const 32)⟩] }, + -- @balanceOf + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 7) .calldatasize [], + .pure 9 .lt [.value 7, .const 36], + .effect (some 11) .calldataload [.const 4], + .pure 28 .shr [.const 160, .value 11], + .word 31 (.value 9), + .pure 32 .or [.value 28, .value 31], + .ne 25 (.value 32) (.const 0)], + .branch (.value 25) 1 2⟩, + -- bb1 + ⟨[], + [], + .revert (.const 0) (.const 0)⟩, + -- bb2 + ⟨[], + [.effect (some 26) .calldataload [.const 4], + .pure 24 .and [.value 26, .const 0xffffffffffffffffffffffffffffffffffffffff], + .effect none .mstore [.const 0, .value 26], + .effect none .mstore [.const 32, .const 0], + .effect (some 22) .keccak256 [.const 0, .const 64], + .effect (some 5) .sload [.value 22], + .effect none .mstore [.const 0, .value 5], + .ne 35 (.value 24) (.value 26)], + .branch (.value 35) 4 5⟩, + -- bb3 + ⟨[(37, [(4, .const 0x102000000030000000200000009)]), (38, [(4, .value 24)]), (39, [(4, .value 26)])], + [.effect none .mstore [.const 32, .value 37], + .effect none .mstore [.const 64, .value 38], + .effect none .mstore [.const 96, .value 39], + .effect none .mstore [.const 0, .const 0xed572b27]], + .revert (.const 28) (.const 100)⟩, + -- bb4 + ⟨[], + [], + .jump 3⟩, + -- bb5 + ⟨[], + [], + .ret (.const 0) (.const 32)⟩] }, + -- @entry + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 0) .callvalue [], + .ne 2 (.value 0) (.const 0)], + .branch (.value 2) 5 1⟩, + -- bb1 + ⟨[], + [.effect (some 4) .calldataload [.const 0], + .pure 6 .shr [.const 224, .value 4]], + .switch (.value 6) 5 [(.const 0x2f4f21e2, 2), (.const 0x70a08231, 3), (.const 0xb6b55f25, 4)]⟩, + -- bb2 + ⟨[], + [], + .tailCall 2 []⟩, + -- bb3 + ⟨[], + [], + .tailCall 3 []⟩, + -- bb4 + ⟨[], + [], + .tailCall 1 []⟩, + -- bb5 + ⟨[], + [], + .revert (.const 0) (.const 0)⟩] }] } + +end SolarTV.Export.Bank diff --git a/Certified/bank/gen/Bank/Mir4.lean b/Certified/bank/gen/Bank/Mir4.lean new file mode 100644 index 00000000..b1d640e5 --- /dev/null +++ b/Certified/bank/gen/Bank/Mir4.lean @@ -0,0 +1,224 @@ +-- solar-lean-stage: kind=mir index=4 pass=evm-inst-schedule +import SolarTV.MIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `Bank`; do not edit. -/ + +namespace SolarTV.Export.Bank + +/-- The lowered MIR module after `evm-inst-schedule`. -/ +def mir4 : MIR.Lowered.Module := + { entry := 4, + functions := [ + -- @credit + { params := [0, 1], + blocks := [ + -- bb0 + ⟨[], + [.effect none .mstore [.const 0, .value 0], + .effect none .mstore [.const 32, .const 0], + .effect (some 29) .keccak256 [.const 0, .const 64], + .effect (some 5) .sload [.value 29], + .pure 15 .add [.value 5, .value 1], + .pure 16 .lt [.value 15, .value 5], + .pure 32 .gt [.value 0, .const 0xffffffffffffffffffffffffffffffffffffffff]], + .branch (.value 32) 5 6⟩, + -- bb1 + ⟨[], + [.effect none .mstore [.const 32, .const 17], + .effect none .mstore [.const 0, .const 0x4e487b71]], + .revert (.const 28) (.const 36)⟩, + -- bb2 + ⟨[], + [.effect none .sstore [.value 29, .value 15], + .effect (some 8) .sload [.const 1], + .pure 23 .add [.value 8, .value 1], + .pure 24 .lt [.value 23, .value 8]], + .branch (.value 24) 1 3⟩, + -- bb3 + ⟨[], + [.effect none .sstore [.const 1, .value 23], + .effect (some 14) .sload [.value 29]], + .leave [.value 14]⟩, + -- bb4 + ⟨[(34, [(5, .const 0x417000000000000000080000000)]), (35, [(5, .value 0)]), (36, [(5, .const 0xffffffffffffffffffffffffffffffffffffffff)])], + [.effect none .mstore [.const 32, .value 34], + .effect none .mstore [.const 64, .value 35], + .effect none .mstore [.const 96, .value 36], + .effect none .mstore [.const 0, .const 0xed572b27]], + .revert (.const 28) (.const 100)⟩, + -- bb5 + ⟨[], + [], + .jump 4⟩, + -- bb6 + ⟨[], + [], + .branch (.value 16) 1 2⟩] }, + -- @deposit + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 11) .calldatasize [], + .pure 13 .lt [.value 11, .const 36]], + .branch (.value 13) 1 2⟩, + -- bb1 + ⟨[], + [], + .revert (.const 0) (.const 0)⟩, + -- bb2 + ⟨[], + [.effect (some 15) .calldataload [.const 4], + .effect (some 1) .caller [], + .call (some 2) 0 [.value 1, .value 15], + .effect none .mstore [.const 0, .value 15], + .effect none (.log 2) [.const 0, .const 32, .const 0xe1fffcc4923d04b559f4d29a8bfc6cda04eb5b0d3c460751c2402c5c5cc9109c, .value 1], + .effect none .mstore [.const 0, .value 2], + .pure 21 .gt [.value 1, .const 0xffffffffffffffffffffffffffffffffffffffff]], + .branch (.value 21) 4 5⟩, + -- bb3 + ⟨[(25, [(4, .const 0x417000000010000000200000000), (6, .const 0x417000000010000000200000000)]), (26, [(4, .value 1), (6, .value 1)]), (27, [(4, .const 0xffffffffffffffffffffffffffffffffffffffff), (6, .const 0xffffffffffffffffffffffffffffffffffffffff)])], + [.effect none .mstore [.const 32, .value 25], + .effect none .mstore [.const 64, .value 26], + .effect none .mstore [.const 96, .value 27], + .effect none .mstore [.const 0, .const 0xed572b27]], + .revert (.const 28) (.const 100)⟩, + -- bb4 + ⟨[], + [], + .jump 3⟩, + -- bb5 + ⟨[], + [.pure 23 .gt [.value 1, .const 0xffffffffffffffffffffffffffffffffffffffff]], + .branch (.value 23) 6 7⟩, + -- bb6 + ⟨[], + [], + .jump 3⟩, + -- bb7 + ⟨[], + [], + .ret (.const 0) (.const 32)⟩] }, + -- @depositFor + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 9) .calldataload [.const 4], + .pure 24 .shr [.const 160, .value 9], + .effect (some 5) .calldatasize [], + .pure 7 .lt [.value 5, .const 68], + .word 27 (.value 7), + .pure 28 .or [.value 24, .value 27], + .ne 21 (.value 28) (.const 0)], + .branch (.value 21) 1 2⟩, + -- bb1 + ⟨[], + [], + .revert (.const 0) (.const 0)⟩, + -- bb2 + ⟨[], + [.effect (some 22) .calldataload [.const 4], + .effect (some 13) .calldataload [.const 36], + .pure 19 .and [.value 22, .const 0xffffffffffffffffffffffffffffffffffffffff], + .call (some 3) 0 [.value 22, .value 13], + .effect none .mstore [.const 0, .value 3], + .pure 31 .gt [.value 22, .const 0xffffffffffffffffffffffffffffffffffffffff]], + .branch (.value 31) 4 5⟩, + -- bb3 + ⟨[(35, [(4, .const 0x417000000020000000200000009), (6, .const 0x102000000020000000200000007)]), (36, [(4, .value 22), (6, .value 19)]), (37, [(4, .const 0xffffffffffffffffffffffffffffffffffffffff), (6, .value 22)])], + [.effect none .mstore [.const 32, .value 35], + .effect none .mstore [.const 64, .value 36], + .effect none .mstore [.const 96, .value 37], + .effect none .mstore [.const 0, .const 0xed572b27]], + .revert (.const 28) (.const 100)⟩, + -- bb4 + ⟨[], + [], + .jump 3⟩, + -- bb5 + ⟨[], + [.ne 33 (.value 19) (.value 22)], + .branch (.value 33) 6 7⟩, + -- bb6 + ⟨[], + [], + .jump 3⟩, + -- bb7 + ⟨[], + [], + .ret (.const 0) (.const 32)⟩] }, + -- @balanceOf + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 11) .calldataload [.const 4], + .pure 28 .shr [.const 160, .value 11], + .effect (some 7) .calldatasize [], + .pure 9 .lt [.value 7, .const 36], + .word 31 (.value 9), + .pure 32 .or [.value 28, .value 31], + .ne 25 (.value 32) (.const 0)], + .branch (.value 25) 1 2⟩, + -- bb1 + ⟨[], + [], + .revert (.const 0) (.const 0)⟩, + -- bb2 + ⟨[], + [.effect (some 26) .calldataload [.const 4], + .pure 24 .and [.value 26, .const 0xffffffffffffffffffffffffffffffffffffffff], + .effect none .mstore [.const 0, .value 26], + .effect none .mstore [.const 32, .const 0], + .effect (some 22) .keccak256 [.const 0, .const 64], + .effect (some 5) .sload [.value 22], + .effect none .mstore [.const 0, .value 5], + .ne 35 (.value 24) (.value 26)], + .branch (.value 35) 4 5⟩, + -- bb3 + ⟨[(37, [(4, .const 0x102000000030000000200000009)]), (38, [(4, .value 24)]), (39, [(4, .value 26)])], + [.effect none .mstore [.const 32, .value 37], + .effect none .mstore [.const 64, .value 38], + .effect none .mstore [.const 96, .value 39], + .effect none .mstore [.const 0, .const 0xed572b27]], + .revert (.const 28) (.const 100)⟩, + -- bb4 + ⟨[], + [], + .jump 3⟩, + -- bb5 + ⟨[], + [], + .ret (.const 0) (.const 32)⟩] }, + -- @entry + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 0) .callvalue [], + .ne 2 (.value 0) (.const 0)], + .branch (.value 2) 5 1⟩, + -- bb1 + ⟨[], + [.effect (some 4) .calldataload [.const 0], + .pure 6 .shr [.const 224, .value 4]], + .switch (.value 6) 5 [(.const 0x2f4f21e2, 2), (.const 0x70a08231, 3), (.const 0xb6b55f25, 4)]⟩, + -- bb2 + ⟨[], + [], + .tailCall 2 []⟩, + -- bb3 + ⟨[], + [], + .tailCall 3 []⟩, + -- bb4 + ⟨[], + [], + .tailCall 1 []⟩, + -- bb5 + ⟨[], + [], + .revert (.const 0) (.const 0)⟩] }] } + +end SolarTV.Export.Bank diff --git a/Certified/bank/gen/Bank/Sched.lean b/Certified/bank/gen/Bank/Sched.lean new file mode 100644 index 00000000..1133f424 --- /dev/null +++ b/Certified/bank/gen/Bank/Sched.lean @@ -0,0 +1,321 @@ +-- solar-lean-stage: kind=sched index=0 pass=stack-schedule +import SolarTV.EVMIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `Bank`; do not edit. -/ + +namespace SolarTV.Export.Bank + +/-- The runtime EVM IR as stack scheduling emits it. -/ +def sched : EVM.Program.Program := + { blocks := [ + -- bb0 + [.effect .callvalue 0, + .jumpi 5, + .jump 1], + -- bb1 + [.op (.stack (.push 0)), + .effect .calldataload 1, + .op (.stack (.push 224)), + .op (.stack .shr), + .op (.stack (.dup 0)), + .op (.stack (.push 0x2f4f21e2)), + .op (.stack .eq), + .jumpi 4, + .op (.stack (.dup 0)), + .op (.stack (.push 0x70a08231)), + .op (.stack .eq), + .jumpi 3, + .op (.stack (.dup 0)), + .op (.stack (.push 0xb6b55f25)), + .op (.stack .eq), + .jumpi 2, + .jump 5], + -- bb2 + [.jump 6], + -- bb3 + [.jump 24], + -- bb4 + [.jump 15], + -- bb5 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb6 + [.op (.stack (.push 36)), + .op (.stack .calldatasize), + .op (.stack .lt), + .jumpi 14, + .jump 7], + -- bb7 + [.op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.dup 0)), + .effect .caller 0, + .pushLabel 8, + .jump 30], + -- bb8 + [.op (.stack (.swap 0)), + .op (.stack (.push 0)), + .op .store, + .effect .caller 0, + .op (.stack (.push 0xe1fffcc4923d04b559f4d29a8bfc6cda04eb5b0d3c460751c2402c5c5cc9109c)), + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .effect (.log 2) 4, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 0xffffffffffffffffffffffffffffffffffffffff)), + .effect .caller 0, + .op (.stack .gt), + .jumpi 12, + .jump 9], + -- bb9 + [.op (.stack (.push 0xffffffffffffffffffffffffffffffffffffffff)), + .effect .caller 0, + .op (.stack .gt), + .jumpi 11, + .jump 10], + -- bb10 + [.op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb11 + [.op (.stack (.push 0x417000000010000000200000000)), + .effect .caller 0, + .op (.stack (.push 0xffffffffffffffffffffffffffffffffffffffff)), + .jump 13], + -- bb12 + [.op (.stack (.push 0x417000000010000000200000000)), + .effect .caller 0, + .op (.stack (.push 0xffffffffffffffffffffffffffffffffffffffff)), + .jump 13], + -- bb13 + [.op (.stack (.swap 1)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op .store, + .op (.stack (.push 96)), + .op .store, + .op (.stack (.push 0xed572b27)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 100)), + .op (.stack (.push 28)), + .revert], + -- bb14 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb15 + [.op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 160)), + .op (.stack .shr), + .op (.stack (.push 68)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack .or), + .jumpi 23, + .jump 16], + -- bb16 + [.op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 0xffffffffffffffffffffffffffffffffffffffff)), + .op (.stack (.dup 1)), + .op (.stack .and), + .op (.stack (.push 36)), + .effect .calldataload 1, + .op (.stack (.dup 2)), + .pushLabel 17, + .jump 30], + -- bb17 + [.op (.stack (.push 0)), + .op .store, + .op (.stack (.push 0xffffffffffffffffffffffffffffffffffffffff)), + .op (.stack (.dup 2)), + .op (.stack .gt), + .jumpi 21, + .jump 18], + -- bb18 + [.op (.stack (.dup 1)), + .op (.stack (.dup 1)), + .op (.stack .eq), + .op (.stack .iszero), + .jumpi 20, + .jump 19], + -- bb19 + [.op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb20 + [.op (.stack (.push 0x102000000020000000200000007)), + .jump 22], + -- bb21 + [.op (.stack .pop), + .op (.stack (.push 0xffffffffffffffffffffffffffffffffffffffff)), + .op (.stack (.push 0x417000000020000000200000009)), + .op (.stack (.swap 1)), + .op (.stack (.swap 0)), + .op (.stack (.swap 1)), + .jump 22], + -- bb22 + [.op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op .store, + .op (.stack (.push 96)), + .op .store, + .op (.stack (.push 0xed572b27)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 100)), + .op (.stack (.push 28)), + .revert], + -- bb23 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb24 + [.op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 160)), + .op (.stack .shr), + .op (.stack (.push 36)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack .or), + .jumpi 29, + .jump 25], + -- bb25 + [.op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 0xffffffffffffffffffffffffffffffffffffffff)), + .op (.stack (.dup 1)), + .op (.stack .and), + .op (.stack (.dup 1)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 0)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .effect .sload 1, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.dup 1)), + .op (.stack (.dup 1)), + .op (.stack .eq), + .op (.stack .iszero), + .jumpi 27, + .jump 26], + -- bb26 + [.op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb27 + [.op (.stack (.push 0x102000000030000000200000009)), + .jump 28], + -- bb28 + [.op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op .store, + .op (.stack (.push 96)), + .op .store, + .op (.stack (.push 0xed572b27)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 100)), + .op (.stack (.push 28)), + .revert], + -- bb29 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb30 + [.op (.stack (.dup 1)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 0)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .op (.stack (.dup 0)), + .effect .sload 1, + .op (.stack (.dup 4)), + .op (.stack (.dup 1)), + .op (.stack .add), + .op (.stack (.swap 0)), + .op (.stack (.dup 1)), + .op (.stack .lt), + .op (.stack (.push 0xffffffffffffffffffffffffffffffffffffffff)), + .op (.stack (.dup 5)), + .op (.stack .gt), + .jumpi 35, + .jump 31], + -- bb31 + [.jumpi 34, + .jump 32], + -- bb32 + [.op (.stack (.dup 1)), + .effect .sstore 2, + .op (.stack (.push 1)), + .effect .sload 1, + .op (.stack (.swap 3)), + .op (.stack (.dup 4)), + .op (.stack .add), + .op (.stack (.swap 3)), + .op (.stack (.dup 4)), + .op (.stack .lt), + .jumpi 34, + .jump 33], + -- bb33 + [.op (.stack (.swap 2)), + .op (.stack (.push 1)), + .effect .sstore 2, + .op (.stack (.swap 1)), + .effect .sload 1, + .op (.stack (.swap 0)), + .op (.stack .pop), + .op (.stack (.swap 0)), + .jumpDyn], + -- bb34 + [.op (.stack (.push 17)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 0x4e487b71)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 36)), + .op (.stack (.push 28)), + .revert], + -- bb35 + [.op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack (.push 0x417000000000000000080000000)), + .op (.stack (.push 0xffffffffffffffffffffffffffffffffffffffff)), + .jump 36], + -- bb36 + [.op (.stack (.swap 0)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.swap 0)), + .op (.stack (.push 64)), + .op .store, + .op (.stack (.push 96)), + .op .store, + .op (.stack (.push 0xed572b27)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 100)), + .op (.stack (.push 28)), + .revert]] } + +end SolarTV.Export.Bank diff --git a/Certified/bank/gen/Bank/Stage0.lean b/Certified/bank/gen/Bank/Stage0.lean new file mode 100644 index 00000000..1cb02230 --- /dev/null +++ b/Certified/bank/gen/Bank/Stage0.lean @@ -0,0 +1,144 @@ +-- solar-lean-stage: kind=mir index=0 pass=lower-evm-shaped +import SolarTV.MIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `Bank`; do not edit. -/ + +namespace SolarTV.Export.Bank + +/-- The first lowered MIR module, after `lower-evm-shaped` advanced the phase. -/ +def stage0 : MIR.Lowered.Module := + { entry := 4, + functions := [ + -- @credit + { params := [0, 30, 1], + blocks := [ + -- bb0 + ⟨[], + [.effect none .mstore [.const 0, .value 0], + .effect none .mstore [.const 32, .const 0], + .effect (some 29) .keccak256 [.const 0, .const 64], + .effect (some 5) .sload [.value 29], + .pure 15 .add [.value 5, .value 1], + .pure 16 .lt [.value 15, .value 5], + .assume true .gt [.value 30, .const 0xffffffffffffffffffffffffffffffffffffffff]], + .branch (.value 16) 1 2⟩, + -- bb1 + ⟨[], + [.effect none .mstore [.const 32, .const 17], + .effect none .mstore [.const 0, .const 0x4e487b71]], + .revert (.const 28) (.const 36)⟩, + -- bb2 + ⟨[], + [.effect none .sstore [.value 29, .value 15], + .effect (some 8) .sload [.const 1], + .pure 23 .add [.value 8, .value 1], + .pure 24 .lt [.value 23, .value 8]], + .branch (.value 24) 1 3⟩, + -- bb3 + ⟨[], + [.effect none .sstore [.const 1, .value 23], + .effect (some 14) .sload [.value 29]], + .leave [.value 14]⟩] }, + -- @deposit + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 11) .calldatasize [], + .pure 13 .lt [.value 11, .const 36]], + .branch (.value 13) 1 2⟩, + -- bb1 + ⟨[], + [], + .revert (.const 0) (.const 0)⟩, + -- bb2 + ⟨[], + [.effect (some 15) .calldataload [.const 4], + .effect (some 1) .caller [], + .call (some 2) 0 [.value 1, .value 1, .value 15], + .effect none .mstore [.const 0, .value 15], + .effect none (.log 2) [.const 0, .const 32, .const 0xe1fffcc4923d04b559f4d29a8bfc6cda04eb5b0d3c460751c2402c5c5cc9109c, .value 1], + .effect none .mstore [.const 0, .value 2], + .assume true .gt [.value 1, .const 0xffffffffffffffffffffffffffffffffffffffff], + .assume true .gt [.value 1, .const 0xffffffffffffffffffffffffffffffffffffffff]], + .ret (.const 0) (.const 32)⟩] }, + -- @depositFor + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 5) .calldatasize [], + .pure 7 .lt [.value 5, .const 68], + .effect (some 9) .calldataload [.const 4], + .pure 11 .gt [.value 9, .const 0xffffffffffffffffffffffffffffffffffffffff], + .pure 21 .or [.value 7, .value 11]], + .branch (.value 21) 1 2⟩, + -- bb1 + ⟨[], + [], + .revert (.const 0) (.const 0)⟩, + -- bb2 + ⟨[], + [.effect (some 13) .calldataload [.const 36], + .pure 19 .and [.value 9, .const 0xffffffffffffffffffffffffffffffffffffffff], + .call (some 3) 0 [.value 9, .value 9, .value 13], + .effect none .mstore [.const 0, .value 3], + .assume true .gt [.value 9, .const 0xffffffffffffffffffffffffffffffffffffffff], + .assume false .eq [.value 19, .value 9]], + .ret (.const 0) (.const 32)⟩] }, + -- @balanceOf + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 7) .calldatasize [], + .pure 9 .lt [.value 7, .const 36], + .effect (some 11) .calldataload [.const 4], + .pure 13 .gt [.value 11, .const 0xffffffffffffffffffffffffffffffffffffffff], + .pure 25 .or [.value 9, .value 13]], + .branch (.value 25) 1 2⟩, + -- bb1 + ⟨[], + [], + .revert (.const 0) (.const 0)⟩, + -- bb2 + ⟨[], + [.pure 24 .and [.value 11, .const 0xffffffffffffffffffffffffffffffffffffffff], + .effect none .mstore [.const 0, .value 11], + .effect none .mstore [.const 32, .const 0], + .effect (some 22) .keccak256 [.const 0, .const 64], + .effect (some 5) .sload [.value 22], + .effect none .mstore [.const 0, .value 5], + .assume false .eq [.value 24, .value 11]], + .ret (.const 0) (.const 32)⟩] }, + -- @entry + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 0) .callvalue [], + .ne 2 (.value 0) (.const 0)], + .branch (.value 2) 5 1⟩, + -- bb1 + ⟨[], + [.effect (some 4) .calldataload [.const 0], + .pure 6 .shr [.const 224, .value 4]], + .switch (.value 6) 5 [(.const 0x2f4f21e2, 2), (.const 0x70a08231, 3), (.const 0xb6b55f25, 4)]⟩, + -- bb2 + ⟨[], + [], + .tailCall 2 []⟩, + -- bb3 + ⟨[], + [], + .tailCall 3 []⟩, + -- bb4 + ⟨[], + [], + .tailCall 1 []⟩, + -- bb5 + ⟨[], + [], + .revert (.const 0) (.const 0)⟩] }] } + +end SolarTV.Export.Bank diff --git a/Certified/bank/gen/Bank/manifest.json b/Certified/bank/gen/Bank/manifest.json new file mode 100644 index 00000000..de1bacdb --- /dev/null +++ b/Certified/bank/gen/Bank/manifest.json @@ -0,0 +1,169 @@ +{ + "arguments": [ + "solar-tv/milestone/bank/bank.sol", + "-Ogas", + "--evm-version", + "osaka", + "--emit=bin-runtime", + "-Zemit-lean-stages=solar-tv/milestone/bank/gen" + ], + "bytecode": "346028575f3560e01c80632f4f21e21460f857806370a0823114610161578063b6b55f2514603e575b5f5ffd5b6011602052634e487b715f526024601cfd5b60243610602857600435803360875b815f525f60205260405f2080548481019081105f1960601c85116101a657602c578155600154938401938410602c57926001559154905090565b905f52337fe1fffcc4923d04b559f4d29a8bfc6cda04eb5b0d3c460751c2402c5c5cc9109c60205fa25f525f1960601c331160cb575f1960601c331160cb5760205ff35b690417000000010000000260201b335f1960601c915b6020525b60405260605263ed572b275f526064601cfd5b60043560a01c60443610176028576004355f1960601c81166024358261011b604d565b5f525f1960601c8211610147578181036101345760205ff35b6d010200000002000000020000000760e1565b505f1960601c906d041700000002000000020000000960e1565b60043560a01c60243610176028576004355f1960601c8116815f525f60205260405f20545f528181036101935760205ff35b6d010200000003000000020000000960e1565b505050505f1960601c6d04170000000000000000800000006020529060e556", + "bytecode_sha256": "bff0578068ce4ab4a041f226e4e960c13d358c8b430718fefe9ce3a22d760543", + "compiler": "0.8.38+commit.4a7d9ede.solar.0.3.0-dev", + "contract": "Bank", + "evm_version": "osaka", + "optimization": "Gas", + "options": "CompileOpts { input: [\"solar-tv/milestone/bank/bank.sol\"], import_remappings: [], base_path: None, include_paths: [], allow_paths: [], no_import_callback: false, language: Solidity, threads: 4, evm_version: Osaka, stop_after: None, optimization: Gas, optimizer_runs: None, revert_strings: Default, libraries: [], out_dir: None, emit: [BinRuntime], standard_json: false, color: Auto, verbose: false, pretty_json: false, pretty_json_err: false, error_format: Human, error_format_human: Unicode, diagnostic_width: None, no_warnings: false, allow: [], _unstable: [\"emit-lean-stages=solar-tv/milestone/bank/gen\"], unstable: UnstableOpts { ui_testing: false, track_diagnostics: false, parse_yul: false, no_resolve_imports: false, recover_incomplete_input: false, dump: None, ast_stats: false, hir_stats: false, standard_json_stats: false, span_visitor: false, print_max_storage_sizes: false, print_natspec: false, mir_pipeline: None, evm_ir_pipeline: None, print_after_each: false, pass_diff: false, debugify: None, debugify_output: None, solar_tv: None, validate_ir: None, time_passes: false, codegen_all_functions: false, switch_lowering: Auto, switch_max_gas_code_growth: None, switch_max_bit_slice_gas_code_growth: None, tune: None, pack_wide_jump_tables: false, check_analyses: None, prove_analyses: None, validate_passes: None, validate_passes_fault: None, validate_backend: None, validate_backend_fault: None, validate_evm_ir_passes: None, validate_assembly: false, validate_assembly_fault: None, emit_lean_stages: Some(\"solar-tv/milestone/bank/gen\"), forget_gcx: true, help: (), _non_exhaustive: () }, _non_exhaustive: () }", + "sources": [ + { + "path": "solar-tv/milestone/bank/bank.sol", + "sha256": "513398d47335b204a6b047493dd86e9c05066e950ba1300ba5d25850a5f8cb1f" + } + ], + "stages": [ + { + "definition": "stage0", + "file": "Stage0.lean", + "index": 0, + "kind": "mir", + "pass": "lower-evm-shaped", + "sha256": "7d145b2998661cb5c4592a5374f9cc79d94794bba2f6f17b3dfdd0e2a87e0fcc" + }, + { + "definition": "mir1", + "file": "Mir1.lean", + "index": 1, + "kind": "mir", + "pass": "place-reads", + "sha256": "fc18b9f9f61ef53c23dcf6f6799dee7c57a15ca47bb4da2255c633f82b1308ab" + }, + { + "definition": "mir2", + "file": "Mir2.lean", + "index": 2, + "kind": "mir", + "pass": "spell-width-tests", + "sha256": "706bb5ac9ec0a0d67f08496e91c62af4ae17405eb912f83decf45e9a8292b2c0" + }, + { + "definition": "mir3", + "file": "Mir3.lean", + "index": 3, + "kind": "mir", + "pass": "lower-assumes", + "sha256": "aedcd4a2b80c765f6e037a756d6db7b1fab1a2447bdf0ca62eda37ae64185e34" + }, + { + "definition": "mir4", + "file": "Mir4.lean", + "index": 4, + "kind": "mir", + "pass": "evm-inst-schedule", + "sha256": "6f68722b113a0f8f2cda66280547c0601f97b443d416806a6803322a38ae51b9" + }, + { + "definition": "sched", + "file": "Sched.lean", + "index": 0, + "kind": "sched", + "pass": "stack-schedule", + "sha256": "7867a2d8d7a8605c655c1bc038b5cee9a7e714d6c152c9e267afc6dcfd8f9586" + }, + { + "definition": "evm1", + "file": "Evm1.lean", + "index": 1, + "kind": "evm", + "pass": "peephole-early", + "sha256": "92adb3e54ee739c60d8e69961ba9619245df9ae42f1dca9df06fa352fd35f652" + }, + { + "definition": "evm2", + "file": "Evm2.lean", + "index": 2, + "kind": "evm", + "pass": "cfg-simplify-early", + "sha256": "357042975eaf869a3c7f3a65ee4fc68bf6ef1cbb39d2c129c7aa730ac4ce95c7" + }, + { + "definition": "evm3", + "file": "Evm3.lean", + "index": 3, + "kind": "evm", + "pass": "compact-pushes", + "sha256": "95b583b99ae08080b2753dc74b9a3d0f0921e23147a0419959612ea9afb91025" + }, + { + "definition": "evm4", + "file": "Evm4.lean", + "index": 4, + "kind": "evm", + "pass": "block-layout", + "sha256": "5c18eab01a900c5e39d0cac1415ad8339a52ba78c43649f4e3fbfb8cb380e6e1" + }, + { + "definition": "evm5", + "file": "Evm5.lean", + "index": 5, + "kind": "evm", + "pass": "terminal-dedup", + "sha256": "6ebad5531b56a0b055f247364e211b2ed1882f40858c9d75ce5b15ffcd5d9ea2" + }, + { + "definition": "evm6", + "file": "Evm6.lean", + "index": 6, + "kind": "evm", + "pass": "cfg-simplify-early", + "sha256": "5f9a29c13202ce893fa142487c112f530321e5ac8041c28597d23504b278b7f8" + }, + { + "definition": "evm7", + "file": "Evm7.lean", + "index": 7, + "kind": "evm", + "pass": "tail-merge", + "sha256": "baa56a2fc6e55d128e88f34ce5e6bcfdf7e4cbb78a0a907bf7ddcea3a8502bfa" + }, + { + "definition": "evm8", + "file": "Evm8.lean", + "index": 8, + "kind": "evm", + "pass": "cfg-simplify-early", + "sha256": "b954ed58f56daec2d604a03ac02aa0ef3e543767b4a5d0bb13f68ea7f74fead6" + }, + { + "definition": "evm9", + "file": "Evm9.lean", + "index": 9, + "kind": "evm", + "pass": "reorder-pushes", + "sha256": "43597405f5bd81147174381637469732e796aa4056f192d37311c7b21f95b65c" + }, + { + "definition": "evm10", + "file": "Evm10.lean", + "index": 10, + "kind": "evm", + "pass": "block-layout", + "sha256": "0153e265384d5fa0bb56bbcddac12cb7724b905dafbd698d03461bba22095730" + }, + { + "definition": "evm11", + "file": "Evm11.lean", + "index": 11, + "kind": "evm", + "pass": "stack-reschedule", + "sha256": "d55f0c281937953166c7fe2d2176bcb62145f1e1a597546d95ae4e3d903329aa" + }, + { + "definition": "bytecode", + "file": "Bytecode.lean", + "index": 0, + "kind": "bytecode", + "pass": "assemble", + "sha256": "48ec986cf2d82ee746b044677549cc626376293bd6701e44e04d9b1e8e93bd8a" + } + ] +} diff --git a/Certified/bank/options b/Certified/bank/options new file mode 100644 index 00000000..da38913c --- /dev/null +++ b/Certified/bank/options @@ -0,0 +1,3 @@ +-Ogas +--evm-version +osaka diff --git a/Certified/c4/Proofs.lean b/Certified/c4/Proofs.lean new file mode 100644 index 00000000..917eee10 --- /dev/null +++ b/Certified/c4/Proofs.lean @@ -0,0 +1,3 @@ +-- Generated by solar-tv/milestone/certify.py; do not edit. +import c4.Proofs.Stages +import c4.Proofs.Assembly diff --git a/Certified/c4/Proofs/Assembly.lean b/Certified/c4/Proofs/Assembly.lean new file mode 100644 index 00000000..2c390c0a --- /dev/null +++ b/Certified/c4/Proofs/Assembly.lean @@ -0,0 +1,42 @@ +-- Generated by solar-tv/milestone/certify.py; do not edit. +import W1Proofs.Items +import c4.gen.Main.Evm5 +import c4.gen.Main.Bytecode + +/-! The final EVM IR of `Main` against its bytecode, by the assembly checker's walk: the bytecode decodes, linearly from offset 0, to exactly the program's instructions, each jumped-to block at its `JUMPDEST`. -/ + +namespace SolarTV.Milestone.C4 + +open SolarTV.Assembly SolarTV.Export.Main SolarTV.Milestone.W1 + +set_option maxRecDepth 100000 + +/-- The items of the final EVM IR. -/ +def items : List Item := (itemsOf evm5).getD [] + +theorem items_eq : itemsOf evm5 = some items := by decide + +/-- The layout: each jumped-to block at the bytecode's next `JUMPDEST`. The walk checks it. -/ +def offset (label : Nat) : Nat := if label = 1 then 0x55 else if label = 2 then 0x59 else 0 + +/-- The instructions the walk reaches, each at its offset. -/ +def stream : List (Nat × Instr) := (walk bytecode offset 0 items).getD [] + +/-- The checker's walk accepts the exported bytecode against the final EVM IR. -/ +theorem walk_eq : walk bytecode offset 0 items = some stream := by decide +kernel + +theorem checked : Walk bytecode offset 0 items stream := walk_sound walk_eq + +/-- The bytecode's linear decoding is the final EVM IR's instructions at the layout. -/ +theorem decodes : decodeFrom bytecode (bytecode.length + 1) 0 = stream := + walk_decodes checked _ (by have := walk_length checked; omega) + +/-- info: 'SolarTV.Milestone.C4.walk_eq' depends on axioms: [propext, Quot.sound] -/ +#guard_msgs in +#print axioms walk_eq + +/-- info: 'SolarTV.Milestone.C4.decodes' depends on axioms: [propext, Quot.sound] -/ +#guard_msgs in +#print axioms decodes + +end SolarTV.Milestone.C4 diff --git a/Certified/c4/Proofs/Runs/Evm1.lean b/Certified/c4/Proofs/Runs/Evm1.lean new file mode 100644 index 00000000..b75819fc --- /dev/null +++ b/Certified/c4/Proofs/Runs/Evm1.lean @@ -0,0 +1,22 @@ +-- Generated by solar-tv/milestone/certify.py; do not edit. +import W1Proofs.Tactic +import W1Proofs.Axioms +import c4.gen.Main.Evm1 +import c4.gen.Main.Sched + +/-! `cfg-simplify-early`: its input and output end in the same result on every call. -/ + +namespace SolarTV.Milestone.C4 + +open Machine SolarTV.Export.Main SolarTV.Milestone.W1 + +set_option maxHeartbeats 2000000 in +theorem evm1_run (o : Oracle) (call : Call) : + EVM.Program.run o sched call 9 = EVM.Program.run o evm1 call 5 := by + sym_exec + +/-- info: 'SolarTV.Milestone.C4.evm1_run' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within evm1_run + +end SolarTV.Milestone.C4 diff --git a/Certified/c4/Proofs/Runs/Evm2.lean b/Certified/c4/Proofs/Runs/Evm2.lean new file mode 100644 index 00000000..b7cf671b --- /dev/null +++ b/Certified/c4/Proofs/Runs/Evm2.lean @@ -0,0 +1,22 @@ +-- Generated by solar-tv/milestone/certify.py; do not edit. +import W1Proofs.Tactic +import W1Proofs.Axioms +import c4.gen.Main.Evm2 +import c4.gen.Main.Evm1 + +/-! `compact-pushes`: its input and output end in the same result on every call. -/ + +namespace SolarTV.Milestone.C4 + +open Machine SolarTV.Export.Main SolarTV.Milestone.W1 + +set_option maxHeartbeats 2000000 in +theorem evm2_run (o : Oracle) (call : Call) : + EVM.Program.run o evm1 call 5 = EVM.Program.run o evm2 call 5 := by + sym_exec + +/-- info: 'SolarTV.Milestone.C4.evm2_run' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within evm2_run + +end SolarTV.Milestone.C4 diff --git a/Certified/c4/Proofs/Runs/Evm3.lean b/Certified/c4/Proofs/Runs/Evm3.lean new file mode 100644 index 00000000..ed72962b --- /dev/null +++ b/Certified/c4/Proofs/Runs/Evm3.lean @@ -0,0 +1,22 @@ +-- Generated by solar-tv/milestone/certify.py; do not edit. +import W1Proofs.Tactic +import W1Proofs.Axioms +import c4.gen.Main.Evm3 +import c4.gen.Main.Evm2 + +/-! `share-reverts`: its input and output end in the same result on every call. -/ + +namespace SolarTV.Milestone.C4 + +open Machine SolarTV.Export.Main SolarTV.Milestone.W1 + +set_option maxHeartbeats 2000000 in +theorem evm3_run (o : Oracle) (call : Call) : + EVM.Program.run o evm2 call 5 = EVM.Program.run o evm3 call 5 := by + sym_exec + +/-- info: 'SolarTV.Milestone.C4.evm3_run' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within evm3_run + +end SolarTV.Milestone.C4 diff --git a/Certified/c4/Proofs/Runs/Evm4.lean b/Certified/c4/Proofs/Runs/Evm4.lean new file mode 100644 index 00000000..c32ed649 --- /dev/null +++ b/Certified/c4/Proofs/Runs/Evm4.lean @@ -0,0 +1,22 @@ +-- Generated by solar-tv/milestone/certify.py; do not edit. +import W1Proofs.Tactic +import W1Proofs.Axioms +import c4.gen.Main.Evm4 +import c4.gen.Main.Evm3 + +/-! `terminal-dedup`: its input and output end in the same result on every call. -/ + +namespace SolarTV.Milestone.C4 + +open Machine SolarTV.Export.Main SolarTV.Milestone.W1 + +set_option maxHeartbeats 2000000 in +theorem evm4_run (o : Oracle) (call : Call) : + EVM.Program.run o evm3 call 5 = EVM.Program.run o evm4 call 5 := by + sym_exec + +/-- info: 'SolarTV.Milestone.C4.evm4_run' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within evm4_run + +end SolarTV.Milestone.C4 diff --git a/Certified/c4/Proofs/Runs/Evm5.lean b/Certified/c4/Proofs/Runs/Evm5.lean new file mode 100644 index 00000000..67b7aca4 --- /dev/null +++ b/Certified/c4/Proofs/Runs/Evm5.lean @@ -0,0 +1,22 @@ +-- Generated by solar-tv/milestone/certify.py; do not edit. +import W1Proofs.Tactic +import W1Proofs.Axioms +import c4.gen.Main.Evm5 +import c4.gen.Main.Evm4 + +/-! `cfg-simplify-early`: its input and output end in the same result on every call. -/ + +namespace SolarTV.Milestone.C4 + +open Machine SolarTV.Export.Main SolarTV.Milestone.W1 + +set_option maxHeartbeats 2000000 in +theorem evm5_run (o : Oracle) (call : Call) : + EVM.Program.run o evm4 call 5 = EVM.Program.run o evm5 call 3 := by + sym_exec + +/-- info: 'SolarTV.Milestone.C4.evm5_run' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within evm5_run + +end SolarTV.Milestone.C4 diff --git a/Certified/c4/Proofs/Runs/Mir1.lean b/Certified/c4/Proofs/Runs/Mir1.lean new file mode 100644 index 00000000..db851e68 --- /dev/null +++ b/Certified/c4/Proofs/Runs/Mir1.lean @@ -0,0 +1,22 @@ +-- Generated by solar-tv/milestone/certify.py; do not edit. +import W1Proofs.Tactic +import W1Proofs.Axioms +import c4.gen.Main.Mir1 +import c4.gen.Main.Stage0 + +/-! `place-reads`: its input and output end in the same result on every call. -/ + +namespace SolarTV.Milestone.C4 + +open Machine SolarTV.Export.Main SolarTV.Milestone.W1 + +set_option maxHeartbeats 2000000 in +theorem mir1_run (o : Oracle) (call : Call) : + MIR.Lowered.Module.run o stage0 call 9 = MIR.Lowered.Module.run o mir1 call 9 := by + sym_exec + +/-- info: 'SolarTV.Milestone.C4.mir1_run' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within mir1_run + +end SolarTV.Milestone.C4 diff --git a/Certified/c4/Proofs/Runs/Mir2.lean b/Certified/c4/Proofs/Runs/Mir2.lean new file mode 100644 index 00000000..2d539034 --- /dev/null +++ b/Certified/c4/Proofs/Runs/Mir2.lean @@ -0,0 +1,22 @@ +-- Generated by solar-tv/milestone/certify.py; do not edit. +import W1Proofs.Tactic +import W1Proofs.Axioms +import c4.gen.Main.Mir2 +import c4.gen.Main.Mir1 + +/-! `evm-inst-schedule`: its input and output end in the same result on every call. -/ + +namespace SolarTV.Milestone.C4 + +open Machine SolarTV.Export.Main SolarTV.Milestone.W1 + +set_option maxHeartbeats 2000000 in +theorem mir2_run (o : Oracle) (call : Call) : + MIR.Lowered.Module.run o mir1 call 9 = MIR.Lowered.Module.run o mir2 call 9 := by + sym_exec + +/-- info: 'SolarTV.Milestone.C4.mir2_run' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within mir2_run + +end SolarTV.Milestone.C4 diff --git a/Certified/c4/Proofs/Runs/Sched.lean b/Certified/c4/Proofs/Runs/Sched.lean new file mode 100644 index 00000000..8761487d --- /dev/null +++ b/Certified/c4/Proofs/Runs/Sched.lean @@ -0,0 +1,22 @@ +-- Generated by solar-tv/milestone/certify.py; do not edit. +import W1Proofs.Tactic +import W1Proofs.Axioms +import c4.gen.Main.Sched +import c4.gen.Main.Mir2 + +/-! Stack scheduling: the last lowered MIR and the scheduled EVM IR end in the same result on every call. -/ + +namespace SolarTV.Milestone.C4 + +open Machine SolarTV.Export.Main SolarTV.Milestone.W1 + +set_option maxHeartbeats 2000000 in +theorem sched_run (o : Oracle) (call : Call) : + MIR.Lowered.Module.run o mir2 call 9 = EVM.Program.run o sched call 9 := by + sym_exec + +/-- info: 'SolarTV.Milestone.C4.sched_run' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within sched_run + +end SolarTV.Milestone.C4 diff --git a/Certified/c4/Proofs/Runs/Stage0.lean b/Certified/c4/Proofs/Runs/Stage0.lean new file mode 100644 index 00000000..66d35e89 --- /dev/null +++ b/Certified/c4/Proofs/Runs/Stage0.lean @@ -0,0 +1,21 @@ +-- Generated by solar-tv/milestone/certify.py; do not edit. +import W1Proofs.Tactic +import W1Proofs.Axioms +import c4.gen.Main.Stage0 + +/-! The first lowered MIR ends on every call within 9 blocks, the number of its blocks. -/ + +namespace SolarTV.Milestone.C4 + +open Machine SolarTV.Export.Main SolarTV.Milestone.W1 + +set_option maxHeartbeats 2000000 in +theorem stage0_ends (o : Oracle) (call : Call) : + (MIR.Lowered.Module.run o stage0 call 9).isSome = true := by + sym_exec + +/-- info: 'SolarTV.Milestone.C4.stage0_ends' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within stage0_ends + +end SolarTV.Milestone.C4 diff --git a/Certified/c4/Proofs/Stages.lean b/Certified/c4/Proofs/Stages.lean new file mode 100644 index 00000000..3e15b1bf --- /dev/null +++ b/Certified/c4/Proofs/Stages.lean @@ -0,0 +1,147 @@ +-- Generated by solar-tv/milestone/certify.py; do not edit. +import c4.Proofs.Runs.Stage0 +import c4.Proofs.Runs.Mir1 +import c4.Proofs.Runs.Mir2 +import c4.Proofs.Runs.Sched +import c4.Proofs.Runs.Evm1 +import c4.Proofs.Runs.Evm2 +import c4.Proofs.Runs.Evm3 +import c4.Proofs.Runs.Evm4 +import c4.Proofs.Runs.Evm5 +import W1Proofs.Stage +import SolarTV.Composition + +/-! The backend stages of `Main`, each proved on every call (`anyCall`: any calldata, call value and storage) under every oracle, and chained from the first lowered MIR `stage0` to the final EVM IR `evm5`. Fuels are the programs' block counts. -/ + +namespace SolarTV.Milestone.C4 + +open Machine SolarTV.Export.Main SolarTV.Milestone.W1 + +/-- `place-reads`: stage0 to mir1. -/ +theorem stage_mir1 (o : Oracle) : Stage (mirSem o) (mirSem o) stage0 mir1 anyCall := + stage_of_runs (A := MIR.Lowered.moduleLayer) (B := MIR.Lowered.moduleLayer) 9 9 (fun call _ => stage0_ends o call) + (fun call _ => mir1_run o call) + +theorem mir1_ends (o : Oracle) : ∀ call, anyCall call → + (MIR.Lowered.Module.run o mir1 call 9).isSome = true := + ends_of_runs (A := MIR.Lowered.moduleLayer) (B := MIR.Lowered.moduleLayer) + (o := o) (p := stage0) (q := mir1) (n := 9) (m := 9) (fun call _ => stage0_ends o call) + (fun call _ => mir1_run o call) + +/-- `evm-inst-schedule`: mir1 to mir2. -/ +theorem stage_mir2 (o : Oracle) : Stage (mirSem o) (mirSem o) mir1 mir2 anyCall := + stage_of_runs (A := MIR.Lowered.moduleLayer) (B := MIR.Lowered.moduleLayer) 9 9 (mir1_ends o) + (fun call _ => mir2_run o call) + +theorem mir2_ends (o : Oracle) : ∀ call, anyCall call → + (MIR.Lowered.Module.run o mir2 call 9).isSome = true := + ends_of_runs (A := MIR.Lowered.moduleLayer) (B := MIR.Lowered.moduleLayer) + (o := o) (p := mir1) (q := mir2) (n := 9) (m := 9) (mir1_ends o) + (fun call _ => mir2_run o call) + +/-- `stack-schedule`: mir2 to sched. -/ +theorem stage_sched (o : Oracle) : Stage (mirSem o) (evmirSem o) mir2 sched anyCall := + stage_of_runs (A := MIR.Lowered.moduleLayer) (B := EVM.Program.layer) 9 9 (mir2_ends o) + (fun call _ => sched_run o call) + +theorem sched_ends (o : Oracle) : ∀ call, anyCall call → + (EVM.Program.run o sched call 9).isSome = true := + ends_of_runs (A := MIR.Lowered.moduleLayer) (B := EVM.Program.layer) + (o := o) (p := mir2) (q := sched) (n := 9) (m := 9) (mir2_ends o) + (fun call _ => sched_run o call) + +/-- `cfg-simplify-early`: sched to evm1. -/ +theorem stage_evm1 (o : Oracle) : Stage (evmirSem o) (evmirSem o) sched evm1 anyCall := + stage_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) 9 5 (sched_ends o) + (fun call _ => evm1_run o call) + +theorem evm1_ends (o : Oracle) : ∀ call, anyCall call → + (EVM.Program.run o evm1 call 5).isSome = true := + ends_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) + (o := o) (p := sched) (q := evm1) (n := 9) (m := 5) (sched_ends o) + (fun call _ => evm1_run o call) + +/-- `compact-pushes`: evm1 to evm2. -/ +theorem stage_evm2 (o : Oracle) : Stage (evmirSem o) (evmirSem o) evm1 evm2 anyCall := + stage_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) 5 5 (evm1_ends o) + (fun call _ => evm2_run o call) + +theorem evm2_ends (o : Oracle) : ∀ call, anyCall call → + (EVM.Program.run o evm2 call 5).isSome = true := + ends_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) + (o := o) (p := evm1) (q := evm2) (n := 5) (m := 5) (evm1_ends o) + (fun call _ => evm2_run o call) + +/-- `share-reverts`: evm2 to evm3. -/ +theorem stage_evm3 (o : Oracle) : Stage (evmirSem o) (evmirSem o) evm2 evm3 anyCall := + stage_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) 5 5 (evm2_ends o) + (fun call _ => evm3_run o call) + +theorem evm3_ends (o : Oracle) : ∀ call, anyCall call → + (EVM.Program.run o evm3 call 5).isSome = true := + ends_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) + (o := o) (p := evm2) (q := evm3) (n := 5) (m := 5) (evm2_ends o) + (fun call _ => evm3_run o call) + +/-- `terminal-dedup`: evm3 to evm4. -/ +theorem stage_evm4 (o : Oracle) : Stage (evmirSem o) (evmirSem o) evm3 evm4 anyCall := + stage_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) 5 5 (evm3_ends o) + (fun call _ => evm4_run o call) + +theorem evm4_ends (o : Oracle) : ∀ call, anyCall call → + (EVM.Program.run o evm4 call 5).isSome = true := + ends_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) + (o := o) (p := evm3) (q := evm4) (n := 5) (m := 5) (evm3_ends o) + (fun call _ => evm4_run o call) + +/-- `cfg-simplify-early`: evm4 to evm5. -/ +theorem stage_evm5 (o : Oracle) : Stage (evmirSem o) (evmirSem o) evm4 evm5 anyCall := + stage_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) 5 3 (evm4_ends o) + (fun call _ => evm5_run o call) + +/-- The compilation from the first lowered MIR to the final EVM IR. -/ +def compilation : Compilation := + ⟨stage0, [mir1, mir2], sched, [evm1, evm2, evm3, evm4, evm5]⟩ + +/-- Every stage from the first lowered MIR to the final EVM IR, chained by the library's composition, on every call. -/ +theorem c4_mir_to_evmir (o : Oracle) : Stage (mirSem o) (evmirSem o) stage0 evm5 anyCall := + mir_to_evmir o anyCall compilation ⟨stage_mir1 o, stage_mir2 o, trivial⟩ (stage_sched o) + ⟨stage_evm1 o, stage_evm2 o, stage_evm3 o, stage_evm4 o, stage_evm5 o, trivial⟩ + +/-- info: 'SolarTV.Milestone.C4.stage_mir1' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms stage_mir1 + +/-- info: 'SolarTV.Milestone.C4.stage_mir2' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms stage_mir2 + +/-- info: 'SolarTV.Milestone.C4.stage_sched' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms stage_sched + +/-- info: 'SolarTV.Milestone.C4.stage_evm1' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms stage_evm1 + +/-- info: 'SolarTV.Milestone.C4.stage_evm2' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms stage_evm2 + +/-- info: 'SolarTV.Milestone.C4.stage_evm3' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms stage_evm3 + +/-- info: 'SolarTV.Milestone.C4.stage_evm4' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms stage_evm4 + +/-- info: 'SolarTV.Milestone.C4.stage_evm5' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms stage_evm5 + +/-- info: 'SolarTV.Milestone.C4.c4_mir_to_evmir' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms c4_mir_to_evmir + +end SolarTV.Milestone.C4 diff --git a/Certified/c4/bytecode.hex b/Certified/c4/bytecode.hex new file mode 100644 index 00000000..fc159c91 --- /dev/null +++ b/Certified/c4/bytecode.hex @@ -0,0 +1 @@ +346055575f3560e01c806302067e6a036055576024361060ff60043511176055576004355f5460ff8116820160ff81116059579060ff1916179081601e1a1860081b9061ff00191617805f5560ff165f5260205ff35b5f5ffd5b6011602052634e487b715f526024601cfd diff --git a/Certified/c4/c4.sol b/Certified/c4/c4.sol new file mode 100644 index 00000000..44d5fc4f --- /dev/null +++ b/Certified/c4/c4.sol @@ -0,0 +1,3 @@ +// SPDX-License-Identifier: UNLICENSED +pragma solidity ^0.8.28; +contract Main { uint8 v; uint8 w = 7; function add(uint8 x) external returns (uint8) { v += x; w ^= x; return v; } } diff --git a/Certified/c4/gen/Main/Bytecode.lean b/Certified/c4/gen/Main/Bytecode.lean new file mode 100644 index 00000000..a05abfcf --- /dev/null +++ b/Certified/c4/gen/Main/Bytecode.lean @@ -0,0 +1,20 @@ +-- solar-lean-stage: kind=bytecode index=0 pass=assemble +/-! Generated by `solar -Zemit-lean-stages` for `Main`; do not edit. -/ + +namespace SolarTV.Export.Main + +/-- The runtime bytecode, byte by byte. -/ +def bytecode : List Nat := + [0x34, 0x60, 0x55, 0x57, 0x5f, 0x35, 0x60, 0xe0, 0x1c, 0x80, 0x63, 0x02, 0x06, 0x7e, 0x6a, 0x03, + 0x60, 0x55, 0x57, 0x60, 0x24, 0x36, 0x10, 0x60, 0xff, 0x60, 0x04, 0x35, 0x11, 0x17, 0x60, 0x55, + 0x57, 0x60, 0x04, 0x35, 0x5f, 0x54, 0x60, 0xff, 0x81, 0x16, 0x82, 0x01, 0x60, 0xff, 0x81, 0x11, + 0x60, 0x59, 0x57, 0x90, 0x60, 0xff, 0x19, 0x16, 0x17, 0x90, 0x81, 0x60, 0x1e, 0x1a, 0x18, 0x60, + 0x08, 0x1b, 0x90, 0x61, 0xff, 0x00, 0x19, 0x16, 0x17, 0x80, 0x5f, 0x55, 0x60, 0xff, 0x16, 0x5f, + 0x52, 0x60, 0x20, 0x5f, 0xf3, 0x5b, 0x5f, 0x5f, 0xfd, 0x5b, 0x60, 0x11, 0x60, 0x20, 0x52, 0x63, + 0x4e, 0x48, 0x7b, 0x71, 0x5f, 0x52, 0x60, 0x24, 0x60, 0x1c, 0xfd] + +/-- The runtime bytecode in hex, as `--emit=bin-runtime` prints it. -/ +def bytecodeHex : String := + "346055575f3560e01c806302067e6a036055576024361060ff60043511176055576004355f5460ff8116820160ff81116059579060ff1916179081601e1a1860081b9061ff00191617805f5560ff165f5260205ff35b5f5ffd5b6011602052634e487b715f526024601cfd" + +end SolarTV.Export.Main diff --git a/Certified/c4/gen/Main/Evm1.lean b/Certified/c4/gen/Main/Evm1.lean new file mode 100644 index 00000000..cd1ead6a --- /dev/null +++ b/Certified/c4/gen/Main/Evm1.lean @@ -0,0 +1,90 @@ +-- solar-lean-stage: kind=evm index=1 pass=cfg-simplify-early +import SolarTV.EVMIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `Main`; do not edit. -/ + +namespace SolarTV.Export.Main + +/-- The runtime EVM IR after `cfg-simplify-early`. -/ +def evm1 : EVM.Program.Program := + { blocks := [ + -- bb0 + [.effect .callvalue 0, + .jumpi 1, + .op (.stack (.push 0)), + .effect .calldataload 1, + .op (.stack (.push 224)), + .op (.stack .shr), + .op (.stack (.dup 0)), + .op (.stack (.push 0x2067e6a)), + .op (.stack .eq), + .jumpi 2, + .jump 1], + -- bb3 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb4 + [.op (.stack (.push 36)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack (.push 255)), + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack .gt), + .op (.stack .or), + .jumpi 4, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 0)), + .effect .sload 1, + .op (.stack (.push 255)), + .op (.stack (.dup 1)), + .op (.stack .and), + .op (.stack (.dup 2)), + .op (.stack .add), + .op (.stack (.push 255)), + .op (.stack (.dup 1)), + .op (.stack .gt), + .jumpi 3, + .op (.stack (.swap 0)), + .op (.stack (.push 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff00)), + .op (.stack .and), + .op (.stack .or), + .op (.stack (.swap 0)), + .op (.stack (.dup 1)), + .op (.stack (.push 30)), + .op (.stack .byte), + .op (.stack .xor), + .op (.stack (.push 8)), + .op (.stack .shl), + .op (.stack (.swap 0)), + .op (.stack (.push 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff00ff)), + .op (.stack .and), + .op (.stack .or), + .op (.stack (.dup 0)), + .op (.stack (.push 0)), + .effect .sstore 2, + .op (.stack (.push 255)), + .op (.stack .and), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb7 + [.op (.stack (.push 17)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 0x4e487b71)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 36)), + .op (.stack (.push 28)), + .revert], + -- bb8 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert]] } + +end SolarTV.Export.Main diff --git a/Certified/c4/gen/Main/Evm2.lean b/Certified/c4/gen/Main/Evm2.lean new file mode 100644 index 00000000..ba01cae0 --- /dev/null +++ b/Certified/c4/gen/Main/Evm2.lean @@ -0,0 +1,92 @@ +-- solar-lean-stage: kind=evm index=2 pass=compact-pushes +import SolarTV.EVMIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `Main`; do not edit. -/ + +namespace SolarTV.Export.Main + +/-- The runtime EVM IR after `compact-pushes`. -/ +def evm2 : EVM.Program.Program := + { blocks := [ + -- bb0 + [.effect .callvalue 0, + .jumpi 1, + .op (.stack (.push 0)), + .effect .calldataload 1, + .op (.stack (.push 224)), + .op (.stack .shr), + .op (.stack (.dup 0)), + .op (.stack (.push 0x2067e6a)), + .op (.stack .eq), + .jumpi 2, + .jump 1], + -- bb3 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb4 + [.op (.stack (.push 36)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack (.push 255)), + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack .gt), + .op (.stack .or), + .jumpi 4, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 0)), + .effect .sload 1, + .op (.stack (.push 255)), + .op (.stack (.dup 1)), + .op (.stack .and), + .op (.stack (.dup 2)), + .op (.stack .add), + .op (.stack (.push 255)), + .op (.stack (.dup 1)), + .op (.stack .gt), + .jumpi 3, + .op (.stack (.swap 0)), + .op (.stack (.push 255)), + .op (.stack .not), + .op (.stack .and), + .op (.stack .or), + .op (.stack (.swap 0)), + .op (.stack (.dup 1)), + .op (.stack (.push 30)), + .op (.stack .byte), + .op (.stack .xor), + .op (.stack (.push 8)), + .op (.stack .shl), + .op (.stack (.swap 0)), + .op (.stack (.push 65280)), + .op (.stack .not), + .op (.stack .and), + .op (.stack .or), + .op (.stack (.dup 0)), + .op (.stack (.push 0)), + .effect .sstore 2, + .op (.stack (.push 255)), + .op (.stack .and), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb7 + [.op (.stack (.push 17)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 0x4e487b71)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 36)), + .op (.stack (.push 28)), + .revert], + -- bb8 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert]] } + +end SolarTV.Export.Main diff --git a/Certified/c4/gen/Main/Evm3.lean b/Certified/c4/gen/Main/Evm3.lean new file mode 100644 index 00000000..f46f65c5 --- /dev/null +++ b/Certified/c4/gen/Main/Evm3.lean @@ -0,0 +1,92 @@ +-- solar-lean-stage: kind=evm index=3 pass=share-reverts +import SolarTV.EVMIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `Main`; do not edit. -/ + +namespace SolarTV.Export.Main + +/-- The runtime EVM IR after `share-reverts`. -/ +def evm3 : EVM.Program.Program := + { blocks := [ + -- bb0 + [.effect .callvalue 0, + .jumpi 1, + .op (.stack (.push 0)), + .effect .calldataload 1, + .op (.stack (.push 224)), + .op (.stack .shr), + .op (.stack (.dup 0)), + .op (.stack (.push 0x2067e6a)), + .op (.stack .sub), + .jumpi 1, + .jump 2], + -- bb3 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb4 + [.op (.stack (.push 36)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack (.push 255)), + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack .gt), + .op (.stack .or), + .jumpi 4, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 0)), + .effect .sload 1, + .op (.stack (.push 255)), + .op (.stack (.dup 1)), + .op (.stack .and), + .op (.stack (.dup 2)), + .op (.stack .add), + .op (.stack (.push 255)), + .op (.stack (.dup 1)), + .op (.stack .gt), + .jumpi 3, + .op (.stack (.swap 0)), + .op (.stack (.push 255)), + .op (.stack .not), + .op (.stack .and), + .op (.stack .or), + .op (.stack (.swap 0)), + .op (.stack (.dup 1)), + .op (.stack (.push 30)), + .op (.stack .byte), + .op (.stack .xor), + .op (.stack (.push 8)), + .op (.stack .shl), + .op (.stack (.swap 0)), + .op (.stack (.push 65280)), + .op (.stack .not), + .op (.stack .and), + .op (.stack .or), + .op (.stack (.dup 0)), + .op (.stack (.push 0)), + .effect .sstore 2, + .op (.stack (.push 255)), + .op (.stack .and), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb7 + [.op (.stack (.push 17)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 0x4e487b71)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 36)), + .op (.stack (.push 28)), + .revert], + -- bb8 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert]] } + +end SolarTV.Export.Main diff --git a/Certified/c4/gen/Main/Evm4.lean b/Certified/c4/gen/Main/Evm4.lean new file mode 100644 index 00000000..3254f449 --- /dev/null +++ b/Certified/c4/gen/Main/Evm4.lean @@ -0,0 +1,90 @@ +-- solar-lean-stage: kind=evm index=4 pass=terminal-dedup +import SolarTV.EVMIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `Main`; do not edit. -/ + +namespace SolarTV.Export.Main + +/-- The runtime EVM IR after `terminal-dedup`. -/ +def evm4 : EVM.Program.Program := + { blocks := [ + -- bb0 + [.effect .callvalue 0, + .jumpi 1, + .op (.stack (.push 0)), + .effect .calldataload 1, + .op (.stack (.push 224)), + .op (.stack .shr), + .op (.stack (.dup 0)), + .op (.stack (.push 0x2067e6a)), + .op (.stack .sub), + .jumpi 1, + .jump 2], + -- bb3 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb4 + [.op (.stack (.push 36)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack (.push 255)), + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack .gt), + .op (.stack .or), + .jumpi 4, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 0)), + .effect .sload 1, + .op (.stack (.push 255)), + .op (.stack (.dup 1)), + .op (.stack .and), + .op (.stack (.dup 2)), + .op (.stack .add), + .op (.stack (.push 255)), + .op (.stack (.dup 1)), + .op (.stack .gt), + .jumpi 3, + .op (.stack (.swap 0)), + .op (.stack (.push 255)), + .op (.stack .not), + .op (.stack .and), + .op (.stack .or), + .op (.stack (.swap 0)), + .op (.stack (.dup 1)), + .op (.stack (.push 30)), + .op (.stack .byte), + .op (.stack .xor), + .op (.stack (.push 8)), + .op (.stack .shl), + .op (.stack (.swap 0)), + .op (.stack (.push 65280)), + .op (.stack .not), + .op (.stack .and), + .op (.stack .or), + .op (.stack (.dup 0)), + .op (.stack (.push 0)), + .effect .sstore 2, + .op (.stack (.push 255)), + .op (.stack .and), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb7 + [.op (.stack (.push 17)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 0x4e487b71)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 36)), + .op (.stack (.push 28)), + .revert], + -- bb8 + [.jump 1]] } + +end SolarTV.Export.Main diff --git a/Certified/c4/gen/Main/Evm5.lean b/Certified/c4/gen/Main/Evm5.lean new file mode 100644 index 00000000..d2dab63e --- /dev/null +++ b/Certified/c4/gen/Main/Evm5.lean @@ -0,0 +1,86 @@ +-- solar-lean-stage: kind=evm index=5 pass=cfg-simplify-early +import SolarTV.EVMIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `Main`; do not edit. -/ + +namespace SolarTV.Export.Main + +/-- The runtime EVM IR after `cfg-simplify-early`. -/ +def evm5 : EVM.Program.Program := + { blocks := [ + -- bb0 + [.effect .callvalue 0, + .jumpi 1, + .op (.stack (.push 0)), + .effect .calldataload 1, + .op (.stack (.push 224)), + .op (.stack .shr), + .op (.stack (.dup 0)), + .op (.stack (.push 0x2067e6a)), + .op (.stack .sub), + .jumpi 1, + .op (.stack (.push 36)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack (.push 255)), + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack .gt), + .op (.stack .or), + .jumpi 1, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 0)), + .effect .sload 1, + .op (.stack (.push 255)), + .op (.stack (.dup 1)), + .op (.stack .and), + .op (.stack (.dup 2)), + .op (.stack .add), + .op (.stack (.push 255)), + .op (.stack (.dup 1)), + .op (.stack .gt), + .jumpi 2, + .op (.stack (.swap 0)), + .op (.stack (.push 255)), + .op (.stack .not), + .op (.stack .and), + .op (.stack .or), + .op (.stack (.swap 0)), + .op (.stack (.dup 1)), + .op (.stack (.push 30)), + .op (.stack .byte), + .op (.stack .xor), + .op (.stack (.push 8)), + .op (.stack .shl), + .op (.stack (.swap 0)), + .op (.stack (.push 65280)), + .op (.stack .not), + .op (.stack .and), + .op (.stack .or), + .op (.stack (.dup 0)), + .op (.stack (.push 0)), + .effect .sstore 2, + .op (.stack (.push 255)), + .op (.stack .and), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb3 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb7 + [.op (.stack (.push 17)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 0x4e487b71)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 36)), + .op (.stack (.push 28)), + .revert]] } + +end SolarTV.Export.Main diff --git a/Certified/c4/gen/Main/Manifest.lean b/Certified/c4/gen/Main/Manifest.lean new file mode 100644 index 00000000..fa2e01b2 --- /dev/null +++ b/Certified/c4/gen/Main/Manifest.lean @@ -0,0 +1,42 @@ +-- solar-lean-stage: kind=manifest index=0 pass=none +/-! Generated by `solar -Zemit-lean-stages` for `Main`; do not edit. + +What the stages of this directory were compiled from and by. `stages` lists each +stage's file, its definition, the pass whose output it is, and the SHA-256 of the file. +-/ + +namespace SolarTV.Export.Main.Manifest + +def sources : List (String × String) := + [("solar-tv/milestone/c4/c4.sol", "31c39cd4e9c5cba0f78aff3a986d69be40c5f68cdb36fbf05ad3d0a5e950e858")] + +def compiler : String := "0.8.38+commit.a8179dfc.solar.0.3.0-dev" + +def arguments : List String := + ["solar-tv/milestone/c4/c4.sol", + "-Zcheck-analyses=false", + "--emit=bin-runtime", + "-Zemit-lean-stages=solar-tv/milestone/c4/gen"] + +def evmVersion : String := "osaka" + +def optimization : String := "Gas" + +def stages : List (String × String × String × String) := + [("Stage0", "stage0", "lower-evm-shaped", "fc9bd372cfa93042b6948b6b52ce83f8c868b0832c2cd076bdd4bf4c481b521a"), + ("Mir1", "mir1", "place-reads", "0e5c81b03404896a8f12b5e1df4636f4922bc80cef6e06f297fa024a3965ecb9"), + ("Mir2", "mir2", "evm-inst-schedule", "b50596a2f7dc4831a1789f42dd5d0502e13b266ca9e5f7567e1292c450b94af4"), + ("Sched", "sched", "stack-schedule", "fdf061032cfc51bfca74d7977cb5944bdb0af4147d7048cb86e77fa7d4742160"), + ("Evm1", "evm1", "cfg-simplify-early", "b10980301296d4887ba4322567653012d670c2a5441dcba1f4044ffb40d1d1d8"), + ("Evm2", "evm2", "compact-pushes", "512034f050a4fe708788f1c7e7db6c570432aedfd9fdd308c3a993849ba8c28c"), + ("Evm3", "evm3", "share-reverts", "955fa46e2c6701e3644da10a0129e72c06cdf0624a7bd4fa4f7faae7f71be222"), + ("Evm4", "evm4", "terminal-dedup", "4009d1232a8b5bc57afbbe5ac64c2fde908da9b958d007f9f9759078bdf9093b"), + ("Evm5", "evm5", "cfg-simplify-early", "1309fae9f4a8d9561fe138c69b13b7c6e57a71404ed92f861c9a7370738fc7bc"), + ("Bytecode", "bytecode", "assemble", "7d5d01d3952b98c24d030dfd189808f507cdd5e523b997b80aa4baff836df2af")] + +def bytecodeHex : String := + "346055575f3560e01c806302067e6a036055576024361060ff60043511176055576004355f5460ff8116820160ff81116059579060ff1916179081601e1a1860081b9061ff00191617805f5560ff165f5260205ff35b5f5ffd5b6011602052634e487b715f526024601cfd" + +def bytecodeSha256 : String := "8a21bc207d9dd8be48d921a717eda3ecb7e5bfcb5397850bc3d64a29037fac47" + +end SolarTV.Export.Main.Manifest diff --git a/Certified/c4/gen/Main/Mir1.lean b/Certified/c4/gen/Main/Mir1.lean new file mode 100644 index 00000000..0c3e9059 --- /dev/null +++ b/Certified/c4/gen/Main/Mir1.lean @@ -0,0 +1,77 @@ +-- solar-lean-stage: kind=mir index=1 pass=place-reads +import SolarTV.MIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `Main`; do not edit. -/ + +namespace SolarTV.Export.Main + +/-- The lowered MIR module after `place-reads`. -/ +def mir1 : MIR.Lowered.Module := + { entry := 2, + functions := [ + -- @add + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 45) .calldatasize [], + .pure 47 .lt [.value 45, .const 36], + .effect (some 49) .calldataload [.const 4], + .pure 51 .gt [.value 49, .const 255], + .pure 71 .or [.value 47, .value 51]], + .branch (.value 71) 3 4⟩, + -- bb1 + ⟨[], + [.effect none .mstore [.const 32, .const 17], + .effect none .mstore [.const 0, .const 0x4e487b71]], + .revert (.const 28) (.const 36)⟩, + -- bb2 + ⟨[], + [.pure 8 .and [.value 2, .const 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff00], + .pure 11 .or [.value 8, .value 34], + .pure 60 .byte [.const 30, .value 11], + .pure 61 .xor [.value 60, .value 72], + .pure 23 .and [.value 11, .const 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff00ff], + .pure 26 .shl [.const 8, .value 61], + .pure 27 .or [.value 23, .value 26], + .effect none .sstore [.const 0, .value 27], + .pure 65 .and [.value 27, .const 255], + .effect none .mstore [.const 0, .value 65]], + .ret (.const 0) (.const 32)⟩, + -- bb3 + ⟨[], + [], + .revert (.const 0) (.const 0)⟩, + -- bb4 + ⟨[], + [.effect (some 72) .calldataload [.const 4], + .effect (some 2) .sload [.const 0], + .pure 69 .and [.value 2, .const 255], + .pure 34 .add [.value 69, .value 72], + .pure 36 .gt [.value 34, .const 255]], + .branch (.value 36) 1 2⟩] }, + -- @constructor: not reachable from the runtime entry, so it has no blocks here + { blocks := [] }, + -- @entry + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 0) .callvalue [], + .ne 2 (.value 0) (.const 0)], + .branch (.value 2) 3 1⟩, + -- bb1 + ⟨[], + [.effect (some 4) .calldataload [.const 0], + .pure 6 .shr [.const 224, .value 4]], + .switch (.value 6) 3 [(.const 0x2067e6a, 2)]⟩, + -- bb2 + ⟨[], + [], + .tailCall 0 []⟩, + -- bb3 + ⟨[], + [], + .revert (.const 0) (.const 0)⟩] }] } + +end SolarTV.Export.Main diff --git a/Certified/c4/gen/Main/Mir2.lean b/Certified/c4/gen/Main/Mir2.lean new file mode 100644 index 00000000..47615e5f --- /dev/null +++ b/Certified/c4/gen/Main/Mir2.lean @@ -0,0 +1,77 @@ +-- solar-lean-stage: kind=mir index=2 pass=evm-inst-schedule +import SolarTV.MIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `Main`; do not edit. -/ + +namespace SolarTV.Export.Main + +/-- The lowered MIR module after `evm-inst-schedule`. -/ +def mir2 : MIR.Lowered.Module := + { entry := 2, + functions := [ + -- @add + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 45) .calldatasize [], + .pure 47 .lt [.value 45, .const 36], + .effect (some 49) .calldataload [.const 4], + .pure 51 .gt [.value 49, .const 255], + .pure 71 .or [.value 47, .value 51]], + .branch (.value 71) 3 4⟩, + -- bb1 + ⟨[], + [.effect none .mstore [.const 32, .const 17], + .effect none .mstore [.const 0, .const 0x4e487b71]], + .revert (.const 28) (.const 36)⟩, + -- bb2 + ⟨[], + [.pure 8 .and [.value 2, .const 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff00], + .pure 11 .or [.value 8, .value 34], + .pure 60 .byte [.const 30, .value 11], + .pure 61 .xor [.value 60, .value 72], + .pure 26 .shl [.const 8, .value 61], + .pure 23 .and [.value 11, .const 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff00ff], + .pure 27 .or [.value 23, .value 26], + .effect none .sstore [.const 0, .value 27], + .pure 65 .and [.value 27, .const 255], + .effect none .mstore [.const 0, .value 65]], + .ret (.const 0) (.const 32)⟩, + -- bb3 + ⟨[], + [], + .revert (.const 0) (.const 0)⟩, + -- bb4 + ⟨[], + [.effect (some 72) .calldataload [.const 4], + .effect (some 2) .sload [.const 0], + .pure 69 .and [.value 2, .const 255], + .pure 34 .add [.value 69, .value 72], + .pure 36 .gt [.value 34, .const 255]], + .branch (.value 36) 1 2⟩] }, + -- @constructor: not reachable from the runtime entry, so it has no blocks here + { blocks := [] }, + -- @entry + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 0) .callvalue [], + .ne 2 (.value 0) (.const 0)], + .branch (.value 2) 3 1⟩, + -- bb1 + ⟨[], + [.effect (some 4) .calldataload [.const 0], + .pure 6 .shr [.const 224, .value 4]], + .switch (.value 6) 3 [(.const 0x2067e6a, 2)]⟩, + -- bb2 + ⟨[], + [], + .tailCall 0 []⟩, + -- bb3 + ⟨[], + [], + .revert (.const 0) (.const 0)⟩] }] } + +end SolarTV.Export.Main diff --git a/Certified/c4/gen/Main/Sched.lean b/Certified/c4/gen/Main/Sched.lean new file mode 100644 index 00000000..0d041c9a --- /dev/null +++ b/Certified/c4/gen/Main/Sched.lean @@ -0,0 +1,98 @@ +-- solar-lean-stage: kind=sched index=0 pass=stack-schedule +import SolarTV.EVMIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `Main`; do not edit. -/ + +namespace SolarTV.Export.Main + +/-- The runtime EVM IR as stack scheduling emits it. -/ +def sched : EVM.Program.Program := + { blocks := [ + -- bb0 + [.effect .callvalue 0, + .jumpi 3, + .jump 1], + -- bb1 + [.op (.stack (.push 0)), + .effect .calldataload 1, + .op (.stack (.push 224)), + .op (.stack .shr), + .op (.stack (.dup 0)), + .op (.stack (.push 0x2067e6a)), + .op (.stack .eq), + .jumpi 2, + .jump 3], + -- bb2 + [.jump 4], + -- bb3 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb4 + [.op (.stack (.push 36)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack (.push 255)), + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack .gt), + .op (.stack .or), + .jumpi 8, + .jump 5], + -- bb5 + [.op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 0)), + .effect .sload 1, + .op (.stack (.push 255)), + .op (.stack (.dup 1)), + .op (.stack .and), + .op (.stack (.dup 2)), + .op (.stack .add), + .op (.stack (.push 255)), + .op (.stack (.dup 1)), + .op (.stack .gt), + .jumpi 7, + .jump 6], + -- bb6 + [.op (.stack (.swap 0)), + .op (.stack (.push 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff00)), + .op (.stack .and), + .op (.stack .or), + .op (.stack (.swap 0)), + .op (.stack (.dup 1)), + .op (.stack (.push 30)), + .op (.stack .byte), + .op (.stack .xor), + .op (.stack (.push 8)), + .op (.stack .shl), + .op (.stack (.swap 0)), + .op (.stack (.push 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff00ff)), + .op (.stack .and), + .op (.stack .or), + .op (.stack (.dup 0)), + .op (.stack (.push 0)), + .effect .sstore 2, + .op (.stack (.push 255)), + .op (.stack .and), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb7 + [.op (.stack (.push 17)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 0x4e487b71)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 36)), + .op (.stack (.push 28)), + .revert], + -- bb8 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert]] } + +end SolarTV.Export.Main diff --git a/Certified/c4/gen/Main/Stage0.lean b/Certified/c4/gen/Main/Stage0.lean new file mode 100644 index 00000000..e758272d --- /dev/null +++ b/Certified/c4/gen/Main/Stage0.lean @@ -0,0 +1,76 @@ +-- solar-lean-stage: kind=mir index=0 pass=lower-evm-shaped +import SolarTV.MIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `Main`; do not edit. -/ + +namespace SolarTV.Export.Main + +/-- The first lowered MIR module, after `lower-evm-shaped` advanced the phase. -/ +def stage0 : MIR.Lowered.Module := + { entry := 2, + functions := [ + -- @add + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 45) .calldatasize [], + .pure 47 .lt [.value 45, .const 36], + .effect (some 49) .calldataload [.const 4], + .pure 51 .gt [.value 49, .const 255], + .pure 71 .or [.value 47, .value 51]], + .branch (.value 71) 3 4⟩, + -- bb1 + ⟨[], + [.effect none .mstore [.const 32, .const 17], + .effect none .mstore [.const 0, .const 0x4e487b71]], + .revert (.const 28) (.const 36)⟩, + -- bb2 + ⟨[], + [.pure 8 .and [.value 2, .const 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff00], + .pure 11 .or [.value 8, .value 34], + .pure 60 .byte [.const 30, .value 11], + .pure 61 .xor [.value 60, .value 49], + .pure 23 .and [.value 11, .const 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff00ff], + .pure 26 .shl [.const 8, .value 61], + .pure 27 .or [.value 23, .value 26], + .effect none .sstore [.const 0, .value 27], + .pure 65 .and [.value 27, .const 255], + .effect none .mstore [.const 0, .value 65]], + .ret (.const 0) (.const 32)⟩, + -- bb3 + ⟨[], + [], + .revert (.const 0) (.const 0)⟩, + -- bb4 + ⟨[], + [.effect (some 2) .sload [.const 0], + .pure 69 .and [.value 2, .const 255], + .pure 34 .add [.value 69, .value 49], + .pure 36 .gt [.value 34, .const 255]], + .branch (.value 36) 1 2⟩] }, + -- @constructor: not reachable from the runtime entry, so it has no blocks here + { blocks := [] }, + -- @entry + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 0) .callvalue [], + .ne 2 (.value 0) (.const 0)], + .branch (.value 2) 3 1⟩, + -- bb1 + ⟨[], + [.effect (some 4) .calldataload [.const 0], + .pure 6 .shr [.const 224, .value 4]], + .switch (.value 6) 3 [(.const 0x2067e6a, 2)]⟩, + -- bb2 + ⟨[], + [], + .tailCall 0 []⟩, + -- bb3 + ⟨[], + [], + .revert (.const 0) (.const 0)⟩] }] } + +end SolarTV.Export.Main diff --git a/Certified/c4/gen/Main/manifest.json b/Certified/c4/gen/Main/manifest.json new file mode 100644 index 00000000..e366f591 --- /dev/null +++ b/Certified/c4/gen/Main/manifest.json @@ -0,0 +1,103 @@ +{ + "arguments": [ + "solar-tv/milestone/c4/c4.sol", + "-Zcheck-analyses=false", + "--emit=bin-runtime", + "-Zemit-lean-stages=solar-tv/milestone/c4/gen" + ], + "bytecode": "346055575f3560e01c806302067e6a036055576024361060ff60043511176055576004355f5460ff8116820160ff81116059579060ff1916179081601e1a1860081b9061ff00191617805f5560ff165f5260205ff35b5f5ffd5b6011602052634e487b715f526024601cfd", + "bytecode_sha256": "8a21bc207d9dd8be48d921a717eda3ecb7e5bfcb5397850bc3d64a29037fac47", + "compiler": "0.8.38+commit.a8179dfc.solar.0.3.0-dev", + "contract": "Main", + "evm_version": "osaka", + "optimization": "Gas", + "options": "CompileOpts { input: [\"solar-tv/milestone/c4/c4.sol\"], import_remappings: [], base_path: None, include_paths: [], allow_paths: [], no_import_callback: false, language: Solidity, threads: 4, evm_version: Osaka, stop_after: None, optimization: Gas, optimizer_runs: None, revert_strings: Default, libraries: [], out_dir: None, emit: [BinRuntime], standard_json: false, color: Auto, verbose: false, pretty_json: false, pretty_json_err: false, error_format: Human, error_format_human: Unicode, diagnostic_width: None, no_warnings: false, allow: [], _unstable: [\"check-analyses=false\", \"emit-lean-stages=solar-tv/milestone/c4/gen\"], unstable: UnstableOpts { ui_testing: false, track_diagnostics: false, parse_yul: false, no_resolve_imports: false, recover_incomplete_input: false, dump: None, ast_stats: false, hir_stats: false, standard_json_stats: false, span_visitor: false, print_max_storage_sizes: false, print_natspec: false, mir_pipeline: None, evm_ir_pipeline: None, print_after_each: false, pass_diff: false, debugify: None, debugify_output: None, solar_tv: None, validate_ir: None, time_passes: false, codegen_all_functions: false, switch_lowering: Auto, switch_max_gas_code_growth: None, switch_max_bit_slice_gas_code_growth: None, tune: None, pack_wide_jump_tables: false, check_analyses: Some(false), prove_analyses: None, validate_passes: None, validate_passes_fault: None, validate_backend: None, validate_backend_fault: None, validate_evm_ir_passes: None, validate_assembly: false, validate_assembly_fault: None, emit_lean_stages: Some(\"solar-tv/milestone/c4/gen\"), forget_gcx: true, help: (), _non_exhaustive: () }, _non_exhaustive: () }", + "sources": [ + { + "path": "solar-tv/milestone/c4/c4.sol", + "sha256": "31c39cd4e9c5cba0f78aff3a986d69be40c5f68cdb36fbf05ad3d0a5e950e858" + } + ], + "stages": [ + { + "definition": "stage0", + "file": "Stage0.lean", + "index": 0, + "kind": "mir", + "pass": "lower-evm-shaped", + "sha256": "fc9bd372cfa93042b6948b6b52ce83f8c868b0832c2cd076bdd4bf4c481b521a" + }, + { + "definition": "mir1", + "file": "Mir1.lean", + "index": 1, + "kind": "mir", + "pass": "place-reads", + "sha256": "0e5c81b03404896a8f12b5e1df4636f4922bc80cef6e06f297fa024a3965ecb9" + }, + { + "definition": "mir2", + "file": "Mir2.lean", + "index": 2, + "kind": "mir", + "pass": "evm-inst-schedule", + "sha256": "b50596a2f7dc4831a1789f42dd5d0502e13b266ca9e5f7567e1292c450b94af4" + }, + { + "definition": "sched", + "file": "Sched.lean", + "index": 0, + "kind": "sched", + "pass": "stack-schedule", + "sha256": "fdf061032cfc51bfca74d7977cb5944bdb0af4147d7048cb86e77fa7d4742160" + }, + { + "definition": "evm1", + "file": "Evm1.lean", + "index": 1, + "kind": "evm", + "pass": "cfg-simplify-early", + "sha256": "b10980301296d4887ba4322567653012d670c2a5441dcba1f4044ffb40d1d1d8" + }, + { + "definition": "evm2", + "file": "Evm2.lean", + "index": 2, + "kind": "evm", + "pass": "compact-pushes", + "sha256": "512034f050a4fe708788f1c7e7db6c570432aedfd9fdd308c3a993849ba8c28c" + }, + { + "definition": "evm3", + "file": "Evm3.lean", + "index": 3, + "kind": "evm", + "pass": "share-reverts", + "sha256": "955fa46e2c6701e3644da10a0129e72c06cdf0624a7bd4fa4f7faae7f71be222" + }, + { + "definition": "evm4", + "file": "Evm4.lean", + "index": 4, + "kind": "evm", + "pass": "terminal-dedup", + "sha256": "4009d1232a8b5bc57afbbe5ac64c2fde908da9b958d007f9f9759078bdf9093b" + }, + { + "definition": "evm5", + "file": "Evm5.lean", + "index": 5, + "kind": "evm", + "pass": "cfg-simplify-early", + "sha256": "1309fae9f4a8d9561fe138c69b13b7c6e57a71404ed92f861c9a7370738fc7bc" + }, + { + "definition": "bytecode", + "file": "Bytecode.lean", + "index": 0, + "kind": "bytecode", + "pass": "assemble", + "sha256": "7d5d01d3952b98c24d030dfd189808f507cdd5e523b997b80aa4baff836df2af" + } + ] +} diff --git a/Certified/c4/options b/Certified/c4/options new file mode 100644 index 00000000..55fc63cf --- /dev/null +++ b/Certified/c4/options @@ -0,0 +1 @@ +-Zcheck-analyses=false diff --git a/Certified/counter/Proofs.lean b/Certified/counter/Proofs.lean new file mode 100644 index 00000000..ca069136 --- /dev/null +++ b/Certified/counter/Proofs.lean @@ -0,0 +1,3 @@ +-- Generated by solar-tv/milestone/certify.py; do not edit. +import counter.Proofs.Stages +import counter.Proofs.Assembly diff --git a/Certified/counter/Proofs/Assembly.lean b/Certified/counter/Proofs/Assembly.lean new file mode 100644 index 00000000..318bc818 --- /dev/null +++ b/Certified/counter/Proofs/Assembly.lean @@ -0,0 +1,42 @@ +-- Generated by solar-tv/milestone/certify.py; do not edit. +import W1Proofs.Items +import counter.gen.Counter.Evm5 +import counter.gen.Counter.Bytecode + +/-! The final EVM IR of `Counter` against its bytecode, by the assembly checker's walk: the bytecode decodes, linearly from offset 0, to exactly the program's instructions, each jumped-to block at its `JUMPDEST`. -/ + +namespace SolarTV.Milestone.Counter + +open SolarTV.Assembly SolarTV.Export.Counter SolarTV.Milestone.W1 + +set_option maxRecDepth 100000 + +/-- The items of the final EVM IR. -/ +def items : List Item := (itemsOf evm5).getD [] + +theorem items_eq : itemsOf evm5 = some items := by decide + +/-- The layout: each jumped-to block at the bytecode's next `JUMPDEST`. The walk checks it. -/ +def offset (label : Nat) : Nat := if label = 1 then 0x34 else if label = 2 then 0x38 else if label = 3 then 0x41 else 0 + +/-- The instructions the walk reaches, each at its offset. -/ +def stream : List (Nat × Instr) := (walk bytecode offset 0 items).getD [] + +/-- The checker's walk accepts the exported bytecode against the final EVM IR. -/ +theorem walk_eq : walk bytecode offset 0 items = some stream := by decide +kernel + +theorem checked : Walk bytecode offset 0 items stream := walk_sound walk_eq + +/-- The bytecode's linear decoding is the final EVM IR's instructions at the layout. -/ +theorem decodes : decodeFrom bytecode (bytecode.length + 1) 0 = stream := + walk_decodes checked _ (by have := walk_length checked; omega) + +/-- info: 'SolarTV.Milestone.Counter.walk_eq' depends on axioms: [propext, Quot.sound] -/ +#guard_msgs in +#print axioms walk_eq + +/-- info: 'SolarTV.Milestone.Counter.decodes' depends on axioms: [propext, Quot.sound] -/ +#guard_msgs in +#print axioms decodes + +end SolarTV.Milestone.Counter diff --git a/Certified/counter/Proofs/Runs/Evm1.lean b/Certified/counter/Proofs/Runs/Evm1.lean new file mode 100644 index 00000000..a5dbb270 --- /dev/null +++ b/Certified/counter/Proofs/Runs/Evm1.lean @@ -0,0 +1,22 @@ +-- Generated by solar-tv/milestone/certify.py; do not edit. +import W1Proofs.Tactic +import W1Proofs.Axioms +import counter.gen.Counter.Evm1 +import counter.gen.Counter.Sched + +/-! `cfg-simplify-early`: its input and output end in the same result on every call. -/ + +namespace SolarTV.Milestone.Counter + +open Machine SolarTV.Export.Counter SolarTV.Milestone.W1 + +set_option maxHeartbeats 2000000 in +theorem evm1_run (o : Oracle) (call : Call) : + EVM.Program.run o sched call 11 = EVM.Program.run o evm1 call 6 := by + sym_exec + +/-- info: 'SolarTV.Milestone.Counter.evm1_run' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within evm1_run + +end SolarTV.Milestone.Counter diff --git a/Certified/counter/Proofs/Runs/Evm2.lean b/Certified/counter/Proofs/Runs/Evm2.lean new file mode 100644 index 00000000..ae5b491c --- /dev/null +++ b/Certified/counter/Proofs/Runs/Evm2.lean @@ -0,0 +1,22 @@ +-- Generated by solar-tv/milestone/certify.py; do not edit. +import W1Proofs.Tactic +import W1Proofs.Axioms +import counter.gen.Counter.Evm2 +import counter.gen.Counter.Evm1 + +/-! `block-layout`: its input and output end in the same result on every call. -/ + +namespace SolarTV.Milestone.Counter + +open Machine SolarTV.Export.Counter SolarTV.Milestone.W1 + +set_option maxHeartbeats 2000000 in +theorem evm2_run (o : Oracle) (call : Call) : + EVM.Program.run o evm1 call 6 = EVM.Program.run o evm2 call 6 := by + sym_exec + +/-- info: 'SolarTV.Milestone.Counter.evm2_run' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within evm2_run + +end SolarTV.Milestone.Counter diff --git a/Certified/counter/Proofs/Runs/Evm3.lean b/Certified/counter/Proofs/Runs/Evm3.lean new file mode 100644 index 00000000..04fc3dd8 --- /dev/null +++ b/Certified/counter/Proofs/Runs/Evm3.lean @@ -0,0 +1,22 @@ +-- Generated by solar-tv/milestone/certify.py; do not edit. +import W1Proofs.Tactic +import W1Proofs.Axioms +import counter.gen.Counter.Evm3 +import counter.gen.Counter.Evm2 + +/-! `share-reverts`: its input and output end in the same result on every call. -/ + +namespace SolarTV.Milestone.Counter + +open Machine SolarTV.Export.Counter SolarTV.Milestone.W1 + +set_option maxHeartbeats 2000000 in +theorem evm3_run (o : Oracle) (call : Call) : + EVM.Program.run o evm2 call 6 = EVM.Program.run o evm3 call 6 := by + sym_exec + +/-- info: 'SolarTV.Milestone.Counter.evm3_run' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within evm3_run + +end SolarTV.Milestone.Counter diff --git a/Certified/counter/Proofs/Runs/Evm4.lean b/Certified/counter/Proofs/Runs/Evm4.lean new file mode 100644 index 00000000..5ef315d8 --- /dev/null +++ b/Certified/counter/Proofs/Runs/Evm4.lean @@ -0,0 +1,22 @@ +-- Generated by solar-tv/milestone/certify.py; do not edit. +import W1Proofs.Tactic +import W1Proofs.Axioms +import counter.gen.Counter.Evm4 +import counter.gen.Counter.Evm3 + +/-! `terminal-dedup`: its input and output end in the same result on every call. -/ + +namespace SolarTV.Milestone.Counter + +open Machine SolarTV.Export.Counter SolarTV.Milestone.W1 + +set_option maxHeartbeats 2000000 in +theorem evm4_run (o : Oracle) (call : Call) : + EVM.Program.run o evm3 call 6 = EVM.Program.run o evm4 call 6 := by + sym_exec + +/-- info: 'SolarTV.Milestone.Counter.evm4_run' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within evm4_run + +end SolarTV.Milestone.Counter diff --git a/Certified/counter/Proofs/Runs/Evm5.lean b/Certified/counter/Proofs/Runs/Evm5.lean new file mode 100644 index 00000000..4fd13129 --- /dev/null +++ b/Certified/counter/Proofs/Runs/Evm5.lean @@ -0,0 +1,22 @@ +-- Generated by solar-tv/milestone/certify.py; do not edit. +import W1Proofs.Tactic +import W1Proofs.Axioms +import counter.gen.Counter.Evm5 +import counter.gen.Counter.Evm4 + +/-! `cfg-simplify-early`: its input and output end in the same result on every call. -/ + +namespace SolarTV.Milestone.Counter + +open Machine SolarTV.Export.Counter SolarTV.Milestone.W1 + +set_option maxHeartbeats 2000000 in +theorem evm5_run (o : Oracle) (call : Call) : + EVM.Program.run o evm4 call 6 = EVM.Program.run o evm5 call 4 := by + sym_exec + +/-- info: 'SolarTV.Milestone.Counter.evm5_run' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within evm5_run + +end SolarTV.Milestone.Counter diff --git a/Certified/counter/Proofs/Runs/Sched.lean b/Certified/counter/Proofs/Runs/Sched.lean new file mode 100644 index 00000000..21088a28 --- /dev/null +++ b/Certified/counter/Proofs/Runs/Sched.lean @@ -0,0 +1,22 @@ +-- Generated by solar-tv/milestone/certify.py; do not edit. +import W1Proofs.Tactic +import W1Proofs.Axioms +import counter.gen.Counter.Sched +import counter.gen.Counter.Stage0 + +/-! Stack scheduling: the last lowered MIR and the scheduled EVM IR end in the same result on every call. -/ + +namespace SolarTV.Milestone.Counter + +open Machine SolarTV.Export.Counter SolarTV.Milestone.W1 + +set_option maxHeartbeats 2000000 in +theorem sched_run (o : Oracle) (call : Call) : + MIR.Lowered.Module.run o stage0 call 11 = EVM.Program.run o sched call 11 := by + sym_exec + +/-- info: 'SolarTV.Milestone.Counter.sched_run' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within sched_run + +end SolarTV.Milestone.Counter diff --git a/Certified/counter/Proofs/Runs/Stage0.lean b/Certified/counter/Proofs/Runs/Stage0.lean new file mode 100644 index 00000000..887491d0 --- /dev/null +++ b/Certified/counter/Proofs/Runs/Stage0.lean @@ -0,0 +1,21 @@ +-- Generated by solar-tv/milestone/certify.py; do not edit. +import W1Proofs.Tactic +import W1Proofs.Axioms +import counter.gen.Counter.Stage0 + +/-! The first lowered MIR ends on every call within 11 blocks, the number of its blocks. -/ + +namespace SolarTV.Milestone.Counter + +open Machine SolarTV.Export.Counter SolarTV.Milestone.W1 + +set_option maxHeartbeats 2000000 in +theorem stage0_ends (o : Oracle) (call : Call) : + (MIR.Lowered.Module.run o stage0 call 11).isSome = true := by + sym_exec + +/-- info: 'SolarTV.Milestone.Counter.stage0_ends' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within stage0_ends + +end SolarTV.Milestone.Counter diff --git a/Certified/counter/Proofs/Stages.lean b/Certified/counter/Proofs/Stages.lean new file mode 100644 index 00000000..c3be22b8 --- /dev/null +++ b/Certified/counter/Proofs/Stages.lean @@ -0,0 +1,115 @@ +-- Generated by solar-tv/milestone/certify.py; do not edit. +import counter.Proofs.Runs.Stage0 +import counter.Proofs.Runs.Sched +import counter.Proofs.Runs.Evm1 +import counter.Proofs.Runs.Evm2 +import counter.Proofs.Runs.Evm3 +import counter.Proofs.Runs.Evm4 +import counter.Proofs.Runs.Evm5 +import W1Proofs.Stage +import SolarTV.Composition + +/-! The backend stages of `Counter`, each proved on every call (`anyCall`: any calldata, call value and storage) under every oracle, and chained from the first lowered MIR `stage0` to the final EVM IR `evm5`. Fuels are the programs' block counts. -/ + +namespace SolarTV.Milestone.Counter + +open Machine SolarTV.Export.Counter SolarTV.Milestone.W1 + +/-- `stack-schedule`: stage0 to sched. -/ +theorem stage_sched (o : Oracle) : Stage (mirSem o) (evmirSem o) stage0 sched anyCall := + stage_of_runs (A := MIR.Lowered.moduleLayer) (B := EVM.Program.layer) 11 11 (fun call _ => stage0_ends o call) + (fun call _ => sched_run o call) + +theorem sched_ends (o : Oracle) : ∀ call, anyCall call → + (EVM.Program.run o sched call 11).isSome = true := + ends_of_runs (A := MIR.Lowered.moduleLayer) (B := EVM.Program.layer) + (o := o) (p := stage0) (q := sched) (n := 11) (m := 11) (fun call _ => stage0_ends o call) + (fun call _ => sched_run o call) + +/-- `cfg-simplify-early`: sched to evm1. -/ +theorem stage_evm1 (o : Oracle) : Stage (evmirSem o) (evmirSem o) sched evm1 anyCall := + stage_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) 11 6 (sched_ends o) + (fun call _ => evm1_run o call) + +theorem evm1_ends (o : Oracle) : ∀ call, anyCall call → + (EVM.Program.run o evm1 call 6).isSome = true := + ends_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) + (o := o) (p := sched) (q := evm1) (n := 11) (m := 6) (sched_ends o) + (fun call _ => evm1_run o call) + +/-- `block-layout`: evm1 to evm2. -/ +theorem stage_evm2 (o : Oracle) : Stage (evmirSem o) (evmirSem o) evm1 evm2 anyCall := + stage_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) 6 6 (evm1_ends o) + (fun call _ => evm2_run o call) + +theorem evm2_ends (o : Oracle) : ∀ call, anyCall call → + (EVM.Program.run o evm2 call 6).isSome = true := + ends_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) + (o := o) (p := evm1) (q := evm2) (n := 6) (m := 6) (evm1_ends o) + (fun call _ => evm2_run o call) + +/-- `share-reverts`: evm2 to evm3. -/ +theorem stage_evm3 (o : Oracle) : Stage (evmirSem o) (evmirSem o) evm2 evm3 anyCall := + stage_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) 6 6 (evm2_ends o) + (fun call _ => evm3_run o call) + +theorem evm3_ends (o : Oracle) : ∀ call, anyCall call → + (EVM.Program.run o evm3 call 6).isSome = true := + ends_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) + (o := o) (p := evm2) (q := evm3) (n := 6) (m := 6) (evm2_ends o) + (fun call _ => evm3_run o call) + +/-- `terminal-dedup`: evm3 to evm4. -/ +theorem stage_evm4 (o : Oracle) : Stage (evmirSem o) (evmirSem o) evm3 evm4 anyCall := + stage_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) 6 6 (evm3_ends o) + (fun call _ => evm4_run o call) + +theorem evm4_ends (o : Oracle) : ∀ call, anyCall call → + (EVM.Program.run o evm4 call 6).isSome = true := + ends_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) + (o := o) (p := evm3) (q := evm4) (n := 6) (m := 6) (evm3_ends o) + (fun call _ => evm4_run o call) + +/-- `cfg-simplify-early`: evm4 to evm5. -/ +theorem stage_evm5 (o : Oracle) : Stage (evmirSem o) (evmirSem o) evm4 evm5 anyCall := + stage_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) 6 4 (evm4_ends o) + (fun call _ => evm5_run o call) + +/-- The compilation from the first lowered MIR to the final EVM IR. -/ +def compilation : Compilation := + ⟨stage0, [], sched, [evm1, evm2, evm3, evm4, evm5]⟩ + +/-- Every stage from the first lowered MIR to the final EVM IR, chained by the library's composition, on every call. -/ +theorem counter_mir_to_evmir (o : Oracle) : Stage (mirSem o) (evmirSem o) stage0 evm5 anyCall := + mir_to_evmir o anyCall compilation trivial (stage_sched o) + ⟨stage_evm1 o, stage_evm2 o, stage_evm3 o, stage_evm4 o, stage_evm5 o, trivial⟩ + +/-- info: 'SolarTV.Milestone.Counter.stage_sched' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms stage_sched + +/-- info: 'SolarTV.Milestone.Counter.stage_evm1' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms stage_evm1 + +/-- info: 'SolarTV.Milestone.Counter.stage_evm2' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms stage_evm2 + +/-- info: 'SolarTV.Milestone.Counter.stage_evm3' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms stage_evm3 + +/-- info: 'SolarTV.Milestone.Counter.stage_evm4' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms stage_evm4 + +/-- info: 'SolarTV.Milestone.Counter.stage_evm5' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms stage_evm5 + +/-- info: 'SolarTV.Milestone.Counter.counter_mir_to_evmir' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms counter_mir_to_evmir + +end SolarTV.Milestone.Counter diff --git a/Certified/counter/bytecode.hex b/Certified/counter/bytecode.hex new file mode 100644 index 00000000..158c777c --- /dev/null +++ b/Certified/counter/bytecode.hex @@ -0,0 +1 @@ +346034575f3560e01c80636d4ce63c146038578063812600df03603457602436106034575f5460043581019081106041575f55005b5f5ffd5b5f545f5260205ff35b6011602052634e487b715f526024601cfd diff --git a/Certified/counter/counter.sol b/Certified/counter/counter.sol new file mode 100644 index 00000000..0159f465 --- /dev/null +++ b/Certified/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/Certified/counter/gen/Counter/Bytecode.lean b/Certified/counter/gen/Counter/Bytecode.lean new file mode 100644 index 00000000..37f4d190 --- /dev/null +++ b/Certified/counter/gen/Counter/Bytecode.lean @@ -0,0 +1,19 @@ +-- solar-lean-stage: kind=bytecode index=0 pass=assemble +/-! Generated by `solar -Zemit-lean-stages` for `Counter`; do not edit. -/ + +namespace SolarTV.Export.Counter + +/-- The runtime bytecode, byte by byte. -/ +def bytecode : List Nat := + [0x34, 0x60, 0x34, 0x57, 0x5f, 0x35, 0x60, 0xe0, 0x1c, 0x80, 0x63, 0x6d, 0x4c, 0xe6, 0x3c, 0x14, + 0x60, 0x38, 0x57, 0x80, 0x63, 0x81, 0x26, 0x00, 0xdf, 0x03, 0x60, 0x34, 0x57, 0x60, 0x24, 0x36, + 0x10, 0x60, 0x34, 0x57, 0x5f, 0x54, 0x60, 0x04, 0x35, 0x81, 0x01, 0x90, 0x81, 0x10, 0x60, 0x41, + 0x57, 0x5f, 0x55, 0x00, 0x5b, 0x5f, 0x5f, 0xfd, 0x5b, 0x5f, 0x54, 0x5f, 0x52, 0x60, 0x20, 0x5f, + 0xf3, 0x5b, 0x60, 0x11, 0x60, 0x20, 0x52, 0x63, 0x4e, 0x48, 0x7b, 0x71, 0x5f, 0x52, 0x60, 0x24, + 0x60, 0x1c, 0xfd] + +/-- The runtime bytecode in hex, as `--emit=bin-runtime` prints it. -/ +def bytecodeHex : String := + "346034575f3560e01c80636d4ce63c146038578063812600df03603457602436106034575f5460043581019081106041575f55005b5f5ffd5b5f545f5260205ff35b6011602052634e487b715f526024601cfd" + +end SolarTV.Export.Counter diff --git a/Certified/counter/gen/Counter/Evm1.lean b/Certified/counter/gen/Counter/Evm1.lean new file mode 100644 index 00000000..7d53247b --- /dev/null +++ b/Certified/counter/gen/Counter/Evm1.lean @@ -0,0 +1,72 @@ +-- solar-lean-stage: kind=evm index=1 pass=cfg-simplify-early +import SolarTV.EVMIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `Counter`; do not edit. -/ + +namespace SolarTV.Export.Counter + +/-- The runtime EVM IR after `cfg-simplify-early`. -/ +def evm1 : EVM.Program.Program := + { blocks := [ + -- bb0 + [.effect .callvalue 0, + .jumpi 1, + .op (.stack (.push 0)), + .effect .calldataload 1, + .op (.stack (.push 224)), + .op (.stack .shr), + .op (.stack (.dup 0)), + .op (.stack (.push 0x6d4ce63c)), + .op (.stack .eq), + .jumpi 5, + .op (.stack (.dup 0)), + .op (.stack (.push 0x812600df)), + .op (.stack .eq), + .jumpi 2, + .jump 1], + -- bb4 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb5 + [.op (.stack (.push 36)), + .op (.stack .calldatasize), + .op (.stack .lt), + .jumpi 4, + .op (.stack (.push 0)), + .effect .sload 1, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.dup 1)), + .op (.stack .add), + .op (.stack (.swap 0)), + .op (.stack (.dup 1)), + .op (.stack .lt), + .jumpi 3, + .op (.stack (.push 0)), + .effect .sstore 2, + .stop], + -- bb8 + [.op (.stack (.push 17)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 0x4e487b71)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 36)), + .op (.stack (.push 28)), + .revert], + -- bb9 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb10 + [.op (.stack (.push 0)), + .effect .sload 1, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret]] } + +end SolarTV.Export.Counter diff --git a/Certified/counter/gen/Counter/Evm2.lean b/Certified/counter/gen/Counter/Evm2.lean new file mode 100644 index 00000000..6d229db0 --- /dev/null +++ b/Certified/counter/gen/Counter/Evm2.lean @@ -0,0 +1,72 @@ +-- solar-lean-stage: kind=evm index=2 pass=block-layout +import SolarTV.EVMIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `Counter`; do not edit. -/ + +namespace SolarTV.Export.Counter + +/-- The runtime EVM IR after `block-layout`. -/ +def evm2 : EVM.Program.Program := + { blocks := [ + -- bb0 + [.effect .callvalue 0, + .jumpi 1, + .op (.stack (.push 0)), + .effect .calldataload 1, + .op (.stack (.push 224)), + .op (.stack .shr), + .op (.stack (.dup 0)), + .op (.stack (.push 0x6d4ce63c)), + .op (.stack .eq), + .jumpi 3, + .op (.stack (.dup 0)), + .op (.stack (.push 0x812600df)), + .op (.stack .eq), + .jumpi 2, + .jump 1], + -- bb4 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb5 + [.op (.stack (.push 36)), + .op (.stack .calldatasize), + .op (.stack .lt), + .jumpi 5, + .op (.stack (.push 0)), + .effect .sload 1, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.dup 1)), + .op (.stack .add), + .op (.stack (.swap 0)), + .op (.stack (.dup 1)), + .op (.stack .lt), + .jumpi 4, + .op (.stack (.push 0)), + .effect .sstore 2, + .stop], + -- bb10 + [.op (.stack (.push 0)), + .effect .sload 1, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb8 + [.op (.stack (.push 17)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 0x4e487b71)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 36)), + .op (.stack (.push 28)), + .revert], + -- bb9 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert]] } + +end SolarTV.Export.Counter diff --git a/Certified/counter/gen/Counter/Evm3.lean b/Certified/counter/gen/Counter/Evm3.lean new file mode 100644 index 00000000..bae9066e --- /dev/null +++ b/Certified/counter/gen/Counter/Evm3.lean @@ -0,0 +1,72 @@ +-- solar-lean-stage: kind=evm index=3 pass=share-reverts +import SolarTV.EVMIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `Counter`; do not edit. -/ + +namespace SolarTV.Export.Counter + +/-- The runtime EVM IR after `share-reverts`. -/ +def evm3 : EVM.Program.Program := + { blocks := [ + -- bb0 + [.effect .callvalue 0, + .jumpi 1, + .op (.stack (.push 0)), + .effect .calldataload 1, + .op (.stack (.push 224)), + .op (.stack .shr), + .op (.stack (.dup 0)), + .op (.stack (.push 0x6d4ce63c)), + .op (.stack .eq), + .jumpi 3, + .op (.stack (.dup 0)), + .op (.stack (.push 0x812600df)), + .op (.stack .sub), + .jumpi 1, + .jump 2], + -- bb4 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb5 + [.op (.stack (.push 36)), + .op (.stack .calldatasize), + .op (.stack .lt), + .jumpi 5, + .op (.stack (.push 0)), + .effect .sload 1, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.dup 1)), + .op (.stack .add), + .op (.stack (.swap 0)), + .op (.stack (.dup 1)), + .op (.stack .lt), + .jumpi 4, + .op (.stack (.push 0)), + .effect .sstore 2, + .stop], + -- bb10 + [.op (.stack (.push 0)), + .effect .sload 1, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb8 + [.op (.stack (.push 17)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 0x4e487b71)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 36)), + .op (.stack (.push 28)), + .revert], + -- bb9 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert]] } + +end SolarTV.Export.Counter diff --git a/Certified/counter/gen/Counter/Evm4.lean b/Certified/counter/gen/Counter/Evm4.lean new file mode 100644 index 00000000..b3a24bd5 --- /dev/null +++ b/Certified/counter/gen/Counter/Evm4.lean @@ -0,0 +1,70 @@ +-- solar-lean-stage: kind=evm index=4 pass=terminal-dedup +import SolarTV.EVMIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `Counter`; do not edit. -/ + +namespace SolarTV.Export.Counter + +/-- The runtime EVM IR after `terminal-dedup`. -/ +def evm4 : EVM.Program.Program := + { blocks := [ + -- bb0 + [.effect .callvalue 0, + .jumpi 1, + .op (.stack (.push 0)), + .effect .calldataload 1, + .op (.stack (.push 224)), + .op (.stack .shr), + .op (.stack (.dup 0)), + .op (.stack (.push 0x6d4ce63c)), + .op (.stack .eq), + .jumpi 3, + .op (.stack (.dup 0)), + .op (.stack (.push 0x812600df)), + .op (.stack .sub), + .jumpi 1, + .jump 2], + -- bb4 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb5 + [.op (.stack (.push 36)), + .op (.stack .calldatasize), + .op (.stack .lt), + .jumpi 5, + .op (.stack (.push 0)), + .effect .sload 1, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.dup 1)), + .op (.stack .add), + .op (.stack (.swap 0)), + .op (.stack (.dup 1)), + .op (.stack .lt), + .jumpi 4, + .op (.stack (.push 0)), + .effect .sstore 2, + .stop], + -- bb10 + [.op (.stack (.push 0)), + .effect .sload 1, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb8 + [.op (.stack (.push 17)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 0x4e487b71)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 36)), + .op (.stack (.push 28)), + .revert], + -- bb9 + [.jump 1]] } + +end SolarTV.Export.Counter diff --git a/Certified/counter/gen/Counter/Evm5.lean b/Certified/counter/gen/Counter/Evm5.lean new file mode 100644 index 00000000..97dc193a --- /dev/null +++ b/Certified/counter/gen/Counter/Evm5.lean @@ -0,0 +1,66 @@ +-- solar-lean-stage: kind=evm index=5 pass=cfg-simplify-early +import SolarTV.EVMIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `Counter`; do not edit. -/ + +namespace SolarTV.Export.Counter + +/-- The runtime EVM IR after `cfg-simplify-early`. -/ +def evm5 : EVM.Program.Program := + { blocks := [ + -- bb0 + [.effect .callvalue 0, + .jumpi 1, + .op (.stack (.push 0)), + .effect .calldataload 1, + .op (.stack (.push 224)), + .op (.stack .shr), + .op (.stack (.dup 0)), + .op (.stack (.push 0x6d4ce63c)), + .op (.stack .eq), + .jumpi 2, + .op (.stack (.dup 0)), + .op (.stack (.push 0x812600df)), + .op (.stack .sub), + .jumpi 1, + .op (.stack (.push 36)), + .op (.stack .calldatasize), + .op (.stack .lt), + .jumpi 1, + .op (.stack (.push 0)), + .effect .sload 1, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.dup 1)), + .op (.stack .add), + .op (.stack (.swap 0)), + .op (.stack (.dup 1)), + .op (.stack .lt), + .jumpi 3, + .op (.stack (.push 0)), + .effect .sstore 2, + .stop], + -- bb4 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb10 + [.op (.stack (.push 0)), + .effect .sload 1, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb8 + [.op (.stack (.push 17)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 0x4e487b71)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 36)), + .op (.stack (.push 28)), + .revert]] } + +end SolarTV.Export.Counter diff --git a/Certified/counter/gen/Counter/Manifest.lean b/Certified/counter/gen/Counter/Manifest.lean new file mode 100644 index 00000000..bdb31633 --- /dev/null +++ b/Certified/counter/gen/Counter/Manifest.lean @@ -0,0 +1,42 @@ +-- solar-lean-stage: kind=manifest index=0 pass=none +/-! Generated by `solar -Zemit-lean-stages` for `Counter`; do not edit. + +What the stages of this directory were compiled from and by. `stages` lists each +stage's file, its definition, the pass whose output it is, and the SHA-256 of the file. +-/ + +namespace SolarTV.Export.Counter.Manifest + +def sources : List (String × String) := + [("solar-tv/milestone/counter/counter.sol", "28af3c6bf35e4bde0636e2861c1f3eb6a5791d6f944a96af70b00fa46df54ad5")] + +def compiler : String := "0.8.38+commit.1134e61f.solar.0.3.0-dev" + +def arguments : List String := + ["solar-tv/milestone/counter/counter.sol", + "-Ogas", + "--evm-version", + "osaka", + "--emit=bin-runtime", + "-Zemit-lean-stages=solar-tv/milestone/counter/gen"] + +def evmVersion : String := "osaka" + +def optimization : String := "Gas" + +def stages : List (String × String × String × String) := + [("Stage0", "stage0", "lower-evm-shaped", "455c5c9bc1edc79a8525008cafaa56bfbed84a0af77282cb1d60aacf04d52045"), + ("Sched", "sched", "stack-schedule", "18e30c45562a1863be5c810b37b374c8376cb5f093ab3ee3d2663947f1346011"), + ("Evm1", "evm1", "cfg-simplify-early", "31c90cb533b38c43aca3259f29283b635ecb2fd484be8e383b0dfe97a2a3f475"), + ("Evm2", "evm2", "block-layout", "8d28ef5f0d949d948a1a0f5f1dfd859c0fecbea894cf62a009a9345ff37fd5af"), + ("Evm3", "evm3", "share-reverts", "8171f571ac99ad077dc819ff7bd8fd5c4b1c08b0b3bf77e97a8e3a61924542d1"), + ("Evm4", "evm4", "terminal-dedup", "f840c77ead93175f074b51c9a550a287db6e86ed2cbb2218afeae7331d4badfa"), + ("Evm5", "evm5", "cfg-simplify-early", "8bf84a55156ac80e2af70c987aecdb04f40b38fd962516c466b2d601c3e89f09"), + ("Bytecode", "bytecode", "assemble", "5e1da0f07568e12e2177a30c1ed98662ce5e731e153644472bdfcfa38203b0e5")] + +def bytecodeHex : String := + "346034575f3560e01c80636d4ce63c146038578063812600df03603457602436106034575f5460043581019081106041575f55005b5f5ffd5b5f545f5260205ff35b6011602052634e487b715f526024601cfd" + +def bytecodeSha256 : String := "daed21b0c790bb2c08bcf999c9ebc6fea950c213ea0a799418552aa14c18f6ec" + +end SolarTV.Export.Counter.Manifest diff --git a/Certified/counter/gen/Counter/Sched.lean b/Certified/counter/gen/Counter/Sched.lean new file mode 100644 index 00000000..e7359f24 --- /dev/null +++ b/Certified/counter/gen/Counter/Sched.lean @@ -0,0 +1,82 @@ +-- solar-lean-stage: kind=sched index=0 pass=stack-schedule +import SolarTV.EVMIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `Counter`; do not edit. -/ + +namespace SolarTV.Export.Counter + +/-- The runtime EVM IR as stack scheduling emits it. -/ +def sched : EVM.Program.Program := + { blocks := [ + -- bb0 + [.effect .callvalue 0, + .jumpi 4, + .jump 1], + -- bb1 + [.op (.stack (.push 0)), + .effect .calldataload 1, + .op (.stack (.push 224)), + .op (.stack .shr), + .op (.stack (.dup 0)), + .op (.stack (.push 0x6d4ce63c)), + .op (.stack .eq), + .jumpi 3, + .op (.stack (.dup 0)), + .op (.stack (.push 0x812600df)), + .op (.stack .eq), + .jumpi 2, + .jump 4], + -- bb2 + [.jump 5], + -- bb3 + [.jump 10], + -- bb4 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb5 + [.op (.stack (.push 36)), + .op (.stack .calldatasize), + .op (.stack .lt), + .jumpi 9, + .jump 6], + -- bb6 + [.op (.stack (.push 0)), + .effect .sload 1, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.dup 1)), + .op (.stack .add), + .op (.stack (.swap 0)), + .op (.stack (.dup 1)), + .op (.stack .lt), + .jumpi 8, + .jump 7], + -- bb7 + [.op (.stack (.push 0)), + .effect .sstore 2, + .stop], + -- bb8 + [.op (.stack (.push 17)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 0x4e487b71)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 36)), + .op (.stack (.push 28)), + .revert], + -- bb9 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb10 + [.op (.stack (.push 0)), + .effect .sload 1, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret]] } + +end SolarTV.Export.Counter diff --git a/Certified/counter/gen/Counter/Stage0.lean b/Certified/counter/gen/Counter/Stage0.lean new file mode 100644 index 00000000..fc30c311 --- /dev/null +++ b/Certified/counter/gen/Counter/Stage0.lean @@ -0,0 +1,74 @@ +-- solar-lean-stage: kind=mir index=0 pass=lower-evm-shaped +import SolarTV.MIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `Counter`; do not edit. -/ + +namespace SolarTV.Export.Counter + +/-- The first lowered MIR module, after `lower-evm-shaped` advanced the phase. -/ +def stage0 : MIR.Lowered.Module := + { entry := 2, + functions := [ + -- @inc + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 13) .calldatasize [], + .pure 15 .lt [.value 13, .const 36]], + .branch (.value 15) 3 4⟩, + -- bb1 + ⟨[], + [.effect none .mstore [.const 32, .const 17], + .effect none .mstore [.const 0, .const 0x4e487b71]], + .revert (.const 28) (.const 36)⟩, + -- bb2 + ⟨[], + [.effect none .sstore [.const 0, .value 4]], + .stop⟩, + -- bb3 + ⟨[], + [], + .revert (.const 0) (.const 0)⟩, + -- bb4 + ⟨[], + [.effect (some 17) .calldataload [.const 4], + .effect (some 2) .sload [.const 0], + .pure 4 .add [.value 2, .value 17], + .pure 5 .lt [.value 4, .value 2]], + .branch (.value 5) 1 2⟩] }, + -- @get + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 2) .sload [.const 0], + .effect none .mstore [.const 0, .value 2]], + .ret (.const 0) (.const 32)⟩] }, + -- @entry + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 0) .callvalue [], + .ne 2 (.value 0) (.const 0)], + .branch (.value 2) 4 1⟩, + -- bb1 + ⟨[], + [.effect (some 4) .calldataload [.const 0], + .pure 6 .shr [.const 224, .value 4]], + .switch (.value 6) 4 [(.const 0x6d4ce63c, 2), (.const 0x812600df, 3)]⟩, + -- bb2 + ⟨[], + [], + .tailCall 1 []⟩, + -- bb3 + ⟨[], + [], + .tailCall 0 []⟩, + -- bb4 + ⟨[], + [], + .revert (.const 0) (.const 0)⟩] }] } + +end SolarTV.Export.Counter diff --git a/Certified/counter/gen/Counter/manifest.json b/Certified/counter/gen/Counter/manifest.json new file mode 100644 index 00000000..3a8d94c9 --- /dev/null +++ b/Certified/counter/gen/Counter/manifest.json @@ -0,0 +1,89 @@ +{ + "arguments": [ + "solar-tv/milestone/counter/counter.sol", + "-Ogas", + "--evm-version", + "osaka", + "--emit=bin-runtime", + "-Zemit-lean-stages=solar-tv/milestone/counter/gen" + ], + "bytecode": "346034575f3560e01c80636d4ce63c146038578063812600df03603457602436106034575f5460043581019081106041575f55005b5f5ffd5b5f545f5260205ff35b6011602052634e487b715f526024601cfd", + "bytecode_sha256": "daed21b0c790bb2c08bcf999c9ebc6fea950c213ea0a799418552aa14c18f6ec", + "compiler": "0.8.38+commit.1134e61f.solar.0.3.0-dev", + "contract": "Counter", + "evm_version": "osaka", + "optimization": "Gas", + "options": "CompileOpts { input: [\"solar-tv/milestone/counter/counter.sol\"], import_remappings: [], base_path: None, include_paths: [], allow_paths: [], no_import_callback: false, language: Solidity, threads: 4, evm_version: Osaka, stop_after: None, optimization: Gas, optimizer_runs: None, revert_strings: Default, libraries: [], out_dir: None, emit: [BinRuntime], standard_json: false, color: Auto, verbose: false, pretty_json: false, pretty_json_err: false, error_format: Human, error_format_human: Unicode, diagnostic_width: None, no_warnings: false, allow: [], _unstable: [\"emit-lean-stages=solar-tv/milestone/counter/gen\"], unstable: UnstableOpts { ui_testing: false, track_diagnostics: false, parse_yul: false, no_resolve_imports: false, recover_incomplete_input: false, dump: None, ast_stats: false, hir_stats: false, standard_json_stats: false, span_visitor: false, print_max_storage_sizes: false, print_natspec: false, mir_pipeline: None, evm_ir_pipeline: None, print_after_each: false, pass_diff: false, debugify: None, debugify_output: None, solar_tv: None, validate_ir: None, time_passes: false, codegen_all_functions: false, switch_lowering: Auto, switch_max_gas_code_growth: None, switch_max_bit_slice_gas_code_growth: None, tune: None, pack_wide_jump_tables: false, check_analyses: None, prove_analyses: None, validate_passes: None, validate_passes_fault: None, validate_backend: None, validate_backend_fault: None, validate_evm_ir_passes: None, validate_assembly: false, validate_assembly_fault: None, emit_lean_stages: Some(\"solar-tv/milestone/counter/gen\"), forget_gcx: true, help: (), _non_exhaustive: () }, _non_exhaustive: () }", + "sources": [ + { + "path": "solar-tv/milestone/counter/counter.sol", + "sha256": "28af3c6bf35e4bde0636e2861c1f3eb6a5791d6f944a96af70b00fa46df54ad5" + } + ], + "stages": [ + { + "definition": "stage0", + "file": "Stage0.lean", + "index": 0, + "kind": "mir", + "pass": "lower-evm-shaped", + "sha256": "455c5c9bc1edc79a8525008cafaa56bfbed84a0af77282cb1d60aacf04d52045" + }, + { + "definition": "sched", + "file": "Sched.lean", + "index": 0, + "kind": "sched", + "pass": "stack-schedule", + "sha256": "18e30c45562a1863be5c810b37b374c8376cb5f093ab3ee3d2663947f1346011" + }, + { + "definition": "evm1", + "file": "Evm1.lean", + "index": 1, + "kind": "evm", + "pass": "cfg-simplify-early", + "sha256": "31c90cb533b38c43aca3259f29283b635ecb2fd484be8e383b0dfe97a2a3f475" + }, + { + "definition": "evm2", + "file": "Evm2.lean", + "index": 2, + "kind": "evm", + "pass": "block-layout", + "sha256": "8d28ef5f0d949d948a1a0f5f1dfd859c0fecbea894cf62a009a9345ff37fd5af" + }, + { + "definition": "evm3", + "file": "Evm3.lean", + "index": 3, + "kind": "evm", + "pass": "share-reverts", + "sha256": "8171f571ac99ad077dc819ff7bd8fd5c4b1c08b0b3bf77e97a8e3a61924542d1" + }, + { + "definition": "evm4", + "file": "Evm4.lean", + "index": 4, + "kind": "evm", + "pass": "terminal-dedup", + "sha256": "f840c77ead93175f074b51c9a550a287db6e86ed2cbb2218afeae7331d4badfa" + }, + { + "definition": "evm5", + "file": "Evm5.lean", + "index": 5, + "kind": "evm", + "pass": "cfg-simplify-early", + "sha256": "8bf84a55156ac80e2af70c987aecdb04f40b38fd962516c466b2d601c3e89f09" + }, + { + "definition": "bytecode", + "file": "Bytecode.lean", + "index": 0, + "kind": "bytecode", + "pass": "assemble", + "sha256": "5e1da0f07568e12e2177a30c1ed98662ce5e731e153644472bdfcfa38203b0e5" + } + ] +} diff --git a/Certified/counter/options b/Certified/counter/options new file mode 100644 index 00000000..da38913c --- /dev/null +++ b/Certified/counter/options @@ -0,0 +1,3 @@ +-Ogas +--evm-version +osaka diff --git a/Certified/events/Proofs.lean b/Certified/events/Proofs.lean new file mode 100644 index 00000000..7169ff3c --- /dev/null +++ b/Certified/events/Proofs.lean @@ -0,0 +1,3 @@ +-- Generated by solar-tv/milestone/certify.py; do not edit. +import events.Proofs.Stages +import events.Proofs.Assembly diff --git a/Certified/events/Proofs/Assembly.lean b/Certified/events/Proofs/Assembly.lean new file mode 100644 index 00000000..fefb7aa2 --- /dev/null +++ b/Certified/events/Proofs/Assembly.lean @@ -0,0 +1,42 @@ +-- Generated by solar-tv/milestone/certify.py; do not edit. +import W1Proofs.Items +import events.gen.Events.Evm5 +import events.gen.Events.Bytecode + +/-! The final EVM IR of `Events` against its bytecode, by the assembly checker's walk: the bytecode decodes, linearly from offset 0, to exactly the program's instructions, each jumped-to block at its `JUMPDEST`. -/ + +namespace SolarTV.Milestone.Events + +open SolarTV.Assembly SolarTV.Export.Events SolarTV.Milestone.W1 + +set_option maxRecDepth 100000 + +/-- The items of the final EVM IR. -/ +def items : List Item := (itemsOf evm5).getD [] + +theorem items_eq : itemsOf evm5 = some items := by decide + +/-- The layout: each jumped-to block at the bytecode's next `JUMPDEST`. The walk checks it. -/ +def offset (label : Nat) : Nat := if label = 1 then 0x53 else if label = 2 then 0x57 else 0 + +/-- The instructions the walk reaches, each at its offset. -/ +def stream : List (Nat × Instr) := (walk bytecode offset 0 items).getD [] + +/-- The checker's walk accepts the exported bytecode against the final EVM IR. -/ +theorem walk_eq : walk bytecode offset 0 items = some stream := by decide +kernel + +theorem checked : Walk bytecode offset 0 items stream := walk_sound walk_eq + +/-- The bytecode's linear decoding is the final EVM IR's instructions at the layout. -/ +theorem decodes : decodeFrom bytecode (bytecode.length + 1) 0 = stream := + walk_decodes checked _ (by have := walk_length checked; omega) + +/-- info: 'SolarTV.Milestone.Events.walk_eq' depends on axioms: [propext, Quot.sound] -/ +#guard_msgs in +#print axioms walk_eq + +/-- info: 'SolarTV.Milestone.Events.decodes' depends on axioms: [propext, Quot.sound] -/ +#guard_msgs in +#print axioms decodes + +end SolarTV.Milestone.Events diff --git a/Certified/events/Proofs/Runs/Evm1.lean b/Certified/events/Proofs/Runs/Evm1.lean new file mode 100644 index 00000000..c61f28f4 --- /dev/null +++ b/Certified/events/Proofs/Runs/Evm1.lean @@ -0,0 +1,22 @@ +-- Generated by solar-tv/milestone/certify.py; do not edit. +import W1Proofs.Tactic +import W1Proofs.Axioms +import events.gen.Events.Evm1 +import events.gen.Events.Sched + +/-! `cfg-simplify-early`: its input and output end in the same result on every call. -/ + +namespace SolarTV.Milestone.Events + +open Machine SolarTV.Export.Events SolarTV.Milestone.W1 + +set_option maxHeartbeats 2000000 in +theorem evm1_run (o : Oracle) (call : Call) : + EVM.Program.run o sched call 10 = EVM.Program.run o evm1 call 5 := by + sym_exec + +/-- info: 'SolarTV.Milestone.Events.evm1_run' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within evm1_run + +end SolarTV.Milestone.Events diff --git a/Certified/events/Proofs/Runs/Evm2.lean b/Certified/events/Proofs/Runs/Evm2.lean new file mode 100644 index 00000000..7d44755c --- /dev/null +++ b/Certified/events/Proofs/Runs/Evm2.lean @@ -0,0 +1,22 @@ +-- Generated by solar-tv/milestone/certify.py; do not edit. +import W1Proofs.Tactic +import W1Proofs.Axioms +import events.gen.Events.Evm2 +import events.gen.Events.Evm1 + +/-! `compact-pushes`: its input and output end in the same result on every call. -/ + +namespace SolarTV.Milestone.Events + +open Machine SolarTV.Export.Events SolarTV.Milestone.W1 + +set_option maxHeartbeats 2000000 in +theorem evm2_run (o : Oracle) (call : Call) : + EVM.Program.run o evm1 call 5 = EVM.Program.run o evm2 call 5 := by + sym_exec + +/-- info: 'SolarTV.Milestone.Events.evm2_run' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within evm2_run + +end SolarTV.Milestone.Events diff --git a/Certified/events/Proofs/Runs/Evm3.lean b/Certified/events/Proofs/Runs/Evm3.lean new file mode 100644 index 00000000..f67143bf --- /dev/null +++ b/Certified/events/Proofs/Runs/Evm3.lean @@ -0,0 +1,22 @@ +-- Generated by solar-tv/milestone/certify.py; do not edit. +import W1Proofs.Tactic +import W1Proofs.Axioms +import events.gen.Events.Evm3 +import events.gen.Events.Evm2 + +/-! `share-reverts`: its input and output end in the same result on every call. -/ + +namespace SolarTV.Milestone.Events + +open Machine SolarTV.Export.Events SolarTV.Milestone.W1 + +set_option maxHeartbeats 2000000 in +theorem evm3_run (o : Oracle) (call : Call) : + EVM.Program.run o evm2 call 5 = EVM.Program.run o evm3 call 5 := by + sym_exec + +/-- info: 'SolarTV.Milestone.Events.evm3_run' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within evm3_run + +end SolarTV.Milestone.Events diff --git a/Certified/events/Proofs/Runs/Evm4.lean b/Certified/events/Proofs/Runs/Evm4.lean new file mode 100644 index 00000000..26dba659 --- /dev/null +++ b/Certified/events/Proofs/Runs/Evm4.lean @@ -0,0 +1,22 @@ +-- Generated by solar-tv/milestone/certify.py; do not edit. +import W1Proofs.Tactic +import W1Proofs.Axioms +import events.gen.Events.Evm4 +import events.gen.Events.Evm3 + +/-! `terminal-dedup`: its input and output end in the same result on every call. -/ + +namespace SolarTV.Milestone.Events + +open Machine SolarTV.Export.Events SolarTV.Milestone.W1 + +set_option maxHeartbeats 2000000 in +theorem evm4_run (o : Oracle) (call : Call) : + EVM.Program.run o evm3 call 5 = EVM.Program.run o evm4 call 5 := by + sym_exec + +/-- info: 'SolarTV.Milestone.Events.evm4_run' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within evm4_run + +end SolarTV.Milestone.Events diff --git a/Certified/events/Proofs/Runs/Evm5.lean b/Certified/events/Proofs/Runs/Evm5.lean new file mode 100644 index 00000000..cd6beaab --- /dev/null +++ b/Certified/events/Proofs/Runs/Evm5.lean @@ -0,0 +1,22 @@ +-- Generated by solar-tv/milestone/certify.py; do not edit. +import W1Proofs.Tactic +import W1Proofs.Axioms +import events.gen.Events.Evm5 +import events.gen.Events.Evm4 + +/-! `cfg-simplify-early`: its input and output end in the same result on every call. -/ + +namespace SolarTV.Milestone.Events + +open Machine SolarTV.Export.Events SolarTV.Milestone.W1 + +set_option maxHeartbeats 2000000 in +theorem evm5_run (o : Oracle) (call : Call) : + EVM.Program.run o evm4 call 5 = EVM.Program.run o evm5 call 3 := by + sym_exec + +/-- info: 'SolarTV.Milestone.Events.evm5_run' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within evm5_run + +end SolarTV.Milestone.Events diff --git a/Certified/events/Proofs/Runs/Mir1.lean b/Certified/events/Proofs/Runs/Mir1.lean new file mode 100644 index 00000000..a401b50d --- /dev/null +++ b/Certified/events/Proofs/Runs/Mir1.lean @@ -0,0 +1,22 @@ +-- Generated by solar-tv/milestone/certify.py; do not edit. +import W1Proofs.Tactic +import W1Proofs.Axioms +import events.gen.Events.Mir1 +import events.gen.Events.Stage0 + +/-! `lower-assumes`: its input and output end in the same result on every call. -/ + +namespace SolarTV.Milestone.Events + +open Machine SolarTV.Export.Events SolarTV.Milestone.W1 + +set_option maxHeartbeats 2000000 in +theorem mir1_run (o : Oracle) (call : Call) : + MIR.Lowered.Module.run o stage0 call 7 = MIR.Lowered.Module.run o mir1 call 10 := by + sym_exec + +/-- info: 'SolarTV.Milestone.Events.mir1_run' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within mir1_run + +end SolarTV.Milestone.Events diff --git a/Certified/events/Proofs/Runs/Sched.lean b/Certified/events/Proofs/Runs/Sched.lean new file mode 100644 index 00000000..9b8e620f --- /dev/null +++ b/Certified/events/Proofs/Runs/Sched.lean @@ -0,0 +1,22 @@ +-- Generated by solar-tv/milestone/certify.py; do not edit. +import W1Proofs.Tactic +import W1Proofs.Axioms +import events.gen.Events.Sched +import events.gen.Events.Mir1 + +/-! Stack scheduling: the last lowered MIR and the scheduled EVM IR end in the same result on every call. -/ + +namespace SolarTV.Milestone.Events + +open Machine SolarTV.Export.Events SolarTV.Milestone.W1 + +set_option maxHeartbeats 2000000 in +theorem sched_run (o : Oracle) (call : Call) : + MIR.Lowered.Module.run o mir1 call 10 = EVM.Program.run o sched call 10 := by + sym_exec + +/-- info: 'SolarTV.Milestone.Events.sched_run' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within sched_run + +end SolarTV.Milestone.Events diff --git a/Certified/events/Proofs/Runs/Stage0.lean b/Certified/events/Proofs/Runs/Stage0.lean new file mode 100644 index 00000000..d92a90d1 --- /dev/null +++ b/Certified/events/Proofs/Runs/Stage0.lean @@ -0,0 +1,21 @@ +-- Generated by solar-tv/milestone/certify.py; do not edit. +import W1Proofs.Tactic +import W1Proofs.Axioms +import events.gen.Events.Stage0 + +/-! The first lowered MIR ends on every call within 7 blocks, the number of its blocks. -/ + +namespace SolarTV.Milestone.Events + +open Machine SolarTV.Export.Events SolarTV.Milestone.W1 + +set_option maxHeartbeats 2000000 in +theorem stage0_ends (o : Oracle) (call : Call) : + (MIR.Lowered.Module.run o stage0 call 7).isSome = true := by + sym_exec + +/-- info: 'SolarTV.Milestone.Events.stage0_ends' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within stage0_ends + +end SolarTV.Milestone.Events diff --git a/Certified/events/Proofs/Stages.lean b/Certified/events/Proofs/Stages.lean new file mode 100644 index 00000000..f652182d --- /dev/null +++ b/Certified/events/Proofs/Stages.lean @@ -0,0 +1,131 @@ +-- Generated by solar-tv/milestone/certify.py; do not edit. +import events.Proofs.Runs.Stage0 +import events.Proofs.Runs.Mir1 +import events.Proofs.Runs.Sched +import events.Proofs.Runs.Evm1 +import events.Proofs.Runs.Evm2 +import events.Proofs.Runs.Evm3 +import events.Proofs.Runs.Evm4 +import events.Proofs.Runs.Evm5 +import W1Proofs.Stage +import SolarTV.Composition + +/-! The backend stages of `Events`, each proved on every call (`anyCall`: any calldata, call value and storage) under every oracle, and chained from the first lowered MIR `stage0` to the final EVM IR `evm5`. Fuels are the programs' block counts. -/ + +namespace SolarTV.Milestone.Events + +open Machine SolarTV.Export.Events SolarTV.Milestone.W1 + +/-- `lower-assumes`: stage0 to mir1. -/ +theorem stage_mir1 (o : Oracle) : Stage (mirSem o) (mirSem o) stage0 mir1 anyCall := + stage_of_runs (A := MIR.Lowered.moduleLayer) (B := MIR.Lowered.moduleLayer) 7 10 (fun call _ => stage0_ends o call) + (fun call _ => mir1_run o call) + +theorem mir1_ends (o : Oracle) : ∀ call, anyCall call → + (MIR.Lowered.Module.run o mir1 call 10).isSome = true := + ends_of_runs (A := MIR.Lowered.moduleLayer) (B := MIR.Lowered.moduleLayer) + (o := o) (p := stage0) (q := mir1) (n := 7) (m := 10) (fun call _ => stage0_ends o call) + (fun call _ => mir1_run o call) + +/-- `stack-schedule`: mir1 to sched. -/ +theorem stage_sched (o : Oracle) : Stage (mirSem o) (evmirSem o) mir1 sched anyCall := + stage_of_runs (A := MIR.Lowered.moduleLayer) (B := EVM.Program.layer) 10 10 (mir1_ends o) + (fun call _ => sched_run o call) + +theorem sched_ends (o : Oracle) : ∀ call, anyCall call → + (EVM.Program.run o sched call 10).isSome = true := + ends_of_runs (A := MIR.Lowered.moduleLayer) (B := EVM.Program.layer) + (o := o) (p := mir1) (q := sched) (n := 10) (m := 10) (mir1_ends o) + (fun call _ => sched_run o call) + +/-- `cfg-simplify-early`: sched to evm1. -/ +theorem stage_evm1 (o : Oracle) : Stage (evmirSem o) (evmirSem o) sched evm1 anyCall := + stage_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) 10 5 (sched_ends o) + (fun call _ => evm1_run o call) + +theorem evm1_ends (o : Oracle) : ∀ call, anyCall call → + (EVM.Program.run o evm1 call 5).isSome = true := + ends_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) + (o := o) (p := sched) (q := evm1) (n := 10) (m := 5) (sched_ends o) + (fun call _ => evm1_run o call) + +/-- `compact-pushes`: evm1 to evm2. -/ +theorem stage_evm2 (o : Oracle) : Stage (evmirSem o) (evmirSem o) evm1 evm2 anyCall := + stage_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) 5 5 (evm1_ends o) + (fun call _ => evm2_run o call) + +theorem evm2_ends (o : Oracle) : ∀ call, anyCall call → + (EVM.Program.run o evm2 call 5).isSome = true := + ends_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) + (o := o) (p := evm1) (q := evm2) (n := 5) (m := 5) (evm1_ends o) + (fun call _ => evm2_run o call) + +/-- `share-reverts`: evm2 to evm3. -/ +theorem stage_evm3 (o : Oracle) : Stage (evmirSem o) (evmirSem o) evm2 evm3 anyCall := + stage_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) 5 5 (evm2_ends o) + (fun call _ => evm3_run o call) + +theorem evm3_ends (o : Oracle) : ∀ call, anyCall call → + (EVM.Program.run o evm3 call 5).isSome = true := + ends_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) + (o := o) (p := evm2) (q := evm3) (n := 5) (m := 5) (evm2_ends o) + (fun call _ => evm3_run o call) + +/-- `terminal-dedup`: evm3 to evm4. -/ +theorem stage_evm4 (o : Oracle) : Stage (evmirSem o) (evmirSem o) evm3 evm4 anyCall := + stage_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) 5 5 (evm3_ends o) + (fun call _ => evm4_run o call) + +theorem evm4_ends (o : Oracle) : ∀ call, anyCall call → + (EVM.Program.run o evm4 call 5).isSome = true := + ends_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) + (o := o) (p := evm3) (q := evm4) (n := 5) (m := 5) (evm3_ends o) + (fun call _ => evm4_run o call) + +/-- `cfg-simplify-early`: evm4 to evm5. -/ +theorem stage_evm5 (o : Oracle) : Stage (evmirSem o) (evmirSem o) evm4 evm5 anyCall := + stage_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) 5 3 (evm4_ends o) + (fun call _ => evm5_run o call) + +/-- The compilation from the first lowered MIR to the final EVM IR. -/ +def compilation : Compilation := + ⟨stage0, [mir1], sched, [evm1, evm2, evm3, evm4, evm5]⟩ + +/-- Every stage from the first lowered MIR to the final EVM IR, chained by the library's composition, on every call. -/ +theorem events_mir_to_evmir (o : Oracle) : Stage (mirSem o) (evmirSem o) stage0 evm5 anyCall := + mir_to_evmir o anyCall compilation ⟨stage_mir1 o, trivial⟩ (stage_sched o) + ⟨stage_evm1 o, stage_evm2 o, stage_evm3 o, stage_evm4 o, stage_evm5 o, trivial⟩ + +/-- info: 'SolarTV.Milestone.Events.stage_mir1' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms stage_mir1 + +/-- info: 'SolarTV.Milestone.Events.stage_sched' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms stage_sched + +/-- info: 'SolarTV.Milestone.Events.stage_evm1' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms stage_evm1 + +/-- info: 'SolarTV.Milestone.Events.stage_evm2' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms stage_evm2 + +/-- info: 'SolarTV.Milestone.Events.stage_evm3' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms stage_evm3 + +/-- info: 'SolarTV.Milestone.Events.stage_evm4' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms stage_evm4 + +/-- info: 'SolarTV.Milestone.Events.stage_evm5' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms stage_evm5 + +/-- info: 'SolarTV.Milestone.Events.events_mir_to_evmir' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms events_mir_to_evmir + +end SolarTV.Milestone.Events diff --git a/Certified/events/bytecode.hex b/Certified/events/bytecode.hex new file mode 100644 index 00000000..2b4036d4 --- /dev/null +++ b/Certified/events/bytecode.hex @@ -0,0 +1 @@ +346053575f3560e01c80630cf79e0a03605357604436106053576024355f52600435337f7fa9aafeb8bb803d77de5d84bc2f2edbd842ca91b20cd5020aa21dfe26ab0be960205fa35f1960601c3311605757005b5f5ffd5b690417000000000000000260201b335f1960601c9160205260405260605263ed572b275f526064601cfd diff --git a/Certified/events/events.sol b/Certified/events/events.sol new file mode 100644 index 00000000..cb5412f7 --- /dev/null +++ b/Certified/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/Certified/events/gen/Events/Bytecode.lean b/Certified/events/gen/Events/Bytecode.lean new file mode 100644 index 00000000..620b7eab --- /dev/null +++ b/Certified/events/gen/Events/Bytecode.lean @@ -0,0 +1,22 @@ +-- solar-lean-stage: kind=bytecode index=0 pass=assemble +/-! Generated by `solar -Zemit-lean-stages` for `Events`; do not edit. -/ + +namespace SolarTV.Export.Events + +/-- The runtime bytecode, byte by byte. -/ +def bytecode : List Nat := + [0x34, 0x60, 0x53, 0x57, 0x5f, 0x35, 0x60, 0xe0, 0x1c, 0x80, 0x63, 0x0c, 0xf7, 0x9e, 0x0a, 0x03, + 0x60, 0x53, 0x57, 0x60, 0x44, 0x36, 0x10, 0x60, 0x53, 0x57, 0x60, 0x24, 0x35, 0x5f, 0x52, 0x60, + 0x04, 0x35, 0x33, 0x7f, 0x7f, 0xa9, 0xaa, 0xfe, 0xb8, 0xbb, 0x80, 0x3d, 0x77, 0xde, 0x5d, 0x84, + 0xbc, 0x2f, 0x2e, 0xdb, 0xd8, 0x42, 0xca, 0x91, 0xb2, 0x0c, 0xd5, 0x02, 0x0a, 0xa2, 0x1d, 0xfe, + 0x26, 0xab, 0x0b, 0xe9, 0x60, 0x20, 0x5f, 0xa3, 0x5f, 0x19, 0x60, 0x60, 0x1c, 0x33, 0x11, 0x60, + 0x57, 0x57, 0x00, 0x5b, 0x5f, 0x5f, 0xfd, 0x5b, 0x69, 0x04, 0x17, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x02, 0x60, 0x20, 0x1b, 0x33, 0x5f, 0x19, 0x60, 0x60, 0x1c, 0x91, 0x60, 0x20, 0x52, + 0x60, 0x40, 0x52, 0x60, 0x60, 0x52, 0x63, 0xed, 0x57, 0x2b, 0x27, 0x5f, 0x52, 0x60, 0x64, 0x60, + 0x1c, 0xfd] + +/-- The runtime bytecode in hex, as `--emit=bin-runtime` prints it. -/ +def bytecodeHex : String := + "346053575f3560e01c80630cf79e0a03605357604436106053576024355f52600435337f7fa9aafeb8bb803d77de5d84bc2f2edbd842ca91b20cd5020aa21dfe26ab0be960205fa35f1960601c3311605757005b5f5ffd5b690417000000000000000260201b335f1960601c9160205260405260605263ed572b275f526064601cfd" + +end SolarTV.Export.Events diff --git a/Certified/events/gen/Events/Evm1.lean b/Certified/events/gen/Events/Evm1.lean new file mode 100644 index 00000000..171dc29e --- /dev/null +++ b/Certified/events/gen/Events/Evm1.lean @@ -0,0 +1,70 @@ +-- solar-lean-stage: kind=evm index=1 pass=cfg-simplify-early +import SolarTV.EVMIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `Events`; do not edit. -/ + +namespace SolarTV.Export.Events + +/-- The runtime EVM IR after `cfg-simplify-early`. -/ +def evm1 : EVM.Program.Program := + { blocks := [ + -- bb0 + [.effect .callvalue 0, + .jumpi 1, + .op (.stack (.push 0)), + .effect .calldataload 1, + .op (.stack (.push 224)), + .op (.stack .shr), + .op (.stack (.dup 0)), + .op (.stack (.push 0xcf79e0a)), + .op (.stack .eq), + .jumpi 2, + .jump 1], + -- bb3 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb4 + [.op (.stack (.push 68)), + .op (.stack .calldatasize), + .op (.stack .lt), + .jumpi 4, + .op (.stack (.push 36)), + .effect .calldataload 1, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 4)), + .effect .calldataload 1, + .effect .caller 0, + .op (.stack (.push 0x7fa9aafeb8bb803d77de5d84bc2f2edbd842ca91b20cd5020aa21dfe26ab0be9)), + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .effect (.log 3) 5, + .op (.stack (.push 0xffffffffffffffffffffffffffffffffffffffff)), + .effect .caller 0, + .op (.stack .gt), + .jumpi 3, + .stop], + -- bb7 + [.op (.stack (.push 0x417000000000000000200000000)), + .effect .caller 0, + .op (.stack (.push 0xffffffffffffffffffffffffffffffffffffffff)), + .op (.stack (.swap 1)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op .store, + .op (.stack (.push 96)), + .op .store, + .op (.stack (.push 0xed572b27)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 100)), + .op (.stack (.push 28)), + .revert], + -- bb9 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert]] } + +end SolarTV.Export.Events diff --git a/Certified/events/gen/Events/Evm2.lean b/Certified/events/gen/Events/Evm2.lean new file mode 100644 index 00000000..a0988c3d --- /dev/null +++ b/Certified/events/gen/Events/Evm2.lean @@ -0,0 +1,78 @@ +-- solar-lean-stage: kind=evm index=2 pass=compact-pushes +import SolarTV.EVMIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `Events`; do not edit. -/ + +namespace SolarTV.Export.Events + +/-- The runtime EVM IR after `compact-pushes`. -/ +def evm2 : EVM.Program.Program := + { blocks := [ + -- bb0 + [.effect .callvalue 0, + .jumpi 1, + .op (.stack (.push 0)), + .effect .calldataload 1, + .op (.stack (.push 224)), + .op (.stack .shr), + .op (.stack (.dup 0)), + .op (.stack (.push 0xcf79e0a)), + .op (.stack .eq), + .jumpi 2, + .jump 1], + -- bb3 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb4 + [.op (.stack (.push 68)), + .op (.stack .calldatasize), + .op (.stack .lt), + .jumpi 4, + .op (.stack (.push 36)), + .effect .calldataload 1, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 4)), + .effect .calldataload 1, + .effect .caller 0, + .op (.stack (.push 0x7fa9aafeb8bb803d77de5d84bc2f2edbd842ca91b20cd5020aa21dfe26ab0be9)), + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .effect (.log 3) 5, + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .effect .caller 0, + .op (.stack .gt), + .jumpi 3, + .stop], + -- bb7 + [.op (.stack (.push 0x4170000000000000002)), + .op (.stack (.push 32)), + .op (.stack .shl), + .effect .caller 0, + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .op (.stack (.swap 1)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op .store, + .op (.stack (.push 96)), + .op .store, + .op (.stack (.push 0xed572b27)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 100)), + .op (.stack (.push 28)), + .revert], + -- bb9 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert]] } + +end SolarTV.Export.Events diff --git a/Certified/events/gen/Events/Evm3.lean b/Certified/events/gen/Events/Evm3.lean new file mode 100644 index 00000000..dae18f7f --- /dev/null +++ b/Certified/events/gen/Events/Evm3.lean @@ -0,0 +1,78 @@ +-- solar-lean-stage: kind=evm index=3 pass=share-reverts +import SolarTV.EVMIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `Events`; do not edit. -/ + +namespace SolarTV.Export.Events + +/-- The runtime EVM IR after `share-reverts`. -/ +def evm3 : EVM.Program.Program := + { blocks := [ + -- bb0 + [.effect .callvalue 0, + .jumpi 1, + .op (.stack (.push 0)), + .effect .calldataload 1, + .op (.stack (.push 224)), + .op (.stack .shr), + .op (.stack (.dup 0)), + .op (.stack (.push 0xcf79e0a)), + .op (.stack .sub), + .jumpi 1, + .jump 2], + -- bb3 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb4 + [.op (.stack (.push 68)), + .op (.stack .calldatasize), + .op (.stack .lt), + .jumpi 4, + .op (.stack (.push 36)), + .effect .calldataload 1, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 4)), + .effect .calldataload 1, + .effect .caller 0, + .op (.stack (.push 0x7fa9aafeb8bb803d77de5d84bc2f2edbd842ca91b20cd5020aa21dfe26ab0be9)), + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .effect (.log 3) 5, + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .effect .caller 0, + .op (.stack .gt), + .jumpi 3, + .stop], + -- bb7 + [.op (.stack (.push 0x4170000000000000002)), + .op (.stack (.push 32)), + .op (.stack .shl), + .effect .caller 0, + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .op (.stack (.swap 1)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op .store, + .op (.stack (.push 96)), + .op .store, + .op (.stack (.push 0xed572b27)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 100)), + .op (.stack (.push 28)), + .revert], + -- bb9 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert]] } + +end SolarTV.Export.Events diff --git a/Certified/events/gen/Events/Evm4.lean b/Certified/events/gen/Events/Evm4.lean new file mode 100644 index 00000000..422a8ed5 --- /dev/null +++ b/Certified/events/gen/Events/Evm4.lean @@ -0,0 +1,76 @@ +-- solar-lean-stage: kind=evm index=4 pass=terminal-dedup +import SolarTV.EVMIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `Events`; do not edit. -/ + +namespace SolarTV.Export.Events + +/-- The runtime EVM IR after `terminal-dedup`. -/ +def evm4 : EVM.Program.Program := + { blocks := [ + -- bb0 + [.effect .callvalue 0, + .jumpi 1, + .op (.stack (.push 0)), + .effect .calldataload 1, + .op (.stack (.push 224)), + .op (.stack .shr), + .op (.stack (.dup 0)), + .op (.stack (.push 0xcf79e0a)), + .op (.stack .sub), + .jumpi 1, + .jump 2], + -- bb3 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb4 + [.op (.stack (.push 68)), + .op (.stack .calldatasize), + .op (.stack .lt), + .jumpi 4, + .op (.stack (.push 36)), + .effect .calldataload 1, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 4)), + .effect .calldataload 1, + .effect .caller 0, + .op (.stack (.push 0x7fa9aafeb8bb803d77de5d84bc2f2edbd842ca91b20cd5020aa21dfe26ab0be9)), + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .effect (.log 3) 5, + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .effect .caller 0, + .op (.stack .gt), + .jumpi 3, + .stop], + -- bb7 + [.op (.stack (.push 0x4170000000000000002)), + .op (.stack (.push 32)), + .op (.stack .shl), + .effect .caller 0, + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .op (.stack (.swap 1)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op .store, + .op (.stack (.push 96)), + .op .store, + .op (.stack (.push 0xed572b27)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 100)), + .op (.stack (.push 28)), + .revert], + -- bb9 + [.jump 1]] } + +end SolarTV.Export.Events diff --git a/Certified/events/gen/Events/Evm5.lean b/Certified/events/gen/Events/Evm5.lean new file mode 100644 index 00000000..b8236ef6 --- /dev/null +++ b/Certified/events/gen/Events/Evm5.lean @@ -0,0 +1,72 @@ +-- solar-lean-stage: kind=evm index=5 pass=cfg-simplify-early +import SolarTV.EVMIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `Events`; do not edit. -/ + +namespace SolarTV.Export.Events + +/-- The runtime EVM IR after `cfg-simplify-early`. -/ +def evm5 : EVM.Program.Program := + { blocks := [ + -- bb0 + [.effect .callvalue 0, + .jumpi 1, + .op (.stack (.push 0)), + .effect .calldataload 1, + .op (.stack (.push 224)), + .op (.stack .shr), + .op (.stack (.dup 0)), + .op (.stack (.push 0xcf79e0a)), + .op (.stack .sub), + .jumpi 1, + .op (.stack (.push 68)), + .op (.stack .calldatasize), + .op (.stack .lt), + .jumpi 1, + .op (.stack (.push 36)), + .effect .calldataload 1, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 4)), + .effect .calldataload 1, + .effect .caller 0, + .op (.stack (.push 0x7fa9aafeb8bb803d77de5d84bc2f2edbd842ca91b20cd5020aa21dfe26ab0be9)), + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .effect (.log 3) 5, + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .effect .caller 0, + .op (.stack .gt), + .jumpi 2, + .stop], + -- bb3 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb7 + [.op (.stack (.push 0x4170000000000000002)), + .op (.stack (.push 32)), + .op (.stack .shl), + .effect .caller 0, + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .op (.stack (.swap 1)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op .store, + .op (.stack (.push 96)), + .op .store, + .op (.stack (.push 0xed572b27)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 100)), + .op (.stack (.push 28)), + .revert]] } + +end SolarTV.Export.Events diff --git a/Certified/events/gen/Events/Manifest.lean b/Certified/events/gen/Events/Manifest.lean new file mode 100644 index 00000000..f7a522e1 --- /dev/null +++ b/Certified/events/gen/Events/Manifest.lean @@ -0,0 +1,43 @@ +-- solar-lean-stage: kind=manifest index=0 pass=none +/-! Generated by `solar -Zemit-lean-stages` for `Events`; do not edit. + +What the stages of this directory were compiled from and by. `stages` lists each +stage's file, its definition, the pass whose output it is, and the SHA-256 of the file. +-/ + +namespace SolarTV.Export.Events.Manifest + +def sources : List (String × String) := + [("solar-tv/milestone/events/events.sol", "8b951679cab695d07c193e56dd5d96d14a1c63976673c79a72c690f07c50b5b0")] + +def compiler : String := "0.8.38+commit.0a455fda.solar.0.3.0-dev" + +def arguments : List String := + ["solar-tv/milestone/events/events.sol", + "-Ogas", + "--evm-version", + "osaka", + "--emit=bin-runtime", + "-Zemit-lean-stages=solar-tv/milestone/events/gen"] + +def evmVersion : String := "osaka" + +def optimization : String := "Gas" + +def stages : List (String × String × String × String) := + [("Stage0", "stage0", "lower-evm-shaped", "68677a695510baf2870afd0103eb47704edc8ef3364bd447b4adca68bbae9872"), + ("Mir1", "mir1", "lower-assumes", "2d42087e761656008220641508b6b751973cea26f4fe9cd5c0c03dd904852144"), + ("Sched", "sched", "stack-schedule", "929791fc4e57353df07b33d8162fea62bb0c2e2b4813e1931736baecd9699549"), + ("Evm1", "evm1", "cfg-simplify-early", "e326484f2b9d99b6b5c1d840ac3b1fb9c839a16a52bbf0a2aae10cc92d2a8919"), + ("Evm2", "evm2", "compact-pushes", "b86a90a2aaddfe85d8fb1cfe30fe9c326001fb6bb3901e81c624c90168f3df6b"), + ("Evm3", "evm3", "share-reverts", "34129f64acafdee66806e77d9771942beaed85ab32da0e25a4432541413a4235"), + ("Evm4", "evm4", "terminal-dedup", "3644c7996119ff8509849b1a3dbc32429efe7c7088c8920cc0a11675feb223e2"), + ("Evm5", "evm5", "cfg-simplify-early", "7fd8518f82d6a049aac367739d04580b006674baba38f47b193be4950cb2b082"), + ("Bytecode", "bytecode", "assemble", "c598af1c73cf0b943d5ee96c6a76400d8f34e2df60f4f818ca582f427da9acf1")] + +def bytecodeHex : String := + "346053575f3560e01c80630cf79e0a03605357604436106053576024355f52600435337f7fa9aafeb8bb803d77de5d84bc2f2edbd842ca91b20cd5020aa21dfe26ab0be960205fa35f1960601c3311605757005b5f5ffd5b690417000000000000000260201b335f1960601c9160205260405260605263ed572b275f526064601cfd" + +def bytecodeSha256 : String := "5ad38c8bca24e0ca8c4a5e95f1f07bf993aad9a02ac3bc0872fc41fab8a6298b" + +end SolarTV.Export.Events.Manifest diff --git a/Certified/events/gen/Events/Mir1.lean b/Certified/events/gen/Events/Mir1.lean new file mode 100644 index 00000000..0c224421 --- /dev/null +++ b/Certified/events/gen/Events/Mir1.lean @@ -0,0 +1,70 @@ +-- solar-lean-stage: kind=mir index=1 pass=lower-assumes +import SolarTV.MIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `Events`; do not edit. -/ + +namespace SolarTV.Export.Events + +/-- The lowered MIR module after `lower-assumes`. -/ +def mir1 : MIR.Lowered.Module := + { entry := 1, + functions := [ + -- @transfer + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 9) .calldatasize [], + .pure 11 .lt [.value 9, .const 68]], + .branch (.value 11) 1 2⟩, + -- bb1 + ⟨[], + [], + .revert (.const 0) (.const 0)⟩, + -- bb2 + ⟨[], + [.effect (some 13) .calldataload [.const 4], + .effect (some 15) .calldataload [.const 36], + .effect (some 3) .caller [], + .effect none .mstore [.const 0, .value 15], + .effect none (.log 3) [.const 0, .const 32, .const 0x7fa9aafeb8bb803d77de5d84bc2f2edbd842ca91b20cd5020aa21dfe26ab0be9, .value 3, .value 13], + .pure 18 .gt [.value 3, .const 0xffffffffffffffffffffffffffffffffffffffff]], + .branch (.value 18) 4 5⟩, + -- bb3 + ⟨[(20, [(4, .const 0x417000000000000000200000000)]), (21, [(4, .value 3)]), (22, [(4, .const 0xffffffffffffffffffffffffffffffffffffffff)])], + [.effect none .mstore [.const 32, .value 20], + .effect none .mstore [.const 64, .value 21], + .effect none .mstore [.const 96, .value 22], + .effect none .mstore [.const 0, .const 0xed572b27]], + .revert (.const 28) (.const 100)⟩, + -- bb4 + ⟨[], + [], + .jump 3⟩, + -- bb5 + ⟨[], + [], + .stop⟩] }, + -- @entry + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 0) .callvalue [], + .ne 2 (.value 0) (.const 0)], + .branch (.value 2) 3 1⟩, + -- bb1 + ⟨[], + [.effect (some 4) .calldataload [.const 0], + .pure 6 .shr [.const 224, .value 4]], + .switch (.value 6) 3 [(.const 0xcf79e0a, 2)]⟩, + -- bb2 + ⟨[], + [], + .tailCall 0 []⟩, + -- bb3 + ⟨[], + [], + .revert (.const 0) (.const 0)⟩] }] } + +end SolarTV.Export.Events diff --git a/Certified/events/gen/Events/Sched.lean b/Certified/events/gen/Events/Sched.lean new file mode 100644 index 00000000..86e1db31 --- /dev/null +++ b/Certified/events/gen/Events/Sched.lean @@ -0,0 +1,80 @@ +-- solar-lean-stage: kind=sched index=0 pass=stack-schedule +import SolarTV.EVMIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `Events`; do not edit. -/ + +namespace SolarTV.Export.Events + +/-- The runtime EVM IR as stack scheduling emits it. -/ +def sched : EVM.Program.Program := + { blocks := [ + -- bb0 + [.effect .callvalue 0, + .jumpi 3, + .jump 1], + -- bb1 + [.op (.stack (.push 0)), + .effect .calldataload 1, + .op (.stack (.push 224)), + .op (.stack .shr), + .op (.stack (.dup 0)), + .op (.stack (.push 0xcf79e0a)), + .op (.stack .eq), + .jumpi 2, + .jump 3], + -- bb2 + [.jump 4], + -- bb3 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb4 + [.op (.stack (.push 68)), + .op (.stack .calldatasize), + .op (.stack .lt), + .jumpi 9, + .jump 5], + -- bb5 + [.op (.stack (.push 36)), + .effect .calldataload 1, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 4)), + .effect .calldataload 1, + .effect .caller 0, + .op (.stack (.push 0x7fa9aafeb8bb803d77de5d84bc2f2edbd842ca91b20cd5020aa21dfe26ab0be9)), + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .effect (.log 3) 5, + .op (.stack (.push 0xffffffffffffffffffffffffffffffffffffffff)), + .effect .caller 0, + .op (.stack .gt), + .jumpi 7, + .jump 6], + -- bb6 + [.stop], + -- bb7 + [.op (.stack (.push 0x417000000000000000200000000)), + .effect .caller 0, + .op (.stack (.push 0xffffffffffffffffffffffffffffffffffffffff)), + .jump 8], + -- bb8 + [.op (.stack (.swap 1)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op .store, + .op (.stack (.push 96)), + .op .store, + .op (.stack (.push 0xed572b27)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 100)), + .op (.stack (.push 28)), + .revert], + -- bb9 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert]] } + +end SolarTV.Export.Events diff --git a/Certified/events/gen/Events/Stage0.lean b/Certified/events/gen/Events/Stage0.lean new file mode 100644 index 00000000..a0a7e03b --- /dev/null +++ b/Certified/events/gen/Events/Stage0.lean @@ -0,0 +1,55 @@ +-- solar-lean-stage: kind=mir index=0 pass=lower-evm-shaped +import SolarTV.MIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `Events`; do not edit. -/ + +namespace SolarTV.Export.Events + +/-- The first lowered MIR module, after `lower-evm-shaped` advanced the phase. -/ +def stage0 : MIR.Lowered.Module := + { entry := 1, + functions := [ + -- @transfer + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 9) .calldatasize [], + .pure 11 .lt [.value 9, .const 68]], + .branch (.value 11) 1 2⟩, + -- bb1 + ⟨[], + [], + .revert (.const 0) (.const 0)⟩, + -- bb2 + ⟨[], + [.effect (some 13) .calldataload [.const 4], + .effect (some 15) .calldataload [.const 36], + .effect (some 3) .caller [], + .effect none .mstore [.const 0, .value 15], + .effect none (.log 3) [.const 0, .const 32, .const 0x7fa9aafeb8bb803d77de5d84bc2f2edbd842ca91b20cd5020aa21dfe26ab0be9, .value 3, .value 13], + .assume true .gt [.value 3, .const 0xffffffffffffffffffffffffffffffffffffffff]], + .stop⟩] }, + -- @entry + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 0) .callvalue [], + .ne 2 (.value 0) (.const 0)], + .branch (.value 2) 3 1⟩, + -- bb1 + ⟨[], + [.effect (some 4) .calldataload [.const 0], + .pure 6 .shr [.const 224, .value 4]], + .switch (.value 6) 3 [(.const 0xcf79e0a, 2)]⟩, + -- bb2 + ⟨[], + [], + .tailCall 0 []⟩, + -- bb3 + ⟨[], + [], + .revert (.const 0) (.const 0)⟩] }] } + +end SolarTV.Export.Events diff --git a/Certified/events/gen/Events/manifest.json b/Certified/events/gen/Events/manifest.json new file mode 100644 index 00000000..15090bc3 --- /dev/null +++ b/Certified/events/gen/Events/manifest.json @@ -0,0 +1,97 @@ +{ + "arguments": [ + "solar-tv/milestone/events/events.sol", + "-Ogas", + "--evm-version", + "osaka", + "--emit=bin-runtime", + "-Zemit-lean-stages=solar-tv/milestone/events/gen" + ], + "bytecode": "346053575f3560e01c80630cf79e0a03605357604436106053576024355f52600435337f7fa9aafeb8bb803d77de5d84bc2f2edbd842ca91b20cd5020aa21dfe26ab0be960205fa35f1960601c3311605757005b5f5ffd5b690417000000000000000260201b335f1960601c9160205260405260605263ed572b275f526064601cfd", + "bytecode_sha256": "5ad38c8bca24e0ca8c4a5e95f1f07bf993aad9a02ac3bc0872fc41fab8a6298b", + "compiler": "0.8.38+commit.0a455fda.solar.0.3.0-dev", + "contract": "Events", + "evm_version": "osaka", + "optimization": "Gas", + "options": "CompileOpts { input: [\"solar-tv/milestone/events/events.sol\"], import_remappings: [], base_path: None, include_paths: [], allow_paths: [], no_import_callback: false, language: Solidity, threads: 4, evm_version: Osaka, stop_after: None, optimization: Gas, optimizer_runs: None, revert_strings: Default, libraries: [], out_dir: None, emit: [BinRuntime], standard_json: false, color: Auto, verbose: false, pretty_json: false, pretty_json_err: false, error_format: Human, error_format_human: Unicode, diagnostic_width: None, no_warnings: false, allow: [], _unstable: [\"emit-lean-stages=solar-tv/milestone/events/gen\"], unstable: UnstableOpts { ui_testing: false, track_diagnostics: false, parse_yul: false, no_resolve_imports: false, recover_incomplete_input: false, dump: None, ast_stats: false, hir_stats: false, standard_json_stats: false, span_visitor: false, print_max_storage_sizes: false, print_natspec: false, mir_pipeline: None, evm_ir_pipeline: None, print_after_each: false, pass_diff: false, debugify: None, debugify_output: None, solar_tv: None, validate_ir: None, time_passes: false, codegen_all_functions: false, switch_lowering: Auto, switch_max_gas_code_growth: None, switch_max_bit_slice_gas_code_growth: None, tune: None, pack_wide_jump_tables: false, check_analyses: None, prove_analyses: None, validate_passes: None, validate_passes_fault: None, validate_backend: None, validate_backend_fault: None, validate_evm_ir_passes: None, validate_assembly: false, validate_assembly_fault: None, emit_lean_stages: Some(\"solar-tv/milestone/events/gen\"), forget_gcx: true, help: (), _non_exhaustive: () }, _non_exhaustive: () }", + "sources": [ + { + "path": "solar-tv/milestone/events/events.sol", + "sha256": "8b951679cab695d07c193e56dd5d96d14a1c63976673c79a72c690f07c50b5b0" + } + ], + "stages": [ + { + "definition": "stage0", + "file": "Stage0.lean", + "index": 0, + "kind": "mir", + "pass": "lower-evm-shaped", + "sha256": "68677a695510baf2870afd0103eb47704edc8ef3364bd447b4adca68bbae9872" + }, + { + "definition": "mir1", + "file": "Mir1.lean", + "index": 1, + "kind": "mir", + "pass": "lower-assumes", + "sha256": "2d42087e761656008220641508b6b751973cea26f4fe9cd5c0c03dd904852144" + }, + { + "definition": "sched", + "file": "Sched.lean", + "index": 0, + "kind": "sched", + "pass": "stack-schedule", + "sha256": "929791fc4e57353df07b33d8162fea62bb0c2e2b4813e1931736baecd9699549" + }, + { + "definition": "evm1", + "file": "Evm1.lean", + "index": 1, + "kind": "evm", + "pass": "cfg-simplify-early", + "sha256": "e326484f2b9d99b6b5c1d840ac3b1fb9c839a16a52bbf0a2aae10cc92d2a8919" + }, + { + "definition": "evm2", + "file": "Evm2.lean", + "index": 2, + "kind": "evm", + "pass": "compact-pushes", + "sha256": "b86a90a2aaddfe85d8fb1cfe30fe9c326001fb6bb3901e81c624c90168f3df6b" + }, + { + "definition": "evm3", + "file": "Evm3.lean", + "index": 3, + "kind": "evm", + "pass": "share-reverts", + "sha256": "34129f64acafdee66806e77d9771942beaed85ab32da0e25a4432541413a4235" + }, + { + "definition": "evm4", + "file": "Evm4.lean", + "index": 4, + "kind": "evm", + "pass": "terminal-dedup", + "sha256": "3644c7996119ff8509849b1a3dbc32429efe7c7088c8920cc0a11675feb223e2" + }, + { + "definition": "evm5", + "file": "Evm5.lean", + "index": 5, + "kind": "evm", + "pass": "cfg-simplify-early", + "sha256": "7fd8518f82d6a049aac367739d04580b006674baba38f47b193be4950cb2b082" + }, + { + "definition": "bytecode", + "file": "Bytecode.lean", + "index": 0, + "kind": "bytecode", + "pass": "assemble", + "sha256": "c598af1c73cf0b943d5ee96c6a76400d8f34e2df60f4f818ca582f427da9acf1" + } + ] +} diff --git a/Certified/events/options b/Certified/events/options new file mode 100644 index 00000000..da38913c --- /dev/null +++ b/Certified/events/options @@ -0,0 +1,3 @@ +-Ogas +--evm-version +osaka diff --git a/Certified/masks/Proofs.lean b/Certified/masks/Proofs.lean new file mode 100644 index 00000000..55be915f --- /dev/null +++ b/Certified/masks/Proofs.lean @@ -0,0 +1,3 @@ +-- Generated by solar-tv/milestone/certify.py; do not edit. +import masks.Proofs.Stages +import masks.Proofs.Assembly diff --git a/Certified/masks/Proofs/Assembly.lean b/Certified/masks/Proofs/Assembly.lean new file mode 100644 index 00000000..d958e4f2 --- /dev/null +++ b/Certified/masks/Proofs/Assembly.lean @@ -0,0 +1,42 @@ +-- Generated by solar-tv/milestone/certify.py; do not edit. +import W1Proofs.Items +import masks.gen.Masks.Evm6 +import masks.gen.Masks.Bytecode + +/-! The final EVM IR of `Masks` against its bytecode, by the assembly checker's walk: the bytecode decodes, linearly from offset 0, to exactly the program's instructions, each jumped-to block at its `JUMPDEST`. -/ + +namespace SolarTV.Milestone.Masks + +open SolarTV.Assembly SolarTV.Export.Masks SolarTV.Milestone.W1 + +set_option maxRecDepth 100000 + +/-- The items of the final EVM IR. -/ +def items : List Item := (itemsOf evm6).getD [] + +theorem items_eq : itemsOf evm6 = some items := by decide + +/-- The layout: each jumped-to block at the bytecode's next `JUMPDEST`. The walk checks it. -/ +def offset (label : Nat) : Nat := if label = 1 then 0x3e else if label = 2 then 0x42 else if label = 3 then 0x4b else if label = 4 then 0x71 else if label = 5 then 0x83 else 0 + +/-- The instructions the walk reaches, each at its offset. -/ +def stream : List (Nat × Instr) := (walk bytecode offset 0 items).getD [] + +/-- The checker's walk accepts the exported bytecode against the final EVM IR. -/ +theorem walk_eq : walk bytecode offset 0 items = some stream := by decide +kernel + +theorem checked : Walk bytecode offset 0 items stream := walk_sound walk_eq + +/-- The bytecode's linear decoding is the final EVM IR's instructions at the layout. -/ +theorem decodes : decodeFrom bytecode (bytecode.length + 1) 0 = stream := + walk_decodes checked _ (by have := walk_length checked; omega) + +/-- info: 'SolarTV.Milestone.Masks.walk_eq' depends on axioms: [propext, Quot.sound] -/ +#guard_msgs in +#print axioms walk_eq + +/-- info: 'SolarTV.Milestone.Masks.decodes' depends on axioms: [propext, Quot.sound] -/ +#guard_msgs in +#print axioms decodes + +end SolarTV.Milestone.Masks diff --git a/Certified/masks/Proofs/Runs/Evm1.lean b/Certified/masks/Proofs/Runs/Evm1.lean new file mode 100644 index 00000000..1951d905 --- /dev/null +++ b/Certified/masks/Proofs/Runs/Evm1.lean @@ -0,0 +1,22 @@ +-- Generated by solar-tv/milestone/certify.py; do not edit. +import W1Proofs.Tactic +import W1Proofs.Axioms +import masks.gen.Masks.Evm1 +import masks.gen.Masks.Sched + +/-! `peephole-early`: its input and output end in the same result on every call. -/ + +namespace SolarTV.Milestone.Masks + +open Machine SolarTV.Export.Masks SolarTV.Milestone.W1 + +set_option maxHeartbeats 2000000 in +theorem evm1_run (o : Oracle) (call : Call) : + EVM.Program.run o sched call 18 = EVM.Program.run o evm1 call 18 := by + sym_exec + +/-- info: 'SolarTV.Milestone.Masks.evm1_run' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within evm1_run + +end SolarTV.Milestone.Masks diff --git a/Certified/masks/Proofs/Runs/Evm2.lean b/Certified/masks/Proofs/Runs/Evm2.lean new file mode 100644 index 00000000..2852f520 --- /dev/null +++ b/Certified/masks/Proofs/Runs/Evm2.lean @@ -0,0 +1,22 @@ +-- Generated by solar-tv/milestone/certify.py; do not edit. +import W1Proofs.Tactic +import W1Proofs.Axioms +import masks.gen.Masks.Evm2 +import masks.gen.Masks.Evm1 + +/-! `cfg-simplify-early`: its input and output end in the same result on every call. -/ + +namespace SolarTV.Milestone.Masks + +open Machine SolarTV.Export.Masks SolarTV.Milestone.W1 + +set_option maxHeartbeats 2000000 in +theorem evm2_run (o : Oracle) (call : Call) : + EVM.Program.run o evm1 call 18 = EVM.Program.run o evm2 call 9 := by + sym_exec + +/-- info: 'SolarTV.Milestone.Masks.evm2_run' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within evm2_run + +end SolarTV.Milestone.Masks diff --git a/Certified/masks/Proofs/Runs/Evm3.lean b/Certified/masks/Proofs/Runs/Evm3.lean new file mode 100644 index 00000000..ecb2e72d --- /dev/null +++ b/Certified/masks/Proofs/Runs/Evm3.lean @@ -0,0 +1,22 @@ +-- Generated by solar-tv/milestone/certify.py; do not edit. +import W1Proofs.Tactic +import W1Proofs.Axioms +import masks.gen.Masks.Evm3 +import masks.gen.Masks.Evm2 + +/-! `block-layout`: its input and output end in the same result on every call. -/ + +namespace SolarTV.Milestone.Masks + +open Machine SolarTV.Export.Masks SolarTV.Milestone.W1 + +set_option maxHeartbeats 2000000 in +theorem evm3_run (o : Oracle) (call : Call) : + EVM.Program.run o evm2 call 9 = EVM.Program.run o evm3 call 9 := by + sym_exec + +/-- info: 'SolarTV.Milestone.Masks.evm3_run' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within evm3_run + +end SolarTV.Milestone.Masks diff --git a/Certified/masks/Proofs/Runs/Evm4.lean b/Certified/masks/Proofs/Runs/Evm4.lean new file mode 100644 index 00000000..09b3b60d --- /dev/null +++ b/Certified/masks/Proofs/Runs/Evm4.lean @@ -0,0 +1,22 @@ +-- Generated by solar-tv/milestone/certify.py; do not edit. +import W1Proofs.Tactic +import W1Proofs.Axioms +import masks.gen.Masks.Evm4 +import masks.gen.Masks.Evm3 + +/-! `share-reverts`: its input and output end in the same result on every call. -/ + +namespace SolarTV.Milestone.Masks + +open Machine SolarTV.Export.Masks SolarTV.Milestone.W1 + +set_option maxHeartbeats 2000000 in +theorem evm4_run (o : Oracle) (call : Call) : + EVM.Program.run o evm3 call 9 = EVM.Program.run o evm4 call 9 := by + sym_exec + +/-- info: 'SolarTV.Milestone.Masks.evm4_run' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within evm4_run + +end SolarTV.Milestone.Masks diff --git a/Certified/masks/Proofs/Runs/Evm5.lean b/Certified/masks/Proofs/Runs/Evm5.lean new file mode 100644 index 00000000..bfe00fbd --- /dev/null +++ b/Certified/masks/Proofs/Runs/Evm5.lean @@ -0,0 +1,22 @@ +-- Generated by solar-tv/milestone/certify.py; do not edit. +import W1Proofs.Tactic +import W1Proofs.Axioms +import masks.gen.Masks.Evm5 +import masks.gen.Masks.Evm4 + +/-! `terminal-dedup`: its input and output end in the same result on every call. -/ + +namespace SolarTV.Milestone.Masks + +open Machine SolarTV.Export.Masks SolarTV.Milestone.W1 + +set_option maxHeartbeats 2000000 in +theorem evm5_run (o : Oracle) (call : Call) : + EVM.Program.run o evm4 call 9 = EVM.Program.run o evm5 call 9 := by + sym_exec + +/-- info: 'SolarTV.Milestone.Masks.evm5_run' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within evm5_run + +end SolarTV.Milestone.Masks diff --git a/Certified/masks/Proofs/Runs/Evm6.lean b/Certified/masks/Proofs/Runs/Evm6.lean new file mode 100644 index 00000000..f4a45a28 --- /dev/null +++ b/Certified/masks/Proofs/Runs/Evm6.lean @@ -0,0 +1,22 @@ +-- Generated by solar-tv/milestone/certify.py; do not edit. +import W1Proofs.Tactic +import W1Proofs.Axioms +import masks.gen.Masks.Evm6 +import masks.gen.Masks.Evm5 + +/-! `cfg-simplify-early`: its input and output end in the same result on every call. -/ + +namespace SolarTV.Milestone.Masks + +open Machine SolarTV.Export.Masks SolarTV.Milestone.W1 + +set_option maxHeartbeats 2000000 in +theorem evm6_run (o : Oracle) (call : Call) : + EVM.Program.run o evm5 call 9 = EVM.Program.run o evm6 call 6 := by + sym_exec + +/-- info: 'SolarTV.Milestone.Masks.evm6_run' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within evm6_run + +end SolarTV.Milestone.Masks diff --git a/Certified/masks/Proofs/Runs/Mir1.lean b/Certified/masks/Proofs/Runs/Mir1.lean new file mode 100644 index 00000000..51a356e2 --- /dev/null +++ b/Certified/masks/Proofs/Runs/Mir1.lean @@ -0,0 +1,22 @@ +-- Generated by solar-tv/milestone/certify.py; do not edit. +import W1Proofs.Tactic +import W1Proofs.Axioms +import masks.gen.Masks.Mir1 +import masks.gen.Masks.Stage0 + +/-! `place-reads`: its input and output end in the same result on every call. -/ + +namespace SolarTV.Milestone.Masks + +open Machine SolarTV.Export.Masks SolarTV.Milestone.W1 + +set_option maxHeartbeats 2000000 in +theorem mir1_run (o : Oracle) (call : Call) : + MIR.Lowered.Module.run o stage0 call 15 = MIR.Lowered.Module.run o mir1 call 15 := by + sym_exec + +/-- info: 'SolarTV.Milestone.Masks.mir1_run' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within mir1_run + +end SolarTV.Milestone.Masks diff --git a/Certified/masks/Proofs/Runs/Mir2.lean b/Certified/masks/Proofs/Runs/Mir2.lean new file mode 100644 index 00000000..178daa27 --- /dev/null +++ b/Certified/masks/Proofs/Runs/Mir2.lean @@ -0,0 +1,22 @@ +-- Generated by solar-tv/milestone/certify.py; do not edit. +import W1Proofs.Tactic +import W1Proofs.Axioms +import masks.gen.Masks.Mir2 +import masks.gen.Masks.Mir1 + +/-! `lower-assumes`: its input and output end in the same result on every call. -/ + +namespace SolarTV.Milestone.Masks + +open Machine SolarTV.Export.Masks SolarTV.Milestone.W1 + +set_option maxHeartbeats 2000000 in +theorem mir2_run (o : Oracle) (call : Call) : + MIR.Lowered.Module.run o mir1 call 15 = MIR.Lowered.Module.run o mir2 call 18 := by + sym_exec + +/-- info: 'SolarTV.Milestone.Masks.mir2_run' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within mir2_run + +end SolarTV.Milestone.Masks diff --git a/Certified/masks/Proofs/Runs/Sched.lean b/Certified/masks/Proofs/Runs/Sched.lean new file mode 100644 index 00000000..32370923 --- /dev/null +++ b/Certified/masks/Proofs/Runs/Sched.lean @@ -0,0 +1,22 @@ +-- Generated by solar-tv/milestone/certify.py; do not edit. +import W1Proofs.Tactic +import W1Proofs.Axioms +import masks.gen.Masks.Sched +import masks.gen.Masks.Mir2 + +/-! Stack scheduling: the last lowered MIR and the scheduled EVM IR end in the same result on every call. -/ + +namespace SolarTV.Milestone.Masks + +open Machine SolarTV.Export.Masks SolarTV.Milestone.W1 + +set_option maxHeartbeats 2000000 in +theorem sched_run (o : Oracle) (call : Call) : + MIR.Lowered.Module.run o mir2 call 18 = EVM.Program.run o sched call 18 := by + sym_exec + +/-- info: 'SolarTV.Milestone.Masks.sched_run' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within sched_run + +end SolarTV.Milestone.Masks diff --git a/Certified/masks/Proofs/Runs/Stage0.lean b/Certified/masks/Proofs/Runs/Stage0.lean new file mode 100644 index 00000000..4a46fe52 --- /dev/null +++ b/Certified/masks/Proofs/Runs/Stage0.lean @@ -0,0 +1,21 @@ +-- Generated by solar-tv/milestone/certify.py; do not edit. +import W1Proofs.Tactic +import W1Proofs.Axioms +import masks.gen.Masks.Stage0 + +/-! The first lowered MIR ends on every call within 15 blocks, the number of its blocks. -/ + +namespace SolarTV.Milestone.Masks + +open Machine SolarTV.Export.Masks SolarTV.Milestone.W1 + +set_option maxHeartbeats 2000000 in +theorem stage0_ends (o : Oracle) (call : Call) : + (MIR.Lowered.Module.run o stage0 call 15).isSome = true := by + sym_exec + +/-- info: 'SolarTV.Milestone.Masks.stage0_ends' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within stage0_ends + +end SolarTV.Milestone.Masks diff --git a/Certified/masks/Proofs/Stages.lean b/Certified/masks/Proofs/Stages.lean new file mode 100644 index 00000000..881b3fb6 --- /dev/null +++ b/Certified/masks/Proofs/Stages.lean @@ -0,0 +1,163 @@ +-- Generated by solar-tv/milestone/certify.py; do not edit. +import masks.Proofs.Runs.Stage0 +import masks.Proofs.Runs.Mir1 +import masks.Proofs.Runs.Mir2 +import masks.Proofs.Runs.Sched +import masks.Proofs.Runs.Evm1 +import masks.Proofs.Runs.Evm2 +import masks.Proofs.Runs.Evm3 +import masks.Proofs.Runs.Evm4 +import masks.Proofs.Runs.Evm5 +import masks.Proofs.Runs.Evm6 +import W1Proofs.Stage +import SolarTV.Composition + +/-! The backend stages of `Masks`, each proved on every call (`anyCall`: any calldata, call value and storage) under every oracle, and chained from the first lowered MIR `stage0` to the final EVM IR `evm6`. Fuels are the programs' block counts. -/ + +namespace SolarTV.Milestone.Masks + +open Machine SolarTV.Export.Masks SolarTV.Milestone.W1 + +/-- `place-reads`: stage0 to mir1. -/ +theorem stage_mir1 (o : Oracle) : Stage (mirSem o) (mirSem o) stage0 mir1 anyCall := + stage_of_runs (A := MIR.Lowered.moduleLayer) (B := MIR.Lowered.moduleLayer) 15 15 (fun call _ => stage0_ends o call) + (fun call _ => mir1_run o call) + +theorem mir1_ends (o : Oracle) : ∀ call, anyCall call → + (MIR.Lowered.Module.run o mir1 call 15).isSome = true := + ends_of_runs (A := MIR.Lowered.moduleLayer) (B := MIR.Lowered.moduleLayer) + (o := o) (p := stage0) (q := mir1) (n := 15) (m := 15) (fun call _ => stage0_ends o call) + (fun call _ => mir1_run o call) + +/-- `lower-assumes`: mir1 to mir2. -/ +theorem stage_mir2 (o : Oracle) : Stage (mirSem o) (mirSem o) mir1 mir2 anyCall := + stage_of_runs (A := MIR.Lowered.moduleLayer) (B := MIR.Lowered.moduleLayer) 15 18 (mir1_ends o) + (fun call _ => mir2_run o call) + +theorem mir2_ends (o : Oracle) : ∀ call, anyCall call → + (MIR.Lowered.Module.run o mir2 call 18).isSome = true := + ends_of_runs (A := MIR.Lowered.moduleLayer) (B := MIR.Lowered.moduleLayer) + (o := o) (p := mir1) (q := mir2) (n := 15) (m := 18) (mir1_ends o) + (fun call _ => mir2_run o call) + +/-- `stack-schedule`: mir2 to sched. -/ +theorem stage_sched (o : Oracle) : Stage (mirSem o) (evmirSem o) mir2 sched anyCall := + stage_of_runs (A := MIR.Lowered.moduleLayer) (B := EVM.Program.layer) 18 18 (mir2_ends o) + (fun call _ => sched_run o call) + +theorem sched_ends (o : Oracle) : ∀ call, anyCall call → + (EVM.Program.run o sched call 18).isSome = true := + ends_of_runs (A := MIR.Lowered.moduleLayer) (B := EVM.Program.layer) + (o := o) (p := mir2) (q := sched) (n := 18) (m := 18) (mir2_ends o) + (fun call _ => sched_run o call) + +/-- `peephole-early`: sched to evm1. -/ +theorem stage_evm1 (o : Oracle) : Stage (evmirSem o) (evmirSem o) sched evm1 anyCall := + stage_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) 18 18 (sched_ends o) + (fun call _ => evm1_run o call) + +theorem evm1_ends (o : Oracle) : ∀ call, anyCall call → + (EVM.Program.run o evm1 call 18).isSome = true := + ends_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) + (o := o) (p := sched) (q := evm1) (n := 18) (m := 18) (sched_ends o) + (fun call _ => evm1_run o call) + +/-- `cfg-simplify-early`: evm1 to evm2. -/ +theorem stage_evm2 (o : Oracle) : Stage (evmirSem o) (evmirSem o) evm1 evm2 anyCall := + stage_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) 18 9 (evm1_ends o) + (fun call _ => evm2_run o call) + +theorem evm2_ends (o : Oracle) : ∀ call, anyCall call → + (EVM.Program.run o evm2 call 9).isSome = true := + ends_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) + (o := o) (p := evm1) (q := evm2) (n := 18) (m := 9) (evm1_ends o) + (fun call _ => evm2_run o call) + +/-- `block-layout`: evm2 to evm3. -/ +theorem stage_evm3 (o : Oracle) : Stage (evmirSem o) (evmirSem o) evm2 evm3 anyCall := + stage_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) 9 9 (evm2_ends o) + (fun call _ => evm3_run o call) + +theorem evm3_ends (o : Oracle) : ∀ call, anyCall call → + (EVM.Program.run o evm3 call 9).isSome = true := + ends_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) + (o := o) (p := evm2) (q := evm3) (n := 9) (m := 9) (evm2_ends o) + (fun call _ => evm3_run o call) + +/-- `share-reverts`: evm3 to evm4. -/ +theorem stage_evm4 (o : Oracle) : Stage (evmirSem o) (evmirSem o) evm3 evm4 anyCall := + stage_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) 9 9 (evm3_ends o) + (fun call _ => evm4_run o call) + +theorem evm4_ends (o : Oracle) : ∀ call, anyCall call → + (EVM.Program.run o evm4 call 9).isSome = true := + ends_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) + (o := o) (p := evm3) (q := evm4) (n := 9) (m := 9) (evm3_ends o) + (fun call _ => evm4_run o call) + +/-- `terminal-dedup`: evm4 to evm5. -/ +theorem stage_evm5 (o : Oracle) : Stage (evmirSem o) (evmirSem o) evm4 evm5 anyCall := + stage_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) 9 9 (evm4_ends o) + (fun call _ => evm5_run o call) + +theorem evm5_ends (o : Oracle) : ∀ call, anyCall call → + (EVM.Program.run o evm5 call 9).isSome = true := + ends_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) + (o := o) (p := evm4) (q := evm5) (n := 9) (m := 9) (evm4_ends o) + (fun call _ => evm5_run o call) + +/-- `cfg-simplify-early`: evm5 to evm6. -/ +theorem stage_evm6 (o : Oracle) : Stage (evmirSem o) (evmirSem o) evm5 evm6 anyCall := + stage_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) 9 6 (evm5_ends o) + (fun call _ => evm6_run o call) + +/-- The compilation from the first lowered MIR to the final EVM IR. -/ +def compilation : Compilation := + ⟨stage0, [mir1, mir2], sched, [evm1, evm2, evm3, evm4, evm5, evm6]⟩ + +/-- Every stage from the first lowered MIR to the final EVM IR, chained by the library's composition, on every call. -/ +theorem masks_mir_to_evmir (o : Oracle) : Stage (mirSem o) (evmirSem o) stage0 evm6 anyCall := + mir_to_evmir o anyCall compilation ⟨stage_mir1 o, stage_mir2 o, trivial⟩ (stage_sched o) + ⟨stage_evm1 o, stage_evm2 o, stage_evm3 o, stage_evm4 o, stage_evm5 o, stage_evm6 o, trivial⟩ + +/-- info: 'SolarTV.Milestone.Masks.stage_mir1' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms stage_mir1 + +/-- info: 'SolarTV.Milestone.Masks.stage_mir2' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms stage_mir2 + +/-- info: 'SolarTV.Milestone.Masks.stage_sched' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms stage_sched + +/-- info: 'SolarTV.Milestone.Masks.stage_evm1' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms stage_evm1 + +/-- info: 'SolarTV.Milestone.Masks.stage_evm2' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms stage_evm2 + +/-- info: 'SolarTV.Milestone.Masks.stage_evm3' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms stage_evm3 + +/-- info: 'SolarTV.Milestone.Masks.stage_evm4' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms stage_evm4 + +/-- info: 'SolarTV.Milestone.Masks.stage_evm5' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms stage_evm5 + +/-- info: 'SolarTV.Milestone.Masks.stage_evm6' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms stage_evm6 + +/-- info: 'SolarTV.Milestone.Masks.masks_mir_to_evmir' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms masks_mir_to_evmir + +end SolarTV.Milestone.Masks diff --git a/Certified/masks/bytecode.hex b/Certified/masks/bytecode.hex new file mode 100644 index 00000000..65beef34 --- /dev/null +++ b/Certified/masks/bytecode.hex @@ -0,0 +1 @@ +34603e575f3560e01c806341fa8d2d14604b5780636d4ce63c146042578063812600df03603e5760243610603e575f5460043581019081106071575f55005b5f5ffd5b5f545f5260205ff35b6024361060ff6004351117603e5760043560ff8116600f82165f5281810360835760205ff35b6011602052634e487b715f526024601cfd5b6d010200000002000000020000000760205260405260605263ed572b275f526064601cfd diff --git a/Certified/masks/gen/Masks/Bytecode.lean b/Certified/masks/gen/Masks/Bytecode.lean new file mode 100644 index 00000000..a347b183 --- /dev/null +++ b/Certified/masks/gen/Masks/Bytecode.lean @@ -0,0 +1,24 @@ +-- solar-lean-stage: kind=bytecode index=0 pass=assemble +/-! Generated by `solar -Zemit-lean-stages` for `Masks`; do not edit. -/ + +namespace SolarTV.Export.Masks + +/-- The runtime bytecode, byte by byte. -/ +def bytecode : List Nat := + [0x34, 0x60, 0x3e, 0x57, 0x5f, 0x35, 0x60, 0xe0, 0x1c, 0x80, 0x63, 0x41, 0xfa, 0x8d, 0x2d, 0x14, + 0x60, 0x4b, 0x57, 0x80, 0x63, 0x6d, 0x4c, 0xe6, 0x3c, 0x14, 0x60, 0x42, 0x57, 0x80, 0x63, 0x81, + 0x26, 0x00, 0xdf, 0x03, 0x60, 0x3e, 0x57, 0x60, 0x24, 0x36, 0x10, 0x60, 0x3e, 0x57, 0x5f, 0x54, + 0x60, 0x04, 0x35, 0x81, 0x01, 0x90, 0x81, 0x10, 0x60, 0x71, 0x57, 0x5f, 0x55, 0x00, 0x5b, 0x5f, + 0x5f, 0xfd, 0x5b, 0x5f, 0x54, 0x5f, 0x52, 0x60, 0x20, 0x5f, 0xf3, 0x5b, 0x60, 0x24, 0x36, 0x10, + 0x60, 0xff, 0x60, 0x04, 0x35, 0x11, 0x17, 0x60, 0x3e, 0x57, 0x60, 0x04, 0x35, 0x60, 0xff, 0x81, + 0x16, 0x60, 0x0f, 0x82, 0x16, 0x5f, 0x52, 0x81, 0x81, 0x03, 0x60, 0x83, 0x57, 0x60, 0x20, 0x5f, + 0xf3, 0x5b, 0x60, 0x11, 0x60, 0x20, 0x52, 0x63, 0x4e, 0x48, 0x7b, 0x71, 0x5f, 0x52, 0x60, 0x24, + 0x60, 0x1c, 0xfd, 0x5b, 0x6d, 0x01, 0x02, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x02, 0x00, + 0x00, 0x00, 0x07, 0x60, 0x20, 0x52, 0x60, 0x40, 0x52, 0x60, 0x60, 0x52, 0x63, 0xed, 0x57, 0x2b, + 0x27, 0x5f, 0x52, 0x60, 0x64, 0x60, 0x1c, 0xfd] + +/-- The runtime bytecode in hex, as `--emit=bin-runtime` prints it. -/ +def bytecodeHex : String := + "34603e575f3560e01c806341fa8d2d14604b5780636d4ce63c146042578063812600df03603e5760243610603e575f5460043581019081106071575f55005b5f5ffd5b5f545f5260205ff35b6024361060ff6004351117603e5760043560ff8116600f82165f5281810360835760205ff35b6011602052634e487b715f526024601cfd5b6d010200000002000000020000000760205260405260605263ed572b275f526064601cfd" + +end SolarTV.Export.Masks diff --git a/Certified/masks/gen/Masks/Evm1.lean b/Certified/masks/gen/Masks/Evm1.lean new file mode 100644 index 00000000..902102a1 --- /dev/null +++ b/Certified/masks/gen/Masks/Evm1.lean @@ -0,0 +1,139 @@ +-- solar-lean-stage: kind=evm index=1 pass=peephole-early +import SolarTV.EVMIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `Masks`; do not edit. -/ + +namespace SolarTV.Export.Masks + +/-- The runtime EVM IR after `peephole-early`. -/ +def evm1 : EVM.Program.Program := + { blocks := [ + -- bb0 + [.effect .callvalue 0, + .jumpi 5, + .jump 1], + -- bb1 + [.op (.stack (.push 0)), + .effect .calldataload 1, + .op (.stack (.push 224)), + .op (.stack .shr), + .op (.stack (.dup 0)), + .op (.stack (.push 0x41fa8d2d)), + .op (.stack .eq), + .jumpi 4, + .op (.stack (.dup 0)), + .op (.stack (.push 0x6d4ce63c)), + .op (.stack .eq), + .jumpi 3, + .op (.stack (.dup 0)), + .op (.stack (.push 0x812600df)), + .op (.stack .eq), + .jumpi 2, + .jump 5], + -- bb2 + [.jump 6], + -- bb3 + [.jump 11], + -- bb4 + [.jump 12], + -- bb5 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb6 + [.op (.stack (.push 36)), + .op (.stack .calldatasize), + .op (.stack .lt), + .jumpi 10, + .jump 7], + -- bb7 + [.op (.stack (.push 0)), + .effect .sload 1, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.dup 1)), + .op (.stack .add), + .op (.stack (.swap 0)), + .op (.stack (.dup 1)), + .op (.stack .lt), + .jumpi 9, + .jump 8], + -- bb8 + [.op (.stack (.push 0)), + .effect .sstore 2, + .stop], + -- bb9 + [.op (.stack (.push 17)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 0x4e487b71)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 36)), + .op (.stack (.push 28)), + .revert], + -- bb10 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb11 + [.op (.stack (.push 0)), + .effect .sload 1, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb12 + [.op (.stack (.push 36)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack (.push 255)), + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack .gt), + .op (.stack .or), + .jumpi 17, + .jump 13], + -- bb13 + [.op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 255)), + .op (.stack (.dup 1)), + .op (.stack .and), + .op (.stack (.push 15)), + .op (.stack (.dup 2)), + .op (.stack .and), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.dup 1)), + .op (.stack (.dup 1)), + .op (.stack .sub), + .jumpi 15, + .jump 14], + -- bb14 + [.op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb15 + [.op (.stack (.push 0x102000000020000000200000007)), + .jump 16], + -- bb16 + [.op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op .store, + .op (.stack (.push 96)), + .op .store, + .op (.stack (.push 0xed572b27)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 100)), + .op (.stack (.push 28)), + .revert], + -- bb17 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert]] } + +end SolarTV.Export.Masks diff --git a/Certified/masks/gen/Masks/Evm2.lean b/Certified/masks/gen/Masks/Evm2.lean new file mode 100644 index 00000000..c272319c --- /dev/null +++ b/Certified/masks/gen/Masks/Evm2.lean @@ -0,0 +1,121 @@ +-- solar-lean-stage: kind=evm index=2 pass=cfg-simplify-early +import SolarTV.EVMIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `Masks`; do not edit. -/ + +namespace SolarTV.Export.Masks + +/-- The runtime EVM IR after `cfg-simplify-early`. -/ +def evm2 : EVM.Program.Program := + { blocks := [ + -- bb0 + [.effect .callvalue 0, + .jumpi 1, + .op (.stack (.push 0)), + .effect .calldataload 1, + .op (.stack (.push 224)), + .op (.stack .shr), + .op (.stack (.dup 0)), + .op (.stack (.push 0x41fa8d2d)), + .op (.stack .eq), + .jumpi 6, + .op (.stack (.dup 0)), + .op (.stack (.push 0x6d4ce63c)), + .op (.stack .eq), + .jumpi 5, + .op (.stack (.dup 0)), + .op (.stack (.push 0x812600df)), + .op (.stack .eq), + .jumpi 2, + .jump 1], + -- bb5 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb6 + [.op (.stack (.push 36)), + .op (.stack .calldatasize), + .op (.stack .lt), + .jumpi 4, + .op (.stack (.push 0)), + .effect .sload 1, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.dup 1)), + .op (.stack .add), + .op (.stack (.swap 0)), + .op (.stack (.dup 1)), + .op (.stack .lt), + .jumpi 3, + .op (.stack (.push 0)), + .effect .sstore 2, + .stop], + -- bb9 + [.op (.stack (.push 17)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 0x4e487b71)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 36)), + .op (.stack (.push 28)), + .revert], + -- bb10 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb11 + [.op (.stack (.push 0)), + .effect .sload 1, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb12 + [.op (.stack (.push 36)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack (.push 255)), + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack .gt), + .op (.stack .or), + .jumpi 8, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 255)), + .op (.stack (.dup 1)), + .op (.stack .and), + .op (.stack (.push 15)), + .op (.stack (.dup 2)), + .op (.stack .and), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.dup 1)), + .op (.stack (.dup 1)), + .op (.stack .sub), + .jumpi 7, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb15 + [.op (.stack (.push 0x102000000020000000200000007)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op .store, + .op (.stack (.push 96)), + .op .store, + .op (.stack (.push 0xed572b27)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 100)), + .op (.stack (.push 28)), + .revert], + -- bb17 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert]] } + +end SolarTV.Export.Masks diff --git a/Certified/masks/gen/Masks/Evm3.lean b/Certified/masks/gen/Masks/Evm3.lean new file mode 100644 index 00000000..b2a00fed --- /dev/null +++ b/Certified/masks/gen/Masks/Evm3.lean @@ -0,0 +1,121 @@ +-- solar-lean-stage: kind=evm index=3 pass=block-layout +import SolarTV.EVMIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `Masks`; do not edit. -/ + +namespace SolarTV.Export.Masks + +/-- The runtime EVM IR after `block-layout`. -/ +def evm3 : EVM.Program.Program := + { blocks := [ + -- bb0 + [.effect .callvalue 0, + .jumpi 1, + .op (.stack (.push 0)), + .effect .calldataload 1, + .op (.stack (.push 224)), + .op (.stack .shr), + .op (.stack (.dup 0)), + .op (.stack (.push 0x41fa8d2d)), + .op (.stack .eq), + .jumpi 4, + .op (.stack (.dup 0)), + .op (.stack (.push 0x6d4ce63c)), + .op (.stack .eq), + .jumpi 3, + .op (.stack (.dup 0)), + .op (.stack (.push 0x812600df)), + .op (.stack .eq), + .jumpi 2, + .jump 1], + -- bb5 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb6 + [.op (.stack (.push 36)), + .op (.stack .calldatasize), + .op (.stack .lt), + .jumpi 6, + .op (.stack (.push 0)), + .effect .sload 1, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.dup 1)), + .op (.stack .add), + .op (.stack (.swap 0)), + .op (.stack (.dup 1)), + .op (.stack .lt), + .jumpi 5, + .op (.stack (.push 0)), + .effect .sstore 2, + .stop], + -- bb11 + [.op (.stack (.push 0)), + .effect .sload 1, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb12 + [.op (.stack (.push 36)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack (.push 255)), + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack .gt), + .op (.stack .or), + .jumpi 8, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 255)), + .op (.stack (.dup 1)), + .op (.stack .and), + .op (.stack (.push 15)), + .op (.stack (.dup 2)), + .op (.stack .and), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.dup 1)), + .op (.stack (.dup 1)), + .op (.stack .sub), + .jumpi 7, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb9 + [.op (.stack (.push 17)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 0x4e487b71)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 36)), + .op (.stack (.push 28)), + .revert], + -- bb10 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb15 + [.op (.stack (.push 0x102000000020000000200000007)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op .store, + .op (.stack (.push 96)), + .op .store, + .op (.stack (.push 0xed572b27)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 100)), + .op (.stack (.push 28)), + .revert], + -- bb17 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert]] } + +end SolarTV.Export.Masks diff --git a/Certified/masks/gen/Masks/Evm4.lean b/Certified/masks/gen/Masks/Evm4.lean new file mode 100644 index 00000000..97bd42b8 --- /dev/null +++ b/Certified/masks/gen/Masks/Evm4.lean @@ -0,0 +1,121 @@ +-- solar-lean-stage: kind=evm index=4 pass=share-reverts +import SolarTV.EVMIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `Masks`; do not edit. -/ + +namespace SolarTV.Export.Masks + +/-- The runtime EVM IR after `share-reverts`. -/ +def evm4 : EVM.Program.Program := + { blocks := [ + -- bb0 + [.effect .callvalue 0, + .jumpi 1, + .op (.stack (.push 0)), + .effect .calldataload 1, + .op (.stack (.push 224)), + .op (.stack .shr), + .op (.stack (.dup 0)), + .op (.stack (.push 0x41fa8d2d)), + .op (.stack .eq), + .jumpi 4, + .op (.stack (.dup 0)), + .op (.stack (.push 0x6d4ce63c)), + .op (.stack .eq), + .jumpi 3, + .op (.stack (.dup 0)), + .op (.stack (.push 0x812600df)), + .op (.stack .sub), + .jumpi 1, + .jump 2], + -- bb5 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb6 + [.op (.stack (.push 36)), + .op (.stack .calldatasize), + .op (.stack .lt), + .jumpi 6, + .op (.stack (.push 0)), + .effect .sload 1, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.dup 1)), + .op (.stack .add), + .op (.stack (.swap 0)), + .op (.stack (.dup 1)), + .op (.stack .lt), + .jumpi 5, + .op (.stack (.push 0)), + .effect .sstore 2, + .stop], + -- bb11 + [.op (.stack (.push 0)), + .effect .sload 1, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb12 + [.op (.stack (.push 36)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack (.push 255)), + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack .gt), + .op (.stack .or), + .jumpi 8, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 255)), + .op (.stack (.dup 1)), + .op (.stack .and), + .op (.stack (.push 15)), + .op (.stack (.dup 2)), + .op (.stack .and), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.dup 1)), + .op (.stack (.dup 1)), + .op (.stack .sub), + .jumpi 7, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb9 + [.op (.stack (.push 17)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 0x4e487b71)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 36)), + .op (.stack (.push 28)), + .revert], + -- bb10 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb15 + [.op (.stack (.push 0x102000000020000000200000007)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op .store, + .op (.stack (.push 96)), + .op .store, + .op (.stack (.push 0xed572b27)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 100)), + .op (.stack (.push 28)), + .revert], + -- bb17 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert]] } + +end SolarTV.Export.Masks diff --git a/Certified/masks/gen/Masks/Evm5.lean b/Certified/masks/gen/Masks/Evm5.lean new file mode 100644 index 00000000..6953fbe3 --- /dev/null +++ b/Certified/masks/gen/Masks/Evm5.lean @@ -0,0 +1,117 @@ +-- solar-lean-stage: kind=evm index=5 pass=terminal-dedup +import SolarTV.EVMIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `Masks`; do not edit. -/ + +namespace SolarTV.Export.Masks + +/-- The runtime EVM IR after `terminal-dedup`. -/ +def evm5 : EVM.Program.Program := + { blocks := [ + -- bb0 + [.effect .callvalue 0, + .jumpi 1, + .op (.stack (.push 0)), + .effect .calldataload 1, + .op (.stack (.push 224)), + .op (.stack .shr), + .op (.stack (.dup 0)), + .op (.stack (.push 0x41fa8d2d)), + .op (.stack .eq), + .jumpi 4, + .op (.stack (.dup 0)), + .op (.stack (.push 0x6d4ce63c)), + .op (.stack .eq), + .jumpi 3, + .op (.stack (.dup 0)), + .op (.stack (.push 0x812600df)), + .op (.stack .sub), + .jumpi 1, + .jump 2], + -- bb5 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb6 + [.op (.stack (.push 36)), + .op (.stack .calldatasize), + .op (.stack .lt), + .jumpi 6, + .op (.stack (.push 0)), + .effect .sload 1, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.dup 1)), + .op (.stack .add), + .op (.stack (.swap 0)), + .op (.stack (.dup 1)), + .op (.stack .lt), + .jumpi 5, + .op (.stack (.push 0)), + .effect .sstore 2, + .stop], + -- bb11 + [.op (.stack (.push 0)), + .effect .sload 1, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb12 + [.op (.stack (.push 36)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack (.push 255)), + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack .gt), + .op (.stack .or), + .jumpi 8, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 255)), + .op (.stack (.dup 1)), + .op (.stack .and), + .op (.stack (.push 15)), + .op (.stack (.dup 2)), + .op (.stack .and), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.dup 1)), + .op (.stack (.dup 1)), + .op (.stack .sub), + .jumpi 7, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb9 + [.op (.stack (.push 17)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 0x4e487b71)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 36)), + .op (.stack (.push 28)), + .revert], + -- bb10 + [.jump 1], + -- bb15 + [.op (.stack (.push 0x102000000020000000200000007)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op .store, + .op (.stack (.push 96)), + .op .store, + .op (.stack (.push 0xed572b27)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 100)), + .op (.stack (.push 28)), + .revert], + -- bb17 + [.jump 1]] } + +end SolarTV.Export.Masks diff --git a/Certified/masks/gen/Masks/Evm6.lean b/Certified/masks/gen/Masks/Evm6.lean new file mode 100644 index 00000000..491c9dc0 --- /dev/null +++ b/Certified/masks/gen/Masks/Evm6.lean @@ -0,0 +1,111 @@ +-- solar-lean-stage: kind=evm index=6 pass=cfg-simplify-early +import SolarTV.EVMIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `Masks`; do not edit. -/ + +namespace SolarTV.Export.Masks + +/-- The runtime EVM IR after `cfg-simplify-early`. -/ +def evm6 : EVM.Program.Program := + { blocks := [ + -- bb0 + [.effect .callvalue 0, + .jumpi 1, + .op (.stack (.push 0)), + .effect .calldataload 1, + .op (.stack (.push 224)), + .op (.stack .shr), + .op (.stack (.dup 0)), + .op (.stack (.push 0x41fa8d2d)), + .op (.stack .eq), + .jumpi 3, + .op (.stack (.dup 0)), + .op (.stack (.push 0x6d4ce63c)), + .op (.stack .eq), + .jumpi 2, + .op (.stack (.dup 0)), + .op (.stack (.push 0x812600df)), + .op (.stack .sub), + .jumpi 1, + .op (.stack (.push 36)), + .op (.stack .calldatasize), + .op (.stack .lt), + .jumpi 1, + .op (.stack (.push 0)), + .effect .sload 1, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.dup 1)), + .op (.stack .add), + .op (.stack (.swap 0)), + .op (.stack (.dup 1)), + .op (.stack .lt), + .jumpi 4, + .op (.stack (.push 0)), + .effect .sstore 2, + .stop], + -- bb5 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb11 + [.op (.stack (.push 0)), + .effect .sload 1, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb12 + [.op (.stack (.push 36)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack (.push 255)), + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack .gt), + .op (.stack .or), + .jumpi 1, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 255)), + .op (.stack (.dup 1)), + .op (.stack .and), + .op (.stack (.push 15)), + .op (.stack (.dup 2)), + .op (.stack .and), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.dup 1)), + .op (.stack (.dup 1)), + .op (.stack .sub), + .jumpi 5, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb9 + [.op (.stack (.push 17)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 0x4e487b71)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 36)), + .op (.stack (.push 28)), + .revert], + -- bb15 + [.op (.stack (.push 0x102000000020000000200000007)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op .store, + .op (.stack (.push 96)), + .op .store, + .op (.stack (.push 0xed572b27)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 100)), + .op (.stack (.push 28)), + .revert]] } + +end SolarTV.Export.Masks diff --git a/Certified/masks/gen/Masks/Manifest.lean b/Certified/masks/gen/Masks/Manifest.lean new file mode 100644 index 00000000..608b12a5 --- /dev/null +++ b/Certified/masks/gen/Masks/Manifest.lean @@ -0,0 +1,45 @@ +-- solar-lean-stage: kind=manifest index=0 pass=none +/-! Generated by `solar -Zemit-lean-stages` for `Masks`; do not edit. + +What the stages of this directory were compiled from and by. `stages` lists each +stage's file, its definition, the pass whose output it is, and the SHA-256 of the file. +-/ + +namespace SolarTV.Export.Masks.Manifest + +def sources : List (String × String) := + [("solar-tv/milestone/masks/masks.sol", "07aea44de99801385666f8de90ffb4edfba9f7ce9c874a89392f7d19fcd34d8e")] + +def compiler : String := "0.8.38+commit.4a7d9ede.solar.0.3.0-dev" + +def arguments : List String := + ["solar-tv/milestone/masks/masks.sol", + "-Ogas", + "--evm-version", + "osaka", + "--emit=bin-runtime", + "-Zemit-lean-stages=solar-tv/milestone/masks/gen"] + +def evmVersion : String := "osaka" + +def optimization : String := "Gas" + +def stages : List (String × String × String × String) := + [("Stage0", "stage0", "lower-evm-shaped", "f2ac4b40da1be05e27ff460d855b8469c615cb90e23ed4139c5bae770ff392a6"), + ("Mir1", "mir1", "place-reads", "7e81d3e6e02f5b7189eef395a33abdbb0ddc9ab401f45e3f6e295a8e13b2767e"), + ("Mir2", "mir2", "lower-assumes", "35d0dd1e7e4afcc9a8a678114e8fca543da1b45cc2c6d229dd50f65269fc7d5b"), + ("Sched", "sched", "stack-schedule", "8566264d5747d0e0f9b124d30e112b2e4fb6634bf30f8901c8dc5314aa5e6b29"), + ("Evm1", "evm1", "peephole-early", "45f1839dac2612d414827e908263089e616b479f5ae0fa3b5508a0390ebd0f1f"), + ("Evm2", "evm2", "cfg-simplify-early", "1107efe81108adac52babb7c8ea8ccf956dc728be4c423ebe7a1a8d6fe969694"), + ("Evm3", "evm3", "block-layout", "b874dab5e2fd397b3cdb4078ce26400188307e4edca63b6c052da46c5015bf3c"), + ("Evm4", "evm4", "share-reverts", "1605fd858459857f03b1f6082f5992ec5f89bbac6dc80c39250c6e5a7ab723eb"), + ("Evm5", "evm5", "terminal-dedup", "cae48f97a155f2f2ac01ac680ac86f1674ad292b3fce1150bfe04be45931918b"), + ("Evm6", "evm6", "cfg-simplify-early", "4a76d0ff6a898e1dfbfc1acdab9d6fd29b5ccae1d45008fa06df18a932378cfd"), + ("Bytecode", "bytecode", "assemble", "1d90f37bbc86f39a55f34258e7f04d1806cf26bed44399f55c57260a5c7d3d2f")] + +def bytecodeHex : String := + "34603e575f3560e01c806341fa8d2d14604b5780636d4ce63c146042578063812600df03603e5760243610603e575f5460043581019081106071575f55005b5f5ffd5b5f545f5260205ff35b6024361060ff6004351117603e5760043560ff8116600f82165f5281810360835760205ff35b6011602052634e487b715f526024601cfd5b6d010200000002000000020000000760205260405260605263ed572b275f526064601cfd" + +def bytecodeSha256 : String := "43bd25ba9b579f0623a2d7181e6cf0f1094c31f96143a747470cd125d735dfe7" + +end SolarTV.Export.Masks.Manifest diff --git a/Certified/masks/gen/Masks/Mir1.lean b/Certified/masks/gen/Masks/Mir1.lean new file mode 100644 index 00000000..39fb6354 --- /dev/null +++ b/Certified/masks/gen/Masks/Mir1.lean @@ -0,0 +1,101 @@ +-- solar-lean-stage: kind=mir index=1 pass=place-reads +import SolarTV.MIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `Masks`; do not edit. -/ + +namespace SolarTV.Export.Masks + +/-- The lowered MIR module after `place-reads`. -/ +def mir1 : MIR.Lowered.Module := + { entry := 3, + functions := [ + -- @inc + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 13) .calldatasize [], + .pure 15 .lt [.value 13, .const 36]], + .branch (.value 15) 3 4⟩, + -- bb1 + ⟨[], + [.effect none .mstore [.const 32, .const 17], + .effect none .mstore [.const 0, .const 0x4e487b71]], + .revert (.const 28) (.const 36)⟩, + -- bb2 + ⟨[], + [.effect none .sstore [.const 0, .value 4]], + .stop⟩, + -- bb3 + ⟨[], + [], + .revert (.const 0) (.const 0)⟩, + -- bb4 + ⟨[], + [.effect (some 17) .calldataload [.const 4], + .effect (some 2) .sload [.const 0], + .pure 4 .add [.value 2, .value 17], + .pure 5 .lt [.value 4, .value 2]], + .branch (.value 5) 1 2⟩] }, + -- @get + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 2) .sload [.const 0], + .effect none .mstore [.const 0, .value 2]], + .ret (.const 0) (.const 32)⟩] }, + -- @low + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 6) .calldatasize [], + .pure 8 .lt [.value 6, .const 36], + .effect (some 10) .calldataload [.const 4], + .pure 12 .gt [.value 10, .const 255], + .pure 23 .or [.value 8, .value 12]], + .branch (.value 23) 1 2⟩, + -- bb1 + ⟨[], + [], + .revert (.const 0) (.const 0)⟩, + -- bb2 + ⟨[], + [.effect (some 24) .calldataload [.const 4], + .pure 19 .and [.value 24, .const 255], + .pure 20 .and [.value 24, .const 15], + .effect none .mstore [.const 0, .value 20], + .assume false .eq [.value 19, .value 24]], + .ret (.const 0) (.const 32)⟩] }, + -- @entry + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 0) .callvalue [], + .ne 2 (.value 0) (.const 0)], + .branch (.value 2) 5 1⟩, + -- bb1 + ⟨[], + [.effect (some 4) .calldataload [.const 0], + .pure 6 .shr [.const 224, .value 4]], + .switch (.value 6) 5 [(.const 0x41fa8d2d, 2), (.const 0x6d4ce63c, 3), (.const 0x812600df, 4)]⟩, + -- bb2 + ⟨[], + [], + .tailCall 2 []⟩, + -- bb3 + ⟨[], + [], + .tailCall 1 []⟩, + -- bb4 + ⟨[], + [], + .tailCall 0 []⟩, + -- bb5 + ⟨[], + [], + .revert (.const 0) (.const 0)⟩] }] } + +end SolarTV.Export.Masks diff --git a/Certified/masks/gen/Masks/Mir2.lean b/Certified/masks/gen/Masks/Mir2.lean new file mode 100644 index 00000000..0737f92f --- /dev/null +++ b/Certified/masks/gen/Masks/Mir2.lean @@ -0,0 +1,116 @@ +-- solar-lean-stage: kind=mir index=2 pass=lower-assumes +import SolarTV.MIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `Masks`; do not edit. -/ + +namespace SolarTV.Export.Masks + +/-- The lowered MIR module after `lower-assumes`. -/ +def mir2 : MIR.Lowered.Module := + { entry := 3, + functions := [ + -- @inc + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 13) .calldatasize [], + .pure 15 .lt [.value 13, .const 36]], + .branch (.value 15) 3 4⟩, + -- bb1 + ⟨[], + [.effect none .mstore [.const 32, .const 17], + .effect none .mstore [.const 0, .const 0x4e487b71]], + .revert (.const 28) (.const 36)⟩, + -- bb2 + ⟨[], + [.effect none .sstore [.const 0, .value 4]], + .stop⟩, + -- bb3 + ⟨[], + [], + .revert (.const 0) (.const 0)⟩, + -- bb4 + ⟨[], + [.effect (some 17) .calldataload [.const 4], + .effect (some 2) .sload [.const 0], + .pure 4 .add [.value 2, .value 17], + .pure 5 .lt [.value 4, .value 2]], + .branch (.value 5) 1 2⟩] }, + -- @get + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 2) .sload [.const 0], + .effect none .mstore [.const 0, .value 2]], + .ret (.const 0) (.const 32)⟩] }, + -- @low + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 6) .calldatasize [], + .pure 8 .lt [.value 6, .const 36], + .effect (some 10) .calldataload [.const 4], + .pure 12 .gt [.value 10, .const 255], + .pure 23 .or [.value 8, .value 12]], + .branch (.value 23) 1 2⟩, + -- bb1 + ⟨[], + [], + .revert (.const 0) (.const 0)⟩, + -- bb2 + ⟨[], + [.effect (some 24) .calldataload [.const 4], + .pure 19 .and [.value 24, .const 255], + .pure 20 .and [.value 24, .const 15], + .effect none .mstore [.const 0, .value 20], + .ne 25 (.value 19) (.value 24)], + .branch (.value 25) 4 5⟩, + -- bb3 + ⟨[(27, [(4, .const 0x102000000020000000200000007)]), (28, [(4, .value 19)]), (29, [(4, .value 24)])], + [.effect none .mstore [.const 32, .value 27], + .effect none .mstore [.const 64, .value 28], + .effect none .mstore [.const 96, .value 29], + .effect none .mstore [.const 0, .const 0xed572b27]], + .revert (.const 28) (.const 100)⟩, + -- bb4 + ⟨[], + [], + .jump 3⟩, + -- bb5 + ⟨[], + [], + .ret (.const 0) (.const 32)⟩] }, + -- @entry + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 0) .callvalue [], + .ne 2 (.value 0) (.const 0)], + .branch (.value 2) 5 1⟩, + -- bb1 + ⟨[], + [.effect (some 4) .calldataload [.const 0], + .pure 6 .shr [.const 224, .value 4]], + .switch (.value 6) 5 [(.const 0x41fa8d2d, 2), (.const 0x6d4ce63c, 3), (.const 0x812600df, 4)]⟩, + -- bb2 + ⟨[], + [], + .tailCall 2 []⟩, + -- bb3 + ⟨[], + [], + .tailCall 1 []⟩, + -- bb4 + ⟨[], + [], + .tailCall 0 []⟩, + -- bb5 + ⟨[], + [], + .revert (.const 0) (.const 0)⟩] }] } + +end SolarTV.Export.Masks diff --git a/Certified/masks/gen/Masks/Sched.lean b/Certified/masks/gen/Masks/Sched.lean new file mode 100644 index 00000000..c1b17dea --- /dev/null +++ b/Certified/masks/gen/Masks/Sched.lean @@ -0,0 +1,140 @@ +-- solar-lean-stage: kind=sched index=0 pass=stack-schedule +import SolarTV.EVMIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `Masks`; do not edit. -/ + +namespace SolarTV.Export.Masks + +/-- The runtime EVM IR as stack scheduling emits it. -/ +def sched : EVM.Program.Program := + { blocks := [ + -- bb0 + [.effect .callvalue 0, + .jumpi 5, + .jump 1], + -- bb1 + [.op (.stack (.push 0)), + .effect .calldataload 1, + .op (.stack (.push 224)), + .op (.stack .shr), + .op (.stack (.dup 0)), + .op (.stack (.push 0x41fa8d2d)), + .op (.stack .eq), + .jumpi 4, + .op (.stack (.dup 0)), + .op (.stack (.push 0x6d4ce63c)), + .op (.stack .eq), + .jumpi 3, + .op (.stack (.dup 0)), + .op (.stack (.push 0x812600df)), + .op (.stack .eq), + .jumpi 2, + .jump 5], + -- bb2 + [.jump 6], + -- bb3 + [.jump 11], + -- bb4 + [.jump 12], + -- bb5 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb6 + [.op (.stack (.push 36)), + .op (.stack .calldatasize), + .op (.stack .lt), + .jumpi 10, + .jump 7], + -- bb7 + [.op (.stack (.push 0)), + .effect .sload 1, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.dup 1)), + .op (.stack .add), + .op (.stack (.swap 0)), + .op (.stack (.dup 1)), + .op (.stack .lt), + .jumpi 9, + .jump 8], + -- bb8 + [.op (.stack (.push 0)), + .effect .sstore 2, + .stop], + -- bb9 + [.op (.stack (.push 17)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 0x4e487b71)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 36)), + .op (.stack (.push 28)), + .revert], + -- bb10 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb11 + [.op (.stack (.push 0)), + .effect .sload 1, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb12 + [.op (.stack (.push 36)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack (.push 255)), + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack .gt), + .op (.stack .or), + .jumpi 17, + .jump 13], + -- bb13 + [.op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 255)), + .op (.stack (.dup 1)), + .op (.stack .and), + .op (.stack (.push 15)), + .op (.stack (.dup 2)), + .op (.stack .and), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.dup 1)), + .op (.stack (.dup 1)), + .op (.stack .eq), + .op (.stack .iszero), + .jumpi 15, + .jump 14], + -- bb14 + [.op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb15 + [.op (.stack (.push 0x102000000020000000200000007)), + .jump 16], + -- bb16 + [.op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op .store, + .op (.stack (.push 96)), + .op .store, + .op (.stack (.push 0xed572b27)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 100)), + .op (.stack (.push 28)), + .revert], + -- bb17 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert]] } + +end SolarTV.Export.Masks diff --git a/Certified/masks/gen/Masks/Stage0.lean b/Certified/masks/gen/Masks/Stage0.lean new file mode 100644 index 00000000..5b7cf0a4 --- /dev/null +++ b/Certified/masks/gen/Masks/Stage0.lean @@ -0,0 +1,100 @@ +-- solar-lean-stage: kind=mir index=0 pass=lower-evm-shaped +import SolarTV.MIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `Masks`; do not edit. -/ + +namespace SolarTV.Export.Masks + +/-- The first lowered MIR module, after `lower-evm-shaped` advanced the phase. -/ +def stage0 : MIR.Lowered.Module := + { entry := 3, + functions := [ + -- @inc + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 13) .calldatasize [], + .pure 15 .lt [.value 13, .const 36]], + .branch (.value 15) 3 4⟩, + -- bb1 + ⟨[], + [.effect none .mstore [.const 32, .const 17], + .effect none .mstore [.const 0, .const 0x4e487b71]], + .revert (.const 28) (.const 36)⟩, + -- bb2 + ⟨[], + [.effect none .sstore [.const 0, .value 4]], + .stop⟩, + -- bb3 + ⟨[], + [], + .revert (.const 0) (.const 0)⟩, + -- bb4 + ⟨[], + [.effect (some 17) .calldataload [.const 4], + .effect (some 2) .sload [.const 0], + .pure 4 .add [.value 2, .value 17], + .pure 5 .lt [.value 4, .value 2]], + .branch (.value 5) 1 2⟩] }, + -- @get + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 2) .sload [.const 0], + .effect none .mstore [.const 0, .value 2]], + .ret (.const 0) (.const 32)⟩] }, + -- @low + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 6) .calldatasize [], + .pure 8 .lt [.value 6, .const 36], + .effect (some 10) .calldataload [.const 4], + .pure 12 .gt [.value 10, .const 255], + .pure 23 .or [.value 8, .value 12]], + .branch (.value 23) 1 2⟩, + -- bb1 + ⟨[], + [], + .revert (.const 0) (.const 0)⟩, + -- bb2 + ⟨[], + [.pure 19 .and [.value 10, .const 255], + .pure 20 .and [.value 10, .const 15], + .effect none .mstore [.const 0, .value 20], + .assume false .eq [.value 19, .value 10]], + .ret (.const 0) (.const 32)⟩] }, + -- @entry + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 0) .callvalue [], + .ne 2 (.value 0) (.const 0)], + .branch (.value 2) 5 1⟩, + -- bb1 + ⟨[], + [.effect (some 4) .calldataload [.const 0], + .pure 6 .shr [.const 224, .value 4]], + .switch (.value 6) 5 [(.const 0x41fa8d2d, 2), (.const 0x6d4ce63c, 3), (.const 0x812600df, 4)]⟩, + -- bb2 + ⟨[], + [], + .tailCall 2 []⟩, + -- bb3 + ⟨[], + [], + .tailCall 1 []⟩, + -- bb4 + ⟨[], + [], + .tailCall 0 []⟩, + -- bb5 + ⟨[], + [], + .revert (.const 0) (.const 0)⟩] }] } + +end SolarTV.Export.Masks diff --git a/Certified/masks/gen/Masks/manifest.json b/Certified/masks/gen/Masks/manifest.json new file mode 100644 index 00000000..e1d9de40 --- /dev/null +++ b/Certified/masks/gen/Masks/manifest.json @@ -0,0 +1,113 @@ +{ + "arguments": [ + "solar-tv/milestone/masks/masks.sol", + "-Ogas", + "--evm-version", + "osaka", + "--emit=bin-runtime", + "-Zemit-lean-stages=solar-tv/milestone/masks/gen" + ], + "bytecode": "34603e575f3560e01c806341fa8d2d14604b5780636d4ce63c146042578063812600df03603e5760243610603e575f5460043581019081106071575f55005b5f5ffd5b5f545f5260205ff35b6024361060ff6004351117603e5760043560ff8116600f82165f5281810360835760205ff35b6011602052634e487b715f526024601cfd5b6d010200000002000000020000000760205260405260605263ed572b275f526064601cfd", + "bytecode_sha256": "43bd25ba9b579f0623a2d7181e6cf0f1094c31f96143a747470cd125d735dfe7", + "compiler": "0.8.38+commit.4a7d9ede.solar.0.3.0-dev", + "contract": "Masks", + "evm_version": "osaka", + "optimization": "Gas", + "options": "CompileOpts { input: [\"solar-tv/milestone/masks/masks.sol\"], import_remappings: [], base_path: None, include_paths: [], allow_paths: [], no_import_callback: false, language: Solidity, threads: 4, evm_version: Osaka, stop_after: None, optimization: Gas, optimizer_runs: None, revert_strings: Default, libraries: [], out_dir: None, emit: [BinRuntime], standard_json: false, color: Auto, verbose: false, pretty_json: false, pretty_json_err: false, error_format: Human, error_format_human: Unicode, diagnostic_width: None, no_warnings: false, allow: [], _unstable: [\"emit-lean-stages=solar-tv/milestone/masks/gen\"], unstable: UnstableOpts { ui_testing: false, track_diagnostics: false, parse_yul: false, no_resolve_imports: false, recover_incomplete_input: false, dump: None, ast_stats: false, hir_stats: false, standard_json_stats: false, span_visitor: false, print_max_storage_sizes: false, print_natspec: false, mir_pipeline: None, evm_ir_pipeline: None, print_after_each: false, pass_diff: false, debugify: None, debugify_output: None, solar_tv: None, validate_ir: None, time_passes: false, codegen_all_functions: false, switch_lowering: Auto, switch_max_gas_code_growth: None, switch_max_bit_slice_gas_code_growth: None, tune: None, pack_wide_jump_tables: false, check_analyses: None, prove_analyses: None, validate_passes: None, validate_passes_fault: None, validate_backend: None, validate_backend_fault: None, validate_evm_ir_passes: None, validate_assembly: false, validate_assembly_fault: None, emit_lean_stages: Some(\"solar-tv/milestone/masks/gen\"), forget_gcx: true, help: (), _non_exhaustive: () }, _non_exhaustive: () }", + "sources": [ + { + "path": "solar-tv/milestone/masks/masks.sol", + "sha256": "07aea44de99801385666f8de90ffb4edfba9f7ce9c874a89392f7d19fcd34d8e" + } + ], + "stages": [ + { + "definition": "stage0", + "file": "Stage0.lean", + "index": 0, + "kind": "mir", + "pass": "lower-evm-shaped", + "sha256": "f2ac4b40da1be05e27ff460d855b8469c615cb90e23ed4139c5bae770ff392a6" + }, + { + "definition": "mir1", + "file": "Mir1.lean", + "index": 1, + "kind": "mir", + "pass": "place-reads", + "sha256": "7e81d3e6e02f5b7189eef395a33abdbb0ddc9ab401f45e3f6e295a8e13b2767e" + }, + { + "definition": "mir2", + "file": "Mir2.lean", + "index": 2, + "kind": "mir", + "pass": "lower-assumes", + "sha256": "35d0dd1e7e4afcc9a8a678114e8fca543da1b45cc2c6d229dd50f65269fc7d5b" + }, + { + "definition": "sched", + "file": "Sched.lean", + "index": 0, + "kind": "sched", + "pass": "stack-schedule", + "sha256": "8566264d5747d0e0f9b124d30e112b2e4fb6634bf30f8901c8dc5314aa5e6b29" + }, + { + "definition": "evm1", + "file": "Evm1.lean", + "index": 1, + "kind": "evm", + "pass": "peephole-early", + "sha256": "45f1839dac2612d414827e908263089e616b479f5ae0fa3b5508a0390ebd0f1f" + }, + { + "definition": "evm2", + "file": "Evm2.lean", + "index": 2, + "kind": "evm", + "pass": "cfg-simplify-early", + "sha256": "1107efe81108adac52babb7c8ea8ccf956dc728be4c423ebe7a1a8d6fe969694" + }, + { + "definition": "evm3", + "file": "Evm3.lean", + "index": 3, + "kind": "evm", + "pass": "block-layout", + "sha256": "b874dab5e2fd397b3cdb4078ce26400188307e4edca63b6c052da46c5015bf3c" + }, + { + "definition": "evm4", + "file": "Evm4.lean", + "index": 4, + "kind": "evm", + "pass": "share-reverts", + "sha256": "1605fd858459857f03b1f6082f5992ec5f89bbac6dc80c39250c6e5a7ab723eb" + }, + { + "definition": "evm5", + "file": "Evm5.lean", + "index": 5, + "kind": "evm", + "pass": "terminal-dedup", + "sha256": "cae48f97a155f2f2ac01ac680ac86f1674ad292b3fce1150bfe04be45931918b" + }, + { + "definition": "evm6", + "file": "Evm6.lean", + "index": 6, + "kind": "evm", + "pass": "cfg-simplify-early", + "sha256": "4a76d0ff6a898e1dfbfc1acdab9d6fd29b5ccae1d45008fa06df18a932378cfd" + }, + { + "definition": "bytecode", + "file": "Bytecode.lean", + "index": 0, + "kind": "bytecode", + "pass": "assemble", + "sha256": "1d90f37bbc86f39a55f34258e7f04d1806cf26bed44399f55c57260a5c7d3d2f" + } + ] +} diff --git a/Certified/masks/masks.sol b/Certified/masks/masks.sol new file mode 100644 index 00000000..9fcb7994 --- /dev/null +++ b/Certified/masks/masks.sol @@ -0,0 +1,14 @@ +// SPDX-License-Identifier: UNLICENSED +pragma solidity ^0.8.28; +contract Masks { + uint256 x; + function inc(uint256 d) external { + x += d; + } + function get() external view returns (uint256) { + return x; + } + function low(uint8 a) external pure returns (uint8) { + return a & 0x0f; + } +} diff --git a/Certified/masks/options b/Certified/masks/options new file mode 100644 index 00000000..da38913c --- /dev/null +++ b/Certified/masks/options @@ -0,0 +1,3 @@ +-Ogas +--evm-version +osaka diff --git a/Certified/mulx/Proofs.lean b/Certified/mulx/Proofs.lean new file mode 100644 index 00000000..9c08ead2 --- /dev/null +++ b/Certified/mulx/Proofs.lean @@ -0,0 +1,3 @@ +-- Generated by solar-tv/milestone/certify.py; do not edit. +import mulx.Proofs.Stages +import mulx.Proofs.Assembly diff --git a/Certified/mulx/Proofs/Assembly.lean b/Certified/mulx/Proofs/Assembly.lean new file mode 100644 index 00000000..331d063b --- /dev/null +++ b/Certified/mulx/Proofs/Assembly.lean @@ -0,0 +1,42 @@ +-- Generated by solar-tv/milestone/certify.py; do not edit. +import W1Proofs.Items +import mulx.gen.Main.Evm8 +import mulx.gen.Main.Bytecode + +/-! The final EVM IR of `Main` against its bytecode, by the assembly checker's walk: the bytecode decodes, linearly from offset 0, to exactly the program's instructions, each jumped-to block at its `JUMPDEST`. -/ + +namespace SolarTV.Milestone.Mulx + +open SolarTV.Assembly SolarTV.Export.Main SolarTV.Milestone.W1 + +set_option maxRecDepth 100000 + +/-- The items of the final EVM IR. -/ +def items : List Item := (itemsOf evm8).getD [] + +theorem items_eq : itemsOf evm8 = some items := by decide + +/-- The layout: each jumped-to block at the bytecode's next `JUMPDEST`. The walk checks it. -/ +def offset (label : Nat) : Nat := if label = 1 then 0x1d else if label = 2 then 0x21 else if label = 3 then 0x33 else if label = 4 then 0x6d else 0 + +/-- The instructions the walk reaches, each at its offset. -/ +def stream : List (Nat × Instr) := (walk bytecode offset 0 items).getD [] + +/-- The checker's walk accepts the exported bytecode against the final EVM IR. -/ +theorem walk_eq : walk bytecode offset 0 items = some stream := by decide +kernel + +theorem checked : Walk bytecode offset 0 items stream := walk_sound walk_eq + +/-- The bytecode's linear decoding is the final EVM IR's instructions at the layout. -/ +theorem decodes : decodeFrom bytecode (bytecode.length + 1) 0 = stream := + walk_decodes checked _ (by have := walk_length checked; omega) + +/-- info: 'SolarTV.Milestone.Mulx.walk_eq' depends on axioms: [propext, Quot.sound] -/ +#guard_msgs in +#print axioms walk_eq + +/-- info: 'SolarTV.Milestone.Mulx.decodes' depends on axioms: [propext, Quot.sound] -/ +#guard_msgs in +#print axioms decodes + +end SolarTV.Milestone.Mulx diff --git a/Certified/mulx/Proofs/Runs/Evm1.lean b/Certified/mulx/Proofs/Runs/Evm1.lean new file mode 100644 index 00000000..a5e5511f --- /dev/null +++ b/Certified/mulx/Proofs/Runs/Evm1.lean @@ -0,0 +1,22 @@ +-- Generated by solar-tv/milestone/certify.py; do not edit. +import W1Proofs.Tactic +import W1Proofs.Axioms +import mulx.gen.Main.Evm1 +import mulx.gen.Main.Sched + +/-! `cfg-simplify-early`: its input and output end in the same result on every call. -/ + +namespace SolarTV.Milestone.Mulx + +open Machine SolarTV.Export.Main SolarTV.Milestone.W1 + +set_option maxHeartbeats 2000000 in +theorem evm1_run (o : Oracle) (call : Call) : + EVM.Program.run o sched call 15 = EVM.Program.run o evm1 call 8 := by + sym_exec + +/-- info: 'SolarTV.Milestone.Mulx.evm1_run' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within evm1_run + +end SolarTV.Milestone.Mulx diff --git a/Certified/mulx/Proofs/Runs/Evm2.lean b/Certified/mulx/Proofs/Runs/Evm2.lean new file mode 100644 index 00000000..2f227c2c --- /dev/null +++ b/Certified/mulx/Proofs/Runs/Evm2.lean @@ -0,0 +1,22 @@ +-- Generated by solar-tv/milestone/certify.py; do not edit. +import W1Proofs.Tactic +import W1Proofs.Axioms +import mulx.gen.Main.Evm2 +import mulx.gen.Main.Evm1 + +/-! `compact-pushes`: its input and output end in the same result on every call. -/ + +namespace SolarTV.Milestone.Mulx + +open Machine SolarTV.Export.Main SolarTV.Milestone.W1 + +set_option maxHeartbeats 2000000 in +theorem evm2_run (o : Oracle) (call : Call) : + EVM.Program.run o evm1 call 8 = EVM.Program.run o evm2 call 8 := by + sym_exec + +/-- info: 'SolarTV.Milestone.Mulx.evm2_run' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within evm2_run + +end SolarTV.Milestone.Mulx diff --git a/Certified/mulx/Proofs/Runs/Evm3.lean b/Certified/mulx/Proofs/Runs/Evm3.lean new file mode 100644 index 00000000..ff7ae833 --- /dev/null +++ b/Certified/mulx/Proofs/Runs/Evm3.lean @@ -0,0 +1,22 @@ +-- Generated by solar-tv/milestone/certify.py; do not edit. +import W1Proofs.Tactic +import W1Proofs.Axioms +import mulx.gen.Main.Evm3 +import mulx.gen.Main.Evm2 + +/-! `block-layout`: its input and output end in the same result on every call. -/ + +namespace SolarTV.Milestone.Mulx + +open Machine SolarTV.Export.Main SolarTV.Milestone.W1 + +set_option maxHeartbeats 2000000 in +theorem evm3_run (o : Oracle) (call : Call) : + EVM.Program.run o evm2 call 8 = EVM.Program.run o evm3 call 8 := by + sym_exec + +/-- info: 'SolarTV.Milestone.Mulx.evm3_run' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within evm3_run + +end SolarTV.Milestone.Mulx diff --git a/Certified/mulx/Proofs/Runs/Evm4.lean b/Certified/mulx/Proofs/Runs/Evm4.lean new file mode 100644 index 00000000..9a7543a8 --- /dev/null +++ b/Certified/mulx/Proofs/Runs/Evm4.lean @@ -0,0 +1,22 @@ +-- Generated by solar-tv/milestone/certify.py; do not edit. +import W1Proofs.Tactic +import W1Proofs.Axioms +import mulx.gen.Main.Evm4 +import mulx.gen.Main.Evm3 + +/-! `terminal-dedup`: its input and output end in the same result on every call. -/ + +namespace SolarTV.Milestone.Mulx + +open Machine SolarTV.Export.Main SolarTV.Milestone.W1 + +set_option maxHeartbeats 2000000 in +theorem evm4_run (o : Oracle) (call : Call) : + EVM.Program.run o evm3 call 8 = EVM.Program.run o evm4 call 8 := by + sym_exec + +/-- info: 'SolarTV.Milestone.Mulx.evm4_run' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within evm4_run + +end SolarTV.Milestone.Mulx diff --git a/Certified/mulx/Proofs/Runs/Evm5.lean b/Certified/mulx/Proofs/Runs/Evm5.lean new file mode 100644 index 00000000..6b065a64 --- /dev/null +++ b/Certified/mulx/Proofs/Runs/Evm5.lean @@ -0,0 +1,22 @@ +-- Generated by solar-tv/milestone/certify.py; do not edit. +import W1Proofs.Tactic +import W1Proofs.Axioms +import mulx.gen.Main.Evm5 +import mulx.gen.Main.Evm4 + +/-! `cfg-simplify-early`: its input and output end in the same result on every call. -/ + +namespace SolarTV.Milestone.Mulx + +open Machine SolarTV.Export.Main SolarTV.Milestone.W1 + +set_option maxHeartbeats 2000000 in +theorem evm5_run (o : Oracle) (call : Call) : + EVM.Program.run o evm4 call 8 = EVM.Program.run o evm5 call 5 := by + sym_exec + +/-- info: 'SolarTV.Milestone.Mulx.evm5_run' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within evm5_run + +end SolarTV.Milestone.Mulx diff --git a/Certified/mulx/Proofs/Runs/Evm6.lean b/Certified/mulx/Proofs/Runs/Evm6.lean new file mode 100644 index 00000000..afb061af --- /dev/null +++ b/Certified/mulx/Proofs/Runs/Evm6.lean @@ -0,0 +1,22 @@ +-- Generated by solar-tv/milestone/certify.py; do not edit. +import W1Proofs.Tactic +import W1Proofs.Axioms +import mulx.gen.Main.Evm6 +import mulx.gen.Main.Evm5 + +/-! `block-layout`: its input and output end in the same result on every call. -/ + +namespace SolarTV.Milestone.Mulx + +open Machine SolarTV.Export.Main SolarTV.Milestone.W1 + +set_option maxHeartbeats 2000000 in +theorem evm6_run (o : Oracle) (call : Call) : + EVM.Program.run o evm5 call 5 = EVM.Program.run o evm6 call 5 := by + sym_exec + +/-- info: 'SolarTV.Milestone.Mulx.evm6_run' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within evm6_run + +end SolarTV.Milestone.Mulx diff --git a/Certified/mulx/Proofs/Runs/Evm7.lean b/Certified/mulx/Proofs/Runs/Evm7.lean new file mode 100644 index 00000000..7f7a77bb --- /dev/null +++ b/Certified/mulx/Proofs/Runs/Evm7.lean @@ -0,0 +1,22 @@ +-- Generated by solar-tv/milestone/certify.py; do not edit. +import W1Proofs.Tactic +import W1Proofs.Axioms +import mulx.gen.Main.Evm7 +import mulx.gen.Main.Evm6 + +/-! `stack-reschedule`: its input and output end in the same result on every call. -/ + +namespace SolarTV.Milestone.Mulx + +open Machine SolarTV.Export.Main SolarTV.Milestone.W1 + +set_option maxHeartbeats 2000000 in +theorem evm7_run (o : Oracle) (call : Call) : + EVM.Program.run o evm6 call 5 = EVM.Program.run o evm7 call 5 := by + sym_exec + +/-- info: 'SolarTV.Milestone.Mulx.evm7_run' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within evm7_run + +end SolarTV.Milestone.Mulx diff --git a/Certified/mulx/Proofs/Runs/Evm8.lean b/Certified/mulx/Proofs/Runs/Evm8.lean new file mode 100644 index 00000000..4f64de03 --- /dev/null +++ b/Certified/mulx/Proofs/Runs/Evm8.lean @@ -0,0 +1,22 @@ +-- Generated by solar-tv/milestone/certify.py; do not edit. +import W1Proofs.Tactic +import W1Proofs.Axioms +import mulx.gen.Main.Evm8 +import mulx.gen.Main.Evm7 + +/-! `terminal-layout`: its input and output end in the same result on every call. -/ + +namespace SolarTV.Milestone.Mulx + +open Machine SolarTV.Export.Main SolarTV.Milestone.W1 + +set_option maxHeartbeats 2000000 in +theorem evm8_run (o : Oracle) (call : Call) : + EVM.Program.run o evm7 call 5 = EVM.Program.run o evm8 call 5 := by + sym_exec + +/-- info: 'SolarTV.Milestone.Mulx.evm8_run' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within evm8_run + +end SolarTV.Milestone.Mulx diff --git a/Certified/mulx/Proofs/Runs/Mir1.lean b/Certified/mulx/Proofs/Runs/Mir1.lean new file mode 100644 index 00000000..9eeab531 --- /dev/null +++ b/Certified/mulx/Proofs/Runs/Mir1.lean @@ -0,0 +1,22 @@ +-- Generated by solar-tv/milestone/certify.py; do not edit. +import W1Proofs.Tactic +import W1Proofs.Axioms +import mulx.gen.Main.Mir1 +import mulx.gen.Main.Stage0 + +/-! `place-reads`: its input and output end in the same result on every call. -/ + +namespace SolarTV.Milestone.Mulx + +open Machine SolarTV.Export.Main SolarTV.Milestone.W1 + +set_option maxHeartbeats 2000000 in +theorem mir1_run (o : Oracle) (call : Call) : + MIR.Lowered.Module.run o stage0 call 15 = MIR.Lowered.Module.run o mir1 call 15 := by + sym_exec + +/-- info: 'SolarTV.Milestone.Mulx.mir1_run' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within mir1_run + +end SolarTV.Milestone.Mulx diff --git a/Certified/mulx/Proofs/Runs/Mir2.lean b/Certified/mulx/Proofs/Runs/Mir2.lean new file mode 100644 index 00000000..a1cc5560 --- /dev/null +++ b/Certified/mulx/Proofs/Runs/Mir2.lean @@ -0,0 +1,22 @@ +-- Generated by solar-tv/milestone/certify.py; do not edit. +import W1Proofs.Tactic +import W1Proofs.Axioms +import mulx.gen.Main.Mir2 +import mulx.gen.Main.Mir1 + +/-! `spell-width-tests`: its input and output end in the same result on every call. -/ + +namespace SolarTV.Milestone.Mulx + +open Machine SolarTV.Export.Main SolarTV.Milestone.W1 + +set_option maxHeartbeats 2000000 in +theorem mir2_run (o : Oracle) (call : Call) : + MIR.Lowered.Module.run o mir1 call 15 = MIR.Lowered.Module.run o mir2 call 15 := by + sym_exec + +/-- info: 'SolarTV.Milestone.Mulx.mir2_run' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within mir2_run + +end SolarTV.Milestone.Mulx diff --git a/Certified/mulx/Proofs/Runs/Mir3.lean b/Certified/mulx/Proofs/Runs/Mir3.lean new file mode 100644 index 00000000..6a1c903e --- /dev/null +++ b/Certified/mulx/Proofs/Runs/Mir3.lean @@ -0,0 +1,22 @@ +-- Generated by solar-tv/milestone/certify.py; do not edit. +import W1Proofs.Tactic +import W1Proofs.Axioms +import mulx.gen.Main.Mir3 +import mulx.gen.Main.Mir2 + +/-! `evm-inst-schedule`: its input and output end in the same result on every call. -/ + +namespace SolarTV.Milestone.Mulx + +open Machine SolarTV.Export.Main SolarTV.Milestone.W1 + +set_option maxHeartbeats 2000000 in +theorem mir3_run (o : Oracle) (call : Call) : + MIR.Lowered.Module.run o mir2 call 15 = MIR.Lowered.Module.run o mir3 call 15 := by + sym_exec + +/-- info: 'SolarTV.Milestone.Mulx.mir3_run' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within mir3_run + +end SolarTV.Milestone.Mulx diff --git a/Certified/mulx/Proofs/Runs/Sched.lean b/Certified/mulx/Proofs/Runs/Sched.lean new file mode 100644 index 00000000..d2e2b813 --- /dev/null +++ b/Certified/mulx/Proofs/Runs/Sched.lean @@ -0,0 +1,22 @@ +-- Generated by solar-tv/milestone/certify.py; do not edit. +import W1Proofs.Tactic +import W1Proofs.Axioms +import mulx.gen.Main.Sched +import mulx.gen.Main.Mir3 + +/-! Stack scheduling: the last lowered MIR and the scheduled EVM IR end in the same result on every call. -/ + +namespace SolarTV.Milestone.Mulx + +open Machine SolarTV.Export.Main SolarTV.Milestone.W1 + +set_option maxHeartbeats 2000000 in +theorem sched_run (o : Oracle) (call : Call) : + MIR.Lowered.Module.run o mir3 call 15 = EVM.Program.run o sched call 15 := by + sym_exec + +/-- info: 'SolarTV.Milestone.Mulx.sched_run' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within sched_run + +end SolarTV.Milestone.Mulx diff --git a/Certified/mulx/Proofs/Runs/Stage0.lean b/Certified/mulx/Proofs/Runs/Stage0.lean new file mode 100644 index 00000000..b0f63512 --- /dev/null +++ b/Certified/mulx/Proofs/Runs/Stage0.lean @@ -0,0 +1,21 @@ +-- Generated by solar-tv/milestone/certify.py; do not edit. +import W1Proofs.Tactic +import W1Proofs.Axioms +import mulx.gen.Main.Stage0 + +/-! The first lowered MIR ends on every call within 15 blocks, the number of its blocks. -/ + +namespace SolarTV.Milestone.Mulx + +open Machine SolarTV.Export.Main SolarTV.Milestone.W1 + +set_option maxHeartbeats 2000000 in +theorem stage0_ends (o : Oracle) (call : Call) : + (MIR.Lowered.Module.run o stage0 call 15).isSome = true := by + sym_exec + +/-- info: 'SolarTV.Milestone.Mulx.stage0_ends' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within stage0_ends + +end SolarTV.Milestone.Mulx diff --git a/Certified/mulx/Proofs/Stages.lean b/Certified/mulx/Proofs/Stages.lean new file mode 100644 index 00000000..2f21028a --- /dev/null +++ b/Certified/mulx/Proofs/Stages.lean @@ -0,0 +1,211 @@ +-- Generated by solar-tv/milestone/certify.py; do not edit. +import mulx.Proofs.Runs.Stage0 +import mulx.Proofs.Runs.Mir1 +import mulx.Proofs.Runs.Mir2 +import mulx.Proofs.Runs.Mir3 +import mulx.Proofs.Runs.Sched +import mulx.Proofs.Runs.Evm1 +import mulx.Proofs.Runs.Evm2 +import mulx.Proofs.Runs.Evm3 +import mulx.Proofs.Runs.Evm4 +import mulx.Proofs.Runs.Evm5 +import mulx.Proofs.Runs.Evm6 +import mulx.Proofs.Runs.Evm7 +import mulx.Proofs.Runs.Evm8 +import W1Proofs.Stage +import SolarTV.Composition + +/-! The backend stages of `Main`, each proved on every call (`anyCall`: any calldata, call value and storage) under every oracle, and chained from the first lowered MIR `stage0` to the final EVM IR `evm8`. Fuels are the programs' block counts. -/ + +namespace SolarTV.Milestone.Mulx + +open Machine SolarTV.Export.Main SolarTV.Milestone.W1 + +/-- `place-reads`: stage0 to mir1. -/ +theorem stage_mir1 (o : Oracle) : Stage (mirSem o) (mirSem o) stage0 mir1 anyCall := + stage_of_runs (A := MIR.Lowered.moduleLayer) (B := MIR.Lowered.moduleLayer) 15 15 (fun call _ => stage0_ends o call) + (fun call _ => mir1_run o call) + +theorem mir1_ends (o : Oracle) : ∀ call, anyCall call → + (MIR.Lowered.Module.run o mir1 call 15).isSome = true := + ends_of_runs (A := MIR.Lowered.moduleLayer) (B := MIR.Lowered.moduleLayer) + (o := o) (p := stage0) (q := mir1) (n := 15) (m := 15) (fun call _ => stage0_ends o call) + (fun call _ => mir1_run o call) + +/-- `spell-width-tests`: mir1 to mir2. -/ +theorem stage_mir2 (o : Oracle) : Stage (mirSem o) (mirSem o) mir1 mir2 anyCall := + stage_of_runs (A := MIR.Lowered.moduleLayer) (B := MIR.Lowered.moduleLayer) 15 15 (mir1_ends o) + (fun call _ => mir2_run o call) + +theorem mir2_ends (o : Oracle) : ∀ call, anyCall call → + (MIR.Lowered.Module.run o mir2 call 15).isSome = true := + ends_of_runs (A := MIR.Lowered.moduleLayer) (B := MIR.Lowered.moduleLayer) + (o := o) (p := mir1) (q := mir2) (n := 15) (m := 15) (mir1_ends o) + (fun call _ => mir2_run o call) + +/-- `evm-inst-schedule`: mir2 to mir3. -/ +theorem stage_mir3 (o : Oracle) : Stage (mirSem o) (mirSem o) mir2 mir3 anyCall := + stage_of_runs (A := MIR.Lowered.moduleLayer) (B := MIR.Lowered.moduleLayer) 15 15 (mir2_ends o) + (fun call _ => mir3_run o call) + +theorem mir3_ends (o : Oracle) : ∀ call, anyCall call → + (MIR.Lowered.Module.run o mir3 call 15).isSome = true := + ends_of_runs (A := MIR.Lowered.moduleLayer) (B := MIR.Lowered.moduleLayer) + (o := o) (p := mir2) (q := mir3) (n := 15) (m := 15) (mir2_ends o) + (fun call _ => mir3_run o call) + +/-- `stack-schedule`: mir3 to sched. -/ +theorem stage_sched (o : Oracle) : Stage (mirSem o) (evmirSem o) mir3 sched anyCall := + stage_of_runs (A := MIR.Lowered.moduleLayer) (B := EVM.Program.layer) 15 15 (mir3_ends o) + (fun call _ => sched_run o call) + +theorem sched_ends (o : Oracle) : ∀ call, anyCall call → + (EVM.Program.run o sched call 15).isSome = true := + ends_of_runs (A := MIR.Lowered.moduleLayer) (B := EVM.Program.layer) + (o := o) (p := mir3) (q := sched) (n := 15) (m := 15) (mir3_ends o) + (fun call _ => sched_run o call) + +/-- `cfg-simplify-early`: sched to evm1. -/ +theorem stage_evm1 (o : Oracle) : Stage (evmirSem o) (evmirSem o) sched evm1 anyCall := + stage_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) 15 8 (sched_ends o) + (fun call _ => evm1_run o call) + +theorem evm1_ends (o : Oracle) : ∀ call, anyCall call → + (EVM.Program.run o evm1 call 8).isSome = true := + ends_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) + (o := o) (p := sched) (q := evm1) (n := 15) (m := 8) (sched_ends o) + (fun call _ => evm1_run o call) + +/-- `compact-pushes`: evm1 to evm2. -/ +theorem stage_evm2 (o : Oracle) : Stage (evmirSem o) (evmirSem o) evm1 evm2 anyCall := + stage_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) 8 8 (evm1_ends o) + (fun call _ => evm2_run o call) + +theorem evm2_ends (o : Oracle) : ∀ call, anyCall call → + (EVM.Program.run o evm2 call 8).isSome = true := + ends_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) + (o := o) (p := evm1) (q := evm2) (n := 8) (m := 8) (evm1_ends o) + (fun call _ => evm2_run o call) + +/-- `block-layout`: evm2 to evm3. -/ +theorem stage_evm3 (o : Oracle) : Stage (evmirSem o) (evmirSem o) evm2 evm3 anyCall := + stage_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) 8 8 (evm2_ends o) + (fun call _ => evm3_run o call) + +theorem evm3_ends (o : Oracle) : ∀ call, anyCall call → + (EVM.Program.run o evm3 call 8).isSome = true := + ends_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) + (o := o) (p := evm2) (q := evm3) (n := 8) (m := 8) (evm2_ends o) + (fun call _ => evm3_run o call) + +/-- `terminal-dedup`: evm3 to evm4. -/ +theorem stage_evm4 (o : Oracle) : Stage (evmirSem o) (evmirSem o) evm3 evm4 anyCall := + stage_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) 8 8 (evm3_ends o) + (fun call _ => evm4_run o call) + +theorem evm4_ends (o : Oracle) : ∀ call, anyCall call → + (EVM.Program.run o evm4 call 8).isSome = true := + ends_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) + (o := o) (p := evm3) (q := evm4) (n := 8) (m := 8) (evm3_ends o) + (fun call _ => evm4_run o call) + +/-- `cfg-simplify-early`: evm4 to evm5. -/ +theorem stage_evm5 (o : Oracle) : Stage (evmirSem o) (evmirSem o) evm4 evm5 anyCall := + stage_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) 8 5 (evm4_ends o) + (fun call _ => evm5_run o call) + +theorem evm5_ends (o : Oracle) : ∀ call, anyCall call → + (EVM.Program.run o evm5 call 5).isSome = true := + ends_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) + (o := o) (p := evm4) (q := evm5) (n := 8) (m := 5) (evm4_ends o) + (fun call _ => evm5_run o call) + +/-- `block-layout`: evm5 to evm6. -/ +theorem stage_evm6 (o : Oracle) : Stage (evmirSem o) (evmirSem o) evm5 evm6 anyCall := + stage_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) 5 5 (evm5_ends o) + (fun call _ => evm6_run o call) + +theorem evm6_ends (o : Oracle) : ∀ call, anyCall call → + (EVM.Program.run o evm6 call 5).isSome = true := + ends_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) + (o := o) (p := evm5) (q := evm6) (n := 5) (m := 5) (evm5_ends o) + (fun call _ => evm6_run o call) + +/-- `stack-reschedule`: evm6 to evm7. -/ +theorem stage_evm7 (o : Oracle) : Stage (evmirSem o) (evmirSem o) evm6 evm7 anyCall := + stage_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) 5 5 (evm6_ends o) + (fun call _ => evm7_run o call) + +theorem evm7_ends (o : Oracle) : ∀ call, anyCall call → + (EVM.Program.run o evm7 call 5).isSome = true := + ends_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) + (o := o) (p := evm6) (q := evm7) (n := 5) (m := 5) (evm6_ends o) + (fun call _ => evm7_run o call) + +/-- `terminal-layout`: evm7 to evm8. -/ +theorem stage_evm8 (o : Oracle) : Stage (evmirSem o) (evmirSem o) evm7 evm8 anyCall := + stage_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) 5 5 (evm7_ends o) + (fun call _ => evm8_run o call) + +/-- The compilation from the first lowered MIR to the final EVM IR. -/ +def compilation : Compilation := + ⟨stage0, [mir1, mir2, mir3], sched, [evm1, evm2, evm3, evm4, evm5, evm6, evm7, evm8]⟩ + +/-- Every stage from the first lowered MIR to the final EVM IR, chained by the library's composition, on every call. -/ +theorem mulx_mir_to_evmir (o : Oracle) : Stage (mirSem o) (evmirSem o) stage0 evm8 anyCall := + mir_to_evmir o anyCall compilation ⟨stage_mir1 o, stage_mir2 o, stage_mir3 o, trivial⟩ (stage_sched o) + ⟨stage_evm1 o, stage_evm2 o, stage_evm3 o, stage_evm4 o, stage_evm5 o, stage_evm6 o, stage_evm7 o, stage_evm8 o, trivial⟩ + +/-- info: 'SolarTV.Milestone.Mulx.stage_mir1' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms stage_mir1 + +/-- info: 'SolarTV.Milestone.Mulx.stage_mir2' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms stage_mir2 + +/-- info: 'SolarTV.Milestone.Mulx.stage_mir3' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms stage_mir3 + +/-- info: 'SolarTV.Milestone.Mulx.stage_sched' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms stage_sched + +/-- info: 'SolarTV.Milestone.Mulx.stage_evm1' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms stage_evm1 + +/-- info: 'SolarTV.Milestone.Mulx.stage_evm2' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms stage_evm2 + +/-- info: 'SolarTV.Milestone.Mulx.stage_evm3' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms stage_evm3 + +/-- info: 'SolarTV.Milestone.Mulx.stage_evm4' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms stage_evm4 + +/-- info: 'SolarTV.Milestone.Mulx.stage_evm5' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms stage_evm5 + +/-- info: 'SolarTV.Milestone.Mulx.stage_evm6' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms stage_evm6 + +/-- info: 'SolarTV.Milestone.Mulx.stage_evm7' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms stage_evm7 + +/-- info: 'SolarTV.Milestone.Mulx.stage_evm8' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms stage_evm8 + +/-- info: 'SolarTV.Milestone.Mulx.mulx_mir_to_evmir' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms mulx_mir_to_evmir + +end SolarTV.Milestone.Mulx diff --git a/Certified/mulx/bytecode.hex b/Certified/mulx/bytecode.hex new file mode 100644 index 00000000..1e570744 --- /dev/null +++ b/Certified/mulx/bytecode.hex @@ -0,0 +1 @@ +34601d575f3560e01c806316ea58cb14606d5780639db20e58146033575b5f5ffd5b6011602052634e487b715f526024601cfd5b60243560101c6064361060ff600435111717601d576004602435604435913502808280159202928304141715602157806001555f5260205ff35b60243560101c6044361060ff600435111717601d575f5460ff81166004350260ff81119160ff1916178060081c61ffff16602435028060101c90921760215762ffff0019169060081b175f55 diff --git a/Certified/mulx/gen/Main/Bytecode.lean b/Certified/mulx/gen/Main/Bytecode.lean new file mode 100644 index 00000000..7f0a5991 --- /dev/null +++ b/Certified/mulx/gen/Main/Bytecode.lean @@ -0,0 +1,25 @@ +-- solar-lean-stage: kind=bytecode index=0 pass=assemble +/-! Generated by `solar -Zemit-lean-stages` for `Main`; do not edit. -/ + +namespace SolarTV.Export.Main + +/-- The runtime bytecode, byte by byte. -/ +def bytecode : List Nat := + [0x34, 0x60, 0x1d, 0x57, 0x5f, 0x35, 0x60, 0xe0, 0x1c, 0x80, 0x63, 0x16, 0xea, 0x58, 0xcb, 0x14, + 0x60, 0x6d, 0x57, 0x80, 0x63, 0x9d, 0xb2, 0x0e, 0x58, 0x14, 0x60, 0x33, 0x57, 0x5b, 0x5f, 0x5f, + 0xfd, 0x5b, 0x60, 0x11, 0x60, 0x20, 0x52, 0x63, 0x4e, 0x48, 0x7b, 0x71, 0x5f, 0x52, 0x60, 0x24, + 0x60, 0x1c, 0xfd, 0x5b, 0x60, 0x24, 0x35, 0x60, 0x10, 0x1c, 0x60, 0x64, 0x36, 0x10, 0x60, 0xff, + 0x60, 0x04, 0x35, 0x11, 0x17, 0x17, 0x60, 0x1d, 0x57, 0x60, 0x04, 0x60, 0x24, 0x35, 0x60, 0x44, + 0x35, 0x91, 0x35, 0x02, 0x80, 0x82, 0x80, 0x15, 0x92, 0x02, 0x92, 0x83, 0x04, 0x14, 0x17, 0x15, + 0x60, 0x21, 0x57, 0x80, 0x60, 0x01, 0x55, 0x5f, 0x52, 0x60, 0x20, 0x5f, 0xf3, 0x5b, 0x60, 0x24, + 0x35, 0x60, 0x10, 0x1c, 0x60, 0x44, 0x36, 0x10, 0x60, 0xff, 0x60, 0x04, 0x35, 0x11, 0x17, 0x17, + 0x60, 0x1d, 0x57, 0x5f, 0x54, 0x60, 0xff, 0x81, 0x16, 0x60, 0x04, 0x35, 0x02, 0x60, 0xff, 0x81, + 0x11, 0x91, 0x60, 0xff, 0x19, 0x16, 0x17, 0x80, 0x60, 0x08, 0x1c, 0x61, 0xff, 0xff, 0x16, 0x60, + 0x24, 0x35, 0x02, 0x80, 0x60, 0x10, 0x1c, 0x90, 0x92, 0x17, 0x60, 0x21, 0x57, 0x62, 0xff, 0xff, + 0x00, 0x19, 0x16, 0x90, 0x60, 0x08, 0x1b, 0x17, 0x5f, 0x55] + +/-- The runtime bytecode in hex, as `--emit=bin-runtime` prints it. -/ +def bytecodeHex : String := + "34601d575f3560e01c806316ea58cb14606d5780639db20e58146033575b5f5ffd5b6011602052634e487b715f526024601cfd5b60243560101c6064361060ff600435111717601d576004602435604435913502808280159202928304141715602157806001555f5260205ff35b60243560101c6044361060ff600435111717601d575f5460ff81166004350260ff81119160ff1916178060081c61ffff16602435028060101c90921760215762ffff0019169060081b175f55" + +end SolarTV.Export.Main diff --git a/Certified/mulx/gen/Main/Evm1.lean b/Certified/mulx/gen/Main/Evm1.lean new file mode 100644 index 00000000..a248e82f --- /dev/null +++ b/Certified/mulx/gen/Main/Evm1.lean @@ -0,0 +1,159 @@ +-- solar-lean-stage: kind=evm index=1 pass=cfg-simplify-early +import SolarTV.EVMIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `Main`; do not edit. -/ + +namespace SolarTV.Export.Main + +/-- The runtime EVM IR after `cfg-simplify-early`. -/ +def evm1 : EVM.Program.Program := + { blocks := [ + -- bb0 + [.effect .callvalue 0, + .jumpi 1, + .op (.stack (.push 0)), + .effect .calldataload 1, + .op (.stack (.push 224)), + .op (.stack .shr), + .op (.stack (.dup 0)), + .op (.stack (.push 0x16ea58cb)), + .op (.stack .eq), + .jumpi 2, + .op (.stack (.dup 0)), + .op (.stack (.push 0x9db20e58)), + .op (.stack .eq), + .jumpi 5, + .jump 1], + -- bb4 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb5 + [.op (.stack (.push 36)), + .effect .calldataload 1, + .op (.stack (.push 16)), + .op (.stack .shr), + .op (.stack (.push 68)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack (.push 255)), + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack .gt), + .op (.stack .or), + .op (.stack .or), + .jumpi 4, + .op (.stack (.push 0)), + .effect .sload 1, + .op (.stack (.push 255)), + .op (.stack (.dup 1)), + .op (.stack .and), + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack .mul), + .op (.stack (.push 255)), + .op (.stack (.dup 1)), + .op (.stack .gt), + .op (.stack (.swap 1)), + .op (.stack (.push 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff00)), + .op (.stack .and), + .op (.stack .or), + .op (.stack (.dup 0)), + .op (.stack (.push 8)), + .op (.stack .shr), + .op (.stack (.push 65535)), + .op (.stack .and), + .op (.stack (.push 36)), + .effect .calldataload 1, + .op (.stack .mul), + .op (.stack (.dup 0)), + .op (.stack (.push 16)), + .op (.stack .shr), + .op (.stack (.swap 0)), + .op (.stack (.swap 2)), + .op (.stack .or), + .jumpi 3, + .op (.stack (.push 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffff0000ff)), + .op (.stack .and), + .op (.stack (.swap 0)), + .op (.stack (.push 8)), + .op (.stack .shl), + .op (.stack .or), + .op (.stack (.push 0)), + .effect .sstore 2, + .stop], + -- bb8 + [.op (.stack (.push 17)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 0x4e487b71)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 36)), + .op (.stack (.push 28)), + .revert], + -- bb9 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb10 + [.op (.stack (.push 36)), + .effect .calldataload 1, + .op (.stack (.push 16)), + .op (.stack .shr), + .op (.stack (.push 100)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack (.push 255)), + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack .gt), + .op (.stack .or), + .op (.stack .or), + .jumpi 7, + .op (.stack (.push 68)), + .effect .calldataload 1, + .op (.stack (.push 36)), + .effect .calldataload 1, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack .mul), + .op (.stack (.dup 1)), + .op (.stack (.dup 1)), + .op (.stack .mul), + .op (.stack (.swap 0)), + .op (.stack (.dup 2)), + .op (.stack .iszero), + .op (.stack (.swap 2)), + .op (.stack (.dup 2)), + .op (.stack .div), + .op (.stack .eq), + .op (.stack (.swap 0)), + .op (.stack (.swap 1)), + .op (.stack .or), + .op (.stack .iszero), + .jumpi 6, + .op (.stack (.dup 0)), + .op (.stack (.push 1)), + .effect .sstore 2, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb13 + [.op (.stack (.push 17)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 0x4e487b71)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 36)), + .op (.stack (.push 28)), + .revert], + -- bb14 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert]] } + +end SolarTV.Export.Main diff --git a/Certified/mulx/gen/Main/Evm2.lean b/Certified/mulx/gen/Main/Evm2.lean new file mode 100644 index 00000000..7162fb24 --- /dev/null +++ b/Certified/mulx/gen/Main/Evm2.lean @@ -0,0 +1,161 @@ +-- solar-lean-stage: kind=evm index=2 pass=compact-pushes +import SolarTV.EVMIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `Main`; do not edit. -/ + +namespace SolarTV.Export.Main + +/-- The runtime EVM IR after `compact-pushes`. -/ +def evm2 : EVM.Program.Program := + { blocks := [ + -- bb0 + [.effect .callvalue 0, + .jumpi 1, + .op (.stack (.push 0)), + .effect .calldataload 1, + .op (.stack (.push 224)), + .op (.stack .shr), + .op (.stack (.dup 0)), + .op (.stack (.push 0x16ea58cb)), + .op (.stack .eq), + .jumpi 2, + .op (.stack (.dup 0)), + .op (.stack (.push 0x9db20e58)), + .op (.stack .eq), + .jumpi 5, + .jump 1], + -- bb4 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb5 + [.op (.stack (.push 36)), + .effect .calldataload 1, + .op (.stack (.push 16)), + .op (.stack .shr), + .op (.stack (.push 68)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack (.push 255)), + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack .gt), + .op (.stack .or), + .op (.stack .or), + .jumpi 4, + .op (.stack (.push 0)), + .effect .sload 1, + .op (.stack (.push 255)), + .op (.stack (.dup 1)), + .op (.stack .and), + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack .mul), + .op (.stack (.push 255)), + .op (.stack (.dup 1)), + .op (.stack .gt), + .op (.stack (.swap 1)), + .op (.stack (.push 255)), + .op (.stack .not), + .op (.stack .and), + .op (.stack .or), + .op (.stack (.dup 0)), + .op (.stack (.push 8)), + .op (.stack .shr), + .op (.stack (.push 65535)), + .op (.stack .and), + .op (.stack (.push 36)), + .effect .calldataload 1, + .op (.stack .mul), + .op (.stack (.dup 0)), + .op (.stack (.push 16)), + .op (.stack .shr), + .op (.stack (.swap 0)), + .op (.stack (.swap 2)), + .op (.stack .or), + .jumpi 3, + .op (.stack (.push 0xffff00)), + .op (.stack .not), + .op (.stack .and), + .op (.stack (.swap 0)), + .op (.stack (.push 8)), + .op (.stack .shl), + .op (.stack .or), + .op (.stack (.push 0)), + .effect .sstore 2, + .stop], + -- bb8 + [.op (.stack (.push 17)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 0x4e487b71)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 36)), + .op (.stack (.push 28)), + .revert], + -- bb9 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb10 + [.op (.stack (.push 36)), + .effect .calldataload 1, + .op (.stack (.push 16)), + .op (.stack .shr), + .op (.stack (.push 100)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack (.push 255)), + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack .gt), + .op (.stack .or), + .op (.stack .or), + .jumpi 7, + .op (.stack (.push 68)), + .effect .calldataload 1, + .op (.stack (.push 36)), + .effect .calldataload 1, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack .mul), + .op (.stack (.dup 1)), + .op (.stack (.dup 1)), + .op (.stack .mul), + .op (.stack (.swap 0)), + .op (.stack (.dup 2)), + .op (.stack .iszero), + .op (.stack (.swap 2)), + .op (.stack (.dup 2)), + .op (.stack .div), + .op (.stack .eq), + .op (.stack (.swap 0)), + .op (.stack (.swap 1)), + .op (.stack .or), + .op (.stack .iszero), + .jumpi 6, + .op (.stack (.dup 0)), + .op (.stack (.push 1)), + .effect .sstore 2, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb13 + [.op (.stack (.push 17)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 0x4e487b71)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 36)), + .op (.stack (.push 28)), + .revert], + -- bb14 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert]] } + +end SolarTV.Export.Main diff --git a/Certified/mulx/gen/Main/Evm3.lean b/Certified/mulx/gen/Main/Evm3.lean new file mode 100644 index 00000000..aeb68699 --- /dev/null +++ b/Certified/mulx/gen/Main/Evm3.lean @@ -0,0 +1,161 @@ +-- solar-lean-stage: kind=evm index=3 pass=block-layout +import SolarTV.EVMIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `Main`; do not edit. -/ + +namespace SolarTV.Export.Main + +/-- The runtime EVM IR after `block-layout`. -/ +def evm3 : EVM.Program.Program := + { blocks := [ + -- bb0 + [.effect .callvalue 0, + .jumpi 1, + .op (.stack (.push 0)), + .effect .calldataload 1, + .op (.stack (.push 224)), + .op (.stack .shr), + .op (.stack (.dup 0)), + .op (.stack (.push 0x16ea58cb)), + .op (.stack .eq), + .jumpi 2, + .op (.stack (.dup 0)), + .op (.stack (.push 0x9db20e58)), + .op (.stack .eq), + .jumpi 3, + .jump 1], + -- bb4 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb5 + [.op (.stack (.push 36)), + .effect .calldataload 1, + .op (.stack (.push 16)), + .op (.stack .shr), + .op (.stack (.push 68)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack (.push 255)), + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack .gt), + .op (.stack .or), + .op (.stack .or), + .jumpi 5, + .op (.stack (.push 0)), + .effect .sload 1, + .op (.stack (.push 255)), + .op (.stack (.dup 1)), + .op (.stack .and), + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack .mul), + .op (.stack (.push 255)), + .op (.stack (.dup 1)), + .op (.stack .gt), + .op (.stack (.swap 1)), + .op (.stack (.push 255)), + .op (.stack .not), + .op (.stack .and), + .op (.stack .or), + .op (.stack (.dup 0)), + .op (.stack (.push 8)), + .op (.stack .shr), + .op (.stack (.push 65535)), + .op (.stack .and), + .op (.stack (.push 36)), + .effect .calldataload 1, + .op (.stack .mul), + .op (.stack (.dup 0)), + .op (.stack (.push 16)), + .op (.stack .shr), + .op (.stack (.swap 0)), + .op (.stack (.swap 2)), + .op (.stack .or), + .jumpi 4, + .op (.stack (.push 0xffff00)), + .op (.stack .not), + .op (.stack .and), + .op (.stack (.swap 0)), + .op (.stack (.push 8)), + .op (.stack .shl), + .op (.stack .or), + .op (.stack (.push 0)), + .effect .sstore 2, + .stop], + -- bb10 + [.op (.stack (.push 36)), + .effect .calldataload 1, + .op (.stack (.push 16)), + .op (.stack .shr), + .op (.stack (.push 100)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack (.push 255)), + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack .gt), + .op (.stack .or), + .op (.stack .or), + .jumpi 7, + .op (.stack (.push 68)), + .effect .calldataload 1, + .op (.stack (.push 36)), + .effect .calldataload 1, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack .mul), + .op (.stack (.dup 1)), + .op (.stack (.dup 1)), + .op (.stack .mul), + .op (.stack (.swap 0)), + .op (.stack (.dup 2)), + .op (.stack .iszero), + .op (.stack (.swap 2)), + .op (.stack (.dup 2)), + .op (.stack .div), + .op (.stack .eq), + .op (.stack (.swap 0)), + .op (.stack (.swap 1)), + .op (.stack .or), + .op (.stack .iszero), + .jumpi 6, + .op (.stack (.dup 0)), + .op (.stack (.push 1)), + .effect .sstore 2, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb8 + [.op (.stack (.push 17)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 0x4e487b71)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 36)), + .op (.stack (.push 28)), + .revert], + -- bb9 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb13 + [.op (.stack (.push 17)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 0x4e487b71)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 36)), + .op (.stack (.push 28)), + .revert], + -- bb14 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert]] } + +end SolarTV.Export.Main diff --git a/Certified/mulx/gen/Main/Evm4.lean b/Certified/mulx/gen/Main/Evm4.lean new file mode 100644 index 00000000..7de7c98f --- /dev/null +++ b/Certified/mulx/gen/Main/Evm4.lean @@ -0,0 +1,149 @@ +-- solar-lean-stage: kind=evm index=4 pass=terminal-dedup +import SolarTV.EVMIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `Main`; do not edit. -/ + +namespace SolarTV.Export.Main + +/-- The runtime EVM IR after `terminal-dedup`. -/ +def evm4 : EVM.Program.Program := + { blocks := [ + -- bb0 + [.effect .callvalue 0, + .jumpi 1, + .op (.stack (.push 0)), + .effect .calldataload 1, + .op (.stack (.push 224)), + .op (.stack .shr), + .op (.stack (.dup 0)), + .op (.stack (.push 0x16ea58cb)), + .op (.stack .eq), + .jumpi 2, + .op (.stack (.dup 0)), + .op (.stack (.push 0x9db20e58)), + .op (.stack .eq), + .jumpi 3, + .jump 1], + -- bb4 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb5 + [.op (.stack (.push 36)), + .effect .calldataload 1, + .op (.stack (.push 16)), + .op (.stack .shr), + .op (.stack (.push 68)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack (.push 255)), + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack .gt), + .op (.stack .or), + .op (.stack .or), + .jumpi 5, + .op (.stack (.push 0)), + .effect .sload 1, + .op (.stack (.push 255)), + .op (.stack (.dup 1)), + .op (.stack .and), + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack .mul), + .op (.stack (.push 255)), + .op (.stack (.dup 1)), + .op (.stack .gt), + .op (.stack (.swap 1)), + .op (.stack (.push 255)), + .op (.stack .not), + .op (.stack .and), + .op (.stack .or), + .op (.stack (.dup 0)), + .op (.stack (.push 8)), + .op (.stack .shr), + .op (.stack (.push 65535)), + .op (.stack .and), + .op (.stack (.push 36)), + .effect .calldataload 1, + .op (.stack .mul), + .op (.stack (.dup 0)), + .op (.stack (.push 16)), + .op (.stack .shr), + .op (.stack (.swap 0)), + .op (.stack (.swap 2)), + .op (.stack .or), + .jumpi 4, + .op (.stack (.push 0xffff00)), + .op (.stack .not), + .op (.stack .and), + .op (.stack (.swap 0)), + .op (.stack (.push 8)), + .op (.stack .shl), + .op (.stack .or), + .op (.stack (.push 0)), + .effect .sstore 2, + .stop], + -- bb10 + [.op (.stack (.push 36)), + .effect .calldataload 1, + .op (.stack (.push 16)), + .op (.stack .shr), + .op (.stack (.push 100)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack (.push 255)), + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack .gt), + .op (.stack .or), + .op (.stack .or), + .jumpi 7, + .op (.stack (.push 68)), + .effect .calldataload 1, + .op (.stack (.push 36)), + .effect .calldataload 1, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack .mul), + .op (.stack (.dup 1)), + .op (.stack (.dup 1)), + .op (.stack .mul), + .op (.stack (.swap 0)), + .op (.stack (.dup 2)), + .op (.stack .iszero), + .op (.stack (.swap 2)), + .op (.stack (.dup 2)), + .op (.stack .div), + .op (.stack .eq), + .op (.stack (.swap 0)), + .op (.stack (.swap 1)), + .op (.stack .or), + .op (.stack .iszero), + .jumpi 6, + .op (.stack (.dup 0)), + .op (.stack (.push 1)), + .effect .sstore 2, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb8 + [.op (.stack (.push 17)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 0x4e487b71)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 36)), + .op (.stack (.push 28)), + .revert], + -- bb9 + [.jump 1], + -- bb13 + [.jump 4], + -- bb14 + [.jump 1]] } + +end SolarTV.Export.Main diff --git a/Certified/mulx/gen/Main/Evm5.lean b/Certified/mulx/gen/Main/Evm5.lean new file mode 100644 index 00000000..78037090 --- /dev/null +++ b/Certified/mulx/gen/Main/Evm5.lean @@ -0,0 +1,143 @@ +-- solar-lean-stage: kind=evm index=5 pass=cfg-simplify-early +import SolarTV.EVMIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `Main`; do not edit. -/ + +namespace SolarTV.Export.Main + +/-- The runtime EVM IR after `cfg-simplify-early`. -/ +def evm5 : EVM.Program.Program := + { blocks := [ + -- bb0 + [.effect .callvalue 0, + .jumpi 1, + .op (.stack (.push 0)), + .effect .calldataload 1, + .op (.stack (.push 224)), + .op (.stack .shr), + .op (.stack (.dup 0)), + .op (.stack (.push 0x16ea58cb)), + .op (.stack .eq), + .jumpi 2, + .op (.stack (.dup 0)), + .op (.stack (.push 0x9db20e58)), + .op (.stack .eq), + .jumpi 3, + .jump 1], + -- bb4 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb5 + [.op (.stack (.push 36)), + .effect .calldataload 1, + .op (.stack (.push 16)), + .op (.stack .shr), + .op (.stack (.push 68)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack (.push 255)), + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack .gt), + .op (.stack .or), + .op (.stack .or), + .jumpi 1, + .op (.stack (.push 0)), + .effect .sload 1, + .op (.stack (.push 255)), + .op (.stack (.dup 1)), + .op (.stack .and), + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack .mul), + .op (.stack (.push 255)), + .op (.stack (.dup 1)), + .op (.stack .gt), + .op (.stack (.swap 1)), + .op (.stack (.push 255)), + .op (.stack .not), + .op (.stack .and), + .op (.stack .or), + .op (.stack (.dup 0)), + .op (.stack (.push 8)), + .op (.stack .shr), + .op (.stack (.push 65535)), + .op (.stack .and), + .op (.stack (.push 36)), + .effect .calldataload 1, + .op (.stack .mul), + .op (.stack (.dup 0)), + .op (.stack (.push 16)), + .op (.stack .shr), + .op (.stack (.swap 0)), + .op (.stack (.swap 2)), + .op (.stack .or), + .jumpi 4, + .op (.stack (.push 0xffff00)), + .op (.stack .not), + .op (.stack .and), + .op (.stack (.swap 0)), + .op (.stack (.push 8)), + .op (.stack .shl), + .op (.stack .or), + .op (.stack (.push 0)), + .effect .sstore 2, + .stop], + -- bb10 + [.op (.stack (.push 36)), + .effect .calldataload 1, + .op (.stack (.push 16)), + .op (.stack .shr), + .op (.stack (.push 100)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack (.push 255)), + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack .gt), + .op (.stack .or), + .op (.stack .or), + .jumpi 1, + .op (.stack (.push 68)), + .effect .calldataload 1, + .op (.stack (.push 36)), + .effect .calldataload 1, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack .mul), + .op (.stack (.dup 1)), + .op (.stack (.dup 1)), + .op (.stack .mul), + .op (.stack (.swap 0)), + .op (.stack (.dup 2)), + .op (.stack .iszero), + .op (.stack (.swap 2)), + .op (.stack (.dup 2)), + .op (.stack .div), + .op (.stack .eq), + .op (.stack (.swap 0)), + .op (.stack (.swap 1)), + .op (.stack .or), + .op (.stack .iszero), + .jumpi 4, + .op (.stack (.dup 0)), + .op (.stack (.push 1)), + .effect .sstore 2, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb8 + [.op (.stack (.push 17)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 0x4e487b71)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 36)), + .op (.stack (.push 28)), + .revert]] } + +end SolarTV.Export.Main diff --git a/Certified/mulx/gen/Main/Evm6.lean b/Certified/mulx/gen/Main/Evm6.lean new file mode 100644 index 00000000..8aadee35 --- /dev/null +++ b/Certified/mulx/gen/Main/Evm6.lean @@ -0,0 +1,143 @@ +-- solar-lean-stage: kind=evm index=6 pass=block-layout +import SolarTV.EVMIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `Main`; do not edit. -/ + +namespace SolarTV.Export.Main + +/-- The runtime EVM IR after `block-layout`. -/ +def evm6 : EVM.Program.Program := + { blocks := [ + -- bb0 + [.effect .callvalue 0, + .jumpi 1, + .op (.stack (.push 0)), + .effect .calldataload 1, + .op (.stack (.push 224)), + .op (.stack .shr), + .op (.stack (.dup 0)), + .op (.stack (.push 0x16ea58cb)), + .op (.stack .eq), + .jumpi 3, + .op (.stack (.dup 0)), + .op (.stack (.push 0x9db20e58)), + .op (.stack .eq), + .jumpi 4, + .jump 1], + -- bb4 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb8 + [.op (.stack (.push 17)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 0x4e487b71)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 36)), + .op (.stack (.push 28)), + .revert], + -- bb5 + [.op (.stack (.push 36)), + .effect .calldataload 1, + .op (.stack (.push 16)), + .op (.stack .shr), + .op (.stack (.push 68)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack (.push 255)), + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack .gt), + .op (.stack .or), + .op (.stack .or), + .jumpi 1, + .op (.stack (.push 0)), + .effect .sload 1, + .op (.stack (.push 255)), + .op (.stack (.dup 1)), + .op (.stack .and), + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack .mul), + .op (.stack (.push 255)), + .op (.stack (.dup 1)), + .op (.stack .gt), + .op (.stack (.swap 1)), + .op (.stack (.push 255)), + .op (.stack .not), + .op (.stack .and), + .op (.stack .or), + .op (.stack (.dup 0)), + .op (.stack (.push 8)), + .op (.stack .shr), + .op (.stack (.push 65535)), + .op (.stack .and), + .op (.stack (.push 36)), + .effect .calldataload 1, + .op (.stack .mul), + .op (.stack (.dup 0)), + .op (.stack (.push 16)), + .op (.stack .shr), + .op (.stack (.swap 0)), + .op (.stack (.swap 2)), + .op (.stack .or), + .jumpi 2, + .op (.stack (.push 0xffff00)), + .op (.stack .not), + .op (.stack .and), + .op (.stack (.swap 0)), + .op (.stack (.push 8)), + .op (.stack .shl), + .op (.stack .or), + .op (.stack (.push 0)), + .effect .sstore 2, + .stop], + -- bb10 + [.op (.stack (.push 36)), + .effect .calldataload 1, + .op (.stack (.push 16)), + .op (.stack .shr), + .op (.stack (.push 100)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack (.push 255)), + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack .gt), + .op (.stack .or), + .op (.stack .or), + .jumpi 1, + .op (.stack (.push 68)), + .effect .calldataload 1, + .op (.stack (.push 36)), + .effect .calldataload 1, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack .mul), + .op (.stack (.dup 1)), + .op (.stack (.dup 1)), + .op (.stack .mul), + .op (.stack (.swap 0)), + .op (.stack (.dup 2)), + .op (.stack .iszero), + .op (.stack (.swap 2)), + .op (.stack (.dup 2)), + .op (.stack .div), + .op (.stack .eq), + .op (.stack (.swap 0)), + .op (.stack (.swap 1)), + .op (.stack .or), + .op (.stack .iszero), + .jumpi 2, + .op (.stack (.dup 0)), + .op (.stack (.push 1)), + .effect .sstore 2, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret]] } + +end SolarTV.Export.Main diff --git a/Certified/mulx/gen/Main/Evm7.lean b/Certified/mulx/gen/Main/Evm7.lean new file mode 100644 index 00000000..1e6bfb62 --- /dev/null +++ b/Certified/mulx/gen/Main/Evm7.lean @@ -0,0 +1,142 @@ +-- solar-lean-stage: kind=evm index=7 pass=stack-reschedule +import SolarTV.EVMIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `Main`; do not edit. -/ + +namespace SolarTV.Export.Main + +/-- The runtime EVM IR after `stack-reschedule`. -/ +def evm7 : EVM.Program.Program := + { blocks := [ + -- bb0 + [.effect .callvalue 0, + .jumpi 1, + .op (.stack (.push 0)), + .effect .calldataload 1, + .op (.stack (.push 224)), + .op (.stack .shr), + .op (.stack (.dup 0)), + .op (.stack (.push 0x16ea58cb)), + .op (.stack .eq), + .jumpi 3, + .op (.stack (.dup 0)), + .op (.stack (.push 0x9db20e58)), + .op (.stack .eq), + .jumpi 4, + .jump 1], + -- bb4 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb8 + [.op (.stack (.push 17)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 0x4e487b71)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 36)), + .op (.stack (.push 28)), + .revert], + -- bb5 + [.op (.stack (.push 36)), + .effect .calldataload 1, + .op (.stack (.push 16)), + .op (.stack .shr), + .op (.stack (.push 68)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack (.push 255)), + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack .gt), + .op (.stack .or), + .op (.stack .or), + .jumpi 1, + .op (.stack (.push 0)), + .effect .sload 1, + .op (.stack (.push 255)), + .op (.stack (.dup 1)), + .op (.stack .and), + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack .mul), + .op (.stack (.push 255)), + .op (.stack (.dup 1)), + .op (.stack .gt), + .op (.stack (.swap 1)), + .op (.stack (.push 255)), + .op (.stack .not), + .op (.stack .and), + .op (.stack .or), + .op (.stack (.dup 0)), + .op (.stack (.push 8)), + .op (.stack .shr), + .op (.stack (.push 65535)), + .op (.stack .and), + .op (.stack (.push 36)), + .effect .calldataload 1, + .op (.stack .mul), + .op (.stack (.dup 0)), + .op (.stack (.push 16)), + .op (.stack .shr), + .op (.stack (.swap 0)), + .op (.stack (.swap 2)), + .op (.stack .or), + .jumpi 2, + .op (.stack (.push 0xffff00)), + .op (.stack .not), + .op (.stack .and), + .op (.stack (.swap 0)), + .op (.stack (.push 8)), + .op (.stack .shl), + .op (.stack .or), + .op (.stack (.push 0)), + .effect .sstore 2, + .stop], + -- bb10 + [.op (.stack (.push 36)), + .effect .calldataload 1, + .op (.stack (.push 16)), + .op (.stack .shr), + .op (.stack (.push 100)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack (.push 255)), + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack .gt), + .op (.stack .or), + .op (.stack .or), + .jumpi 1, + .op (.stack (.push 4)), + .op (.stack (.push 36)), + .effect .calldataload 1, + .op (.stack (.push 68)), + .effect .calldataload 1, + .op (.stack (.swap 1)), + .effect .calldataload 1, + .op (.stack .mul), + .op (.stack (.dup 0)), + .op (.stack (.dup 2)), + .op (.stack (.dup 0)), + .op (.stack .iszero), + .op (.stack (.swap 2)), + .op (.stack .mul), + .op (.stack (.swap 2)), + .op (.stack (.dup 3)), + .op (.stack .div), + .op (.stack .eq), + .op (.stack .or), + .op (.stack .iszero), + .jumpi 2, + .op (.stack (.dup 0)), + .op (.stack (.push 1)), + .effect .sstore 2, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret]] } + +end SolarTV.Export.Main diff --git a/Certified/mulx/gen/Main/Evm8.lean b/Certified/mulx/gen/Main/Evm8.lean new file mode 100644 index 00000000..9317e0b3 --- /dev/null +++ b/Certified/mulx/gen/Main/Evm8.lean @@ -0,0 +1,142 @@ +-- solar-lean-stage: kind=evm index=8 pass=terminal-layout +import SolarTV.EVMIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `Main`; do not edit. -/ + +namespace SolarTV.Export.Main + +/-- The runtime EVM IR after `terminal-layout`. -/ +def evm8 : EVM.Program.Program := + { blocks := [ + -- bb0 + [.effect .callvalue 0, + .jumpi 1, + .op (.stack (.push 0)), + .effect .calldataload 1, + .op (.stack (.push 224)), + .op (.stack .shr), + .op (.stack (.dup 0)), + .op (.stack (.push 0x16ea58cb)), + .op (.stack .eq), + .jumpi 4, + .op (.stack (.dup 0)), + .op (.stack (.push 0x9db20e58)), + .op (.stack .eq), + .jumpi 3, + .jump 1], + -- bb4 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb8 + [.op (.stack (.push 17)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 0x4e487b71)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 36)), + .op (.stack (.push 28)), + .revert], + -- bb10 + [.op (.stack (.push 36)), + .effect .calldataload 1, + .op (.stack (.push 16)), + .op (.stack .shr), + .op (.stack (.push 100)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack (.push 255)), + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack .gt), + .op (.stack .or), + .op (.stack .or), + .jumpi 1, + .op (.stack (.push 4)), + .op (.stack (.push 36)), + .effect .calldataload 1, + .op (.stack (.push 68)), + .effect .calldataload 1, + .op (.stack (.swap 1)), + .effect .calldataload 1, + .op (.stack .mul), + .op (.stack (.dup 0)), + .op (.stack (.dup 2)), + .op (.stack (.dup 0)), + .op (.stack .iszero), + .op (.stack (.swap 2)), + .op (.stack .mul), + .op (.stack (.swap 2)), + .op (.stack (.dup 3)), + .op (.stack .div), + .op (.stack .eq), + .op (.stack .or), + .op (.stack .iszero), + .jumpi 2, + .op (.stack (.dup 0)), + .op (.stack (.push 1)), + .effect .sstore 2, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb5 + [.op (.stack (.push 36)), + .effect .calldataload 1, + .op (.stack (.push 16)), + .op (.stack .shr), + .op (.stack (.push 68)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack (.push 255)), + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack .gt), + .op (.stack .or), + .op (.stack .or), + .jumpi 1, + .op (.stack (.push 0)), + .effect .sload 1, + .op (.stack (.push 255)), + .op (.stack (.dup 1)), + .op (.stack .and), + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack .mul), + .op (.stack (.push 255)), + .op (.stack (.dup 1)), + .op (.stack .gt), + .op (.stack (.swap 1)), + .op (.stack (.push 255)), + .op (.stack .not), + .op (.stack .and), + .op (.stack .or), + .op (.stack (.dup 0)), + .op (.stack (.push 8)), + .op (.stack .shr), + .op (.stack (.push 65535)), + .op (.stack .and), + .op (.stack (.push 36)), + .effect .calldataload 1, + .op (.stack .mul), + .op (.stack (.dup 0)), + .op (.stack (.push 16)), + .op (.stack .shr), + .op (.stack (.swap 0)), + .op (.stack (.swap 2)), + .op (.stack .or), + .jumpi 2, + .op (.stack (.push 0xffff00)), + .op (.stack .not), + .op (.stack .and), + .op (.stack (.swap 0)), + .op (.stack (.push 8)), + .op (.stack .shl), + .op (.stack .or), + .op (.stack (.push 0)), + .effect .sstore 2, + .stop]] } + +end SolarTV.Export.Main diff --git a/Certified/mulx/gen/Main/Manifest.lean b/Certified/mulx/gen/Main/Manifest.lean new file mode 100644 index 00000000..b62ce15a --- /dev/null +++ b/Certified/mulx/gen/Main/Manifest.lean @@ -0,0 +1,46 @@ +-- solar-lean-stage: kind=manifest index=0 pass=none +/-! Generated by `solar -Zemit-lean-stages` for `Main`; do not edit. + +What the stages of this directory were compiled from and by. `stages` lists each +stage's file, its definition, the pass whose output it is, and the SHA-256 of the file. +-/ + +namespace SolarTV.Export.Main.Manifest + +def sources : List (String × String) := + [("solar-tv/milestone/mulx/mulx.sol", "50ef03a3c5724105509c3ed40b7ee7d92ea43b5d48a67d0e6722b26806dd4980")] + +def compiler : String := "0.8.38+commit.4a7d9ede.solar.0.3.0-dev" + +def arguments : List String := + ["solar-tv/milestone/mulx/mulx.sol", + "-Zcheck-analyses=false", + "--emit=bin-runtime", + "-Zemit-lean-stages=solar-tv/milestone/mulx/gen"] + +def evmVersion : String := "osaka" + +def optimization : String := "Gas" + +def stages : List (String × String × String × String) := + [("Stage0", "stage0", "lower-evm-shaped", "2b9c8cec1601216327fccf673b46da96524d9a9f370a59ba48c0e8c681ab04d3"), + ("Mir1", "mir1", "place-reads", "00bc7419a9e8986262cab286f3b645a02372d763fb479aab53fd441540de293d"), + ("Mir2", "mir2", "spell-width-tests", "c968bd712214b6bee13301512125f77a4a78009ac4645f67c33973bb547da5d5"), + ("Mir3", "mir3", "evm-inst-schedule", "56851b5379010bdddc4322c96d0cf71074a5e03799692441f19bcec896c1f405"), + ("Sched", "sched", "stack-schedule", "65427f39b7dccd0532eea820dcf87913d159dd38432341d3a6eab343af58b1f5"), + ("Evm1", "evm1", "cfg-simplify-early", "0c8207918da2ec50f56ce74e53a462ec5439a64d172ac23415638e4030f18859"), + ("Evm2", "evm2", "compact-pushes", "59aa616e5814a8851865724e044fcc404b09cefa0301b05f3ada06cd397ba4ae"), + ("Evm3", "evm3", "block-layout", "3387cc09f143955e7a4a04c724d47b76f32c50a63b6c62a0d78d3c4f15586cb3"), + ("Evm4", "evm4", "terminal-dedup", "316cd3f9f0b49901c3e2b9a40e25148bfb2865742e41d560f3b5e3984bce857c"), + ("Evm5", "evm5", "cfg-simplify-early", "035c602fd240c7669f4cf04aecffc4d0c92710118d0ed62a04318db45c83adcd"), + ("Evm6", "evm6", "block-layout", "93fd2e565351cdc932aed3af2866ce507178d92df687db5f6073455723ca5081"), + ("Evm7", "evm7", "stack-reschedule", "0944bb89f3c09191c3f4a4f9f93921ba7e046e8b98f170ec37399164b47ade9d"), + ("Evm8", "evm8", "terminal-layout", "cbde24c2d1aca6c969d32bcb0bdfa778c1422db4507b1ee17cc2b85ffc7579bc"), + ("Bytecode", "bytecode", "assemble", "3e3d39a7bf6aea74f26053fb78ffd63c5e14743483a63449fccbf3bffc8eb6e3")] + +def bytecodeHex : String := + "34601d575f3560e01c806316ea58cb14606d5780639db20e58146033575b5f5ffd5b6011602052634e487b715f526024601cfd5b60243560101c6064361060ff600435111717601d576004602435604435913502808280159202928304141715602157806001555f5260205ff35b60243560101c6044361060ff600435111717601d575f5460ff81166004350260ff81119160ff1916178060081c61ffff16602435028060101c90921760215762ffff0019169060081b175f55" + +def bytecodeSha256 : String := "42ecdc71b09d339299d2b7ce61e121c77b141c5386eb9cbf18792a9ba9ca4cfe" + +end SolarTV.Export.Main.Manifest diff --git a/Certified/mulx/gen/Main/Mir1.lean b/Certified/mulx/gen/Main/Mir1.lean new file mode 100644 index 00000000..be9c25bc --- /dev/null +++ b/Certified/mulx/gen/Main/Mir1.lean @@ -0,0 +1,126 @@ +-- solar-lean-stage: kind=mir index=1 pass=place-reads +import SolarTV.MIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `Main`; do not edit. -/ + +namespace SolarTV.Export.Main + +/-- The lowered MIR module after `place-reads`. -/ +def mir1 : MIR.Lowered.Module := + { entry := 3, + functions := [ + -- @m + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 48) .calldatasize [], + .pure 50 .lt [.value 48, .const 68], + .effect (some 52) .calldataload [.const 4], + .pure 54 .gt [.value 52, .const 255], + .pure 74 .or [.value 50, .value 54], + .effect (some 56) .calldataload [.const 36], + .pure 58 .gt [.value 56, .const 65535], + .pure 75 .or [.value 74, .value 58]], + .branch (.value 75) 3 4⟩, + -- bb1 + ⟨[], + [.effect none .mstore [.const 32, .const 17], + .effect none .mstore [.const 0, .const 0x4e487b71]], + .revert (.const 28) (.const 36)⟩, + -- bb2 + ⟨[], + [.pure 24 .and [.value 12, .const 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffff0000ff], + .pure 27 .shl [.const 8, .value 43], + .pure 28 .or [.value 24, .value 27], + .effect none .sstore [.const 0, .value 28]], + .stop⟩, + -- bb3 + ⟨[], + [], + .revert (.const 0) (.const 0)⟩, + -- bb4 + ⟨[], + [.effect (some 78) .calldataload [.const 36], + .effect (some 77) .calldataload [.const 4], + .effect (some 3) .sload [.const 0], + .pure 73 .and [.value 3, .const 255], + .pure 31 .mul [.value 73, .value 77], + .pure 33 .gt [.value 31, .const 255], + .pure 9 .and [.value 3, .const 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff00], + .pure 12 .or [.value 9, .value 31], + .pure 16 .shr [.const 8, .value 12], + .pure 65 .and [.value 16, .const 65535], + .pure 43 .mul [.value 65, .value 78], + .pure 45 .gt [.value 43, .const 65535], + .pure 76 .or [.value 33, .value 45]], + .branch (.value 76) 1 2⟩] }, + -- @n + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 29) .calldatasize [], + .pure 31 .lt [.value 29, .const 100], + .effect (some 33) .calldataload [.const 4], + .pure 35 .gt [.value 33, .const 255], + .pure 51 .or [.value 31, .value 35], + .effect (some 37) .calldataload [.const 36], + .pure 39 .gt [.value 37, .const 65535], + .pure 52 .or [.value 51, .value 39]], + .branch (.value 52) 3 4⟩, + -- bb1 + ⟨[], + [.effect none .mstore [.const 32, .const 17], + .effect none .mstore [.const 0, .const 0x4e487b71]], + .revert (.const 28) (.const 36)⟩, + -- bb2 + ⟨[], + [.effect none .sstore [.const 1, .value 11], + .effect none .mstore [.const 0, .value 11]], + .ret (.const 0) (.const 32)⟩, + -- bb3 + ⟨[], + [], + .revert (.const 0) (.const 0)⟩, + -- bb4 + ⟨[], + [.effect (some 54) .calldataload [.const 36], + .effect (some 53) .calldataload [.const 4], + .effect (some 41) .calldataload [.const 68], + .pure 5 .mul [.value 53, .value 54], + .pure 11 .mul [.value 5, .value 41], + .pure 13 .eq [.value 41, .const 0], + .pure 14 .div [.value 11, .value 41], + .pure 15 .eq [.value 14, .value 5], + .pure 16 .or [.value 13, .value 15]], + .branch (.value 16) 2 1⟩] }, + -- @constructor: not reachable from the runtime entry, so it has no blocks here + { blocks := [] }, + -- @entry + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 0) .callvalue [], + .ne 2 (.value 0) (.const 0)], + .branch (.value 2) 4 1⟩, + -- bb1 + ⟨[], + [.effect (some 4) .calldataload [.const 0], + .pure 6 .shr [.const 224, .value 4]], + .switch (.value 6) 4 [(.const 0x16ea58cb, 2), (.const 0x9db20e58, 3)]⟩, + -- bb2 + ⟨[], + [], + .tailCall 0 []⟩, + -- bb3 + ⟨[], + [], + .tailCall 1 []⟩, + -- bb4 + ⟨[], + [], + .revert (.const 0) (.const 0)⟩] }] } + +end SolarTV.Export.Main diff --git a/Certified/mulx/gen/Main/Mir2.lean b/Certified/mulx/gen/Main/Mir2.lean new file mode 100644 index 00000000..604d6be2 --- /dev/null +++ b/Certified/mulx/gen/Main/Mir2.lean @@ -0,0 +1,132 @@ +-- solar-lean-stage: kind=mir index=2 pass=spell-width-tests +import SolarTV.MIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `Main`; do not edit. -/ + +namespace SolarTV.Export.Main + +/-- The lowered MIR module after `spell-width-tests`. -/ +def mir2 : MIR.Lowered.Module := + { entry := 3, + functions := [ + -- @m + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 48) .calldatasize [], + .pure 50 .lt [.value 48, .const 68], + .effect (some 52) .calldataload [.const 4], + .pure 54 .gt [.value 52, .const 255], + .pure 74 .or [.value 50, .value 54], + .effect (some 56) .calldataload [.const 36], + .pure 80 .shr [.const 16, .value 56], + .word 83 (.value 74), + .pure 84 .or [.value 80, .value 83], + .ne 75 (.value 84) (.const 0)], + .branch (.value 75) 3 4⟩, + -- bb1 + ⟨[], + [.effect none .mstore [.const 32, .const 17], + .effect none .mstore [.const 0, .const 0x4e487b71]], + .revert (.const 28) (.const 36)⟩, + -- bb2 + ⟨[], + [.pure 24 .and [.value 12, .const 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffff0000ff], + .pure 27 .shl [.const 8, .value 43], + .pure 28 .or [.value 24, .value 27], + .effect none .sstore [.const 0, .value 28]], + .stop⟩, + -- bb3 + ⟨[], + [], + .revert (.const 0) (.const 0)⟩, + -- bb4 + ⟨[], + [.effect (some 78) .calldataload [.const 36], + .effect (some 77) .calldataload [.const 4], + .effect (some 3) .sload [.const 0], + .pure 73 .and [.value 3, .const 255], + .pure 31 .mul [.value 73, .value 77], + .pure 33 .gt [.value 31, .const 255], + .pure 9 .and [.value 3, .const 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff00], + .pure 12 .or [.value 9, .value 31], + .pure 16 .shr [.const 8, .value 12], + .pure 65 .and [.value 16, .const 65535], + .pure 43 .mul [.value 65, .value 78], + .pure 88 .shr [.const 16, .value 43], + .word 91 (.value 33), + .pure 92 .or [.value 88, .value 91], + .ne 76 (.value 92) (.const 0)], + .branch (.value 76) 1 2⟩] }, + -- @n + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 29) .calldatasize [], + .pure 31 .lt [.value 29, .const 100], + .effect (some 33) .calldataload [.const 4], + .pure 35 .gt [.value 33, .const 255], + .pure 51 .or [.value 31, .value 35], + .effect (some 37) .calldataload [.const 36], + .pure 56 .shr [.const 16, .value 37], + .word 59 (.value 51), + .pure 60 .or [.value 56, .value 59], + .ne 52 (.value 60) (.const 0)], + .branch (.value 52) 3 4⟩, + -- bb1 + ⟨[], + [.effect none .mstore [.const 32, .const 17], + .effect none .mstore [.const 0, .const 0x4e487b71]], + .revert (.const 28) (.const 36)⟩, + -- bb2 + ⟨[], + [.effect none .sstore [.const 1, .value 11], + .effect none .mstore [.const 0, .value 11]], + .ret (.const 0) (.const 32)⟩, + -- bb3 + ⟨[], + [], + .revert (.const 0) (.const 0)⟩, + -- bb4 + ⟨[], + [.effect (some 54) .calldataload [.const 36], + .effect (some 53) .calldataload [.const 4], + .effect (some 41) .calldataload [.const 68], + .pure 5 .mul [.value 53, .value 54], + .pure 11 .mul [.value 5, .value 41], + .pure 13 .eq [.value 41, .const 0], + .pure 14 .div [.value 11, .value 41], + .pure 15 .eq [.value 14, .value 5], + .pure 16 .or [.value 13, .value 15]], + .branch (.value 16) 2 1⟩] }, + -- @constructor: not reachable from the runtime entry, so it has no blocks here + { blocks := [] }, + -- @entry + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 0) .callvalue [], + .ne 2 (.value 0) (.const 0)], + .branch (.value 2) 4 1⟩, + -- bb1 + ⟨[], + [.effect (some 4) .calldataload [.const 0], + .pure 6 .shr [.const 224, .value 4]], + .switch (.value 6) 4 [(.const 0x16ea58cb, 2), (.const 0x9db20e58, 3)]⟩, + -- bb2 + ⟨[], + [], + .tailCall 0 []⟩, + -- bb3 + ⟨[], + [], + .tailCall 1 []⟩, + -- bb4 + ⟨[], + [], + .revert (.const 0) (.const 0)⟩] }] } + +end SolarTV.Export.Main diff --git a/Certified/mulx/gen/Main/Mir3.lean b/Certified/mulx/gen/Main/Mir3.lean new file mode 100644 index 00000000..51d13904 --- /dev/null +++ b/Certified/mulx/gen/Main/Mir3.lean @@ -0,0 +1,132 @@ +-- solar-lean-stage: kind=mir index=3 pass=evm-inst-schedule +import SolarTV.MIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `Main`; do not edit. -/ + +namespace SolarTV.Export.Main + +/-- The lowered MIR module after `evm-inst-schedule`. -/ +def mir3 : MIR.Lowered.Module := + { entry := 3, + functions := [ + -- @m + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 56) .calldataload [.const 36], + .pure 80 .shr [.const 16, .value 56], + .effect (some 48) .calldatasize [], + .pure 50 .lt [.value 48, .const 68], + .effect (some 52) .calldataload [.const 4], + .pure 54 .gt [.value 52, .const 255], + .pure 74 .or [.value 50, .value 54], + .word 83 (.value 74), + .pure 84 .or [.value 80, .value 83], + .ne 75 (.value 84) (.const 0)], + .branch (.value 75) 3 4⟩, + -- bb1 + ⟨[], + [.effect none .mstore [.const 32, .const 17], + .effect none .mstore [.const 0, .const 0x4e487b71]], + .revert (.const 28) (.const 36)⟩, + -- bb2 + ⟨[], + [.pure 24 .and [.value 12, .const 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffff0000ff], + .pure 27 .shl [.const 8, .value 43], + .pure 28 .or [.value 24, .value 27], + .effect none .sstore [.const 0, .value 28]], + .stop⟩, + -- bb3 + ⟨[], + [], + .revert (.const 0) (.const 0)⟩, + -- bb4 + ⟨[], + [.effect (some 78) .calldataload [.const 36], + .effect (some 77) .calldataload [.const 4], + .effect (some 3) .sload [.const 0], + .pure 73 .and [.value 3, .const 255], + .pure 31 .mul [.value 73, .value 77], + .pure 33 .gt [.value 31, .const 255], + .pure 9 .and [.value 3, .const 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff00], + .pure 12 .or [.value 9, .value 31], + .pure 16 .shr [.const 8, .value 12], + .pure 65 .and [.value 16, .const 65535], + .pure 43 .mul [.value 65, .value 78], + .pure 88 .shr [.const 16, .value 43], + .word 91 (.value 33), + .pure 92 .or [.value 88, .value 91], + .ne 76 (.value 92) (.const 0)], + .branch (.value 76) 1 2⟩] }, + -- @n + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 37) .calldataload [.const 36], + .pure 56 .shr [.const 16, .value 37], + .effect (some 29) .calldatasize [], + .pure 31 .lt [.value 29, .const 100], + .effect (some 33) .calldataload [.const 4], + .pure 35 .gt [.value 33, .const 255], + .pure 51 .or [.value 31, .value 35], + .word 59 (.value 51), + .pure 60 .or [.value 56, .value 59], + .ne 52 (.value 60) (.const 0)], + .branch (.value 52) 3 4⟩, + -- bb1 + ⟨[], + [.effect none .mstore [.const 32, .const 17], + .effect none .mstore [.const 0, .const 0x4e487b71]], + .revert (.const 28) (.const 36)⟩, + -- bb2 + ⟨[], + [.effect none .sstore [.const 1, .value 11], + .effect none .mstore [.const 0, .value 11]], + .ret (.const 0) (.const 32)⟩, + -- bb3 + ⟨[], + [], + .revert (.const 0) (.const 0)⟩, + -- bb4 + ⟨[], + [.effect (some 54) .calldataload [.const 36], + .effect (some 53) .calldataload [.const 4], + .effect (some 41) .calldataload [.const 68], + .pure 5 .mul [.value 53, .value 54], + .pure 11 .mul [.value 5, .value 41], + .pure 13 .eq [.value 41, .const 0], + .pure 14 .div [.value 11, .value 41], + .pure 15 .eq [.value 14, .value 5], + .pure 16 .or [.value 13, .value 15]], + .branch (.value 16) 2 1⟩] }, + -- @constructor: not reachable from the runtime entry, so it has no blocks here + { blocks := [] }, + -- @entry + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 0) .callvalue [], + .ne 2 (.value 0) (.const 0)], + .branch (.value 2) 4 1⟩, + -- bb1 + ⟨[], + [.effect (some 4) .calldataload [.const 0], + .pure 6 .shr [.const 224, .value 4]], + .switch (.value 6) 4 [(.const 0x16ea58cb, 2), (.const 0x9db20e58, 3)]⟩, + -- bb2 + ⟨[], + [], + .tailCall 0 []⟩, + -- bb3 + ⟨[], + [], + .tailCall 1 []⟩, + -- bb4 + ⟨[], + [], + .revert (.const 0) (.const 0)⟩] }] } + +end SolarTV.Export.Main diff --git a/Certified/mulx/gen/Main/Sched.lean b/Certified/mulx/gen/Main/Sched.lean new file mode 100644 index 00000000..38398b2d --- /dev/null +++ b/Certified/mulx/gen/Main/Sched.lean @@ -0,0 +1,173 @@ +-- solar-lean-stage: kind=sched index=0 pass=stack-schedule +import SolarTV.EVMIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `Main`; do not edit. -/ + +namespace SolarTV.Export.Main + +/-- The runtime EVM IR as stack scheduling emits it. -/ +def sched : EVM.Program.Program := + { blocks := [ + -- bb0 + [.effect .callvalue 0, + .jumpi 4, + .jump 1], + -- bb1 + [.op (.stack (.push 0)), + .effect .calldataload 1, + .op (.stack (.push 224)), + .op (.stack .shr), + .op (.stack (.dup 0)), + .op (.stack (.push 0x16ea58cb)), + .op (.stack .eq), + .jumpi 3, + .op (.stack (.dup 0)), + .op (.stack (.push 0x9db20e58)), + .op (.stack .eq), + .jumpi 2, + .jump 4], + -- bb2 + [.jump 10], + -- bb3 + [.jump 5], + -- bb4 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb5 + [.op (.stack (.push 36)), + .effect .calldataload 1, + .op (.stack (.push 16)), + .op (.stack .shr), + .op (.stack (.push 68)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack (.push 255)), + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack .gt), + .op (.stack .or), + .op (.stack .or), + .jumpi 9, + .jump 6], + -- bb6 + [.op (.stack (.push 0)), + .effect .sload 1, + .op (.stack (.push 255)), + .op (.stack (.dup 1)), + .op (.stack .and), + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack .mul), + .op (.stack (.push 255)), + .op (.stack (.dup 1)), + .op (.stack .gt), + .op (.stack (.swap 1)), + .op (.stack (.push 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff00)), + .op (.stack .and), + .op (.stack .or), + .op (.stack (.dup 0)), + .op (.stack (.push 8)), + .op (.stack .shr), + .op (.stack (.push 65535)), + .op (.stack .and), + .op (.stack (.push 36)), + .effect .calldataload 1, + .op (.stack .mul), + .op (.stack (.dup 0)), + .op (.stack (.push 16)), + .op (.stack .shr), + .op (.stack (.swap 0)), + .op (.stack (.swap 2)), + .op (.stack .or), + .jumpi 8, + .jump 7], + -- bb7 + [.op (.stack (.push 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffff0000ff)), + .op (.stack .and), + .op (.stack (.swap 0)), + .op (.stack (.push 8)), + .op (.stack .shl), + .op (.stack .or), + .op (.stack (.push 0)), + .effect .sstore 2, + .stop], + -- bb8 + [.op (.stack (.push 17)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 0x4e487b71)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 36)), + .op (.stack (.push 28)), + .revert], + -- bb9 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb10 + [.op (.stack (.push 36)), + .effect .calldataload 1, + .op (.stack (.push 16)), + .op (.stack .shr), + .op (.stack (.push 100)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack (.push 255)), + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack .gt), + .op (.stack .or), + .op (.stack .or), + .jumpi 14, + .jump 11], + -- bb11 + [.op (.stack (.push 68)), + .effect .calldataload 1, + .op (.stack (.push 36)), + .effect .calldataload 1, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack .mul), + .op (.stack (.dup 1)), + .op (.stack (.dup 1)), + .op (.stack .mul), + .op (.stack (.swap 0)), + .op (.stack (.dup 2)), + .op (.stack .iszero), + .op (.stack (.swap 2)), + .op (.stack (.dup 2)), + .op (.stack .div), + .op (.stack .eq), + .op (.stack (.swap 0)), + .op (.stack (.swap 1)), + .op (.stack .or), + .op (.stack .iszero), + .jumpi 13, + .jump 12], + -- bb12 + [.op (.stack (.dup 0)), + .op (.stack (.push 1)), + .effect .sstore 2, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb13 + [.op (.stack (.push 17)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 0x4e487b71)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 36)), + .op (.stack (.push 28)), + .revert], + -- bb14 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert]] } + +end SolarTV.Export.Main diff --git a/Certified/mulx/gen/Main/Stage0.lean b/Certified/mulx/gen/Main/Stage0.lean new file mode 100644 index 00000000..b240a5bc --- /dev/null +++ b/Certified/mulx/gen/Main/Stage0.lean @@ -0,0 +1,122 @@ +-- solar-lean-stage: kind=mir index=0 pass=lower-evm-shaped +import SolarTV.MIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `Main`; do not edit. -/ + +namespace SolarTV.Export.Main + +/-- The first lowered MIR module, after `lower-evm-shaped` advanced the phase. -/ +def stage0 : MIR.Lowered.Module := + { entry := 3, + functions := [ + -- @m + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 48) .calldatasize [], + .pure 50 .lt [.value 48, .const 68], + .effect (some 52) .calldataload [.const 4], + .pure 54 .gt [.value 52, .const 255], + .pure 74 .or [.value 50, .value 54], + .effect (some 56) .calldataload [.const 36], + .pure 58 .gt [.value 56, .const 65535], + .pure 75 .or [.value 74, .value 58]], + .branch (.value 75) 3 4⟩, + -- bb1 + ⟨[], + [.effect none .mstore [.const 32, .const 17], + .effect none .mstore [.const 0, .const 0x4e487b71]], + .revert (.const 28) (.const 36)⟩, + -- bb2 + ⟨[], + [.pure 24 .and [.value 12, .const 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffff0000ff], + .pure 27 .shl [.const 8, .value 43], + .pure 28 .or [.value 24, .value 27], + .effect none .sstore [.const 0, .value 28]], + .stop⟩, + -- bb3 + ⟨[], + [], + .revert (.const 0) (.const 0)⟩, + -- bb4 + ⟨[], + [.effect (some 3) .sload [.const 0], + .pure 73 .and [.value 3, .const 255], + .pure 31 .mul [.value 73, .value 52], + .pure 33 .gt [.value 31, .const 255], + .pure 9 .and [.value 3, .const 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff00], + .pure 12 .or [.value 9, .value 31], + .pure 16 .shr [.const 8, .value 12], + .pure 65 .and [.value 16, .const 65535], + .pure 43 .mul [.value 65, .value 56], + .pure 45 .gt [.value 43, .const 65535], + .pure 76 .or [.value 33, .value 45]], + .branch (.value 76) 1 2⟩] }, + -- @n + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 29) .calldatasize [], + .pure 31 .lt [.value 29, .const 100], + .effect (some 33) .calldataload [.const 4], + .pure 35 .gt [.value 33, .const 255], + .pure 51 .or [.value 31, .value 35], + .effect (some 37) .calldataload [.const 36], + .pure 39 .gt [.value 37, .const 65535], + .pure 52 .or [.value 51, .value 39]], + .branch (.value 52) 3 4⟩, + -- bb1 + ⟨[], + [.effect none .mstore [.const 32, .const 17], + .effect none .mstore [.const 0, .const 0x4e487b71]], + .revert (.const 28) (.const 36)⟩, + -- bb2 + ⟨[], + [.effect none .sstore [.const 1, .value 11], + .effect none .mstore [.const 0, .value 11]], + .ret (.const 0) (.const 32)⟩, + -- bb3 + ⟨[], + [], + .revert (.const 0) (.const 0)⟩, + -- bb4 + ⟨[], + [.effect (some 41) .calldataload [.const 68], + .pure 5 .mul [.value 33, .value 37], + .pure 11 .mul [.value 5, .value 41], + .pure 13 .eq [.value 41, .const 0], + .pure 14 .div [.value 11, .value 41], + .pure 15 .eq [.value 14, .value 5], + .pure 16 .or [.value 13, .value 15]], + .branch (.value 16) 2 1⟩] }, + -- @constructor: not reachable from the runtime entry, so it has no blocks here + { blocks := [] }, + -- @entry + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 0) .callvalue [], + .ne 2 (.value 0) (.const 0)], + .branch (.value 2) 4 1⟩, + -- bb1 + ⟨[], + [.effect (some 4) .calldataload [.const 0], + .pure 6 .shr [.const 224, .value 4]], + .switch (.value 6) 4 [(.const 0x16ea58cb, 2), (.const 0x9db20e58, 3)]⟩, + -- bb2 + ⟨[], + [], + .tailCall 0 []⟩, + -- bb3 + ⟨[], + [], + .tailCall 1 []⟩, + -- bb4 + ⟨[], + [], + .revert (.const 0) (.const 0)⟩] }] } + +end SolarTV.Export.Main diff --git a/Certified/mulx/gen/Main/manifest.json b/Certified/mulx/gen/Main/manifest.json new file mode 100644 index 00000000..557f81ac --- /dev/null +++ b/Certified/mulx/gen/Main/manifest.json @@ -0,0 +1,135 @@ +{ + "arguments": [ + "solar-tv/milestone/mulx/mulx.sol", + "-Zcheck-analyses=false", + "--emit=bin-runtime", + "-Zemit-lean-stages=solar-tv/milestone/mulx/gen" + ], + "bytecode": "34601d575f3560e01c806316ea58cb14606d5780639db20e58146033575b5f5ffd5b6011602052634e487b715f526024601cfd5b60243560101c6064361060ff600435111717601d576004602435604435913502808280159202928304141715602157806001555f5260205ff35b60243560101c6044361060ff600435111717601d575f5460ff81166004350260ff81119160ff1916178060081c61ffff16602435028060101c90921760215762ffff0019169060081b175f55", + "bytecode_sha256": "42ecdc71b09d339299d2b7ce61e121c77b141c5386eb9cbf18792a9ba9ca4cfe", + "compiler": "0.8.38+commit.4a7d9ede.solar.0.3.0-dev", + "contract": "Main", + "evm_version": "osaka", + "optimization": "Gas", + "options": "CompileOpts { input: [\"solar-tv/milestone/mulx/mulx.sol\"], import_remappings: [], base_path: None, include_paths: [], allow_paths: [], no_import_callback: false, language: Solidity, threads: 4, evm_version: Osaka, stop_after: None, optimization: Gas, optimizer_runs: None, revert_strings: Default, libraries: [], out_dir: None, emit: [BinRuntime], standard_json: false, color: Auto, verbose: false, pretty_json: false, pretty_json_err: false, error_format: Human, error_format_human: Unicode, diagnostic_width: None, no_warnings: false, allow: [], _unstable: [\"check-analyses=false\", \"emit-lean-stages=solar-tv/milestone/mulx/gen\"], unstable: UnstableOpts { ui_testing: false, track_diagnostics: false, parse_yul: false, no_resolve_imports: false, recover_incomplete_input: false, dump: None, ast_stats: false, hir_stats: false, standard_json_stats: false, span_visitor: false, print_max_storage_sizes: false, print_natspec: false, mir_pipeline: None, evm_ir_pipeline: None, print_after_each: false, pass_diff: false, debugify: None, debugify_output: None, solar_tv: None, validate_ir: None, time_passes: false, codegen_all_functions: false, switch_lowering: Auto, switch_max_gas_code_growth: None, switch_max_bit_slice_gas_code_growth: None, tune: None, pack_wide_jump_tables: false, check_analyses: Some(false), prove_analyses: None, validate_passes: None, validate_passes_fault: None, validate_backend: None, validate_backend_fault: None, validate_evm_ir_passes: None, validate_assembly: false, validate_assembly_fault: None, emit_lean_stages: Some(\"solar-tv/milestone/mulx/gen\"), forget_gcx: true, help: (), _non_exhaustive: () }, _non_exhaustive: () }", + "sources": [ + { + "path": "solar-tv/milestone/mulx/mulx.sol", + "sha256": "50ef03a3c5724105509c3ed40b7ee7d92ea43b5d48a67d0e6722b26806dd4980" + } + ], + "stages": [ + { + "definition": "stage0", + "file": "Stage0.lean", + "index": 0, + "kind": "mir", + "pass": "lower-evm-shaped", + "sha256": "2b9c8cec1601216327fccf673b46da96524d9a9f370a59ba48c0e8c681ab04d3" + }, + { + "definition": "mir1", + "file": "Mir1.lean", + "index": 1, + "kind": "mir", + "pass": "place-reads", + "sha256": "00bc7419a9e8986262cab286f3b645a02372d763fb479aab53fd441540de293d" + }, + { + "definition": "mir2", + "file": "Mir2.lean", + "index": 2, + "kind": "mir", + "pass": "spell-width-tests", + "sha256": "c968bd712214b6bee13301512125f77a4a78009ac4645f67c33973bb547da5d5" + }, + { + "definition": "mir3", + "file": "Mir3.lean", + "index": 3, + "kind": "mir", + "pass": "evm-inst-schedule", + "sha256": "56851b5379010bdddc4322c96d0cf71074a5e03799692441f19bcec896c1f405" + }, + { + "definition": "sched", + "file": "Sched.lean", + "index": 0, + "kind": "sched", + "pass": "stack-schedule", + "sha256": "65427f39b7dccd0532eea820dcf87913d159dd38432341d3a6eab343af58b1f5" + }, + { + "definition": "evm1", + "file": "Evm1.lean", + "index": 1, + "kind": "evm", + "pass": "cfg-simplify-early", + "sha256": "0c8207918da2ec50f56ce74e53a462ec5439a64d172ac23415638e4030f18859" + }, + { + "definition": "evm2", + "file": "Evm2.lean", + "index": 2, + "kind": "evm", + "pass": "compact-pushes", + "sha256": "59aa616e5814a8851865724e044fcc404b09cefa0301b05f3ada06cd397ba4ae" + }, + { + "definition": "evm3", + "file": "Evm3.lean", + "index": 3, + "kind": "evm", + "pass": "block-layout", + "sha256": "3387cc09f143955e7a4a04c724d47b76f32c50a63b6c62a0d78d3c4f15586cb3" + }, + { + "definition": "evm4", + "file": "Evm4.lean", + "index": 4, + "kind": "evm", + "pass": "terminal-dedup", + "sha256": "316cd3f9f0b49901c3e2b9a40e25148bfb2865742e41d560f3b5e3984bce857c" + }, + { + "definition": "evm5", + "file": "Evm5.lean", + "index": 5, + "kind": "evm", + "pass": "cfg-simplify-early", + "sha256": "035c602fd240c7669f4cf04aecffc4d0c92710118d0ed62a04318db45c83adcd" + }, + { + "definition": "evm6", + "file": "Evm6.lean", + "index": 6, + "kind": "evm", + "pass": "block-layout", + "sha256": "93fd2e565351cdc932aed3af2866ce507178d92df687db5f6073455723ca5081" + }, + { + "definition": "evm7", + "file": "Evm7.lean", + "index": 7, + "kind": "evm", + "pass": "stack-reschedule", + "sha256": "0944bb89f3c09191c3f4a4f9f93921ba7e046e8b98f170ec37399164b47ade9d" + }, + { + "definition": "evm8", + "file": "Evm8.lean", + "index": 8, + "kind": "evm", + "pass": "terminal-layout", + "sha256": "cbde24c2d1aca6c969d32bcb0bdfa778c1422db4507b1ee17cc2b85ffc7579bc" + }, + { + "definition": "bytecode", + "file": "Bytecode.lean", + "index": 0, + "kind": "bytecode", + "pass": "assemble", + "sha256": "3e3d39a7bf6aea74f26053fb78ffd63c5e14743483a63449fccbf3bffc8eb6e3" + } + ] +} diff --git a/Certified/mulx/mulx.sol b/Certified/mulx/mulx.sol new file mode 100644 index 00000000..efd1c806 --- /dev/null +++ b/Certified/mulx/mulx.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/Certified/mulx/options b/Certified/mulx/options new file mode 100644 index 00000000..55fc63cf --- /dev/null +++ b/Certified/mulx/options @@ -0,0 +1 @@ +-Zcheck-analyses=false diff --git a/Certified/reader/Proofs.lean b/Certified/reader/Proofs.lean new file mode 100644 index 00000000..346ab2d2 --- /dev/null +++ b/Certified/reader/Proofs.lean @@ -0,0 +1,3 @@ +-- Generated by solar-tv/milestone/certify.py; do not edit. +import reader.Proofs.Stages +import reader.Proofs.Assembly diff --git a/Certified/reader/Proofs/Assembly.lean b/Certified/reader/Proofs/Assembly.lean new file mode 100644 index 00000000..4833a07e --- /dev/null +++ b/Certified/reader/Proofs/Assembly.lean @@ -0,0 +1,42 @@ +-- Generated by solar-tv/milestone/certify.py; do not edit. +import W1Proofs.Items +import reader.gen.Reader.Evm7 +import reader.gen.Reader.Bytecode + +/-! The final EVM IR of `Reader` against its bytecode, by the assembly checker's walk: the bytecode decodes, linearly from offset 0, to exactly the program's instructions, each jumped-to block at its `JUMPDEST`. -/ + +namespace SolarTV.Milestone.Reader + +open SolarTV.Assembly SolarTV.Export.Reader SolarTV.Milestone.W1 + +set_option maxRecDepth 100000 + +/-- The items of the final EVM IR. -/ +def items : List Item := (itemsOf evm7).getD [] + +theorem items_eq : itemsOf evm7 = some items := by decide + +/-- The layout: each jumped-to block at the bytecode's next `JUMPDEST`. The walk checks it. -/ +def offset (label : Nat) : Nat := if label = 1 then 0x53 else if label = 2 then 0x57 else if label = 3 then 0x5f else 0 + +/-- The instructions the walk reaches, each at its offset. -/ +def stream : List (Nat × Instr) := (walk bytecode offset 0 items).getD [] + +/-- The checker's walk accepts the exported bytecode against the final EVM IR. -/ +theorem walk_eq : walk bytecode offset 0 items = some stream := by decide +kernel + +theorem checked : Walk bytecode offset 0 items stream := walk_sound walk_eq + +/-- The bytecode's linear decoding is the final EVM IR's instructions at the layout. -/ +theorem decodes : decodeFrom bytecode (bytecode.length + 1) 0 = stream := + walk_decodes checked _ (by have := walk_length checked; omega) + +/-- info: 'SolarTV.Milestone.Reader.walk_eq' depends on axioms: [propext, Quot.sound] -/ +#guard_msgs in +#print axioms walk_eq + +/-- info: 'SolarTV.Milestone.Reader.decodes' depends on axioms: [propext, Quot.sound] -/ +#guard_msgs in +#print axioms decodes + +end SolarTV.Milestone.Reader diff --git a/Certified/reader/Proofs/Runs/Evm1.lean b/Certified/reader/Proofs/Runs/Evm1.lean new file mode 100644 index 00000000..fa95c919 --- /dev/null +++ b/Certified/reader/Proofs/Runs/Evm1.lean @@ -0,0 +1,22 @@ +-- Generated by solar-tv/milestone/certify.py; do not edit. +import W1Proofs.Tactic +import W1Proofs.Axioms +import reader.gen.Reader.Evm1 +import reader.gen.Reader.Sched + +/-! `cfg-simplify-early`: its input and output end in the same result on every call. -/ + +namespace SolarTV.Milestone.Reader + +open Machine SolarTV.Export.Reader SolarTV.Milestone.W1 + +set_option maxHeartbeats 8000000 in +theorem evm1_run (o : Oracle) (call : Call) : + EVM.Program.run o sched call 48 = EVM.Program.run o evm1 call 24 := by + sym_exec + +/-- info: 'SolarTV.Milestone.Reader.evm1_run' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within evm1_run + +end SolarTV.Milestone.Reader diff --git a/Certified/reader/Proofs/Runs/Evm2.lean b/Certified/reader/Proofs/Runs/Evm2.lean new file mode 100644 index 00000000..524dcf8a --- /dev/null +++ b/Certified/reader/Proofs/Runs/Evm2.lean @@ -0,0 +1,22 @@ +-- Generated by solar-tv/milestone/certify.py; do not edit. +import W1Proofs.Tactic +import W1Proofs.Axioms +import reader.gen.Reader.Evm2 +import reader.gen.Reader.Evm1 + +/-! `block-layout`: its input and output end in the same result on every call. -/ + +namespace SolarTV.Milestone.Reader + +open Machine SolarTV.Export.Reader SolarTV.Milestone.W1 + +set_option maxHeartbeats 8000000 in +theorem evm2_run (o : Oracle) (call : Call) : + EVM.Program.run o evm1 call 24 = EVM.Program.run o evm2 call 24 := by + sym_exec + +/-- info: 'SolarTV.Milestone.Reader.evm2_run' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within evm2_run + +end SolarTV.Milestone.Reader diff --git a/Certified/reader/Proofs/Runs/Evm3.lean b/Certified/reader/Proofs/Runs/Evm3.lean new file mode 100644 index 00000000..2e1d1f0d --- /dev/null +++ b/Certified/reader/Proofs/Runs/Evm3.lean @@ -0,0 +1,22 @@ +-- Generated by solar-tv/milestone/certify.py; do not edit. +import W1Proofs.Tactic +import W1Proofs.Axioms +import reader.gen.Reader.Evm3 +import reader.gen.Reader.Evm2 + +/-! `terminal-dedup`: its input and output end in the same result on every call. -/ + +namespace SolarTV.Milestone.Reader + +open Machine SolarTV.Export.Reader SolarTV.Milestone.W1 + +set_option maxHeartbeats 8000000 in +theorem evm3_run (o : Oracle) (call : Call) : + EVM.Program.run o evm2 call 24 = EVM.Program.run o evm3 call 24 := by + sym_exec + +/-- info: 'SolarTV.Milestone.Reader.evm3_run' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within evm3_run + +end SolarTV.Milestone.Reader diff --git a/Certified/reader/Proofs/Runs/Evm4.lean b/Certified/reader/Proofs/Runs/Evm4.lean new file mode 100644 index 00000000..6195570f --- /dev/null +++ b/Certified/reader/Proofs/Runs/Evm4.lean @@ -0,0 +1,22 @@ +-- Generated by solar-tv/milestone/certify.py; do not edit. +import W1Proofs.Tactic +import W1Proofs.Axioms +import reader.gen.Reader.Evm4 +import reader.gen.Reader.Evm3 + +/-! `cfg-simplify-early`: its input and output end in the same result on every call. -/ + +namespace SolarTV.Milestone.Reader + +open Machine SolarTV.Export.Reader SolarTV.Milestone.W1 + +set_option maxHeartbeats 8000000 in +theorem evm4_run (o : Oracle) (call : Call) : + EVM.Program.run o evm3 call 24 = EVM.Program.run o evm4 call 20 := by + sym_exec + +/-- info: 'SolarTV.Milestone.Reader.evm4_run' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within evm4_run + +end SolarTV.Milestone.Reader diff --git a/Certified/reader/Proofs/Runs/Evm5.lean b/Certified/reader/Proofs/Runs/Evm5.lean new file mode 100644 index 00000000..cff6874c --- /dev/null +++ b/Certified/reader/Proofs/Runs/Evm5.lean @@ -0,0 +1,22 @@ +-- Generated by solar-tv/milestone/certify.py; do not edit. +import W1Proofs.Tactic +import W1Proofs.Axioms +import reader.gen.Reader.Evm5 +import reader.gen.Reader.Evm4 + +/-! `block-cse`: its input and output end in the same result on every call. -/ + +namespace SolarTV.Milestone.Reader + +open Machine SolarTV.Export.Reader SolarTV.Milestone.W1 + +set_option maxHeartbeats 8000000 in +theorem evm5_run (o : Oracle) (call : Call) : + EVM.Program.run o evm4 call 20 = EVM.Program.run o evm5 call 20 := by + sym_exec + +/-- info: 'SolarTV.Milestone.Reader.evm5_run' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within evm5_run + +end SolarTV.Milestone.Reader diff --git a/Certified/reader/Proofs/Runs/Evm6.lean b/Certified/reader/Proofs/Runs/Evm6.lean new file mode 100644 index 00000000..bafd5bf6 --- /dev/null +++ b/Certified/reader/Proofs/Runs/Evm6.lean @@ -0,0 +1,22 @@ +-- Generated by solar-tv/milestone/certify.py; do not edit. +import W1Proofs.Tactic +import W1Proofs.Axioms +import reader.gen.Reader.Evm6 +import reader.gen.Reader.Evm5 + +/-! `share-reverts`: its input and output end in the same result on every call. -/ + +namespace SolarTV.Milestone.Reader + +open Machine SolarTV.Export.Reader SolarTV.Milestone.W1 + +set_option maxHeartbeats 8000000 in +theorem evm6_run (o : Oracle) (call : Call) : + EVM.Program.run o evm5 call 20 = EVM.Program.run o evm6 call 20 := by + sym_exec + +/-- info: 'SolarTV.Milestone.Reader.evm6_run' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within evm6_run + +end SolarTV.Milestone.Reader diff --git a/Certified/reader/Proofs/Runs/Evm7.lean b/Certified/reader/Proofs/Runs/Evm7.lean new file mode 100644 index 00000000..92dfe058 --- /dev/null +++ b/Certified/reader/Proofs/Runs/Evm7.lean @@ -0,0 +1,22 @@ +-- Generated by solar-tv/milestone/certify.py; do not edit. +import W1Proofs.Tactic +import W1Proofs.Axioms +import reader.gen.Reader.Evm7 +import reader.gen.Reader.Evm6 + +/-! `cfg-simplify-early`: its input and output end in the same result on every call. -/ + +namespace SolarTV.Milestone.Reader + +open Machine SolarTV.Export.Reader SolarTV.Milestone.W1 + +set_option maxHeartbeats 8000000 in +theorem evm7_run (o : Oracle) (call : Call) : + EVM.Program.run o evm6 call 20 = EVM.Program.run o evm7 call 16 := by + sym_exec + +/-- info: 'SolarTV.Milestone.Reader.evm7_run' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within evm7_run + +end SolarTV.Milestone.Reader diff --git a/Certified/reader/Proofs/Runs/Mir1.lean b/Certified/reader/Proofs/Runs/Mir1.lean new file mode 100644 index 00000000..f3ebd2c5 --- /dev/null +++ b/Certified/reader/Proofs/Runs/Mir1.lean @@ -0,0 +1,22 @@ +-- Generated by solar-tv/milestone/certify.py; do not edit. +import W1Proofs.Tactic +import W1Proofs.Axioms +import reader.gen.Reader.Mir1 +import reader.gen.Reader.Stage0 + +/-! `place-reads`: its input and output end in the same result on every call. -/ + +namespace SolarTV.Milestone.Reader + +open Machine SolarTV.Export.Reader SolarTV.Milestone.W1 + +set_option maxHeartbeats 8000000 in +theorem mir1_run (o : Oracle) (call : Call) : + MIR.Lowered.Module.run o stage0 call 48 = MIR.Lowered.Module.run o mir1 call 48 := by + sym_exec + +/-- info: 'SolarTV.Milestone.Reader.mir1_run' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within mir1_run + +end SolarTV.Milestone.Reader diff --git a/Certified/reader/Proofs/Runs/Mir2.lean b/Certified/reader/Proofs/Runs/Mir2.lean new file mode 100644 index 00000000..1ac8eb7a --- /dev/null +++ b/Certified/reader/Proofs/Runs/Mir2.lean @@ -0,0 +1,22 @@ +-- Generated by solar-tv/milestone/certify.py; do not edit. +import W1Proofs.Tactic +import W1Proofs.Axioms +import reader.gen.Reader.Mir2 +import reader.gen.Reader.Mir1 + +/-! `spell-width-tests`: its input and output end in the same result on every call. -/ + +namespace SolarTV.Milestone.Reader + +open Machine SolarTV.Export.Reader SolarTV.Milestone.W1 + +set_option maxHeartbeats 8000000 in +theorem mir2_run (o : Oracle) (call : Call) : + MIR.Lowered.Module.run o mir1 call 48 = MIR.Lowered.Module.run o mir2 call 48 := by + sym_exec + +/-- info: 'SolarTV.Milestone.Reader.mir2_run' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within mir2_run + +end SolarTV.Milestone.Reader diff --git a/Certified/reader/Proofs/Runs/Mir3.lean b/Certified/reader/Proofs/Runs/Mir3.lean new file mode 100644 index 00000000..261318f3 --- /dev/null +++ b/Certified/reader/Proofs/Runs/Mir3.lean @@ -0,0 +1,22 @@ +-- Generated by solar-tv/milestone/certify.py; do not edit. +import W1Proofs.Tactic +import W1Proofs.Axioms +import reader.gen.Reader.Mir3 +import reader.gen.Reader.Mir2 + +/-! `evm-inst-schedule`: its input and output end in the same result on every call. -/ + +namespace SolarTV.Milestone.Reader + +open Machine SolarTV.Export.Reader SolarTV.Milestone.W1 + +set_option maxHeartbeats 8000000 in +theorem mir3_run (o : Oracle) (call : Call) : + MIR.Lowered.Module.run o mir2 call 48 = MIR.Lowered.Module.run o mir3 call 48 := by + sym_exec + +/-- info: 'SolarTV.Milestone.Reader.mir3_run' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within mir3_run + +end SolarTV.Milestone.Reader diff --git a/Certified/reader/Proofs/Runs/Sched.lean b/Certified/reader/Proofs/Runs/Sched.lean new file mode 100644 index 00000000..eaec8867 --- /dev/null +++ b/Certified/reader/Proofs/Runs/Sched.lean @@ -0,0 +1,22 @@ +-- Generated by solar-tv/milestone/certify.py; do not edit. +import W1Proofs.Tactic +import W1Proofs.Axioms +import reader.gen.Reader.Sched +import reader.gen.Reader.Mir3 + +/-! Stack scheduling: the last lowered MIR and the scheduled EVM IR end in the same result on every call. -/ + +namespace SolarTV.Milestone.Reader + +open Machine SolarTV.Export.Reader SolarTV.Milestone.W1 + +set_option maxHeartbeats 8000000 in +theorem sched_run (o : Oracle) (call : Call) : + MIR.Lowered.Module.run o mir3 call 48 = EVM.Program.run o sched call 48 := by + sym_exec + +/-- info: 'SolarTV.Milestone.Reader.sched_run' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within sched_run + +end SolarTV.Milestone.Reader diff --git a/Certified/reader/Proofs/Runs/Stage0.lean b/Certified/reader/Proofs/Runs/Stage0.lean new file mode 100644 index 00000000..76261936 --- /dev/null +++ b/Certified/reader/Proofs/Runs/Stage0.lean @@ -0,0 +1,21 @@ +-- Generated by solar-tv/milestone/certify.py; do not edit. +import W1Proofs.Tactic +import W1Proofs.Axioms +import reader.gen.Reader.Stage0 + +/-! The first lowered MIR ends on every call within 48 blocks, its block count times the square of one more than its call sites. -/ + +namespace SolarTV.Milestone.Reader + +open Machine SolarTV.Export.Reader SolarTV.Milestone.W1 + +set_option maxHeartbeats 8000000 in +theorem stage0_ends (o : Oracle) (call : Call) : + (MIR.Lowered.Module.run o stage0 call 48).isSome = true := by + sym_exec + +/-- info: 'SolarTV.Milestone.Reader.stage0_ends' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within stage0_ends + +end SolarTV.Milestone.Reader diff --git a/Certified/reader/Proofs/Stages.lean b/Certified/reader/Proofs/Stages.lean new file mode 100644 index 00000000..093fa2a4 --- /dev/null +++ b/Certified/reader/Proofs/Stages.lean @@ -0,0 +1,195 @@ +-- Generated by solar-tv/milestone/certify.py; do not edit. +import reader.Proofs.Runs.Stage0 +import reader.Proofs.Runs.Mir1 +import reader.Proofs.Runs.Mir2 +import reader.Proofs.Runs.Mir3 +import reader.Proofs.Runs.Sched +import reader.Proofs.Runs.Evm1 +import reader.Proofs.Runs.Evm2 +import reader.Proofs.Runs.Evm3 +import reader.Proofs.Runs.Evm4 +import reader.Proofs.Runs.Evm5 +import reader.Proofs.Runs.Evm6 +import reader.Proofs.Runs.Evm7 +import W1Proofs.Stage +import SolarTV.Composition + +/-! The backend stages of `Reader`, each proved on every call (`anyCall`: any calldata, call value and storage) under every oracle, and chained from the first lowered MIR `stage0` to the final EVM IR `evm7`. Fuels are the programs' block counts times the square of one more than their call sites. -/ + +namespace SolarTV.Milestone.Reader + +open Machine SolarTV.Export.Reader SolarTV.Milestone.W1 + +/-- `place-reads`: stage0 to mir1. -/ +theorem stage_mir1 (o : Oracle) : Stage (mirSem o) (mirSem o) stage0 mir1 anyCall := + stage_of_runs (A := MIR.Lowered.moduleLayer) (B := MIR.Lowered.moduleLayer) 48 48 (fun call _ => stage0_ends o call) + (fun call _ => mir1_run o call) + +theorem mir1_ends (o : Oracle) : ∀ call, anyCall call → + (MIR.Lowered.Module.run o mir1 call 48).isSome = true := + ends_of_runs (A := MIR.Lowered.moduleLayer) (B := MIR.Lowered.moduleLayer) + (o := o) (p := stage0) (q := mir1) (n := 48) (m := 48) (fun call _ => stage0_ends o call) + (fun call _ => mir1_run o call) + +/-- `spell-width-tests`: mir1 to mir2. -/ +theorem stage_mir2 (o : Oracle) : Stage (mirSem o) (mirSem o) mir1 mir2 anyCall := + stage_of_runs (A := MIR.Lowered.moduleLayer) (B := MIR.Lowered.moduleLayer) 48 48 (mir1_ends o) + (fun call _ => mir2_run o call) + +theorem mir2_ends (o : Oracle) : ∀ call, anyCall call → + (MIR.Lowered.Module.run o mir2 call 48).isSome = true := + ends_of_runs (A := MIR.Lowered.moduleLayer) (B := MIR.Lowered.moduleLayer) + (o := o) (p := mir1) (q := mir2) (n := 48) (m := 48) (mir1_ends o) + (fun call _ => mir2_run o call) + +/-- `evm-inst-schedule`: mir2 to mir3. -/ +theorem stage_mir3 (o : Oracle) : Stage (mirSem o) (mirSem o) mir2 mir3 anyCall := + stage_of_runs (A := MIR.Lowered.moduleLayer) (B := MIR.Lowered.moduleLayer) 48 48 (mir2_ends o) + (fun call _ => mir3_run o call) + +theorem mir3_ends (o : Oracle) : ∀ call, anyCall call → + (MIR.Lowered.Module.run o mir3 call 48).isSome = true := + ends_of_runs (A := MIR.Lowered.moduleLayer) (B := MIR.Lowered.moduleLayer) + (o := o) (p := mir2) (q := mir3) (n := 48) (m := 48) (mir2_ends o) + (fun call _ => mir3_run o call) + +/-- `stack-schedule`: mir3 to sched. -/ +theorem stage_sched (o : Oracle) : Stage (mirSem o) (evmirSem o) mir3 sched anyCall := + stage_of_runs (A := MIR.Lowered.moduleLayer) (B := EVM.Program.layer) 48 48 (mir3_ends o) + (fun call _ => sched_run o call) + +theorem sched_ends (o : Oracle) : ∀ call, anyCall call → + (EVM.Program.run o sched call 48).isSome = true := + ends_of_runs (A := MIR.Lowered.moduleLayer) (B := EVM.Program.layer) + (o := o) (p := mir3) (q := sched) (n := 48) (m := 48) (mir3_ends o) + (fun call _ => sched_run o call) + +/-- `cfg-simplify-early`: sched to evm1. -/ +theorem stage_evm1 (o : Oracle) : Stage (evmirSem o) (evmirSem o) sched evm1 anyCall := + stage_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) 48 24 (sched_ends o) + (fun call _ => evm1_run o call) + +theorem evm1_ends (o : Oracle) : ∀ call, anyCall call → + (EVM.Program.run o evm1 call 24).isSome = true := + ends_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) + (o := o) (p := sched) (q := evm1) (n := 48) (m := 24) (sched_ends o) + (fun call _ => evm1_run o call) + +/-- `block-layout`: evm1 to evm2. -/ +theorem stage_evm2 (o : Oracle) : Stage (evmirSem o) (evmirSem o) evm1 evm2 anyCall := + stage_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) 24 24 (evm1_ends o) + (fun call _ => evm2_run o call) + +theorem evm2_ends (o : Oracle) : ∀ call, anyCall call → + (EVM.Program.run o evm2 call 24).isSome = true := + ends_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) + (o := o) (p := evm1) (q := evm2) (n := 24) (m := 24) (evm1_ends o) + (fun call _ => evm2_run o call) + +/-- `terminal-dedup`: evm2 to evm3. -/ +theorem stage_evm3 (o : Oracle) : Stage (evmirSem o) (evmirSem o) evm2 evm3 anyCall := + stage_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) 24 24 (evm2_ends o) + (fun call _ => evm3_run o call) + +theorem evm3_ends (o : Oracle) : ∀ call, anyCall call → + (EVM.Program.run o evm3 call 24).isSome = true := + ends_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) + (o := o) (p := evm2) (q := evm3) (n := 24) (m := 24) (evm2_ends o) + (fun call _ => evm3_run o call) + +/-- `cfg-simplify-early`: evm3 to evm4. -/ +theorem stage_evm4 (o : Oracle) : Stage (evmirSem o) (evmirSem o) evm3 evm4 anyCall := + stage_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) 24 20 (evm3_ends o) + (fun call _ => evm4_run o call) + +theorem evm4_ends (o : Oracle) : ∀ call, anyCall call → + (EVM.Program.run o evm4 call 20).isSome = true := + ends_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) + (o := o) (p := evm3) (q := evm4) (n := 24) (m := 20) (evm3_ends o) + (fun call _ => evm4_run o call) + +/-- `block-cse`: evm4 to evm5. -/ +theorem stage_evm5 (o : Oracle) : Stage (evmirSem o) (evmirSem o) evm4 evm5 anyCall := + stage_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) 20 20 (evm4_ends o) + (fun call _ => evm5_run o call) + +theorem evm5_ends (o : Oracle) : ∀ call, anyCall call → + (EVM.Program.run o evm5 call 20).isSome = true := + ends_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) + (o := o) (p := evm4) (q := evm5) (n := 20) (m := 20) (evm4_ends o) + (fun call _ => evm5_run o call) + +/-- `share-reverts`: evm5 to evm6. -/ +theorem stage_evm6 (o : Oracle) : Stage (evmirSem o) (evmirSem o) evm5 evm6 anyCall := + stage_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) 20 20 (evm5_ends o) + (fun call _ => evm6_run o call) + +theorem evm6_ends (o : Oracle) : ∀ call, anyCall call → + (EVM.Program.run o evm6 call 20).isSome = true := + ends_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) + (o := o) (p := evm5) (q := evm6) (n := 20) (m := 20) (evm5_ends o) + (fun call _ => evm6_run o call) + +/-- `cfg-simplify-early`: evm6 to evm7. -/ +theorem stage_evm7 (o : Oracle) : Stage (evmirSem o) (evmirSem o) evm6 evm7 anyCall := + stage_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) 20 16 (evm6_ends o) + (fun call _ => evm7_run o call) + +/-- The compilation from the first lowered MIR to the final EVM IR. -/ +def compilation : Compilation := + ⟨stage0, [mir1, mir2, mir3], sched, [evm1, evm2, evm3, evm4, evm5, evm6, evm7]⟩ + +/-- Every stage from the first lowered MIR to the final EVM IR, chained by the library's composition, on every call. -/ +theorem reader_mir_to_evmir (o : Oracle) : Stage (mirSem o) (evmirSem o) stage0 evm7 anyCall := + mir_to_evmir o anyCall compilation ⟨stage_mir1 o, stage_mir2 o, stage_mir3 o, trivial⟩ (stage_sched o) + ⟨stage_evm1 o, stage_evm2 o, stage_evm3 o, stage_evm4 o, stage_evm5 o, stage_evm6 o, stage_evm7 o, trivial⟩ + +/-- info: 'SolarTV.Milestone.Reader.stage_mir1' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms stage_mir1 + +/-- info: 'SolarTV.Milestone.Reader.stage_mir2' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms stage_mir2 + +/-- info: 'SolarTV.Milestone.Reader.stage_mir3' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms stage_mir3 + +/-- info: 'SolarTV.Milestone.Reader.stage_sched' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms stage_sched + +/-- info: 'SolarTV.Milestone.Reader.stage_evm1' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms stage_evm1 + +/-- info: 'SolarTV.Milestone.Reader.stage_evm2' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms stage_evm2 + +/-- info: 'SolarTV.Milestone.Reader.stage_evm3' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms stage_evm3 + +/-- info: 'SolarTV.Milestone.Reader.stage_evm4' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms stage_evm4 + +/-- info: 'SolarTV.Milestone.Reader.stage_evm5' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms stage_evm5 + +/-- info: 'SolarTV.Milestone.Reader.stage_evm6' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms stage_evm6 + +/-- info: 'SolarTV.Milestone.Reader.stage_evm7' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms stage_evm7 + +/-- info: 'SolarTV.Milestone.Reader.reader_mir_to_evmir' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms reader_mir_to_evmir + +end SolarTV.Milestone.Reader diff --git a/Certified/reader/bytecode.hex b/Certified/reader/bytecode.hex new file mode 100644 index 00000000..38cf9e30 --- /dev/null +++ b/Certified/reader/bytecode.hex @@ -0,0 +1 @@ +346053575f3560e01c8063a087a87e03605357608060405260043560a01c602436101760535763a035b1fe5f5260205f6004601c81355afa156057573d6020116053575f516001018015605f575f5260205ff35b5f5ffd5b3d5f5f3e3d5ffd5b6011602052634e487b715f526024601cfd diff --git a/Certified/reader/gen/Reader/Bytecode.lean b/Certified/reader/gen/Reader/Bytecode.lean new file mode 100644 index 00000000..fdf8bb18 --- /dev/null +++ b/Certified/reader/gen/Reader/Bytecode.lean @@ -0,0 +1,21 @@ +-- solar-lean-stage: kind=bytecode index=0 pass=assemble +/-! Generated by `solar -Zemit-lean-stages` for `Reader`; do not edit. -/ + +namespace SolarTV.Export.Reader + +/-- The runtime bytecode, byte by byte. -/ +def bytecode : List Nat := + [0x34, 0x60, 0x53, 0x57, 0x5f, 0x35, 0x60, 0xe0, 0x1c, 0x80, 0x63, 0xa0, 0x87, 0xa8, 0x7e, 0x03, + 0x60, 0x53, 0x57, 0x60, 0x80, 0x60, 0x40, 0x52, 0x60, 0x04, 0x35, 0x60, 0xa0, 0x1c, 0x60, 0x24, + 0x36, 0x10, 0x17, 0x60, 0x53, 0x57, 0x63, 0xa0, 0x35, 0xb1, 0xfe, 0x5f, 0x52, 0x60, 0x20, 0x5f, + 0x60, 0x04, 0x60, 0x1c, 0x81, 0x35, 0x5a, 0xfa, 0x15, 0x60, 0x57, 0x57, 0x3d, 0x60, 0x20, 0x11, + 0x60, 0x53, 0x57, 0x5f, 0x51, 0x60, 0x01, 0x01, 0x80, 0x15, 0x60, 0x5f, 0x57, 0x5f, 0x52, 0x60, + 0x20, 0x5f, 0xf3, 0x5b, 0x5f, 0x5f, 0xfd, 0x5b, 0x3d, 0x5f, 0x5f, 0x3e, 0x3d, 0x5f, 0xfd, 0x5b, + 0x60, 0x11, 0x60, 0x20, 0x52, 0x63, 0x4e, 0x48, 0x7b, 0x71, 0x5f, 0x52, 0x60, 0x24, 0x60, 0x1c, + 0xfd] + +/-- The runtime bytecode in hex, as `--emit=bin-runtime` prints it. -/ +def bytecodeHex : String := + "346053575f3560e01c8063a087a87e03605357608060405260043560a01c602436101760535763a035b1fe5f5260205f6004601c81355afa156057573d6020116053575f516001018015605f575f5260205ff35b5f5ffd5b3d5f5f3e3d5ffd5b6011602052634e487b715f526024601cfd" + +end SolarTV.Export.Reader diff --git a/Certified/reader/gen/Reader/Evm1.lean b/Certified/reader/gen/Reader/Evm1.lean new file mode 100644 index 00000000..89e56944 --- /dev/null +++ b/Certified/reader/gen/Reader/Evm1.lean @@ -0,0 +1,92 @@ +-- solar-lean-stage: kind=evm index=1 pass=cfg-simplify-early +import SolarTV.EVMIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `Reader`; do not edit. -/ + +namespace SolarTV.Export.Reader + +/-- The runtime EVM IR after `cfg-simplify-early`. -/ +def evm1 : EVM.Program.Program := + { blocks := [ + -- bb0 + [.effect .callvalue 0, + .jumpi 1, + .op (.stack (.push 0)), + .effect .calldataload 1, + .op (.stack (.push 224)), + .op (.stack .shr), + .op (.stack (.dup 0)), + .op (.stack (.push 0xa087a87e)), + .op (.stack .eq), + .jumpi 2, + .jump 1], + -- bb3 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb4 + [.op (.stack (.push 128)), + .op (.stack (.push 64)), + .op .store, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 160)), + .op (.stack .shr), + .op (.stack (.push 36)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack .or), + .jumpi 5, + .op (.stack (.push 0xa035b1fe)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .op (.stack (.push 4)), + .op (.stack (.push 28)), + .op (.stack (.push 4)), + .effect .calldataload 1, + .effect .gas 0, + .effect (.call .staticcall) 6, + .op (.stack .iszero), + .jumpi 3, + .op (.stack .returndatasize), + .op (.stack (.push 32)), + .op (.stack .gt), + .jumpi 5, + .op (.stack (.push 0)), + .op .load, + .op (.stack (.push 1)), + .op (.stack .add), + .op (.stack (.dup 0)), + .op (.stack .iszero), + .jumpi 4, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb9 + [.op (.stack .returndatasize), + .op (.stack (.push 0)), + .op (.stack (.push 0)), + .effect .returndatacopy 3, + .op (.stack .returndatasize), + .op (.stack (.push 0)), + .revert], + -- bb10 + [.op (.stack (.push 17)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 0x4e487b71)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 36)), + .op (.stack (.push 28)), + .revert], + -- bb11 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert]] } + +end SolarTV.Export.Reader diff --git a/Certified/reader/gen/Reader/Evm2.lean b/Certified/reader/gen/Reader/Evm2.lean new file mode 100644 index 00000000..de6983b7 --- /dev/null +++ b/Certified/reader/gen/Reader/Evm2.lean @@ -0,0 +1,92 @@ +-- solar-lean-stage: kind=evm index=2 pass=block-layout +import SolarTV.EVMIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `Reader`; do not edit. -/ + +namespace SolarTV.Export.Reader + +/-- The runtime EVM IR after `block-layout`. -/ +def evm2 : EVM.Program.Program := + { blocks := [ + -- bb0 + [.effect .callvalue 0, + .jumpi 1, + .op (.stack (.push 0)), + .effect .calldataload 1, + .op (.stack (.push 224)), + .op (.stack .shr), + .op (.stack (.dup 0)), + .op (.stack (.push 0xa087a87e)), + .op (.stack .eq), + .jumpi 3, + .jump 1], + -- bb3 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb11 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb4 + [.op (.stack (.push 128)), + .op (.stack (.push 64)), + .op .store, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 160)), + .op (.stack .shr), + .op (.stack (.push 36)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack .or), + .jumpi 2, + .op (.stack (.push 0xa035b1fe)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .op (.stack (.push 4)), + .op (.stack (.push 28)), + .op (.stack (.push 4)), + .effect .calldataload 1, + .effect .gas 0, + .effect (.call .staticcall) 6, + .op (.stack .iszero), + .jumpi 4, + .op (.stack .returndatasize), + .op (.stack (.push 32)), + .op (.stack .gt), + .jumpi 2, + .op (.stack (.push 0)), + .op .load, + .op (.stack (.push 1)), + .op (.stack .add), + .op (.stack (.dup 0)), + .op (.stack .iszero), + .jumpi 5, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb9 + [.op (.stack .returndatasize), + .op (.stack (.push 0)), + .op (.stack (.push 0)), + .effect .returndatacopy 3, + .op (.stack .returndatasize), + .op (.stack (.push 0)), + .revert], + -- bb10 + [.op (.stack (.push 17)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 0x4e487b71)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 36)), + .op (.stack (.push 28)), + .revert]] } + +end SolarTV.Export.Reader diff --git a/Certified/reader/gen/Reader/Evm3.lean b/Certified/reader/gen/Reader/Evm3.lean new file mode 100644 index 00000000..fcfc5566 --- /dev/null +++ b/Certified/reader/gen/Reader/Evm3.lean @@ -0,0 +1,90 @@ +-- solar-lean-stage: kind=evm index=3 pass=terminal-dedup +import SolarTV.EVMIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `Reader`; do not edit. -/ + +namespace SolarTV.Export.Reader + +/-- The runtime EVM IR after `terminal-dedup`. -/ +def evm3 : EVM.Program.Program := + { blocks := [ + -- bb0 + [.effect .callvalue 0, + .jumpi 1, + .op (.stack (.push 0)), + .effect .calldataload 1, + .op (.stack (.push 224)), + .op (.stack .shr), + .op (.stack (.dup 0)), + .op (.stack (.push 0xa087a87e)), + .op (.stack .eq), + .jumpi 3, + .jump 1], + -- bb3 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb11 + [.jump 1], + -- bb4 + [.op (.stack (.push 128)), + .op (.stack (.push 64)), + .op .store, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 160)), + .op (.stack .shr), + .op (.stack (.push 36)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack .or), + .jumpi 2, + .op (.stack (.push 0xa035b1fe)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .op (.stack (.push 4)), + .op (.stack (.push 28)), + .op (.stack (.push 4)), + .effect .calldataload 1, + .effect .gas 0, + .effect (.call .staticcall) 6, + .op (.stack .iszero), + .jumpi 4, + .op (.stack .returndatasize), + .op (.stack (.push 32)), + .op (.stack .gt), + .jumpi 2, + .op (.stack (.push 0)), + .op .load, + .op (.stack (.push 1)), + .op (.stack .add), + .op (.stack (.dup 0)), + .op (.stack .iszero), + .jumpi 5, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb9 + [.op (.stack .returndatasize), + .op (.stack (.push 0)), + .op (.stack (.push 0)), + .effect .returndatacopy 3, + .op (.stack .returndatasize), + .op (.stack (.push 0)), + .revert], + -- bb10 + [.op (.stack (.push 17)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 0x4e487b71)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 36)), + .op (.stack (.push 28)), + .revert]] } + +end SolarTV.Export.Reader diff --git a/Certified/reader/gen/Reader/Evm4.lean b/Certified/reader/gen/Reader/Evm4.lean new file mode 100644 index 00000000..547ef996 --- /dev/null +++ b/Certified/reader/gen/Reader/Evm4.lean @@ -0,0 +1,88 @@ +-- solar-lean-stage: kind=evm index=4 pass=cfg-simplify-early +import SolarTV.EVMIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `Reader`; do not edit. -/ + +namespace SolarTV.Export.Reader + +/-- The runtime EVM IR after `cfg-simplify-early`. -/ +def evm4 : EVM.Program.Program := + { blocks := [ + -- bb0 + [.effect .callvalue 0, + .jumpi 1, + .op (.stack (.push 0)), + .effect .calldataload 1, + .op (.stack (.push 224)), + .op (.stack .shr), + .op (.stack (.dup 0)), + .op (.stack (.push 0xa087a87e)), + .op (.stack .eq), + .jumpi 2, + .jump 1], + -- bb3 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb4 + [.op (.stack (.push 128)), + .op (.stack (.push 64)), + .op .store, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 160)), + .op (.stack .shr), + .op (.stack (.push 36)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack .or), + .jumpi 1, + .op (.stack (.push 0xa035b1fe)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .op (.stack (.push 4)), + .op (.stack (.push 28)), + .op (.stack (.push 4)), + .effect .calldataload 1, + .effect .gas 0, + .effect (.call .staticcall) 6, + .op (.stack .iszero), + .jumpi 3, + .op (.stack .returndatasize), + .op (.stack (.push 32)), + .op (.stack .gt), + .jumpi 1, + .op (.stack (.push 0)), + .op .load, + .op (.stack (.push 1)), + .op (.stack .add), + .op (.stack (.dup 0)), + .op (.stack .iszero), + .jumpi 4, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb9 + [.op (.stack .returndatasize), + .op (.stack (.push 0)), + .op (.stack (.push 0)), + .effect .returndatacopy 3, + .op (.stack .returndatasize), + .op (.stack (.push 0)), + .revert], + -- bb10 + [.op (.stack (.push 17)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 0x4e487b71)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 36)), + .op (.stack (.push 28)), + .revert]] } + +end SolarTV.Export.Reader diff --git a/Certified/reader/gen/Reader/Evm5.lean b/Certified/reader/gen/Reader/Evm5.lean new file mode 100644 index 00000000..8b20556d --- /dev/null +++ b/Certified/reader/gen/Reader/Evm5.lean @@ -0,0 +1,88 @@ +-- solar-lean-stage: kind=evm index=5 pass=block-cse +import SolarTV.EVMIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `Reader`; do not edit. -/ + +namespace SolarTV.Export.Reader + +/-- The runtime EVM IR after `block-cse`. -/ +def evm5 : EVM.Program.Program := + { blocks := [ + -- bb0 + [.effect .callvalue 0, + .jumpi 1, + .op (.stack (.push 0)), + .effect .calldataload 1, + .op (.stack (.push 224)), + .op (.stack .shr), + .op (.stack (.dup 0)), + .op (.stack (.push 0xa087a87e)), + .op (.stack .eq), + .jumpi 2, + .jump 1], + -- bb3 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb4 + [.op (.stack (.push 128)), + .op (.stack (.push 64)), + .op .store, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 160)), + .op (.stack .shr), + .op (.stack (.push 36)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack .or), + .jumpi 1, + .op (.stack (.push 0xa035b1fe)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .op (.stack (.push 4)), + .op (.stack (.push 28)), + .op (.stack (.dup 1)), + .effect .calldataload 1, + .effect .gas 0, + .effect (.call .staticcall) 6, + .op (.stack .iszero), + .jumpi 3, + .op (.stack .returndatasize), + .op (.stack (.push 32)), + .op (.stack .gt), + .jumpi 1, + .op (.stack (.push 0)), + .op .load, + .op (.stack (.push 1)), + .op (.stack .add), + .op (.stack (.dup 0)), + .op (.stack .iszero), + .jumpi 4, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb9 + [.op (.stack .returndatasize), + .op (.stack (.push 0)), + .op (.stack (.push 0)), + .effect .returndatacopy 3, + .op (.stack .returndatasize), + .op (.stack (.push 0)), + .revert], + -- bb10 + [.op (.stack (.push 17)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 0x4e487b71)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 36)), + .op (.stack (.push 28)), + .revert]] } + +end SolarTV.Export.Reader diff --git a/Certified/reader/gen/Reader/Evm6.lean b/Certified/reader/gen/Reader/Evm6.lean new file mode 100644 index 00000000..e63faf9b --- /dev/null +++ b/Certified/reader/gen/Reader/Evm6.lean @@ -0,0 +1,88 @@ +-- solar-lean-stage: kind=evm index=6 pass=share-reverts +import SolarTV.EVMIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `Reader`; do not edit. -/ + +namespace SolarTV.Export.Reader + +/-- The runtime EVM IR after `share-reverts`. -/ +def evm6 : EVM.Program.Program := + { blocks := [ + -- bb0 + [.effect .callvalue 0, + .jumpi 1, + .op (.stack (.push 0)), + .effect .calldataload 1, + .op (.stack (.push 224)), + .op (.stack .shr), + .op (.stack (.dup 0)), + .op (.stack (.push 0xa087a87e)), + .op (.stack .sub), + .jumpi 1, + .jump 2], + -- bb3 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb4 + [.op (.stack (.push 128)), + .op (.stack (.push 64)), + .op .store, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 160)), + .op (.stack .shr), + .op (.stack (.push 36)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack .or), + .jumpi 1, + .op (.stack (.push 0xa035b1fe)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .op (.stack (.push 4)), + .op (.stack (.push 28)), + .op (.stack (.dup 1)), + .effect .calldataload 1, + .effect .gas 0, + .effect (.call .staticcall) 6, + .op (.stack .iszero), + .jumpi 3, + .op (.stack .returndatasize), + .op (.stack (.push 32)), + .op (.stack .gt), + .jumpi 1, + .op (.stack (.push 0)), + .op .load, + .op (.stack (.push 1)), + .op (.stack .add), + .op (.stack (.dup 0)), + .op (.stack .iszero), + .jumpi 4, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb9 + [.op (.stack .returndatasize), + .op (.stack (.push 0)), + .op (.stack (.push 0)), + .effect .returndatacopy 3, + .op (.stack .returndatasize), + .op (.stack (.push 0)), + .revert], + -- bb10 + [.op (.stack (.push 17)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 0x4e487b71)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 36)), + .op (.stack (.push 28)), + .revert]] } + +end SolarTV.Export.Reader diff --git a/Certified/reader/gen/Reader/Evm7.lean b/Certified/reader/gen/Reader/Evm7.lean new file mode 100644 index 00000000..98970e1a --- /dev/null +++ b/Certified/reader/gen/Reader/Evm7.lean @@ -0,0 +1,86 @@ +-- solar-lean-stage: kind=evm index=7 pass=cfg-simplify-early +import SolarTV.EVMIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `Reader`; do not edit. -/ + +namespace SolarTV.Export.Reader + +/-- The runtime EVM IR after `cfg-simplify-early`. -/ +def evm7 : EVM.Program.Program := + { blocks := [ + -- bb0 + [.effect .callvalue 0, + .jumpi 1, + .op (.stack (.push 0)), + .effect .calldataload 1, + .op (.stack (.push 224)), + .op (.stack .shr), + .op (.stack (.dup 0)), + .op (.stack (.push 0xa087a87e)), + .op (.stack .sub), + .jumpi 1, + .op (.stack (.push 128)), + .op (.stack (.push 64)), + .op .store, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 160)), + .op (.stack .shr), + .op (.stack (.push 36)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack .or), + .jumpi 1, + .op (.stack (.push 0xa035b1fe)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .op (.stack (.push 4)), + .op (.stack (.push 28)), + .op (.stack (.dup 1)), + .effect .calldataload 1, + .effect .gas 0, + .effect (.call .staticcall) 6, + .op (.stack .iszero), + .jumpi 2, + .op (.stack .returndatasize), + .op (.stack (.push 32)), + .op (.stack .gt), + .jumpi 1, + .op (.stack (.push 0)), + .op .load, + .op (.stack (.push 1)), + .op (.stack .add), + .op (.stack (.dup 0)), + .op (.stack .iszero), + .jumpi 3, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb3 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb9 + [.op (.stack .returndatasize), + .op (.stack (.push 0)), + .op (.stack (.push 0)), + .effect .returndatacopy 3, + .op (.stack .returndatasize), + .op (.stack (.push 0)), + .revert], + -- bb10 + [.op (.stack (.push 17)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 0x4e487b71)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 36)), + .op (.stack (.push 28)), + .revert]] } + +end SolarTV.Export.Reader diff --git a/Certified/reader/gen/Reader/Manifest.lean b/Certified/reader/gen/Reader/Manifest.lean new file mode 100644 index 00000000..5ea2fd47 --- /dev/null +++ b/Certified/reader/gen/Reader/Manifest.lean @@ -0,0 +1,47 @@ +-- solar-lean-stage: kind=manifest index=0 pass=none +/-! Generated by `solar -Zemit-lean-stages` for `Reader`; do not edit. + +What the stages of this directory were compiled from and by. `stages` lists each +stage's file, its definition, the pass whose output it is, and the SHA-256 of the file. +-/ + +namespace SolarTV.Export.Reader.Manifest + +def sources : List (String × String) := + [("solar-tv/milestone/reader/reader.sol", "bff96eb4b5b33ebc37c3dd379d4d55388525e9787dd991afa41cc0b809b89a7e")] + +def compiler : String := "0.8.38+commit.4a7d9ede.solar.0.3.0-dev" + +def arguments : List String := + ["solar-tv/milestone/reader/reader.sol", + "-Ogas", + "--evm-version", + "osaka", + "--emit=bin-runtime", + "-Zemit-lean-stages=solar-tv/milestone/reader/gen"] + +def evmVersion : String := "osaka" + +def optimization : String := "Gas" + +def stages : List (String × String × String × String) := + [("Stage0", "stage0", "lower-evm-shaped", "c18d3ee3fbe18467c367f0b868bfa6f93511e86bbecab095a1e288d8497f85a2"), + ("Mir1", "mir1", "place-reads", "84085542c96e416459e21e878019f8af37c807d8a7cefd56afaa4238a26029d8"), + ("Mir2", "mir2", "spell-width-tests", "805f70ac294e93760f04edc04a2eaf36b89430d26dc2d4959309a53b0597d114"), + ("Mir3", "mir3", "evm-inst-schedule", "11a9ae1838d817aa69640ad29b7050cbc70b05b56c1ecf54329f5c816a2d4581"), + ("Sched", "sched", "stack-schedule", "f618618c81f32246f89af8bf5a44f7d5407b420836ba4a2527bd07677cb4b153"), + ("Evm1", "evm1", "cfg-simplify-early", "f351e61c85551e0385e65007fff190c72592edd3dad4981277769a3760514ebf"), + ("Evm2", "evm2", "block-layout", "e52785df1aca97d96814a14e02da72c28095e1f81b8e6bd9ca046109cdb22ccd"), + ("Evm3", "evm3", "terminal-dedup", "ceee2fd40bcbe7eb8e855e299c41f8bc03fab804b0fdeb0d7f6f8877ab2f0c23"), + ("Evm4", "evm4", "cfg-simplify-early", "3b74cb48e673f40e6c712cb3139a2c45b5f1acd06512ae9f4dac74d32f65f1c9"), + ("Evm5", "evm5", "block-cse", "fc489b656954d811b262210a2fc8fc512ed285a96cc07841b8ddae9a9139160a"), + ("Evm6", "evm6", "share-reverts", "ba632cf5e20581d34c5ec93d168d8d802d08c52f081a0f19be6323423d8d095b"), + ("Evm7", "evm7", "cfg-simplify-early", "a0bdf8538b97a7dfb6e452bfad93e70f2238db07643497d48ab2aad1bd7b36e7"), + ("Bytecode", "bytecode", "assemble", "ce5b93ef146d00753003f24db5c08fa70ca8cf43dfe6b38f62dfc0f23271af13")] + +def bytecodeHex : String := + "346053575f3560e01c8063a087a87e03605357608060405260043560a01c602436101760535763a035b1fe5f5260205f6004601c81355afa156057573d6020116053575f516001018015605f575f5260205ff35b5f5ffd5b3d5f5f3e3d5ffd5b6011602052634e487b715f526024601cfd" + +def bytecodeSha256 : String := "7e4fced8401133d842f58d3d310e8b78a32039960170ea5d8ad75a53a7b36626" + +end SolarTV.Export.Reader.Manifest diff --git a/Certified/reader/gen/Reader/Mir1.lean b/Certified/reader/gen/Reader/Mir1.lean new file mode 100644 index 00000000..cbc35f7e --- /dev/null +++ b/Certified/reader/gen/Reader/Mir1.lean @@ -0,0 +1,83 @@ +-- solar-lean-stage: kind=mir index=1 pass=place-reads +import SolarTV.MIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `Reader`; do not edit. -/ + +namespace SolarTV.Export.Reader + +/-- The lowered MIR module after `place-reads`. -/ +def mir1 : MIR.Lowered.Module := + { entry := 1, + functions := [ + -- @read + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 33) .calldatasize [], + .pure 35 .lt [.value 33, .const 36], + .effect (some 37) .calldataload [.const 4], + .pure 39 .gt [.value 37, .const 0xffffffffffffffffffffffffffffffffffffffff], + .pure 47 .or [.value 35, .value 39]], + .branch (.value 47) 3 7⟩, + -- bb1 + ⟨[], + [.effect (some 30) .returndatasize [], + .effect none .returndatacopy [.const 0, .const 0, .value 30], + .effect (some 31) .returndatasize []], + .revert (.const 0) (.value 31)⟩, + -- bb2 + ⟨[], + [.effect (some 13) .returndatasize [], + .pure 14 .lt [.value 13, .const 32]], + .branch (.value 14) 3 4⟩, + -- bb3 + ⟨[], + [], + .revert (.const 0) (.const 0)⟩, + -- bb4 + ⟨[], + [.effect (some 15) .mload [.const 0], + .pure 19 .add [.value 15, .const 1], + .pure 20 .eq [.value 19, .const 0]], + .branch (.value 20) 5 6⟩, + -- bb5 + ⟨[], + [.effect none .mstore [.const 32, .const 17], + .effect none .mstore [.const 0, .const 0x4e487b71]], + .revert (.const 28) (.const 36)⟩, + -- bb6 + ⟨[], + [.effect none .mstore [.const 0, .value 19]], + .ret (.const 0) (.const 32)⟩, + -- bb7 + ⟨[], + [.effect (some 48) .calldataload [.const 4], + .effect (some 3) .gas [], + .effect none .mstore [.const 0, .const 0xa035b1fe], + .effect (some 11) (.call .staticcall) [.value 3, .value 48, .const 28, .const 4, .const 0, .const 32]], + .branch (.value 11) 2 1⟩], + entryHeap := some 128 }, + -- @entry + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 0) .callvalue [], + .ne 2 (.value 0) (.const 0)], + .branch (.value 2) 3 1⟩, + -- bb1 + ⟨[], + [.effect (some 4) .calldataload [.const 0], + .pure 6 .shr [.const 224, .value 4]], + .switch (.value 6) 3 [(.const 0xa087a87e, 2)]⟩, + -- bb2 + ⟨[], + [], + .tailCall 0 []⟩, + -- bb3 + ⟨[], + [], + .revert (.const 0) (.const 0)⟩] }] } + +end SolarTV.Export.Reader diff --git a/Certified/reader/gen/Reader/Mir2.lean b/Certified/reader/gen/Reader/Mir2.lean new file mode 100644 index 00000000..6ce5ea16 --- /dev/null +++ b/Certified/reader/gen/Reader/Mir2.lean @@ -0,0 +1,85 @@ +-- solar-lean-stage: kind=mir index=2 pass=spell-width-tests +import SolarTV.MIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `Reader`; do not edit. -/ + +namespace SolarTV.Export.Reader + +/-- The lowered MIR module after `spell-width-tests`. -/ +def mir2 : MIR.Lowered.Module := + { entry := 1, + functions := [ + -- @read + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 33) .calldatasize [], + .pure 35 .lt [.value 33, .const 36], + .effect (some 37) .calldataload [.const 4], + .pure 50 .shr [.const 160, .value 37], + .word 53 (.value 35), + .pure 54 .or [.value 50, .value 53], + .ne 47 (.value 54) (.const 0)], + .branch (.value 47) 3 7⟩, + -- bb1 + ⟨[], + [.effect (some 30) .returndatasize [], + .effect none .returndatacopy [.const 0, .const 0, .value 30], + .effect (some 31) .returndatasize []], + .revert (.const 0) (.value 31)⟩, + -- bb2 + ⟨[], + [.effect (some 13) .returndatasize [], + .pure 14 .lt [.value 13, .const 32]], + .branch (.value 14) 3 4⟩, + -- bb3 + ⟨[], + [], + .revert (.const 0) (.const 0)⟩, + -- bb4 + ⟨[], + [.effect (some 15) .mload [.const 0], + .pure 19 .add [.value 15, .const 1], + .pure 20 .eq [.value 19, .const 0]], + .branch (.value 20) 5 6⟩, + -- bb5 + ⟨[], + [.effect none .mstore [.const 32, .const 17], + .effect none .mstore [.const 0, .const 0x4e487b71]], + .revert (.const 28) (.const 36)⟩, + -- bb6 + ⟨[], + [.effect none .mstore [.const 0, .value 19]], + .ret (.const 0) (.const 32)⟩, + -- bb7 + ⟨[], + [.effect (some 48) .calldataload [.const 4], + .effect (some 3) .gas [], + .effect none .mstore [.const 0, .const 0xa035b1fe], + .effect (some 11) (.call .staticcall) [.value 3, .value 48, .const 28, .const 4, .const 0, .const 32]], + .branch (.value 11) 2 1⟩], + entryHeap := some 128 }, + -- @entry + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 0) .callvalue [], + .ne 2 (.value 0) (.const 0)], + .branch (.value 2) 3 1⟩, + -- bb1 + ⟨[], + [.effect (some 4) .calldataload [.const 0], + .pure 6 .shr [.const 224, .value 4]], + .switch (.value 6) 3 [(.const 0xa087a87e, 2)]⟩, + -- bb2 + ⟨[], + [], + .tailCall 0 []⟩, + -- bb3 + ⟨[], + [], + .revert (.const 0) (.const 0)⟩] }] } + +end SolarTV.Export.Reader diff --git a/Certified/reader/gen/Reader/Mir3.lean b/Certified/reader/gen/Reader/Mir3.lean new file mode 100644 index 00000000..95c1a657 --- /dev/null +++ b/Certified/reader/gen/Reader/Mir3.lean @@ -0,0 +1,85 @@ +-- solar-lean-stage: kind=mir index=3 pass=evm-inst-schedule +import SolarTV.MIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `Reader`; do not edit. -/ + +namespace SolarTV.Export.Reader + +/-- The lowered MIR module after `evm-inst-schedule`. -/ +def mir3 : MIR.Lowered.Module := + { entry := 1, + functions := [ + -- @read + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 37) .calldataload [.const 4], + .pure 50 .shr [.const 160, .value 37], + .effect (some 33) .calldatasize [], + .pure 35 .lt [.value 33, .const 36], + .word 53 (.value 35), + .pure 54 .or [.value 50, .value 53], + .ne 47 (.value 54) (.const 0)], + .branch (.value 47) 3 7⟩, + -- bb1 + ⟨[], + [.effect (some 30) .returndatasize [], + .effect none .returndatacopy [.const 0, .const 0, .value 30], + .effect (some 31) .returndatasize []], + .revert (.const 0) (.value 31)⟩, + -- bb2 + ⟨[], + [.effect (some 13) .returndatasize [], + .pure 14 .lt [.value 13, .const 32]], + .branch (.value 14) 3 4⟩, + -- bb3 + ⟨[], + [], + .revert (.const 0) (.const 0)⟩, + -- bb4 + ⟨[], + [.effect (some 15) .mload [.const 0], + .pure 19 .add [.value 15, .const 1], + .pure 20 .eq [.value 19, .const 0]], + .branch (.value 20) 5 6⟩, + -- bb5 + ⟨[], + [.effect none .mstore [.const 32, .const 17], + .effect none .mstore [.const 0, .const 0x4e487b71]], + .revert (.const 28) (.const 36)⟩, + -- bb6 + ⟨[], + [.effect none .mstore [.const 0, .value 19]], + .ret (.const 0) (.const 32)⟩, + -- bb7 + ⟨[], + [.effect (some 48) .calldataload [.const 4], + .effect (some 3) .gas [], + .effect none .mstore [.const 0, .const 0xa035b1fe], + .effect (some 11) (.call .staticcall) [.value 3, .value 48, .const 28, .const 4, .const 0, .const 32]], + .branch (.value 11) 2 1⟩], + entryHeap := some 128 }, + -- @entry + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 0) .callvalue [], + .ne 2 (.value 0) (.const 0)], + .branch (.value 2) 3 1⟩, + -- bb1 + ⟨[], + [.effect (some 4) .calldataload [.const 0], + .pure 6 .shr [.const 224, .value 4]], + .switch (.value 6) 3 [(.const 0xa087a87e, 2)]⟩, + -- bb2 + ⟨[], + [], + .tailCall 0 []⟩, + -- bb3 + ⟨[], + [], + .revert (.const 0) (.const 0)⟩] }] } + +end SolarTV.Export.Reader diff --git a/Certified/reader/gen/Reader/Sched.lean b/Certified/reader/gen/Reader/Sched.lean new file mode 100644 index 00000000..7903d1cd --- /dev/null +++ b/Certified/reader/gen/Reader/Sched.lean @@ -0,0 +1,104 @@ +-- solar-lean-stage: kind=sched index=0 pass=stack-schedule +import SolarTV.EVMIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `Reader`; do not edit. -/ + +namespace SolarTV.Export.Reader + +/-- The runtime EVM IR as stack scheduling emits it. -/ +def sched : EVM.Program.Program := + { blocks := [ + -- bb0 + [.effect .callvalue 0, + .jumpi 3, + .jump 1], + -- bb1 + [.op (.stack (.push 0)), + .effect .calldataload 1, + .op (.stack (.push 224)), + .op (.stack .shr), + .op (.stack (.dup 0)), + .op (.stack (.push 0xa087a87e)), + .op (.stack .eq), + .jumpi 2, + .jump 3], + -- bb2 + [.jump 4], + -- bb3 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb4 + [.op (.stack (.push 128)), + .op (.stack (.push 64)), + .op .store, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 160)), + .op (.stack .shr), + .op (.stack (.push 36)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack .or), + .jumpi 11, + .jump 5], + -- bb5 + [.op (.stack (.push 0xa035b1fe)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .op (.stack (.push 4)), + .op (.stack (.push 28)), + .op (.stack (.push 4)), + .effect .calldataload 1, + .effect .gas 0, + .effect (.call .staticcall) 6, + .op (.stack .iszero), + .jumpi 9, + .jump 6], + -- bb6 + [.op (.stack .returndatasize), + .op (.stack (.push 32)), + .op (.stack .gt), + .jumpi 11, + .jump 7], + -- bb7 + [.op (.stack (.push 0)), + .op .load, + .op (.stack (.push 1)), + .op (.stack .add), + .op (.stack (.dup 0)), + .op (.stack .iszero), + .jumpi 10, + .jump 8], + -- bb8 + [.op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb9 + [.op (.stack .returndatasize), + .op (.stack (.push 0)), + .op (.stack (.push 0)), + .effect .returndatacopy 3, + .op (.stack .returndatasize), + .op (.stack (.push 0)), + .revert], + -- bb10 + [.op (.stack (.push 17)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 0x4e487b71)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 36)), + .op (.stack (.push 28)), + .revert], + -- bb11 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert]] } + +end SolarTV.Export.Reader diff --git a/Certified/reader/gen/Reader/Stage0.lean b/Certified/reader/gen/Reader/Stage0.lean new file mode 100644 index 00000000..150af153 --- /dev/null +++ b/Certified/reader/gen/Reader/Stage0.lean @@ -0,0 +1,82 @@ +-- solar-lean-stage: kind=mir index=0 pass=lower-evm-shaped +import SolarTV.MIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `Reader`; do not edit. -/ + +namespace SolarTV.Export.Reader + +/-- The first lowered MIR module, after `lower-evm-shaped` advanced the phase. -/ +def stage0 : MIR.Lowered.Module := + { entry := 1, + functions := [ + -- @read + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 33) .calldatasize [], + .pure 35 .lt [.value 33, .const 36], + .effect (some 37) .calldataload [.const 4], + .pure 39 .gt [.value 37, .const 0xffffffffffffffffffffffffffffffffffffffff], + .pure 47 .or [.value 35, .value 39]], + .branch (.value 47) 3 7⟩, + -- bb1 + ⟨[], + [.effect (some 30) .returndatasize [], + .effect none .returndatacopy [.const 0, .const 0, .value 30], + .effect (some 31) .returndatasize []], + .revert (.const 0) (.value 31)⟩, + -- bb2 + ⟨[], + [.effect (some 13) .returndatasize [], + .pure 14 .lt [.value 13, .const 32]], + .branch (.value 14) 3 4⟩, + -- bb3 + ⟨[], + [], + .revert (.const 0) (.const 0)⟩, + -- bb4 + ⟨[], + [.effect (some 15) .mload [.const 0], + .pure 19 .add [.value 15, .const 1], + .pure 20 .eq [.value 19, .const 0]], + .branch (.value 20) 5 6⟩, + -- bb5 + ⟨[], + [.effect none .mstore [.const 32, .const 17], + .effect none .mstore [.const 0, .const 0x4e487b71]], + .revert (.const 28) (.const 36)⟩, + -- bb6 + ⟨[], + [.effect none .mstore [.const 0, .value 19]], + .ret (.const 0) (.const 32)⟩, + -- bb7 + ⟨[], + [.effect (some 3) .gas [], + .effect none .mstore [.const 0, .const 0xa035b1fe], + .effect (some 11) (.call .staticcall) [.value 3, .value 37, .const 28, .const 4, .const 0, .const 32]], + .branch (.value 11) 2 1⟩], + entryHeap := some 128 }, + -- @entry + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 0) .callvalue [], + .ne 2 (.value 0) (.const 0)], + .branch (.value 2) 3 1⟩, + -- bb1 + ⟨[], + [.effect (some 4) .calldataload [.const 0], + .pure 6 .shr [.const 224, .value 4]], + .switch (.value 6) 3 [(.const 0xa087a87e, 2)]⟩, + -- bb2 + ⟨[], + [], + .tailCall 0 []⟩, + -- bb3 + ⟨[], + [], + .revert (.const 0) (.const 0)⟩] }] } + +end SolarTV.Export.Reader diff --git a/Certified/reader/gen/Reader/manifest.json b/Certified/reader/gen/Reader/manifest.json new file mode 100644 index 00000000..e2d8b12d --- /dev/null +++ b/Certified/reader/gen/Reader/manifest.json @@ -0,0 +1,129 @@ +{ + "arguments": [ + "solar-tv/milestone/reader/reader.sol", + "-Ogas", + "--evm-version", + "osaka", + "--emit=bin-runtime", + "-Zemit-lean-stages=solar-tv/milestone/reader/gen" + ], + "bytecode": "346053575f3560e01c8063a087a87e03605357608060405260043560a01c602436101760535763a035b1fe5f5260205f6004601c81355afa156057573d6020116053575f516001018015605f575f5260205ff35b5f5ffd5b3d5f5f3e3d5ffd5b6011602052634e487b715f526024601cfd", + "bytecode_sha256": "7e4fced8401133d842f58d3d310e8b78a32039960170ea5d8ad75a53a7b36626", + "compiler": "0.8.38+commit.4a7d9ede.solar.0.3.0-dev", + "contract": "Reader", + "evm_version": "osaka", + "optimization": "Gas", + "options": "CompileOpts { input: [\"solar-tv/milestone/reader/reader.sol\"], import_remappings: [], base_path: None, include_paths: [], allow_paths: [], no_import_callback: false, language: Solidity, threads: 4, evm_version: Osaka, stop_after: None, optimization: Gas, optimizer_runs: None, revert_strings: Default, libraries: [], out_dir: None, emit: [BinRuntime], standard_json: false, color: Auto, verbose: false, pretty_json: false, pretty_json_err: false, error_format: Human, error_format_human: Unicode, diagnostic_width: None, no_warnings: false, allow: [], _unstable: [\"emit-lean-stages=solar-tv/milestone/reader/gen\"], unstable: UnstableOpts { ui_testing: false, track_diagnostics: false, parse_yul: false, no_resolve_imports: false, recover_incomplete_input: false, dump: None, ast_stats: false, hir_stats: false, standard_json_stats: false, span_visitor: false, print_max_storage_sizes: false, print_natspec: false, mir_pipeline: None, evm_ir_pipeline: None, print_after_each: false, pass_diff: false, debugify: None, debugify_output: None, solar_tv: None, validate_ir: None, time_passes: false, codegen_all_functions: false, switch_lowering: Auto, switch_max_gas_code_growth: None, switch_max_bit_slice_gas_code_growth: None, tune: None, pack_wide_jump_tables: false, check_analyses: None, prove_analyses: None, validate_passes: None, validate_passes_fault: None, validate_backend: None, validate_backend_fault: None, validate_evm_ir_passes: None, validate_assembly: false, validate_assembly_fault: None, emit_lean_stages: Some(\"solar-tv/milestone/reader/gen\"), forget_gcx: true, help: (), _non_exhaustive: () }, _non_exhaustive: () }", + "sources": [ + { + "path": "solar-tv/milestone/reader/reader.sol", + "sha256": "bff96eb4b5b33ebc37c3dd379d4d55388525e9787dd991afa41cc0b809b89a7e" + } + ], + "stages": [ + { + "definition": "stage0", + "file": "Stage0.lean", + "index": 0, + "kind": "mir", + "pass": "lower-evm-shaped", + "sha256": "c18d3ee3fbe18467c367f0b868bfa6f93511e86bbecab095a1e288d8497f85a2" + }, + { + "definition": "mir1", + "file": "Mir1.lean", + "index": 1, + "kind": "mir", + "pass": "place-reads", + "sha256": "84085542c96e416459e21e878019f8af37c807d8a7cefd56afaa4238a26029d8" + }, + { + "definition": "mir2", + "file": "Mir2.lean", + "index": 2, + "kind": "mir", + "pass": "spell-width-tests", + "sha256": "805f70ac294e93760f04edc04a2eaf36b89430d26dc2d4959309a53b0597d114" + }, + { + "definition": "mir3", + "file": "Mir3.lean", + "index": 3, + "kind": "mir", + "pass": "evm-inst-schedule", + "sha256": "11a9ae1838d817aa69640ad29b7050cbc70b05b56c1ecf54329f5c816a2d4581" + }, + { + "definition": "sched", + "file": "Sched.lean", + "index": 0, + "kind": "sched", + "pass": "stack-schedule", + "sha256": "f618618c81f32246f89af8bf5a44f7d5407b420836ba4a2527bd07677cb4b153" + }, + { + "definition": "evm1", + "file": "Evm1.lean", + "index": 1, + "kind": "evm", + "pass": "cfg-simplify-early", + "sha256": "f351e61c85551e0385e65007fff190c72592edd3dad4981277769a3760514ebf" + }, + { + "definition": "evm2", + "file": "Evm2.lean", + "index": 2, + "kind": "evm", + "pass": "block-layout", + "sha256": "e52785df1aca97d96814a14e02da72c28095e1f81b8e6bd9ca046109cdb22ccd" + }, + { + "definition": "evm3", + "file": "Evm3.lean", + "index": 3, + "kind": "evm", + "pass": "terminal-dedup", + "sha256": "ceee2fd40bcbe7eb8e855e299c41f8bc03fab804b0fdeb0d7f6f8877ab2f0c23" + }, + { + "definition": "evm4", + "file": "Evm4.lean", + "index": 4, + "kind": "evm", + "pass": "cfg-simplify-early", + "sha256": "3b74cb48e673f40e6c712cb3139a2c45b5f1acd06512ae9f4dac74d32f65f1c9" + }, + { + "definition": "evm5", + "file": "Evm5.lean", + "index": 5, + "kind": "evm", + "pass": "block-cse", + "sha256": "fc489b656954d811b262210a2fc8fc512ed285a96cc07841b8ddae9a9139160a" + }, + { + "definition": "evm6", + "file": "Evm6.lean", + "index": 6, + "kind": "evm", + "pass": "share-reverts", + "sha256": "ba632cf5e20581d34c5ec93d168d8d802d08c52f081a0f19be6323423d8d095b" + }, + { + "definition": "evm7", + "file": "Evm7.lean", + "index": 7, + "kind": "evm", + "pass": "cfg-simplify-early", + "sha256": "a0bdf8538b97a7dfb6e452bfad93e70f2238db07643497d48ab2aad1bd7b36e7" + }, + { + "definition": "bytecode", + "file": "Bytecode.lean", + "index": 0, + "kind": "bytecode", + "pass": "assemble", + "sha256": "ce5b93ef146d00753003f24db5c08fa70ca8cf43dfe6b38f62dfc0f23271af13" + } + ] +} diff --git a/Certified/reader/options b/Certified/reader/options new file mode 100644 index 00000000..da38913c --- /dev/null +++ b/Certified/reader/options @@ -0,0 +1,3 @@ +-Ogas +--evm-version +osaka diff --git a/Certified/reader/reader.sol b/Certified/reader/reader.sol new file mode 100644 index 00000000..a5e80afe --- /dev/null +++ b/Certified/reader/reader.sol @@ -0,0 +1,13 @@ +// SPDX-License-Identifier: MIT +pragma solidity ^0.8.0; + +interface IOracle { + function price() external view returns (uint256); +} + +contract Reader { + function read(IOracle o) external view returns (uint256) { + return o.price() + 1; + } +} + diff --git a/Certified/token/Proofs.lean b/Certified/token/Proofs.lean new file mode 100644 index 00000000..a8b13e29 --- /dev/null +++ b/Certified/token/Proofs.lean @@ -0,0 +1,3 @@ +-- Generated by solar-tv/milestone/certify.py; do not edit. +import token.Proofs.Stages +import token.Proofs.Assembly diff --git a/Certified/token/Proofs/Assembly.lean b/Certified/token/Proofs/Assembly.lean new file mode 100644 index 00000000..3fb43deb --- /dev/null +++ b/Certified/token/Proofs/Assembly.lean @@ -0,0 +1,42 @@ +-- Generated by solar-tv/milestone/certify.py; do not edit. +import W1Proofs.Items +import token.gen.Token.Evm11 +import token.gen.Token.Bytecode + +/-! The final EVM IR of `Token` against its bytecode, by the assembly checker's walk: the bytecode decodes, linearly from offset 0, to exactly the program's instructions, each jumped-to block at its `JUMPDEST`. -/ + +namespace SolarTV.Milestone.Token + +open SolarTV.Assembly SolarTV.Export.Token SolarTV.Milestone.W1 + +set_option maxRecDepth 100000 + +/-- The items of the final EVM IR. -/ +def items : List Item := (itemsOf evm11).getD [] + +theorem items_eq : itemsOf evm11 = some items := by decide + +/-- The layout: each jumped-to block at the bytecode's next `JUMPDEST`. The walk checks it. -/ +def offset (label : Nat) : Nat := if label = 1 then 0x3d else if label = 2 then 0x41 else if label = 3 then 0x53 else if label = 4 then 0x81 else if label = 5 then 0xa4 else if label = 6 then 0xdb else if label = 7 then 0xeb else if label = 8 then 0x114 else if label = 9 then 0x143 else if label = 10 then 0x19e else if label = 11 then 0x1cc else if label = 12 then 0x1da else if label = 13 then 0x1f1 else if label = 14 then 0x24e else if label = 15 then 0x2aa else if label = 16 then 0x2e5 else 0 + +/-- The instructions the walk reaches, each at its offset. -/ +def stream : List (Nat × Instr) := (walk bytecode offset 0 items).getD [] + +/-- The checker's walk accepts the exported bytecode against the final EVM IR. -/ +theorem walk_eq : walk bytecode offset 0 items = some stream := by decide +kernel + +theorem checked : Walk bytecode offset 0 items stream := walk_sound walk_eq + +/-- The bytecode's linear decoding is the final EVM IR's instructions at the layout. -/ +theorem decodes : decodeFrom bytecode (bytecode.length + 1) 0 = stream := + walk_decodes checked _ (by have := walk_length checked; omega) + +/-- info: 'SolarTV.Milestone.Token.walk_eq' depends on axioms: [propext, Quot.sound] -/ +#guard_msgs in +#print axioms walk_eq + +/-- info: 'SolarTV.Milestone.Token.decodes' depends on axioms: [propext, Quot.sound] -/ +#guard_msgs in +#print axioms decodes + +end SolarTV.Milestone.Token diff --git a/Certified/token/Proofs/Runs/Evm1.lean b/Certified/token/Proofs/Runs/Evm1.lean new file mode 100644 index 00000000..c7cf624d --- /dev/null +++ b/Certified/token/Proofs/Runs/Evm1.lean @@ -0,0 +1,23 @@ +-- Generated by solar-tv/milestone/certify.py; do not edit. +import W1Proofs.Tactic +import W1Proofs.Axioms +import token.gen.Token.Evm1 +import token.gen.Token.Sched + +/-! `peephole-early`: its input and output end in the same result on every call. -/ + +namespace SolarTV.Milestone.Token + +open Machine SolarTV.Export.Token SolarTV.Milestone.W1 + +set_option maxHeartbeats 8000000 in +set_option maxRecDepth 100000 in +theorem evm1_run (o : Oracle) (call : Call) : + EVM.Program.run o sched call 48 = EVM.Program.run o evm1 call 48 := by + sym_exec + +/-- info: 'SolarTV.Milestone.Token.evm1_run' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within evm1_run + +end SolarTV.Milestone.Token diff --git a/Certified/token/Proofs/Runs/Evm10.lean b/Certified/token/Proofs/Runs/Evm10.lean new file mode 100644 index 00000000..9aeedaa0 --- /dev/null +++ b/Certified/token/Proofs/Runs/Evm10.lean @@ -0,0 +1,23 @@ +-- Generated by solar-tv/milestone/certify.py; do not edit. +import W1Proofs.Tactic +import W1Proofs.Axioms +import token.gen.Token.Evm10 +import token.gen.Token.Evm9 + +/-! `inline-returns`: its input and output end in the same result on every call. -/ + +namespace SolarTV.Milestone.Token + +open Machine SolarTV.Export.Token SolarTV.Milestone.W1 + +set_option maxHeartbeats 8000000 in +set_option maxRecDepth 100000 in +theorem evm10_run (o : Oracle) (call : Call) : + EVM.Program.run o evm9 call 17 = EVM.Program.run o evm10 call 17 := by + sym_exec + +/-- info: 'SolarTV.Milestone.Token.evm10_run' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within evm10_run + +end SolarTV.Milestone.Token diff --git a/Certified/token/Proofs/Runs/Evm11.lean b/Certified/token/Proofs/Runs/Evm11.lean new file mode 100644 index 00000000..ff56e73a --- /dev/null +++ b/Certified/token/Proofs/Runs/Evm11.lean @@ -0,0 +1,23 @@ +-- Generated by solar-tv/milestone/certify.py; do not edit. +import W1Proofs.Tactic +import W1Proofs.Axioms +import token.gen.Token.Evm11 +import token.gen.Token.Evm10 + +/-! `late-word`: its input and output end in the same result on every call. -/ + +namespace SolarTV.Milestone.Token + +open Machine SolarTV.Export.Token SolarTV.Milestone.W1 + +set_option maxHeartbeats 8000000 in +set_option maxRecDepth 100000 in +theorem evm11_run (o : Oracle) (call : Call) : + EVM.Program.run o evm10 call 17 = EVM.Program.run o evm11 call 17 := by + sym_exec + +/-- info: 'SolarTV.Milestone.Token.evm11_run' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within evm11_run + +end SolarTV.Milestone.Token diff --git a/Certified/token/Proofs/Runs/Evm2.lean b/Certified/token/Proofs/Runs/Evm2.lean new file mode 100644 index 00000000..1bb77b7d --- /dev/null +++ b/Certified/token/Proofs/Runs/Evm2.lean @@ -0,0 +1,23 @@ +-- Generated by solar-tv/milestone/certify.py; do not edit. +import W1Proofs.Tactic +import W1Proofs.Axioms +import token.gen.Token.Evm2 +import token.gen.Token.Evm1 + +/-! `cfg-simplify-early`: its input and output end in the same result on every call. -/ + +namespace SolarTV.Milestone.Token + +open Machine SolarTV.Export.Token SolarTV.Milestone.W1 + +set_option maxHeartbeats 8000000 in +set_option maxRecDepth 100000 in +theorem evm2_run (o : Oracle) (call : Call) : + EVM.Program.run o evm1 call 48 = EVM.Program.run o evm2 call 24 := by + sym_exec + +/-- info: 'SolarTV.Milestone.Token.evm2_run' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within evm2_run + +end SolarTV.Milestone.Token diff --git a/Certified/token/Proofs/Runs/Evm3.lean b/Certified/token/Proofs/Runs/Evm3.lean new file mode 100644 index 00000000..236a5cdf --- /dev/null +++ b/Certified/token/Proofs/Runs/Evm3.lean @@ -0,0 +1,23 @@ +-- Generated by solar-tv/milestone/certify.py; do not edit. +import W1Proofs.Tactic +import W1Proofs.Axioms +import token.gen.Token.Evm3 +import token.gen.Token.Evm2 + +/-! `compact-pushes`: its input and output end in the same result on every call. -/ + +namespace SolarTV.Milestone.Token + +open Machine SolarTV.Export.Token SolarTV.Milestone.W1 + +set_option maxHeartbeats 8000000 in +set_option maxRecDepth 100000 in +theorem evm3_run (o : Oracle) (call : Call) : + EVM.Program.run o evm2 call 24 = EVM.Program.run o evm3 call 24 := by + sym_exec + +/-- info: 'SolarTV.Milestone.Token.evm3_run' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within evm3_run + +end SolarTV.Milestone.Token diff --git a/Certified/token/Proofs/Runs/Evm4.lean b/Certified/token/Proofs/Runs/Evm4.lean new file mode 100644 index 00000000..b4ee50e2 --- /dev/null +++ b/Certified/token/Proofs/Runs/Evm4.lean @@ -0,0 +1,23 @@ +-- Generated by solar-tv/milestone/certify.py; do not edit. +import W1Proofs.Tactic +import W1Proofs.Axioms +import token.gen.Token.Evm4 +import token.gen.Token.Evm3 + +/-! `block-layout`: its input and output end in the same result on every call. -/ + +namespace SolarTV.Milestone.Token + +open Machine SolarTV.Export.Token SolarTV.Milestone.W1 + +set_option maxHeartbeats 8000000 in +set_option maxRecDepth 100000 in +theorem evm4_run (o : Oracle) (call : Call) : + EVM.Program.run o evm3 call 24 = EVM.Program.run o evm4 call 24 := by + sym_exec + +/-- info: 'SolarTV.Milestone.Token.evm4_run' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within evm4_run + +end SolarTV.Milestone.Token diff --git a/Certified/token/Proofs/Runs/Evm5.lean b/Certified/token/Proofs/Runs/Evm5.lean new file mode 100644 index 00000000..0cd4c8a8 --- /dev/null +++ b/Certified/token/Proofs/Runs/Evm5.lean @@ -0,0 +1,23 @@ +-- Generated by solar-tv/milestone/certify.py; do not edit. +import W1Proofs.Tactic +import W1Proofs.Axioms +import token.gen.Token.Evm5 +import token.gen.Token.Evm4 + +/-! `terminal-dedup`: its input and output end in the same result on every call. -/ + +namespace SolarTV.Milestone.Token + +open Machine SolarTV.Export.Token SolarTV.Milestone.W1 + +set_option maxHeartbeats 8000000 in +set_option maxRecDepth 100000 in +theorem evm5_run (o : Oracle) (call : Call) : + EVM.Program.run o evm4 call 24 = EVM.Program.run o evm5 call 24 := by + sym_exec + +/-- info: 'SolarTV.Milestone.Token.evm5_run' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within evm5_run + +end SolarTV.Milestone.Token diff --git a/Certified/token/Proofs/Runs/Evm6.lean b/Certified/token/Proofs/Runs/Evm6.lean new file mode 100644 index 00000000..19c97b17 --- /dev/null +++ b/Certified/token/Proofs/Runs/Evm6.lean @@ -0,0 +1,23 @@ +-- Generated by solar-tv/milestone/certify.py; do not edit. +import W1Proofs.Tactic +import W1Proofs.Axioms +import token.gen.Token.Evm6 +import token.gen.Token.Evm5 + +/-! `cfg-simplify-early`: its input and output end in the same result on every call. -/ + +namespace SolarTV.Milestone.Token + +open Machine SolarTV.Export.Token SolarTV.Milestone.W1 + +set_option maxHeartbeats 8000000 in +set_option maxRecDepth 100000 in +theorem evm6_run (o : Oracle) (call : Call) : + EVM.Program.run o evm5 call 24 = EVM.Program.run o evm6 call 16 := by + sym_exec + +/-- info: 'SolarTV.Milestone.Token.evm6_run' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within evm6_run + +end SolarTV.Milestone.Token diff --git a/Certified/token/Proofs/Runs/Evm7.lean b/Certified/token/Proofs/Runs/Evm7.lean new file mode 100644 index 00000000..9dde2407 --- /dev/null +++ b/Certified/token/Proofs/Runs/Evm7.lean @@ -0,0 +1,23 @@ +-- Generated by solar-tv/milestone/certify.py; do not edit. +import W1Proofs.Tactic +import W1Proofs.Axioms +import token.gen.Token.Evm7 +import token.gen.Token.Evm6 + +/-! `tail-merge`: its input and output end in the same result on every call. -/ + +namespace SolarTV.Milestone.Token + +open Machine SolarTV.Export.Token SolarTV.Milestone.W1 + +set_option maxHeartbeats 8000000 in +set_option maxRecDepth 100000 in +theorem evm7_run (o : Oracle) (call : Call) : + EVM.Program.run o evm6 call 16 = EVM.Program.run o evm7 call 17 := by + sym_exec + +/-- info: 'SolarTV.Milestone.Token.evm7_run' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within evm7_run + +end SolarTV.Milestone.Token diff --git a/Certified/token/Proofs/Runs/Evm8.lean b/Certified/token/Proofs/Runs/Evm8.lean new file mode 100644 index 00000000..dd5f565e --- /dev/null +++ b/Certified/token/Proofs/Runs/Evm8.lean @@ -0,0 +1,23 @@ +-- Generated by solar-tv/milestone/certify.py; do not edit. +import W1Proofs.Tactic +import W1Proofs.Axioms +import token.gen.Token.Evm8 +import token.gen.Token.Evm7 + +/-! `block-cse`: its input and output end in the same result on every call. -/ + +namespace SolarTV.Milestone.Token + +open Machine SolarTV.Export.Token SolarTV.Milestone.W1 + +set_option maxHeartbeats 8000000 in +set_option maxRecDepth 100000 in +theorem evm8_run (o : Oracle) (call : Call) : + EVM.Program.run o evm7 call 17 = EVM.Program.run o evm8 call 17 := by + sym_exec + +/-- info: 'SolarTV.Milestone.Token.evm8_run' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within evm8_run + +end SolarTV.Milestone.Token diff --git a/Certified/token/Proofs/Runs/Evm9.lean b/Certified/token/Proofs/Runs/Evm9.lean new file mode 100644 index 00000000..94db21eb --- /dev/null +++ b/Certified/token/Proofs/Runs/Evm9.lean @@ -0,0 +1,23 @@ +-- Generated by solar-tv/milestone/certify.py; do not edit. +import W1Proofs.Tactic +import W1Proofs.Axioms +import token.gen.Token.Evm9 +import token.gen.Token.Evm8 + +/-! `block-layout`: its input and output end in the same result on every call. -/ + +namespace SolarTV.Milestone.Token + +open Machine SolarTV.Export.Token SolarTV.Milestone.W1 + +set_option maxHeartbeats 8000000 in +set_option maxRecDepth 100000 in +theorem evm9_run (o : Oracle) (call : Call) : + EVM.Program.run o evm8 call 17 = EVM.Program.run o evm9 call 17 := by + sym_exec + +/-- info: 'SolarTV.Milestone.Token.evm9_run' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within evm9_run + +end SolarTV.Milestone.Token diff --git a/Certified/token/Proofs/Runs/Mir1.lean b/Certified/token/Proofs/Runs/Mir1.lean new file mode 100644 index 00000000..f6d5aa9f --- /dev/null +++ b/Certified/token/Proofs/Runs/Mir1.lean @@ -0,0 +1,23 @@ +-- Generated by solar-tv/milestone/certify.py; do not edit. +import W1Proofs.Tactic +import W1Proofs.Axioms +import token.gen.Token.Mir1 +import token.gen.Token.Stage0 + +/-! `place-reads`: its input and output end in the same result on every call. -/ + +namespace SolarTV.Milestone.Token + +open Machine SolarTV.Export.Token SolarTV.Milestone.W1 + +set_option maxHeartbeats 8000000 in +set_option maxRecDepth 100000 in +theorem mir1_run (o : Oracle) (call : Call) : + MIR.Lowered.Module.run o stage0 call 47 = MIR.Lowered.Module.run o mir1 call 47 := by + sym_exec + +/-- info: 'SolarTV.Milestone.Token.mir1_run' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within mir1_run + +end SolarTV.Milestone.Token diff --git a/Certified/token/Proofs/Runs/Mir2.lean b/Certified/token/Proofs/Runs/Mir2.lean new file mode 100644 index 00000000..98496f43 --- /dev/null +++ b/Certified/token/Proofs/Runs/Mir2.lean @@ -0,0 +1,23 @@ +-- Generated by solar-tv/milestone/certify.py; do not edit. +import W1Proofs.Tactic +import W1Proofs.Axioms +import token.gen.Token.Mir2 +import token.gen.Token.Mir1 + +/-! `dce`: its input and output end in the same result on every call. -/ + +namespace SolarTV.Milestone.Token + +open Machine SolarTV.Export.Token SolarTV.Milestone.W1 + +set_option maxHeartbeats 8000000 in +set_option maxRecDepth 100000 in +theorem mir2_run (o : Oracle) (call : Call) : + MIR.Lowered.Module.run o mir1 call 47 = MIR.Lowered.Module.run o mir2 call 47 := by + sym_exec + +/-- info: 'SolarTV.Milestone.Token.mir2_run' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within mir2_run + +end SolarTV.Milestone.Token diff --git a/Certified/token/Proofs/Runs/Mir3.lean b/Certified/token/Proofs/Runs/Mir3.lean new file mode 100644 index 00000000..bdeacf13 --- /dev/null +++ b/Certified/token/Proofs/Runs/Mir3.lean @@ -0,0 +1,23 @@ +-- Generated by solar-tv/milestone/certify.py; do not edit. +import W1Proofs.Tactic +import W1Proofs.Axioms +import token.gen.Token.Mir3 +import token.gen.Token.Mir2 + +/-! `spell-width-tests`: its input and output end in the same result on every call. -/ + +namespace SolarTV.Milestone.Token + +open Machine SolarTV.Export.Token SolarTV.Milestone.W1 + +set_option maxHeartbeats 8000000 in +set_option maxRecDepth 100000 in +theorem mir3_run (o : Oracle) (call : Call) : + MIR.Lowered.Module.run o mir2 call 47 = MIR.Lowered.Module.run o mir3 call 47 := by + sym_exec + +/-- info: 'SolarTV.Milestone.Token.mir3_run' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within mir3_run + +end SolarTV.Milestone.Token diff --git a/Certified/token/Proofs/Runs/Mir4.lean b/Certified/token/Proofs/Runs/Mir4.lean new file mode 100644 index 00000000..ff63260e --- /dev/null +++ b/Certified/token/Proofs/Runs/Mir4.lean @@ -0,0 +1,23 @@ +-- Generated by solar-tv/milestone/certify.py; do not edit. +import W1Proofs.Tactic +import W1Proofs.Axioms +import token.gen.Token.Mir4 +import token.gen.Token.Mir3 + +/-! `evm-inst-schedule`: its input and output end in the same result on every call. -/ + +namespace SolarTV.Milestone.Token + +open Machine SolarTV.Export.Token SolarTV.Milestone.W1 + +set_option maxHeartbeats 8000000 in +set_option maxRecDepth 100000 in +theorem mir4_run (o : Oracle) (call : Call) : + MIR.Lowered.Module.run o mir3 call 47 = MIR.Lowered.Module.run o mir4 call 47 := by + sym_exec + +/-- info: 'SolarTV.Milestone.Token.mir4_run' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within mir4_run + +end SolarTV.Milestone.Token diff --git a/Certified/token/Proofs/Runs/Sched.lean b/Certified/token/Proofs/Runs/Sched.lean new file mode 100644 index 00000000..fb687d29 --- /dev/null +++ b/Certified/token/Proofs/Runs/Sched.lean @@ -0,0 +1,23 @@ +-- Generated by solar-tv/milestone/certify.py; do not edit. +import W1Proofs.Tactic +import W1Proofs.Axioms +import token.gen.Token.Sched +import token.gen.Token.Mir4 + +/-! Stack scheduling: the last lowered MIR and the scheduled EVM IR end in the same result on every call. -/ + +namespace SolarTV.Milestone.Token + +open Machine SolarTV.Export.Token SolarTV.Milestone.W1 + +set_option maxHeartbeats 8000000 in +set_option maxRecDepth 100000 in +theorem sched_run (o : Oracle) (call : Call) : + MIR.Lowered.Module.run o mir4 call 47 = EVM.Program.run o sched call 48 := by + sym_exec + +/-- info: 'SolarTV.Milestone.Token.sched_run' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within sched_run + +end SolarTV.Milestone.Token diff --git a/Certified/token/Proofs/Runs/Stage0.lean b/Certified/token/Proofs/Runs/Stage0.lean new file mode 100644 index 00000000..a858df82 --- /dev/null +++ b/Certified/token/Proofs/Runs/Stage0.lean @@ -0,0 +1,22 @@ +-- Generated by solar-tv/milestone/certify.py; do not edit. +import W1Proofs.Tactic +import W1Proofs.Axioms +import token.gen.Token.Stage0 + +/-! The first lowered MIR ends on every call within 47 blocks, the number of its blocks. -/ + +namespace SolarTV.Milestone.Token + +open Machine SolarTV.Export.Token SolarTV.Milestone.W1 + +set_option maxHeartbeats 8000000 in +set_option maxRecDepth 100000 in +theorem stage0_ends (o : Oracle) (call : Call) : + (MIR.Lowered.Module.run o stage0 call 47).isSome = true := by + sym_exec + +/-- info: 'SolarTV.Milestone.Token.stage0_ends' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within stage0_ends + +end SolarTV.Milestone.Token diff --git a/Certified/token/Proofs/Stages.lean b/Certified/token/Proofs/Stages.lean new file mode 100644 index 00000000..e2070494 --- /dev/null +++ b/Certified/token/Proofs/Stages.lean @@ -0,0 +1,275 @@ +-- Generated by solar-tv/milestone/certify.py; do not edit. +import token.Proofs.Runs.Stage0 +import token.Proofs.Runs.Mir1 +import token.Proofs.Runs.Mir2 +import token.Proofs.Runs.Mir3 +import token.Proofs.Runs.Mir4 +import token.Proofs.Runs.Sched +import token.Proofs.Runs.Evm1 +import token.Proofs.Runs.Evm2 +import token.Proofs.Runs.Evm3 +import token.Proofs.Runs.Evm4 +import token.Proofs.Runs.Evm5 +import token.Proofs.Runs.Evm6 +import token.Proofs.Runs.Evm7 +import token.Proofs.Runs.Evm8 +import token.Proofs.Runs.Evm9 +import token.Proofs.Runs.Evm10 +import token.Proofs.Runs.Evm11 +import W1Proofs.Stage +import SolarTV.Composition + +/-! The backend stages of `Token`, each proved on every call (`anyCall`: any calldata, call value and storage) under every oracle, and chained from the first lowered MIR `stage0` to the final EVM IR `evm11`. Fuels are the programs' block counts. -/ + +namespace SolarTV.Milestone.Token + +open Machine SolarTV.Export.Token SolarTV.Milestone.W1 + +/-- `place-reads`: stage0 to mir1. -/ +theorem stage_mir1 (o : Oracle) : Stage (mirSem o) (mirSem o) stage0 mir1 anyCall := + stage_of_runs (A := MIR.Lowered.moduleLayer) (B := MIR.Lowered.moduleLayer) 47 47 (fun call _ => stage0_ends o call) + (fun call _ => mir1_run o call) + +theorem mir1_ends (o : Oracle) : ∀ call, anyCall call → + (MIR.Lowered.Module.run o mir1 call 47).isSome = true := + ends_of_runs (A := MIR.Lowered.moduleLayer) (B := MIR.Lowered.moduleLayer) + (o := o) (p := stage0) (q := mir1) (n := 47) (m := 47) (fun call _ => stage0_ends o call) + (fun call _ => mir1_run o call) + +/-- `dce`: mir1 to mir2. -/ +theorem stage_mir2 (o : Oracle) : Stage (mirSem o) (mirSem o) mir1 mir2 anyCall := + stage_of_runs (A := MIR.Lowered.moduleLayer) (B := MIR.Lowered.moduleLayer) 47 47 (mir1_ends o) + (fun call _ => mir2_run o call) + +theorem mir2_ends (o : Oracle) : ∀ call, anyCall call → + (MIR.Lowered.Module.run o mir2 call 47).isSome = true := + ends_of_runs (A := MIR.Lowered.moduleLayer) (B := MIR.Lowered.moduleLayer) + (o := o) (p := mir1) (q := mir2) (n := 47) (m := 47) (mir1_ends o) + (fun call _ => mir2_run o call) + +/-- `spell-width-tests`: mir2 to mir3. -/ +theorem stage_mir3 (o : Oracle) : Stage (mirSem o) (mirSem o) mir2 mir3 anyCall := + stage_of_runs (A := MIR.Lowered.moduleLayer) (B := MIR.Lowered.moduleLayer) 47 47 (mir2_ends o) + (fun call _ => mir3_run o call) + +theorem mir3_ends (o : Oracle) : ∀ call, anyCall call → + (MIR.Lowered.Module.run o mir3 call 47).isSome = true := + ends_of_runs (A := MIR.Lowered.moduleLayer) (B := MIR.Lowered.moduleLayer) + (o := o) (p := mir2) (q := mir3) (n := 47) (m := 47) (mir2_ends o) + (fun call _ => mir3_run o call) + +/-- `evm-inst-schedule`: mir3 to mir4. -/ +theorem stage_mir4 (o : Oracle) : Stage (mirSem o) (mirSem o) mir3 mir4 anyCall := + stage_of_runs (A := MIR.Lowered.moduleLayer) (B := MIR.Lowered.moduleLayer) 47 47 (mir3_ends o) + (fun call _ => mir4_run o call) + +theorem mir4_ends (o : Oracle) : ∀ call, anyCall call → + (MIR.Lowered.Module.run o mir4 call 47).isSome = true := + ends_of_runs (A := MIR.Lowered.moduleLayer) (B := MIR.Lowered.moduleLayer) + (o := o) (p := mir3) (q := mir4) (n := 47) (m := 47) (mir3_ends o) + (fun call _ => mir4_run o call) + +/-- `stack-schedule`: mir4 to sched. -/ +theorem stage_sched (o : Oracle) : Stage (mirSem o) (evmirSem o) mir4 sched anyCall := + stage_of_runs (A := MIR.Lowered.moduleLayer) (B := EVM.Program.layer) 47 48 (mir4_ends o) + (fun call _ => sched_run o call) + +theorem sched_ends (o : Oracle) : ∀ call, anyCall call → + (EVM.Program.run o sched call 48).isSome = true := + ends_of_runs (A := MIR.Lowered.moduleLayer) (B := EVM.Program.layer) + (o := o) (p := mir4) (q := sched) (n := 47) (m := 48) (mir4_ends o) + (fun call _ => sched_run o call) + +/-- `peephole-early`: sched to evm1. -/ +theorem stage_evm1 (o : Oracle) : Stage (evmirSem o) (evmirSem o) sched evm1 anyCall := + stage_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) 48 48 (sched_ends o) + (fun call _ => evm1_run o call) + +theorem evm1_ends (o : Oracle) : ∀ call, anyCall call → + (EVM.Program.run o evm1 call 48).isSome = true := + ends_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) + (o := o) (p := sched) (q := evm1) (n := 48) (m := 48) (sched_ends o) + (fun call _ => evm1_run o call) + +/-- `cfg-simplify-early`: evm1 to evm2. -/ +theorem stage_evm2 (o : Oracle) : Stage (evmirSem o) (evmirSem o) evm1 evm2 anyCall := + stage_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) 48 24 (evm1_ends o) + (fun call _ => evm2_run o call) + +theorem evm2_ends (o : Oracle) : ∀ call, anyCall call → + (EVM.Program.run o evm2 call 24).isSome = true := + ends_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) + (o := o) (p := evm1) (q := evm2) (n := 48) (m := 24) (evm1_ends o) + (fun call _ => evm2_run o call) + +/-- `compact-pushes`: evm2 to evm3. -/ +theorem stage_evm3 (o : Oracle) : Stage (evmirSem o) (evmirSem o) evm2 evm3 anyCall := + stage_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) 24 24 (evm2_ends o) + (fun call _ => evm3_run o call) + +theorem evm3_ends (o : Oracle) : ∀ call, anyCall call → + (EVM.Program.run o evm3 call 24).isSome = true := + ends_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) + (o := o) (p := evm2) (q := evm3) (n := 24) (m := 24) (evm2_ends o) + (fun call _ => evm3_run o call) + +/-- `block-layout`: evm3 to evm4. -/ +theorem stage_evm4 (o : Oracle) : Stage (evmirSem o) (evmirSem o) evm3 evm4 anyCall := + stage_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) 24 24 (evm3_ends o) + (fun call _ => evm4_run o call) + +theorem evm4_ends (o : Oracle) : ∀ call, anyCall call → + (EVM.Program.run o evm4 call 24).isSome = true := + ends_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) + (o := o) (p := evm3) (q := evm4) (n := 24) (m := 24) (evm3_ends o) + (fun call _ => evm4_run o call) + +/-- `terminal-dedup`: evm4 to evm5. -/ +theorem stage_evm5 (o : Oracle) : Stage (evmirSem o) (evmirSem o) evm4 evm5 anyCall := + stage_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) 24 24 (evm4_ends o) + (fun call _ => evm5_run o call) + +theorem evm5_ends (o : Oracle) : ∀ call, anyCall call → + (EVM.Program.run o evm5 call 24).isSome = true := + ends_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) + (o := o) (p := evm4) (q := evm5) (n := 24) (m := 24) (evm4_ends o) + (fun call _ => evm5_run o call) + +/-- `cfg-simplify-early`: evm5 to evm6. -/ +theorem stage_evm6 (o : Oracle) : Stage (evmirSem o) (evmirSem o) evm5 evm6 anyCall := + stage_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) 24 16 (evm5_ends o) + (fun call _ => evm6_run o call) + +theorem evm6_ends (o : Oracle) : ∀ call, anyCall call → + (EVM.Program.run o evm6 call 16).isSome = true := + ends_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) + (o := o) (p := evm5) (q := evm6) (n := 24) (m := 16) (evm5_ends o) + (fun call _ => evm6_run o call) + +/-- `tail-merge`: evm6 to evm7. -/ +theorem stage_evm7 (o : Oracle) : Stage (evmirSem o) (evmirSem o) evm6 evm7 anyCall := + stage_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) 16 17 (evm6_ends o) + (fun call _ => evm7_run o call) + +theorem evm7_ends (o : Oracle) : ∀ call, anyCall call → + (EVM.Program.run o evm7 call 17).isSome = true := + ends_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) + (o := o) (p := evm6) (q := evm7) (n := 16) (m := 17) (evm6_ends o) + (fun call _ => evm7_run o call) + +/-- `block-cse`: evm7 to evm8. -/ +theorem stage_evm8 (o : Oracle) : Stage (evmirSem o) (evmirSem o) evm7 evm8 anyCall := + stage_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) 17 17 (evm7_ends o) + (fun call _ => evm8_run o call) + +theorem evm8_ends (o : Oracle) : ∀ call, anyCall call → + (EVM.Program.run o evm8 call 17).isSome = true := + ends_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) + (o := o) (p := evm7) (q := evm8) (n := 17) (m := 17) (evm7_ends o) + (fun call _ => evm8_run o call) + +/-- `block-layout`: evm8 to evm9. -/ +theorem stage_evm9 (o : Oracle) : Stage (evmirSem o) (evmirSem o) evm8 evm9 anyCall := + stage_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) 17 17 (evm8_ends o) + (fun call _ => evm9_run o call) + +theorem evm9_ends (o : Oracle) : ∀ call, anyCall call → + (EVM.Program.run o evm9 call 17).isSome = true := + ends_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) + (o := o) (p := evm8) (q := evm9) (n := 17) (m := 17) (evm8_ends o) + (fun call _ => evm9_run o call) + +/-- `inline-returns`: evm9 to evm10. -/ +theorem stage_evm10 (o : Oracle) : Stage (evmirSem o) (evmirSem o) evm9 evm10 anyCall := + stage_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) 17 17 (evm9_ends o) + (fun call _ => evm10_run o call) + +theorem evm10_ends (o : Oracle) : ∀ call, anyCall call → + (EVM.Program.run o evm10 call 17).isSome = true := + ends_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) + (o := o) (p := evm9) (q := evm10) (n := 17) (m := 17) (evm9_ends o) + (fun call _ => evm10_run o call) + +/-- `late-word`: evm10 to evm11. -/ +theorem stage_evm11 (o : Oracle) : Stage (evmirSem o) (evmirSem o) evm10 evm11 anyCall := + stage_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) 17 17 (evm10_ends o) + (fun call _ => evm11_run o call) + +/-- The compilation from the first lowered MIR to the final EVM IR. -/ +def compilation : Compilation := + ⟨stage0, [mir1, mir2, mir3, mir4], sched, [evm1, evm2, evm3, evm4, evm5, evm6, evm7, evm8, evm9, evm10, evm11]⟩ + +/-- Every stage from the first lowered MIR to the final EVM IR, chained by the library's composition, on every call. -/ +theorem token_mir_to_evmir (o : Oracle) : Stage (mirSem o) (evmirSem o) stage0 evm11 anyCall := + mir_to_evmir o anyCall compilation ⟨stage_mir1 o, stage_mir2 o, stage_mir3 o, stage_mir4 o, trivial⟩ (stage_sched o) + ⟨stage_evm1 o, stage_evm2 o, stage_evm3 o, stage_evm4 o, stage_evm5 o, stage_evm6 o, stage_evm7 o, stage_evm8 o, stage_evm9 o, stage_evm10 o, stage_evm11 o, trivial⟩ + +/-- info: 'SolarTV.Milestone.Token.stage_mir1' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms stage_mir1 + +/-- info: 'SolarTV.Milestone.Token.stage_mir2' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms stage_mir2 + +/-- info: 'SolarTV.Milestone.Token.stage_mir3' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms stage_mir3 + +/-- info: 'SolarTV.Milestone.Token.stage_mir4' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms stage_mir4 + +/-- info: 'SolarTV.Milestone.Token.stage_sched' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms stage_sched + +/-- info: 'SolarTV.Milestone.Token.stage_evm1' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms stage_evm1 + +/-- info: 'SolarTV.Milestone.Token.stage_evm2' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms stage_evm2 + +/-- info: 'SolarTV.Milestone.Token.stage_evm3' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms stage_evm3 + +/-- info: 'SolarTV.Milestone.Token.stage_evm4' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms stage_evm4 + +/-- info: 'SolarTV.Milestone.Token.stage_evm5' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms stage_evm5 + +/-- info: 'SolarTV.Milestone.Token.stage_evm6' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms stage_evm6 + +/-- info: 'SolarTV.Milestone.Token.stage_evm7' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms stage_evm7 + +/-- info: 'SolarTV.Milestone.Token.stage_evm8' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms stage_evm8 + +/-- info: 'SolarTV.Milestone.Token.stage_evm9' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms stage_evm9 + +/-- info: 'SolarTV.Milestone.Token.stage_evm10' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms stage_evm10 + +/-- info: 'SolarTV.Milestone.Token.stage_evm11' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms stage_evm11 + +/-- info: 'SolarTV.Milestone.Token.token_mir_to_evmir' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms token_mir_to_evmir + +end SolarTV.Milestone.Token diff --git a/Certified/token/bytecode.hex b/Certified/token/bytecode.hex new file mode 100644 index 00000000..af913097 --- /dev/null +++ b/Certified/token/bytecode.hex @@ -0,0 +1 @@ +34603d575f3560e01c80638d1fdf2f1160535780638d1fdf2f14610114578063a9059cbb14610143578063dd62ed3e1460a4578063e58398361460eb575b5f5ffd5b6011602052634e487b715f526024601cfd5b8063095ea7b3146101f157806323b872dd1461024e57806370a08231146081578063893d20e81460db575f5ffd5b60043560a01c6024361017603d576004355f525f60205260405f20545f5260205ff35b60043560a01c604436101760243560a01c17603d576004355f52600160205260405f206024355f5260205260405f20545f5260205ff35b60045460601b60601c5f5260205ff35b60043560a01c6024361017603d576004355f52600260205260405f205460ff165f105f5260205ff35b60043560a01c6024361017603d5760045460601b60601c3303603d576004355f526002602052600160405f2055005b60043560a01c6044361017603d57335f52600260205260405f205460ff16603d57602435335f525f60205260405f2080548281106101cc5760043583909103909155805f5260405f2080548381019081106041579055905f52335b7fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef60205fa360015f5260205ff35b6662616c616e636560c81b60075b602080526040526060526308c379a05f526064601cfd5b60043560a01c6044361017603d57600435602435335f52600160205260405f20825f526020528060405f20555f52337f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b92560205fa360015f5260205ff35b60043560a01c606436101760243560a01c17603d57600435604435815f52600160205260405f20335f5260205260405f20548181106102e5578019156102aa57819003825f52600160205260405f20335f5260205260405f20555f5b50815f525f60205260405f208054828110603d5760243583909103909155805f5260405f2080548381019081106041579055905f529061019e565b68616c6c6f77616e636560b81b60096101da56 diff --git a/Certified/token/gen/Token/Bytecode.lean b/Certified/token/gen/Token/Bytecode.lean new file mode 100644 index 00000000..baf13946 --- /dev/null +++ b/Certified/token/gen/Token/Bytecode.lean @@ -0,0 +1,61 @@ +-- solar-lean-stage: kind=bytecode index=0 pass=assemble +/-! Generated by `solar -Zemit-lean-stages` for `Token`; do not edit. -/ + +namespace SolarTV.Export.Token + +/-- The runtime bytecode, byte by byte. -/ +def bytecode : List Nat := + [0x34, 0x60, 0x3d, 0x57, 0x5f, 0x35, 0x60, 0xe0, 0x1c, 0x80, 0x63, 0x8d, 0x1f, 0xdf, 0x2f, 0x11, + 0x60, 0x53, 0x57, 0x80, 0x63, 0x8d, 0x1f, 0xdf, 0x2f, 0x14, 0x61, 0x01, 0x14, 0x57, 0x80, 0x63, + 0xa9, 0x05, 0x9c, 0xbb, 0x14, 0x61, 0x01, 0x43, 0x57, 0x80, 0x63, 0xdd, 0x62, 0xed, 0x3e, 0x14, + 0x60, 0xa4, 0x57, 0x80, 0x63, 0xe5, 0x83, 0x98, 0x36, 0x14, 0x60, 0xeb, 0x57, 0x5b, 0x5f, 0x5f, + 0xfd, 0x5b, 0x60, 0x11, 0x60, 0x20, 0x52, 0x63, 0x4e, 0x48, 0x7b, 0x71, 0x5f, 0x52, 0x60, 0x24, + 0x60, 0x1c, 0xfd, 0x5b, 0x80, 0x63, 0x09, 0x5e, 0xa7, 0xb3, 0x14, 0x61, 0x01, 0xf1, 0x57, 0x80, + 0x63, 0x23, 0xb8, 0x72, 0xdd, 0x14, 0x61, 0x02, 0x4e, 0x57, 0x80, 0x63, 0x70, 0xa0, 0x82, 0x31, + 0x14, 0x60, 0x81, 0x57, 0x80, 0x63, 0x89, 0x3d, 0x20, 0xe8, 0x14, 0x60, 0xdb, 0x57, 0x5f, 0x5f, + 0xfd, 0x5b, 0x60, 0x04, 0x35, 0x60, 0xa0, 0x1c, 0x60, 0x24, 0x36, 0x10, 0x17, 0x60, 0x3d, 0x57, + 0x60, 0x04, 0x35, 0x5f, 0x52, 0x5f, 0x60, 0x20, 0x52, 0x60, 0x40, 0x5f, 0x20, 0x54, 0x5f, 0x52, + 0x60, 0x20, 0x5f, 0xf3, 0x5b, 0x60, 0x04, 0x35, 0x60, 0xa0, 0x1c, 0x60, 0x44, 0x36, 0x10, 0x17, + 0x60, 0x24, 0x35, 0x60, 0xa0, 0x1c, 0x17, 0x60, 0x3d, 0x57, 0x60, 0x04, 0x35, 0x5f, 0x52, 0x60, + 0x01, 0x60, 0x20, 0x52, 0x60, 0x40, 0x5f, 0x20, 0x60, 0x24, 0x35, 0x5f, 0x52, 0x60, 0x20, 0x52, + 0x60, 0x40, 0x5f, 0x20, 0x54, 0x5f, 0x52, 0x60, 0x20, 0x5f, 0xf3, 0x5b, 0x60, 0x04, 0x54, 0x60, + 0x60, 0x1b, 0x60, 0x60, 0x1c, 0x5f, 0x52, 0x60, 0x20, 0x5f, 0xf3, 0x5b, 0x60, 0x04, 0x35, 0x60, + 0xa0, 0x1c, 0x60, 0x24, 0x36, 0x10, 0x17, 0x60, 0x3d, 0x57, 0x60, 0x04, 0x35, 0x5f, 0x52, 0x60, + 0x02, 0x60, 0x20, 0x52, 0x60, 0x40, 0x5f, 0x20, 0x54, 0x60, 0xff, 0x16, 0x5f, 0x10, 0x5f, 0x52, + 0x60, 0x20, 0x5f, 0xf3, 0x5b, 0x60, 0x04, 0x35, 0x60, 0xa0, 0x1c, 0x60, 0x24, 0x36, 0x10, 0x17, + 0x60, 0x3d, 0x57, 0x60, 0x04, 0x54, 0x60, 0x60, 0x1b, 0x60, 0x60, 0x1c, 0x33, 0x03, 0x60, 0x3d, + 0x57, 0x60, 0x04, 0x35, 0x5f, 0x52, 0x60, 0x02, 0x60, 0x20, 0x52, 0x60, 0x01, 0x60, 0x40, 0x5f, + 0x20, 0x55, 0x00, 0x5b, 0x60, 0x04, 0x35, 0x60, 0xa0, 0x1c, 0x60, 0x44, 0x36, 0x10, 0x17, 0x60, + 0x3d, 0x57, 0x33, 0x5f, 0x52, 0x60, 0x02, 0x60, 0x20, 0x52, 0x60, 0x40, 0x5f, 0x20, 0x54, 0x60, + 0xff, 0x16, 0x60, 0x3d, 0x57, 0x60, 0x24, 0x35, 0x33, 0x5f, 0x52, 0x5f, 0x60, 0x20, 0x52, 0x60, + 0x40, 0x5f, 0x20, 0x80, 0x54, 0x82, 0x81, 0x10, 0x61, 0x01, 0xcc, 0x57, 0x60, 0x04, 0x35, 0x83, + 0x90, 0x91, 0x03, 0x90, 0x91, 0x55, 0x80, 0x5f, 0x52, 0x60, 0x40, 0x5f, 0x20, 0x80, 0x54, 0x83, + 0x81, 0x01, 0x90, 0x81, 0x10, 0x60, 0x41, 0x57, 0x90, 0x55, 0x90, 0x5f, 0x52, 0x33, 0x5b, 0x7f, + 0xdd, 0xf2, 0x52, 0xad, 0x1b, 0xe2, 0xc8, 0x9b, 0x69, 0xc2, 0xb0, 0x68, 0xfc, 0x37, 0x8d, 0xaa, + 0x95, 0x2b, 0xa7, 0xf1, 0x63, 0xc4, 0xa1, 0x16, 0x28, 0xf5, 0x5a, 0x4d, 0xf5, 0x23, 0xb3, 0xef, + 0x60, 0x20, 0x5f, 0xa3, 0x60, 0x01, 0x5f, 0x52, 0x60, 0x20, 0x5f, 0xf3, 0x5b, 0x66, 0x62, 0x61, + 0x6c, 0x61, 0x6e, 0x63, 0x65, 0x60, 0xc8, 0x1b, 0x60, 0x07, 0x5b, 0x60, 0x20, 0x80, 0x52, 0x60, + 0x40, 0x52, 0x60, 0x60, 0x52, 0x63, 0x08, 0xc3, 0x79, 0xa0, 0x5f, 0x52, 0x60, 0x64, 0x60, 0x1c, + 0xfd, 0x5b, 0x60, 0x04, 0x35, 0x60, 0xa0, 0x1c, 0x60, 0x44, 0x36, 0x10, 0x17, 0x60, 0x3d, 0x57, + 0x60, 0x04, 0x35, 0x60, 0x24, 0x35, 0x33, 0x5f, 0x52, 0x60, 0x01, 0x60, 0x20, 0x52, 0x60, 0x40, + 0x5f, 0x20, 0x82, 0x5f, 0x52, 0x60, 0x20, 0x52, 0x80, 0x60, 0x40, 0x5f, 0x20, 0x55, 0x5f, 0x52, + 0x33, 0x7f, 0x8c, 0x5b, 0xe1, 0xe5, 0xeb, 0xec, 0x7d, 0x5b, 0xd1, 0x4f, 0x71, 0x42, 0x7d, 0x1e, + 0x84, 0xf3, 0xdd, 0x03, 0x14, 0xc0, 0xf7, 0xb2, 0x29, 0x1e, 0x5b, 0x20, 0x0a, 0xc8, 0xc7, 0xc3, + 0xb9, 0x25, 0x60, 0x20, 0x5f, 0xa3, 0x60, 0x01, 0x5f, 0x52, 0x60, 0x20, 0x5f, 0xf3, 0x5b, 0x60, + 0x04, 0x35, 0x60, 0xa0, 0x1c, 0x60, 0x64, 0x36, 0x10, 0x17, 0x60, 0x24, 0x35, 0x60, 0xa0, 0x1c, + 0x17, 0x60, 0x3d, 0x57, 0x60, 0x04, 0x35, 0x60, 0x44, 0x35, 0x81, 0x5f, 0x52, 0x60, 0x01, 0x60, + 0x20, 0x52, 0x60, 0x40, 0x5f, 0x20, 0x33, 0x5f, 0x52, 0x60, 0x20, 0x52, 0x60, 0x40, 0x5f, 0x20, + 0x54, 0x81, 0x81, 0x10, 0x61, 0x02, 0xe5, 0x57, 0x80, 0x19, 0x15, 0x61, 0x02, 0xaa, 0x57, 0x81, + 0x90, 0x03, 0x82, 0x5f, 0x52, 0x60, 0x01, 0x60, 0x20, 0x52, 0x60, 0x40, 0x5f, 0x20, 0x33, 0x5f, + 0x52, 0x60, 0x20, 0x52, 0x60, 0x40, 0x5f, 0x20, 0x55, 0x5f, 0x5b, 0x50, 0x81, 0x5f, 0x52, 0x5f, + 0x60, 0x20, 0x52, 0x60, 0x40, 0x5f, 0x20, 0x80, 0x54, 0x82, 0x81, 0x10, 0x60, 0x3d, 0x57, 0x60, + 0x24, 0x35, 0x83, 0x90, 0x91, 0x03, 0x90, 0x91, 0x55, 0x80, 0x5f, 0x52, 0x60, 0x40, 0x5f, 0x20, + 0x80, 0x54, 0x83, 0x81, 0x01, 0x90, 0x81, 0x10, 0x60, 0x41, 0x57, 0x90, 0x55, 0x90, 0x5f, 0x52, + 0x90, 0x61, 0x01, 0x9e, 0x56, 0x5b, 0x68, 0x61, 0x6c, 0x6c, 0x6f, 0x77, 0x61, 0x6e, 0x63, 0x65, + 0x60, 0xb8, 0x1b, 0x60, 0x09, 0x61, 0x01, 0xda, 0x56] + +/-- The runtime bytecode in hex, as `--emit=bin-runtime` prints it. -/ +def bytecodeHex : String := + "34603d575f3560e01c80638d1fdf2f1160535780638d1fdf2f14610114578063a9059cbb14610143578063dd62ed3e1460a4578063e58398361460eb575b5f5ffd5b6011602052634e487b715f526024601cfd5b8063095ea7b3146101f157806323b872dd1461024e57806370a08231146081578063893d20e81460db575f5ffd5b60043560a01c6024361017603d576004355f525f60205260405f20545f5260205ff35b60043560a01c604436101760243560a01c17603d576004355f52600160205260405f206024355f5260205260405f20545f5260205ff35b60045460601b60601c5f5260205ff35b60043560a01c6024361017603d576004355f52600260205260405f205460ff165f105f5260205ff35b60043560a01c6024361017603d5760045460601b60601c3303603d576004355f526002602052600160405f2055005b60043560a01c6044361017603d57335f52600260205260405f205460ff16603d57602435335f525f60205260405f2080548281106101cc5760043583909103909155805f5260405f2080548381019081106041579055905f52335b7fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef60205fa360015f5260205ff35b6662616c616e636560c81b60075b602080526040526060526308c379a05f526064601cfd5b60043560a01c6044361017603d57600435602435335f52600160205260405f20825f526020528060405f20555f52337f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b92560205fa360015f5260205ff35b60043560a01c606436101760243560a01c17603d57600435604435815f52600160205260405f20335f5260205260405f20548181106102e5578019156102aa57819003825f52600160205260405f20335f5260205260405f20555f5b50815f525f60205260405f208054828110603d5760243583909103909155805f5260405f2080548381019081106041579055905f529061019e565b68616c6c6f77616e636560b81b60096101da56" + +end SolarTV.Export.Token diff --git a/Certified/token/gen/Token/Evm1.lean b/Certified/token/gen/Token/Evm1.lean new file mode 100644 index 00000000..29427bda --- /dev/null +++ b/Certified/token/gen/Token/Evm1.lean @@ -0,0 +1,567 @@ +-- solar-lean-stage: kind=evm index=1 pass=peephole-early +import SolarTV.EVMIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `Token`; do not edit. -/ + +namespace SolarTV.Export.Token + +/-- The runtime EVM IR after `peephole-early`. -/ +def evm1 : EVM.Program.Program := + { blocks := [ + -- bb0 + [.effect .callvalue 0, + .jumpi 11, + .jump 1], + -- bb1 + [.op (.stack (.push 0)), + .effect .calldataload 1, + .op (.stack (.push 224)), + .op (.stack .shr), + .op (.stack (.dup 0)), + .op (.stack (.push 0x8d1fdf2f)), + .op (.stack .gt), + .jumpi 2, + .op (.stack (.dup 0)), + .op (.stack (.push 0x8d1fdf2f)), + .op (.stack .eq), + .jumpi 6, + .op (.stack (.dup 0)), + .op (.stack (.push 0xa9059cbb)), + .op (.stack .eq), + .jumpi 5, + .op (.stack (.dup 0)), + .op (.stack (.push 0xdd62ed3e)), + .op (.stack .eq), + .jumpi 4, + .op (.stack (.dup 0)), + .op (.stack (.push 0xe5839836)), + .op (.stack .eq), + .jumpi 3, + .jump 11], + -- bb2 + [.op (.stack (.dup 0)), + .op (.stack (.push 0x95ea7b3)), + .op (.stack .eq), + .jumpi 10, + .op (.stack (.dup 0)), + .op (.stack (.push 0x23b872dd)), + .op (.stack .eq), + .jumpi 9, + .op (.stack (.dup 0)), + .op (.stack (.push 0x70a08231)), + .op (.stack .eq), + .jumpi 8, + .op (.stack (.dup 0)), + .op (.stack (.push 0x893d20e8)), + .op (.stack .eq), + .jumpi 7, + .jump 11], + -- bb3 + [.jump 19], + -- bb4 + [.jump 15], + -- bb5 + [.jump 26], + -- bb6 + [.jump 22], + -- bb7 + [.jump 18], + -- bb8 + [.jump 12], + -- bb9 + [.jump 37], + -- bb10 + [.jump 34], + -- bb11 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb12 + [.op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 160)), + .op (.stack .shr), + .op (.stack (.push 36)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack .or), + .jumpi 14, + .jump 13], + -- bb13 + [.op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 0)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .effect .sload 1, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb14 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb15 + [.op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 160)), + .op (.stack .shr), + .op (.stack (.push 68)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack .or), + .op (.stack (.push 36)), + .effect .calldataload 1, + .op (.stack (.push 160)), + .op (.stack .shr), + .op (.stack .or), + .jumpi 17, + .jump 16], + -- bb16 + [.op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 1)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .op (.stack (.push 36)), + .effect .calldataload 1, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .effect .sload 1, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb17 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb18 + [.op (.stack (.push 4)), + .effect .sload 1, + .op (.stack (.push 0xffffffffffffffffffffffffffffffffffffffff)), + .op (.stack .and), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb19 + [.op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 160)), + .op (.stack .shr), + .op (.stack (.push 36)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack .or), + .jumpi 21, + .jump 20], + -- bb20 + [.op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 2)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .effect .sload 1, + .op (.stack (.push 255)), + .op (.stack .and), + .op (.stack (.push 0)), + .op (.stack .lt), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb21 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb22 + [.op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 160)), + .op (.stack .shr), + .op (.stack (.push 36)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack .or), + .jumpi 25, + .jump 23], + -- bb23 + [.op (.stack (.push 4)), + .effect .sload 1, + .op (.stack (.push 0xffffffffffffffffffffffffffffffffffffffff)), + .op (.stack .and), + .effect .caller 0, + .op (.stack .sub), + .jumpi 25, + .jump 24], + -- bb24 + [.op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 2)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 1)), + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .effect .sstore 2, + .stop], + -- bb25 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb26 + [.op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 160)), + .op (.stack .shr), + .op (.stack (.push 68)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack .or), + .jumpi 33, + .jump 27], + -- bb27 + [.effect .caller 0, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 2)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .effect .sload 1, + .op (.stack (.push 255)), + .op (.stack .and), + .jumpi 33, + .jump 28], + -- bb28 + [.op (.stack (.push 36)), + .effect .calldataload 1, + .effect .caller 0, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 0)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .op (.stack (.dup 0)), + .effect .sload 1, + .op (.stack (.dup 2)), + .op (.stack (.dup 1)), + .op (.stack .lt), + .jumpi 32, + .jump 29], + -- bb29 + [.op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.dup 3)), + .op (.stack (.swap 0)), + .op (.stack (.swap 1)), + .op (.stack .sub), + .op (.stack (.swap 0)), + .op (.stack (.swap 1)), + .effect .sstore 2, + .op (.stack (.dup 0)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .op (.stack (.dup 0)), + .effect .sload 1, + .op (.stack (.dup 3)), + .op (.stack (.dup 1)), + .op (.stack .add), + .op (.stack (.swap 0)), + .op (.stack (.dup 1)), + .op (.stack .lt), + .jumpi 31, + .jump 30], + -- bb30 + [.op (.stack (.swap 0)), + .effect .sstore 2, + .op (.stack (.swap 0)), + .op (.stack (.push 0)), + .op .store, + .effect .caller 0, + .op (.stack (.push 0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef)), + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .effect (.log 3) 5, + .op (.stack (.push 1)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb31 + [.op (.stack (.push 17)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 0x4e487b71)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 36)), + .op (.stack (.push 28)), + .revert], + -- bb32 + [.op (.stack (.push 0x62616c616e636500000000000000000000000000000000000000000000000000)), + .op (.stack (.push 7)), + .jump 47], + -- bb33 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb34 + [.op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 160)), + .op (.stack .shr), + .op (.stack (.push 68)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack .or), + .jumpi 36, + .jump 35], + -- bb35 + [.op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 36)), + .effect .calldataload 1, + .effect .caller 0, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 1)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .op (.stack (.dup 2)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op .store, + .op (.stack (.dup 0)), + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .effect .sstore 2, + .op (.stack (.push 0)), + .op .store, + .effect .caller 0, + .op (.stack (.push 0x8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925)), + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .effect (.log 3) 5, + .op (.stack (.push 1)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb36 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb37 + [.op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 160)), + .op (.stack .shr), + .op (.stack (.push 100)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack .or), + .op (.stack (.push 36)), + .effect .calldataload 1, + .op (.stack (.push 160)), + .op (.stack .shr), + .op (.stack .or), + .jumpi 46, + .jump 38], + -- bb38 + [.op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 68)), + .effect .calldataload 1, + .op (.stack (.dup 1)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 1)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .effect .caller 0, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .effect .sload 1, + .op (.stack (.dup 1)), + .op (.stack (.dup 1)), + .op (.stack .lt), + .jumpi 45, + .jump 39], + -- bb39 + [.op (.stack (.dup 0)), + .op (.stack .not), + .op (.stack .iszero), + .jumpi 41, + .jump 40], + -- bb40 + [.op (.stack (.dup 1)), + .op (.stack (.swap 0)), + .op (.stack .sub), + .op (.stack (.dup 2)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 1)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .effect .caller 0, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .effect .sstore 2, + .op (.stack (.push 0)), + .jump 41], + -- bb41 + [.op (.stack .pop), + .op (.stack (.dup 1)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 0)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .op (.stack (.dup 0)), + .effect .sload 1, + .op (.stack (.dup 2)), + .op (.stack (.dup 1)), + .op (.stack .lt), + .jumpi 46, + .jump 42], + -- bb42 + [.op (.stack (.push 36)), + .effect .calldataload 1, + .op (.stack (.dup 3)), + .op (.stack (.swap 0)), + .op (.stack (.swap 1)), + .op (.stack .sub), + .op (.stack (.swap 0)), + .op (.stack (.swap 1)), + .effect .sstore 2, + .op (.stack (.dup 0)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .op (.stack (.dup 0)), + .effect .sload 1, + .op (.stack (.dup 3)), + .op (.stack (.dup 1)), + .op (.stack .add), + .op (.stack (.swap 0)), + .op (.stack (.dup 1)), + .op (.stack .lt), + .jumpi 44, + .jump 43], + -- bb43 + [.op (.stack (.swap 0)), + .effect .sstore 2, + .op (.stack (.swap 0)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.swap 0)), + .op (.stack (.push 0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef)), + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .effect (.log 3) 5, + .op (.stack (.push 1)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb44 + [.op (.stack (.push 17)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 0x4e487b71)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 36)), + .op (.stack (.push 28)), + .revert], + -- bb45 + [.op (.stack (.push 0x616c6c6f77616e63650000000000000000000000000000000000000000000000)), + .op (.stack (.push 9)), + .jump 47], + -- bb46 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb47 + [.op (.stack (.push 32)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op .store, + .op (.stack (.push 96)), + .op .store, + .op (.stack (.push 0x8c379a0)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 100)), + .op (.stack (.push 28)), + .revert]] } + +end SolarTV.Export.Token diff --git a/Certified/token/gen/Token/Evm10.lean b/Certified/token/gen/Token/Evm10.lean new file mode 100644 index 00000000..9a7a2518 --- /dev/null +++ b/Certified/token/gen/Token/Evm10.lean @@ -0,0 +1,486 @@ +-- solar-lean-stage: kind=evm index=10 pass=inline-returns +import SolarTV.EVMIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `Token`; do not edit. -/ + +namespace SolarTV.Export.Token + +/-- The runtime EVM IR after `inline-returns`. -/ +def evm10 : EVM.Program.Program := + { blocks := [ + -- bb0 + [.effect .callvalue 0, + .jumpi 1, + .op (.stack (.push 0)), + .effect .calldataload 1, + .op (.stack (.push 224)), + .op (.stack .shr), + .op (.stack (.dup 0)), + .op (.stack (.push 0x8d1fdf2f)), + .op (.stack .gt), + .jumpi 3, + .op (.stack (.dup 0)), + .op (.stack (.push 0x8d1fdf2f)), + .op (.stack .eq), + .jumpi 8, + .op (.stack (.dup 0)), + .op (.stack (.push 0xa9059cbb)), + .op (.stack .eq), + .jumpi 9, + .op (.stack (.dup 0)), + .op (.stack (.push 0xdd62ed3e)), + .op (.stack .eq), + .jumpi 5, + .op (.stack (.dup 0)), + .op (.stack (.push 0xe5839836)), + .op (.stack .eq), + .jumpi 7, + .jump 1], + -- bb11 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb31 + [.op (.stack (.push 17)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 0x4e487b71)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 36)), + .op (.stack (.push 28)), + .revert], + -- bb2 + [.op (.stack (.dup 0)), + .op (.stack (.push 0x95ea7b3)), + .op (.stack .eq), + .jumpi 13, + .op (.stack (.dup 0)), + .op (.stack (.push 0x23b872dd)), + .op (.stack .eq), + .jumpi 14, + .op (.stack (.dup 0)), + .op (.stack (.push 0x70a08231)), + .op (.stack .eq), + .jumpi 4, + .op (.stack (.dup 0)), + .op (.stack (.push 0x893d20e8)), + .op (.stack .eq), + .jumpi 6, + .op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb12 + [.op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 160)), + .op (.stack .shr), + .op (.stack (.push 36)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack .or), + .jumpi 1, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 0)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .effect .sload 1, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb15 + [.op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 160)), + .op (.stack .shr), + .op (.stack (.push 68)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack .or), + .op (.stack (.push 36)), + .effect .calldataload 1, + .op (.stack (.push 160)), + .op (.stack .shr), + .op (.stack .or), + .jumpi 1, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 1)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .op (.stack (.push 36)), + .effect .calldataload 1, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .effect .sload 1, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb18 + [.op (.stack (.push 4)), + .effect .sload 1, + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .op (.stack .and), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb19 + [.op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 160)), + .op (.stack .shr), + .op (.stack (.push 36)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack .or), + .jumpi 1, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 2)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .effect .sload 1, + .op (.stack (.push 255)), + .op (.stack .and), + .op (.stack (.push 0)), + .op (.stack .lt), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb22 + [.op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 160)), + .op (.stack .shr), + .op (.stack (.push 36)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack .or), + .jumpi 1, + .op (.stack (.push 4)), + .effect .sload 1, + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .op (.stack .and), + .effect .caller 0, + .op (.stack .sub), + .jumpi 1, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 2)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 1)), + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .effect .sstore 2, + .stop], + -- bb26 + [.op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 160)), + .op (.stack .shr), + .op (.stack (.push 68)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack .or), + .jumpi 1, + .effect .caller 0, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 2)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .effect .sload 1, + .op (.stack (.push 255)), + .op (.stack .and), + .jumpi 1, + .op (.stack (.push 36)), + .effect .calldataload 1, + .effect .caller 0, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 0)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .op (.stack (.dup 0)), + .effect .sload 1, + .op (.stack (.dup 2)), + .op (.stack (.dup 1)), + .op (.stack .lt), + .jumpi 11, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.dup 3)), + .op (.stack (.swap 0)), + .op (.stack (.swap 1)), + .op (.stack .sub), + .op (.stack (.swap 0)), + .op (.stack (.swap 1)), + .effect .sstore 2, + .op (.stack (.dup 0)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .op (.stack (.dup 0)), + .effect .sload 1, + .op (.stack (.dup 3)), + .op (.stack (.dup 1)), + .op (.stack .add), + .op (.stack (.swap 0)), + .op (.stack (.dup 1)), + .op (.stack .lt), + .jumpi 2, + .op (.stack (.swap 0)), + .effect .sstore 2, + .op (.stack (.swap 0)), + .op (.stack (.push 0)), + .op .store, + .effect .caller 0, + .jump 10], + -- bb48 + [.op (.stack (.push 0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef)), + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .effect (.log 3) 5, + .op (.stack (.push 1)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb32 + [.op (.stack (.push 0x62616c616e6365)), + .op (.stack (.push 200)), + .op (.stack .shl), + .op (.stack (.push 7)), + .jump 12], + -- bb47 + [.op (.stack (.push 32)), + .op (.stack (.dup 0)), + .op .store, + .op (.stack (.push 64)), + .op .store, + .op (.stack (.push 96)), + .op .store, + .op (.stack (.push 0x8c379a0)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 100)), + .op (.stack (.push 28)), + .revert], + -- bb34 + [.op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 160)), + .op (.stack .shr), + .op (.stack (.push 68)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack .or), + .jumpi 1, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 36)), + .effect .calldataload 1, + .effect .caller 0, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 1)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .op (.stack (.dup 2)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op .store, + .op (.stack (.dup 0)), + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .effect .sstore 2, + .op (.stack (.push 0)), + .op .store, + .effect .caller 0, + .op (.stack (.push 0x8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925)), + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .effect (.log 3) 5, + .op (.stack (.push 1)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb37 + [.op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 160)), + .op (.stack .shr), + .op (.stack (.push 100)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack .or), + .op (.stack (.push 36)), + .effect .calldataload 1, + .op (.stack (.push 160)), + .op (.stack .shr), + .op (.stack .or), + .jumpi 1, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 68)), + .effect .calldataload 1, + .op (.stack (.dup 1)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 1)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .effect .caller 0, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .effect .sload 1, + .op (.stack (.dup 1)), + .op (.stack (.dup 1)), + .op (.stack .lt), + .jumpi 16, + .op (.stack (.dup 0)), + .op (.stack .not), + .op (.stack .iszero), + .jumpi 15, + .op (.stack (.dup 1)), + .op (.stack (.swap 0)), + .op (.stack .sub), + .op (.stack (.dup 2)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 1)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .effect .caller 0, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .effect .sstore 2, + .op (.stack (.push 0)), + .jump 15], + -- bb41 + [.op (.stack .pop), + .op (.stack (.dup 1)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 0)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .op (.stack (.dup 0)), + .effect .sload 1, + .op (.stack (.dup 2)), + .op (.stack (.dup 1)), + .op (.stack .lt), + .jumpi 1, + .op (.stack (.push 36)), + .effect .calldataload 1, + .op (.stack (.dup 3)), + .op (.stack (.swap 0)), + .op (.stack (.swap 1)), + .op (.stack .sub), + .op (.stack (.swap 0)), + .op (.stack (.swap 1)), + .effect .sstore 2, + .op (.stack (.dup 0)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .op (.stack (.dup 0)), + .effect .sload 1, + .op (.stack (.dup 3)), + .op (.stack (.dup 1)), + .op (.stack .add), + .op (.stack (.swap 0)), + .op (.stack (.dup 1)), + .op (.stack .lt), + .jumpi 2, + .op (.stack (.swap 0)), + .effect .sstore 2, + .op (.stack (.swap 0)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.swap 0)), + .jump 10], + -- bb45 + [.op (.stack (.push 0x616c6c6f77616e6365)), + .op (.stack (.push 184)), + .op (.stack .shl), + .op (.stack (.push 9)), + .jump 12]] } + +end SolarTV.Export.Token diff --git a/Certified/token/gen/Token/Evm11.lean b/Certified/token/gen/Token/Evm11.lean new file mode 100644 index 00000000..612804f1 --- /dev/null +++ b/Certified/token/gen/Token/Evm11.lean @@ -0,0 +1,484 @@ +-- solar-lean-stage: kind=evm index=11 pass=late-word +import SolarTV.EVMIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `Token`; do not edit. -/ + +namespace SolarTV.Export.Token + +/-- The runtime EVM IR after `late-word`. -/ +def evm11 : EVM.Program.Program := + { blocks := [ + -- bb0 + [.effect .callvalue 0, + .jumpi 1, + .op (.stack (.push 0)), + .effect .calldataload 1, + .op (.stack (.push 224)), + .op (.stack .shr), + .op (.stack (.dup 0)), + .op (.stack (.push 0x8d1fdf2f)), + .op (.stack .gt), + .jumpi 3, + .op (.stack (.dup 0)), + .op (.stack (.push 0x8d1fdf2f)), + .op (.stack .eq), + .jumpi 8, + .op (.stack (.dup 0)), + .op (.stack (.push 0xa9059cbb)), + .op (.stack .eq), + .jumpi 9, + .op (.stack (.dup 0)), + .op (.stack (.push 0xdd62ed3e)), + .op (.stack .eq), + .jumpi 5, + .op (.stack (.dup 0)), + .op (.stack (.push 0xe5839836)), + .op (.stack .eq), + .jumpi 7, + .jump 1], + -- bb11 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb31 + [.op (.stack (.push 17)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 0x4e487b71)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 36)), + .op (.stack (.push 28)), + .revert], + -- bb2 + [.op (.stack (.dup 0)), + .op (.stack (.push 0x95ea7b3)), + .op (.stack .eq), + .jumpi 13, + .op (.stack (.dup 0)), + .op (.stack (.push 0x23b872dd)), + .op (.stack .eq), + .jumpi 14, + .op (.stack (.dup 0)), + .op (.stack (.push 0x70a08231)), + .op (.stack .eq), + .jumpi 4, + .op (.stack (.dup 0)), + .op (.stack (.push 0x893d20e8)), + .op (.stack .eq), + .jumpi 6, + .op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb12 + [.op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 160)), + .op (.stack .shr), + .op (.stack (.push 36)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack .or), + .jumpi 1, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 0)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .effect .sload 1, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb15 + [.op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 160)), + .op (.stack .shr), + .op (.stack (.push 68)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack .or), + .op (.stack (.push 36)), + .effect .calldataload 1, + .op (.stack (.push 160)), + .op (.stack .shr), + .op (.stack .or), + .jumpi 1, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 1)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .op (.stack (.push 36)), + .effect .calldataload 1, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .effect .sload 1, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb18 + [.op (.stack (.push 4)), + .effect .sload 1, + .op (.stack (.push 96)), + .op (.stack .shl), + .op (.stack (.push 96)), + .op (.stack .shr), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb19 + [.op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 160)), + .op (.stack .shr), + .op (.stack (.push 36)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack .or), + .jumpi 1, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 2)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .effect .sload 1, + .op (.stack (.push 255)), + .op (.stack .and), + .op (.stack (.push 0)), + .op (.stack .lt), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb22 + [.op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 160)), + .op (.stack .shr), + .op (.stack (.push 36)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack .or), + .jumpi 1, + .op (.stack (.push 4)), + .effect .sload 1, + .op (.stack (.push 96)), + .op (.stack .shl), + .op (.stack (.push 96)), + .op (.stack .shr), + .effect .caller 0, + .op (.stack .sub), + .jumpi 1, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 2)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 1)), + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .effect .sstore 2, + .stop], + -- bb26 + [.op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 160)), + .op (.stack .shr), + .op (.stack (.push 68)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack .or), + .jumpi 1, + .effect .caller 0, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 2)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .effect .sload 1, + .op (.stack (.push 255)), + .op (.stack .and), + .jumpi 1, + .op (.stack (.push 36)), + .effect .calldataload 1, + .effect .caller 0, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 0)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .op (.stack (.dup 0)), + .effect .sload 1, + .op (.stack (.dup 2)), + .op (.stack (.dup 1)), + .op (.stack .lt), + .jumpi 11, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.dup 3)), + .op (.stack (.swap 0)), + .op (.stack (.swap 1)), + .op (.stack .sub), + .op (.stack (.swap 0)), + .op (.stack (.swap 1)), + .effect .sstore 2, + .op (.stack (.dup 0)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .op (.stack (.dup 0)), + .effect .sload 1, + .op (.stack (.dup 3)), + .op (.stack (.dup 1)), + .op (.stack .add), + .op (.stack (.swap 0)), + .op (.stack (.dup 1)), + .op (.stack .lt), + .jumpi 2, + .op (.stack (.swap 0)), + .effect .sstore 2, + .op (.stack (.swap 0)), + .op (.stack (.push 0)), + .op .store, + .effect .caller 0, + .jump 10], + -- bb48 + [.op (.stack (.push 0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef)), + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .effect (.log 3) 5, + .op (.stack (.push 1)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb32 + [.op (.stack (.push 0x62616c616e6365)), + .op (.stack (.push 200)), + .op (.stack .shl), + .op (.stack (.push 7)), + .jump 12], + -- bb47 + [.op (.stack (.push 32)), + .op (.stack (.dup 0)), + .op .store, + .op (.stack (.push 64)), + .op .store, + .op (.stack (.push 96)), + .op .store, + .op (.stack (.push 0x8c379a0)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 100)), + .op (.stack (.push 28)), + .revert], + -- bb34 + [.op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 160)), + .op (.stack .shr), + .op (.stack (.push 68)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack .or), + .jumpi 1, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 36)), + .effect .calldataload 1, + .effect .caller 0, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 1)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .op (.stack (.dup 2)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op .store, + .op (.stack (.dup 0)), + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .effect .sstore 2, + .op (.stack (.push 0)), + .op .store, + .effect .caller 0, + .op (.stack (.push 0x8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925)), + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .effect (.log 3) 5, + .op (.stack (.push 1)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb37 + [.op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 160)), + .op (.stack .shr), + .op (.stack (.push 100)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack .or), + .op (.stack (.push 36)), + .effect .calldataload 1, + .op (.stack (.push 160)), + .op (.stack .shr), + .op (.stack .or), + .jumpi 1, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 68)), + .effect .calldataload 1, + .op (.stack (.dup 1)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 1)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .effect .caller 0, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .effect .sload 1, + .op (.stack (.dup 1)), + .op (.stack (.dup 1)), + .op (.stack .lt), + .jumpi 16, + .op (.stack (.dup 0)), + .op (.stack .not), + .op (.stack .iszero), + .jumpi 15, + .op (.stack (.dup 1)), + .op (.stack (.swap 0)), + .op (.stack .sub), + .op (.stack (.dup 2)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 1)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .effect .caller 0, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .effect .sstore 2, + .op (.stack (.push 0)), + .jump 15], + -- bb41 + [.op (.stack .pop), + .op (.stack (.dup 1)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 0)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .op (.stack (.dup 0)), + .effect .sload 1, + .op (.stack (.dup 2)), + .op (.stack (.dup 1)), + .op (.stack .lt), + .jumpi 1, + .op (.stack (.push 36)), + .effect .calldataload 1, + .op (.stack (.dup 3)), + .op (.stack (.swap 0)), + .op (.stack (.swap 1)), + .op (.stack .sub), + .op (.stack (.swap 0)), + .op (.stack (.swap 1)), + .effect .sstore 2, + .op (.stack (.dup 0)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .op (.stack (.dup 0)), + .effect .sload 1, + .op (.stack (.dup 3)), + .op (.stack (.dup 1)), + .op (.stack .add), + .op (.stack (.swap 0)), + .op (.stack (.dup 1)), + .op (.stack .lt), + .jumpi 2, + .op (.stack (.swap 0)), + .effect .sstore 2, + .op (.stack (.swap 0)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.swap 0)), + .jump 10], + -- bb45 + [.op (.stack (.push 0x616c6c6f77616e6365)), + .op (.stack (.push 184)), + .op (.stack .shl), + .op (.stack (.push 9)), + .jump 12]] } + +end SolarTV.Export.Token diff --git a/Certified/token/gen/Token/Evm2.lean b/Certified/token/gen/Token/Evm2.lean new file mode 100644 index 00000000..f8931c2d --- /dev/null +++ b/Certified/token/gen/Token/Evm2.lean @@ -0,0 +1,519 @@ +-- solar-lean-stage: kind=evm index=2 pass=cfg-simplify-early +import SolarTV.EVMIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `Token`; do not edit. -/ + +namespace SolarTV.Export.Token + +/-- The runtime EVM IR after `cfg-simplify-early`. -/ +def evm2 : EVM.Program.Program := + { blocks := [ + -- bb0 + [.effect .callvalue 0, + .jumpi 2, + .op (.stack (.push 0)), + .effect .calldataload 1, + .op (.stack (.push 224)), + .op (.stack .shr), + .op (.stack (.dup 0)), + .op (.stack (.push 0x8d1fdf2f)), + .op (.stack .gt), + .jumpi 1, + .op (.stack (.dup 0)), + .op (.stack (.push 0x8d1fdf2f)), + .op (.stack .eq), + .jumpi 10, + .op (.stack (.dup 0)), + .op (.stack (.push 0xa9059cbb)), + .op (.stack .eq), + .jumpi 12, + .op (.stack (.dup 0)), + .op (.stack (.push 0xdd62ed3e)), + .op (.stack .eq), + .jumpi 5, + .op (.stack (.dup 0)), + .op (.stack (.push 0xe5839836)), + .op (.stack .eq), + .jumpi 8, + .jump 2], + -- bb2 + [.op (.stack (.dup 0)), + .op (.stack (.push 0x95ea7b3)), + .op (.stack .eq), + .jumpi 16, + .op (.stack (.dup 0)), + .op (.stack (.push 0x23b872dd)), + .op (.stack .eq), + .jumpi 18, + .op (.stack (.dup 0)), + .op (.stack (.push 0x70a08231)), + .op (.stack .eq), + .jumpi 3, + .op (.stack (.dup 0)), + .op (.stack (.push 0x893d20e8)), + .op (.stack .eq), + .jumpi 7, + .jump 2], + -- bb11 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb12 + [.op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 160)), + .op (.stack .shr), + .op (.stack (.push 36)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack .or), + .jumpi 4, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 0)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .effect .sload 1, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb14 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb15 + [.op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 160)), + .op (.stack .shr), + .op (.stack (.push 68)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack .or), + .op (.stack (.push 36)), + .effect .calldataload 1, + .op (.stack (.push 160)), + .op (.stack .shr), + .op (.stack .or), + .jumpi 6, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 1)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .op (.stack (.push 36)), + .effect .calldataload 1, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .effect .sload 1, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb17 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb18 + [.op (.stack (.push 4)), + .effect .sload 1, + .op (.stack (.push 0xffffffffffffffffffffffffffffffffffffffff)), + .op (.stack .and), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb19 + [.op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 160)), + .op (.stack .shr), + .op (.stack (.push 36)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack .or), + .jumpi 9, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 2)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .effect .sload 1, + .op (.stack (.push 255)), + .op (.stack .and), + .op (.stack (.push 0)), + .op (.stack .lt), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb21 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb22 + [.op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 160)), + .op (.stack .shr), + .op (.stack (.push 36)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack .or), + .jumpi 11, + .op (.stack (.push 4)), + .effect .sload 1, + .op (.stack (.push 0xffffffffffffffffffffffffffffffffffffffff)), + .op (.stack .and), + .effect .caller 0, + .op (.stack .sub), + .jumpi 11, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 2)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 1)), + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .effect .sstore 2, + .stop], + -- bb25 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb26 + [.op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 160)), + .op (.stack .shr), + .op (.stack (.push 68)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack .or), + .jumpi 15, + .effect .caller 0, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 2)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .effect .sload 1, + .op (.stack (.push 255)), + .op (.stack .and), + .jumpi 15, + .op (.stack (.push 36)), + .effect .calldataload 1, + .effect .caller 0, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 0)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .op (.stack (.dup 0)), + .effect .sload 1, + .op (.stack (.dup 2)), + .op (.stack (.dup 1)), + .op (.stack .lt), + .jumpi 14, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.dup 3)), + .op (.stack (.swap 0)), + .op (.stack (.swap 1)), + .op (.stack .sub), + .op (.stack (.swap 0)), + .op (.stack (.swap 1)), + .effect .sstore 2, + .op (.stack (.dup 0)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .op (.stack (.dup 0)), + .effect .sload 1, + .op (.stack (.dup 3)), + .op (.stack (.dup 1)), + .op (.stack .add), + .op (.stack (.swap 0)), + .op (.stack (.dup 1)), + .op (.stack .lt), + .jumpi 13, + .op (.stack (.swap 0)), + .effect .sstore 2, + .op (.stack (.swap 0)), + .op (.stack (.push 0)), + .op .store, + .effect .caller 0, + .op (.stack (.push 0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef)), + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .effect (.log 3) 5, + .op (.stack (.push 1)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb31 + [.op (.stack (.push 17)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 0x4e487b71)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 36)), + .op (.stack (.push 28)), + .revert], + -- bb32 + [.op (.stack (.push 0x62616c616e636500000000000000000000000000000000000000000000000000)), + .op (.stack (.push 7)), + .jump 23], + -- bb33 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb34 + [.op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 160)), + .op (.stack .shr), + .op (.stack (.push 68)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack .or), + .jumpi 17, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 36)), + .effect .calldataload 1, + .effect .caller 0, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 1)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .op (.stack (.dup 2)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op .store, + .op (.stack (.dup 0)), + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .effect .sstore 2, + .op (.stack (.push 0)), + .op .store, + .effect .caller 0, + .op (.stack (.push 0x8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925)), + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .effect (.log 3) 5, + .op (.stack (.push 1)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb36 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb37 + [.op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 160)), + .op (.stack .shr), + .op (.stack (.push 100)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack .or), + .op (.stack (.push 36)), + .effect .calldataload 1, + .op (.stack (.push 160)), + .op (.stack .shr), + .op (.stack .or), + .jumpi 22, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 68)), + .effect .calldataload 1, + .op (.stack (.dup 1)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 1)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .effect .caller 0, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .effect .sload 1, + .op (.stack (.dup 1)), + .op (.stack (.dup 1)), + .op (.stack .lt), + .jumpi 21, + .op (.stack (.dup 0)), + .op (.stack .not), + .op (.stack .iszero), + .jumpi 19, + .op (.stack (.dup 1)), + .op (.stack (.swap 0)), + .op (.stack .sub), + .op (.stack (.dup 2)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 1)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .effect .caller 0, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .effect .sstore 2, + .op (.stack (.push 0)), + .jump 19], + -- bb41 + [.op (.stack .pop), + .op (.stack (.dup 1)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 0)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .op (.stack (.dup 0)), + .effect .sload 1, + .op (.stack (.dup 2)), + .op (.stack (.dup 1)), + .op (.stack .lt), + .jumpi 22, + .op (.stack (.push 36)), + .effect .calldataload 1, + .op (.stack (.dup 3)), + .op (.stack (.swap 0)), + .op (.stack (.swap 1)), + .op (.stack .sub), + .op (.stack (.swap 0)), + .op (.stack (.swap 1)), + .effect .sstore 2, + .op (.stack (.dup 0)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .op (.stack (.dup 0)), + .effect .sload 1, + .op (.stack (.dup 3)), + .op (.stack (.dup 1)), + .op (.stack .add), + .op (.stack (.swap 0)), + .op (.stack (.dup 1)), + .op (.stack .lt), + .jumpi 20, + .op (.stack (.swap 0)), + .effect .sstore 2, + .op (.stack (.swap 0)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.swap 0)), + .op (.stack (.push 0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef)), + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .effect (.log 3) 5, + .op (.stack (.push 1)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb44 + [.op (.stack (.push 17)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 0x4e487b71)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 36)), + .op (.stack (.push 28)), + .revert], + -- bb45 + [.op (.stack (.push 0x616c6c6f77616e63650000000000000000000000000000000000000000000000)), + .op (.stack (.push 9)), + .jump 23], + -- bb46 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb47 + [.op (.stack (.push 32)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op .store, + .op (.stack (.push 96)), + .op .store, + .op (.stack (.push 0x8c379a0)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 100)), + .op (.stack (.push 28)), + .revert]] } + +end SolarTV.Export.Token diff --git a/Certified/token/gen/Token/Evm3.lean b/Certified/token/gen/Token/Evm3.lean new file mode 100644 index 00000000..e88c7c9b --- /dev/null +++ b/Certified/token/gen/Token/Evm3.lean @@ -0,0 +1,529 @@ +-- solar-lean-stage: kind=evm index=3 pass=compact-pushes +import SolarTV.EVMIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `Token`; do not edit. -/ + +namespace SolarTV.Export.Token + +/-- The runtime EVM IR after `compact-pushes`. -/ +def evm3 : EVM.Program.Program := + { blocks := [ + -- bb0 + [.effect .callvalue 0, + .jumpi 2, + .op (.stack (.push 0)), + .effect .calldataload 1, + .op (.stack (.push 224)), + .op (.stack .shr), + .op (.stack (.dup 0)), + .op (.stack (.push 0x8d1fdf2f)), + .op (.stack .gt), + .jumpi 1, + .op (.stack (.dup 0)), + .op (.stack (.push 0x8d1fdf2f)), + .op (.stack .eq), + .jumpi 10, + .op (.stack (.dup 0)), + .op (.stack (.push 0xa9059cbb)), + .op (.stack .eq), + .jumpi 12, + .op (.stack (.dup 0)), + .op (.stack (.push 0xdd62ed3e)), + .op (.stack .eq), + .jumpi 5, + .op (.stack (.dup 0)), + .op (.stack (.push 0xe5839836)), + .op (.stack .eq), + .jumpi 8, + .jump 2], + -- bb2 + [.op (.stack (.dup 0)), + .op (.stack (.push 0x95ea7b3)), + .op (.stack .eq), + .jumpi 16, + .op (.stack (.dup 0)), + .op (.stack (.push 0x23b872dd)), + .op (.stack .eq), + .jumpi 18, + .op (.stack (.dup 0)), + .op (.stack (.push 0x70a08231)), + .op (.stack .eq), + .jumpi 3, + .op (.stack (.dup 0)), + .op (.stack (.push 0x893d20e8)), + .op (.stack .eq), + .jumpi 7, + .jump 2], + -- bb11 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb12 + [.op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 160)), + .op (.stack .shr), + .op (.stack (.push 36)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack .or), + .jumpi 4, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 0)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .effect .sload 1, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb14 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb15 + [.op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 160)), + .op (.stack .shr), + .op (.stack (.push 68)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack .or), + .op (.stack (.push 36)), + .effect .calldataload 1, + .op (.stack (.push 160)), + .op (.stack .shr), + .op (.stack .or), + .jumpi 6, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 1)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .op (.stack (.push 36)), + .effect .calldataload 1, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .effect .sload 1, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb17 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb18 + [.op (.stack (.push 4)), + .effect .sload 1, + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .op (.stack .and), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb19 + [.op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 160)), + .op (.stack .shr), + .op (.stack (.push 36)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack .or), + .jumpi 9, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 2)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .effect .sload 1, + .op (.stack (.push 255)), + .op (.stack .and), + .op (.stack (.push 0)), + .op (.stack .lt), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb21 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb22 + [.op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 160)), + .op (.stack .shr), + .op (.stack (.push 36)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack .or), + .jumpi 11, + .op (.stack (.push 4)), + .effect .sload 1, + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .op (.stack .and), + .effect .caller 0, + .op (.stack .sub), + .jumpi 11, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 2)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 1)), + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .effect .sstore 2, + .stop], + -- bb25 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb26 + [.op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 160)), + .op (.stack .shr), + .op (.stack (.push 68)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack .or), + .jumpi 15, + .effect .caller 0, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 2)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .effect .sload 1, + .op (.stack (.push 255)), + .op (.stack .and), + .jumpi 15, + .op (.stack (.push 36)), + .effect .calldataload 1, + .effect .caller 0, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 0)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .op (.stack (.dup 0)), + .effect .sload 1, + .op (.stack (.dup 2)), + .op (.stack (.dup 1)), + .op (.stack .lt), + .jumpi 14, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.dup 3)), + .op (.stack (.swap 0)), + .op (.stack (.swap 1)), + .op (.stack .sub), + .op (.stack (.swap 0)), + .op (.stack (.swap 1)), + .effect .sstore 2, + .op (.stack (.dup 0)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .op (.stack (.dup 0)), + .effect .sload 1, + .op (.stack (.dup 3)), + .op (.stack (.dup 1)), + .op (.stack .add), + .op (.stack (.swap 0)), + .op (.stack (.dup 1)), + .op (.stack .lt), + .jumpi 13, + .op (.stack (.swap 0)), + .effect .sstore 2, + .op (.stack (.swap 0)), + .op (.stack (.push 0)), + .op .store, + .effect .caller 0, + .op (.stack (.push 0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef)), + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .effect (.log 3) 5, + .op (.stack (.push 1)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb31 + [.op (.stack (.push 17)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 0x4e487b71)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 36)), + .op (.stack (.push 28)), + .revert], + -- bb32 + [.op (.stack (.push 0x62616c616e6365)), + .op (.stack (.push 200)), + .op (.stack .shl), + .op (.stack (.push 7)), + .jump 23], + -- bb33 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb34 + [.op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 160)), + .op (.stack .shr), + .op (.stack (.push 68)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack .or), + .jumpi 17, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 36)), + .effect .calldataload 1, + .effect .caller 0, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 1)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .op (.stack (.dup 2)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op .store, + .op (.stack (.dup 0)), + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .effect .sstore 2, + .op (.stack (.push 0)), + .op .store, + .effect .caller 0, + .op (.stack (.push 0x8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925)), + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .effect (.log 3) 5, + .op (.stack (.push 1)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb36 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb37 + [.op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 160)), + .op (.stack .shr), + .op (.stack (.push 100)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack .or), + .op (.stack (.push 36)), + .effect .calldataload 1, + .op (.stack (.push 160)), + .op (.stack .shr), + .op (.stack .or), + .jumpi 22, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 68)), + .effect .calldataload 1, + .op (.stack (.dup 1)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 1)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .effect .caller 0, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .effect .sload 1, + .op (.stack (.dup 1)), + .op (.stack (.dup 1)), + .op (.stack .lt), + .jumpi 21, + .op (.stack (.dup 0)), + .op (.stack .not), + .op (.stack .iszero), + .jumpi 19, + .op (.stack (.dup 1)), + .op (.stack (.swap 0)), + .op (.stack .sub), + .op (.stack (.dup 2)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 1)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .effect .caller 0, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .effect .sstore 2, + .op (.stack (.push 0)), + .jump 19], + -- bb41 + [.op (.stack .pop), + .op (.stack (.dup 1)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 0)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .op (.stack (.dup 0)), + .effect .sload 1, + .op (.stack (.dup 2)), + .op (.stack (.dup 1)), + .op (.stack .lt), + .jumpi 22, + .op (.stack (.push 36)), + .effect .calldataload 1, + .op (.stack (.dup 3)), + .op (.stack (.swap 0)), + .op (.stack (.swap 1)), + .op (.stack .sub), + .op (.stack (.swap 0)), + .op (.stack (.swap 1)), + .effect .sstore 2, + .op (.stack (.dup 0)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .op (.stack (.dup 0)), + .effect .sload 1, + .op (.stack (.dup 3)), + .op (.stack (.dup 1)), + .op (.stack .add), + .op (.stack (.swap 0)), + .op (.stack (.dup 1)), + .op (.stack .lt), + .jumpi 20, + .op (.stack (.swap 0)), + .effect .sstore 2, + .op (.stack (.swap 0)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.swap 0)), + .op (.stack (.push 0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef)), + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .effect (.log 3) 5, + .op (.stack (.push 1)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb44 + [.op (.stack (.push 17)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 0x4e487b71)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 36)), + .op (.stack (.push 28)), + .revert], + -- bb45 + [.op (.stack (.push 0x616c6c6f77616e6365)), + .op (.stack (.push 184)), + .op (.stack .shl), + .op (.stack (.push 9)), + .jump 23], + -- bb46 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb47 + [.op (.stack (.push 32)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op .store, + .op (.stack (.push 96)), + .op .store, + .op (.stack (.push 0x8c379a0)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 100)), + .op (.stack (.push 28)), + .revert]] } + +end SolarTV.Export.Token diff --git a/Certified/token/gen/Token/Evm4.lean b/Certified/token/gen/Token/Evm4.lean new file mode 100644 index 00000000..ce0796c7 --- /dev/null +++ b/Certified/token/gen/Token/Evm4.lean @@ -0,0 +1,529 @@ +-- solar-lean-stage: kind=evm index=4 pass=block-layout +import SolarTV.EVMIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `Token`; do not edit. -/ + +namespace SolarTV.Export.Token + +/-- The runtime EVM IR after `block-layout`. -/ +def evm4 : EVM.Program.Program := + { blocks := [ + -- bb0 + [.effect .callvalue 0, + .jumpi 1, + .op (.stack (.push 0)), + .effect .calldataload 1, + .op (.stack (.push 224)), + .op (.stack .shr), + .op (.stack (.dup 0)), + .op (.stack (.push 0x8d1fdf2f)), + .op (.stack .gt), + .jumpi 5, + .op (.stack (.dup 0)), + .op (.stack (.push 0x8d1fdf2f)), + .op (.stack .eq), + .jumpi 10, + .op (.stack (.dup 0)), + .op (.stack (.push 0xa9059cbb)), + .op (.stack .eq), + .jumpi 11, + .op (.stack (.dup 0)), + .op (.stack (.push 0xdd62ed3e)), + .op (.stack .eq), + .jumpi 7, + .op (.stack (.dup 0)), + .op (.stack (.push 0xe5839836)), + .op (.stack .eq), + .jumpi 9, + .jump 1], + -- bb11 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb25 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb33 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb46 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb2 + [.op (.stack (.dup 0)), + .op (.stack (.push 0x95ea7b3)), + .op (.stack .eq), + .jumpi 14, + .op (.stack (.dup 0)), + .op (.stack (.push 0x23b872dd)), + .op (.stack .eq), + .jumpi 15, + .op (.stack (.dup 0)), + .op (.stack (.push 0x70a08231)), + .op (.stack .eq), + .jumpi 6, + .op (.stack (.dup 0)), + .op (.stack (.push 0x893d20e8)), + .op (.stack .eq), + .jumpi 8, + .jump 1], + -- bb12 + [.op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 160)), + .op (.stack .shr), + .op (.stack (.push 36)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack .or), + .jumpi 18, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 0)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .effect .sload 1, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb15 + [.op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 160)), + .op (.stack .shr), + .op (.stack (.push 68)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack .or), + .op (.stack (.push 36)), + .effect .calldataload 1, + .op (.stack (.push 160)), + .op (.stack .shr), + .op (.stack .or), + .jumpi 19, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 1)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .op (.stack (.push 36)), + .effect .calldataload 1, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .effect .sload 1, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb18 + [.op (.stack (.push 4)), + .effect .sload 1, + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .op (.stack .and), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb19 + [.op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 160)), + .op (.stack .shr), + .op (.stack (.push 36)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack .or), + .jumpi 20, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 2)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .effect .sload 1, + .op (.stack (.push 255)), + .op (.stack .and), + .op (.stack (.push 0)), + .op (.stack .lt), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb22 + [.op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 160)), + .op (.stack .shr), + .op (.stack (.push 36)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack .or), + .jumpi 2, + .op (.stack (.push 4)), + .effect .sload 1, + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .op (.stack .and), + .effect .caller 0, + .op (.stack .sub), + .jumpi 2, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 2)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 1)), + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .effect .sstore 2, + .stop], + -- bb26 + [.op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 160)), + .op (.stack .shr), + .op (.stack (.push 68)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack .or), + .jumpi 3, + .effect .caller 0, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 2)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .effect .sload 1, + .op (.stack (.push 255)), + .op (.stack .and), + .jumpi 3, + .op (.stack (.push 36)), + .effect .calldataload 1, + .effect .caller 0, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 0)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .op (.stack (.dup 0)), + .effect .sload 1, + .op (.stack (.dup 2)), + .op (.stack (.dup 1)), + .op (.stack .lt), + .jumpi 12, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.dup 3)), + .op (.stack (.swap 0)), + .op (.stack (.swap 1)), + .op (.stack .sub), + .op (.stack (.swap 0)), + .op (.stack (.swap 1)), + .effect .sstore 2, + .op (.stack (.dup 0)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .op (.stack (.dup 0)), + .effect .sload 1, + .op (.stack (.dup 3)), + .op (.stack (.dup 1)), + .op (.stack .add), + .op (.stack (.swap 0)), + .op (.stack (.dup 1)), + .op (.stack .lt), + .jumpi 21, + .op (.stack (.swap 0)), + .effect .sstore 2, + .op (.stack (.swap 0)), + .op (.stack (.push 0)), + .op .store, + .effect .caller 0, + .op (.stack (.push 0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef)), + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .effect (.log 3) 5, + .op (.stack (.push 1)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb32 + [.op (.stack (.push 0x62616c616e6365)), + .op (.stack (.push 200)), + .op (.stack .shl), + .op (.stack (.push 7)), + .jump 13], + -- bb47 + [.op (.stack (.push 32)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op .store, + .op (.stack (.push 96)), + .op .store, + .op (.stack (.push 0x8c379a0)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 100)), + .op (.stack (.push 28)), + .revert], + -- bb34 + [.op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 160)), + .op (.stack .shr), + .op (.stack (.push 68)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack .or), + .jumpi 22, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 36)), + .effect .calldataload 1, + .effect .caller 0, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 1)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .op (.stack (.dup 2)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op .store, + .op (.stack (.dup 0)), + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .effect .sstore 2, + .op (.stack (.push 0)), + .op .store, + .effect .caller 0, + .op (.stack (.push 0x8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925)), + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .effect (.log 3) 5, + .op (.stack (.push 1)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb37 + [.op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 160)), + .op (.stack .shr), + .op (.stack (.push 100)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack .or), + .op (.stack (.push 36)), + .effect .calldataload 1, + .op (.stack (.push 160)), + .op (.stack .shr), + .op (.stack .or), + .jumpi 4, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 68)), + .effect .calldataload 1, + .op (.stack (.dup 1)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 1)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .effect .caller 0, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .effect .sload 1, + .op (.stack (.dup 1)), + .op (.stack (.dup 1)), + .op (.stack .lt), + .jumpi 17, + .op (.stack (.dup 0)), + .op (.stack .not), + .op (.stack .iszero), + .jumpi 16, + .op (.stack (.dup 1)), + .op (.stack (.swap 0)), + .op (.stack .sub), + .op (.stack (.dup 2)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 1)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .effect .caller 0, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .effect .sstore 2, + .op (.stack (.push 0)), + .jump 16], + -- bb41 + [.op (.stack .pop), + .op (.stack (.dup 1)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 0)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .op (.stack (.dup 0)), + .effect .sload 1, + .op (.stack (.dup 2)), + .op (.stack (.dup 1)), + .op (.stack .lt), + .jumpi 4, + .op (.stack (.push 36)), + .effect .calldataload 1, + .op (.stack (.dup 3)), + .op (.stack (.swap 0)), + .op (.stack (.swap 1)), + .op (.stack .sub), + .op (.stack (.swap 0)), + .op (.stack (.swap 1)), + .effect .sstore 2, + .op (.stack (.dup 0)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .op (.stack (.dup 0)), + .effect .sload 1, + .op (.stack (.dup 3)), + .op (.stack (.dup 1)), + .op (.stack .add), + .op (.stack (.swap 0)), + .op (.stack (.dup 1)), + .op (.stack .lt), + .jumpi 23, + .op (.stack (.swap 0)), + .effect .sstore 2, + .op (.stack (.swap 0)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.swap 0)), + .op (.stack (.push 0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef)), + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .effect (.log 3) 5, + .op (.stack (.push 1)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb45 + [.op (.stack (.push 0x616c6c6f77616e6365)), + .op (.stack (.push 184)), + .op (.stack .shl), + .op (.stack (.push 9)), + .jump 13], + -- bb14 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb17 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb21 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb31 + [.op (.stack (.push 17)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 0x4e487b71)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 36)), + .op (.stack (.push 28)), + .revert], + -- bb36 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb44 + [.op (.stack (.push 17)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 0x4e487b71)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 36)), + .op (.stack (.push 28)), + .revert]] } + +end SolarTV.Export.Token diff --git a/Certified/token/gen/Token/Evm5.lean b/Certified/token/gen/Token/Evm5.lean new file mode 100644 index 00000000..da8e3b84 --- /dev/null +++ b/Certified/token/gen/Token/Evm5.lean @@ -0,0 +1,507 @@ +-- solar-lean-stage: kind=evm index=5 pass=terminal-dedup +import SolarTV.EVMIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `Token`; do not edit. -/ + +namespace SolarTV.Export.Token + +/-- The runtime EVM IR after `terminal-dedup`. -/ +def evm5 : EVM.Program.Program := + { blocks := [ + -- bb0 + [.effect .callvalue 0, + .jumpi 1, + .op (.stack (.push 0)), + .effect .calldataload 1, + .op (.stack (.push 224)), + .op (.stack .shr), + .op (.stack (.dup 0)), + .op (.stack (.push 0x8d1fdf2f)), + .op (.stack .gt), + .jumpi 5, + .op (.stack (.dup 0)), + .op (.stack (.push 0x8d1fdf2f)), + .op (.stack .eq), + .jumpi 10, + .op (.stack (.dup 0)), + .op (.stack (.push 0xa9059cbb)), + .op (.stack .eq), + .jumpi 11, + .op (.stack (.dup 0)), + .op (.stack (.push 0xdd62ed3e)), + .op (.stack .eq), + .jumpi 7, + .op (.stack (.dup 0)), + .op (.stack (.push 0xe5839836)), + .op (.stack .eq), + .jumpi 9, + .jump 1], + -- bb11 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb25 + [.jump 1], + -- bb33 + [.jump 1], + -- bb46 + [.jump 1], + -- bb2 + [.op (.stack (.dup 0)), + .op (.stack (.push 0x95ea7b3)), + .op (.stack .eq), + .jumpi 14, + .op (.stack (.dup 0)), + .op (.stack (.push 0x23b872dd)), + .op (.stack .eq), + .jumpi 15, + .op (.stack (.dup 0)), + .op (.stack (.push 0x70a08231)), + .op (.stack .eq), + .jumpi 6, + .op (.stack (.dup 0)), + .op (.stack (.push 0x893d20e8)), + .op (.stack .eq), + .jumpi 8, + .jump 1], + -- bb12 + [.op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 160)), + .op (.stack .shr), + .op (.stack (.push 36)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack .or), + .jumpi 18, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 0)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .effect .sload 1, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb15 + [.op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 160)), + .op (.stack .shr), + .op (.stack (.push 68)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack .or), + .op (.stack (.push 36)), + .effect .calldataload 1, + .op (.stack (.push 160)), + .op (.stack .shr), + .op (.stack .or), + .jumpi 19, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 1)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .op (.stack (.push 36)), + .effect .calldataload 1, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .effect .sload 1, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb18 + [.op (.stack (.push 4)), + .effect .sload 1, + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .op (.stack .and), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb19 + [.op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 160)), + .op (.stack .shr), + .op (.stack (.push 36)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack .or), + .jumpi 20, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 2)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .effect .sload 1, + .op (.stack (.push 255)), + .op (.stack .and), + .op (.stack (.push 0)), + .op (.stack .lt), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb22 + [.op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 160)), + .op (.stack .shr), + .op (.stack (.push 36)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack .or), + .jumpi 2, + .op (.stack (.push 4)), + .effect .sload 1, + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .op (.stack .and), + .effect .caller 0, + .op (.stack .sub), + .jumpi 2, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 2)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 1)), + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .effect .sstore 2, + .stop], + -- bb26 + [.op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 160)), + .op (.stack .shr), + .op (.stack (.push 68)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack .or), + .jumpi 3, + .effect .caller 0, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 2)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .effect .sload 1, + .op (.stack (.push 255)), + .op (.stack .and), + .jumpi 3, + .op (.stack (.push 36)), + .effect .calldataload 1, + .effect .caller 0, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 0)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .op (.stack (.dup 0)), + .effect .sload 1, + .op (.stack (.dup 2)), + .op (.stack (.dup 1)), + .op (.stack .lt), + .jumpi 12, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.dup 3)), + .op (.stack (.swap 0)), + .op (.stack (.swap 1)), + .op (.stack .sub), + .op (.stack (.swap 0)), + .op (.stack (.swap 1)), + .effect .sstore 2, + .op (.stack (.dup 0)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .op (.stack (.dup 0)), + .effect .sload 1, + .op (.stack (.dup 3)), + .op (.stack (.dup 1)), + .op (.stack .add), + .op (.stack (.swap 0)), + .op (.stack (.dup 1)), + .op (.stack .lt), + .jumpi 21, + .op (.stack (.swap 0)), + .effect .sstore 2, + .op (.stack (.swap 0)), + .op (.stack (.push 0)), + .op .store, + .effect .caller 0, + .op (.stack (.push 0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef)), + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .effect (.log 3) 5, + .op (.stack (.push 1)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb32 + [.op (.stack (.push 0x62616c616e6365)), + .op (.stack (.push 200)), + .op (.stack .shl), + .op (.stack (.push 7)), + .jump 13], + -- bb47 + [.op (.stack (.push 32)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op .store, + .op (.stack (.push 96)), + .op .store, + .op (.stack (.push 0x8c379a0)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 100)), + .op (.stack (.push 28)), + .revert], + -- bb34 + [.op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 160)), + .op (.stack .shr), + .op (.stack (.push 68)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack .or), + .jumpi 22, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 36)), + .effect .calldataload 1, + .effect .caller 0, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 1)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .op (.stack (.dup 2)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op .store, + .op (.stack (.dup 0)), + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .effect .sstore 2, + .op (.stack (.push 0)), + .op .store, + .effect .caller 0, + .op (.stack (.push 0x8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925)), + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .effect (.log 3) 5, + .op (.stack (.push 1)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb37 + [.op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 160)), + .op (.stack .shr), + .op (.stack (.push 100)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack .or), + .op (.stack (.push 36)), + .effect .calldataload 1, + .op (.stack (.push 160)), + .op (.stack .shr), + .op (.stack .or), + .jumpi 4, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 68)), + .effect .calldataload 1, + .op (.stack (.dup 1)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 1)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .effect .caller 0, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .effect .sload 1, + .op (.stack (.dup 1)), + .op (.stack (.dup 1)), + .op (.stack .lt), + .jumpi 17, + .op (.stack (.dup 0)), + .op (.stack .not), + .op (.stack .iszero), + .jumpi 16, + .op (.stack (.dup 1)), + .op (.stack (.swap 0)), + .op (.stack .sub), + .op (.stack (.dup 2)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 1)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .effect .caller 0, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .effect .sstore 2, + .op (.stack (.push 0)), + .jump 16], + -- bb41 + [.op (.stack .pop), + .op (.stack (.dup 1)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 0)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .op (.stack (.dup 0)), + .effect .sload 1, + .op (.stack (.dup 2)), + .op (.stack (.dup 1)), + .op (.stack .lt), + .jumpi 4, + .op (.stack (.push 36)), + .effect .calldataload 1, + .op (.stack (.dup 3)), + .op (.stack (.swap 0)), + .op (.stack (.swap 1)), + .op (.stack .sub), + .op (.stack (.swap 0)), + .op (.stack (.swap 1)), + .effect .sstore 2, + .op (.stack (.dup 0)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .op (.stack (.dup 0)), + .effect .sload 1, + .op (.stack (.dup 3)), + .op (.stack (.dup 1)), + .op (.stack .add), + .op (.stack (.swap 0)), + .op (.stack (.dup 1)), + .op (.stack .lt), + .jumpi 23, + .op (.stack (.swap 0)), + .effect .sstore 2, + .op (.stack (.swap 0)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.swap 0)), + .op (.stack (.push 0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef)), + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .effect (.log 3) 5, + .op (.stack (.push 1)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb45 + [.op (.stack (.push 0x616c6c6f77616e6365)), + .op (.stack (.push 184)), + .op (.stack .shl), + .op (.stack (.push 9)), + .jump 13], + -- bb14 + [.jump 1], + -- bb17 + [.jump 1], + -- bb21 + [.jump 1], + -- bb31 + [.op (.stack (.push 17)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 0x4e487b71)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 36)), + .op (.stack (.push 28)), + .revert], + -- bb36 + [.jump 1], + -- bb44 + [.jump 21]] } + +end SolarTV.Export.Token diff --git a/Certified/token/gen/Token/Evm6.lean b/Certified/token/gen/Token/Evm6.lean new file mode 100644 index 00000000..30b3bc5d --- /dev/null +++ b/Certified/token/gen/Token/Evm6.lean @@ -0,0 +1,491 @@ +-- solar-lean-stage: kind=evm index=6 pass=cfg-simplify-early +import SolarTV.EVMIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `Token`; do not edit. -/ + +namespace SolarTV.Export.Token + +/-- The runtime EVM IR after `cfg-simplify-early`. -/ +def evm6 : EVM.Program.Program := + { blocks := [ + -- bb0 + [.effect .callvalue 0, + .jumpi 1, + .op (.stack (.push 0)), + .effect .calldataload 1, + .op (.stack (.push 224)), + .op (.stack .shr), + .op (.stack (.dup 0)), + .op (.stack (.push 0x8d1fdf2f)), + .op (.stack .gt), + .jumpi 2, + .op (.stack (.dup 0)), + .op (.stack (.push 0x8d1fdf2f)), + .op (.stack .eq), + .jumpi 7, + .op (.stack (.dup 0)), + .op (.stack (.push 0xa9059cbb)), + .op (.stack .eq), + .jumpi 8, + .op (.stack (.dup 0)), + .op (.stack (.push 0xdd62ed3e)), + .op (.stack .eq), + .jumpi 4, + .op (.stack (.dup 0)), + .op (.stack (.push 0xe5839836)), + .op (.stack .eq), + .jumpi 6, + .jump 1], + -- bb11 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb2 + [.op (.stack (.dup 0)), + .op (.stack (.push 0x95ea7b3)), + .op (.stack .eq), + .jumpi 11, + .op (.stack (.dup 0)), + .op (.stack (.push 0x23b872dd)), + .op (.stack .eq), + .jumpi 12, + .op (.stack (.dup 0)), + .op (.stack (.push 0x70a08231)), + .op (.stack .eq), + .jumpi 3, + .op (.stack (.dup 0)), + .op (.stack (.push 0x893d20e8)), + .op (.stack .eq), + .jumpi 5, + .jump 1], + -- bb12 + [.op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 160)), + .op (.stack .shr), + .op (.stack (.push 36)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack .or), + .jumpi 1, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 0)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .effect .sload 1, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb15 + [.op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 160)), + .op (.stack .shr), + .op (.stack (.push 68)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack .or), + .op (.stack (.push 36)), + .effect .calldataload 1, + .op (.stack (.push 160)), + .op (.stack .shr), + .op (.stack .or), + .jumpi 1, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 1)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .op (.stack (.push 36)), + .effect .calldataload 1, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .effect .sload 1, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb18 + [.op (.stack (.push 4)), + .effect .sload 1, + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .op (.stack .and), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb19 + [.op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 160)), + .op (.stack .shr), + .op (.stack (.push 36)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack .or), + .jumpi 1, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 2)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .effect .sload 1, + .op (.stack (.push 255)), + .op (.stack .and), + .op (.stack (.push 0)), + .op (.stack .lt), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb22 + [.op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 160)), + .op (.stack .shr), + .op (.stack (.push 36)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack .or), + .jumpi 1, + .op (.stack (.push 4)), + .effect .sload 1, + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .op (.stack .and), + .effect .caller 0, + .op (.stack .sub), + .jumpi 1, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 2)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 1)), + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .effect .sstore 2, + .stop], + -- bb26 + [.op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 160)), + .op (.stack .shr), + .op (.stack (.push 68)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack .or), + .jumpi 1, + .effect .caller 0, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 2)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .effect .sload 1, + .op (.stack (.push 255)), + .op (.stack .and), + .jumpi 1, + .op (.stack (.push 36)), + .effect .calldataload 1, + .effect .caller 0, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 0)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .op (.stack (.dup 0)), + .effect .sload 1, + .op (.stack (.dup 2)), + .op (.stack (.dup 1)), + .op (.stack .lt), + .jumpi 9, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.dup 3)), + .op (.stack (.swap 0)), + .op (.stack (.swap 1)), + .op (.stack .sub), + .op (.stack (.swap 0)), + .op (.stack (.swap 1)), + .effect .sstore 2, + .op (.stack (.dup 0)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .op (.stack (.dup 0)), + .effect .sload 1, + .op (.stack (.dup 3)), + .op (.stack (.dup 1)), + .op (.stack .add), + .op (.stack (.swap 0)), + .op (.stack (.dup 1)), + .op (.stack .lt), + .jumpi 15, + .op (.stack (.swap 0)), + .effect .sstore 2, + .op (.stack (.swap 0)), + .op (.stack (.push 0)), + .op .store, + .effect .caller 0, + .op (.stack (.push 0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef)), + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .effect (.log 3) 5, + .op (.stack (.push 1)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb32 + [.op (.stack (.push 0x62616c616e6365)), + .op (.stack (.push 200)), + .op (.stack .shl), + .op (.stack (.push 7)), + .jump 10], + -- bb47 + [.op (.stack (.push 32)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op .store, + .op (.stack (.push 96)), + .op .store, + .op (.stack (.push 0x8c379a0)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 100)), + .op (.stack (.push 28)), + .revert], + -- bb34 + [.op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 160)), + .op (.stack .shr), + .op (.stack (.push 68)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack .or), + .jumpi 1, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 36)), + .effect .calldataload 1, + .effect .caller 0, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 1)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .op (.stack (.dup 2)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op .store, + .op (.stack (.dup 0)), + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .effect .sstore 2, + .op (.stack (.push 0)), + .op .store, + .effect .caller 0, + .op (.stack (.push 0x8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925)), + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .effect (.log 3) 5, + .op (.stack (.push 1)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb37 + [.op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 160)), + .op (.stack .shr), + .op (.stack (.push 100)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack .or), + .op (.stack (.push 36)), + .effect .calldataload 1, + .op (.stack (.push 160)), + .op (.stack .shr), + .op (.stack .or), + .jumpi 1, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 68)), + .effect .calldataload 1, + .op (.stack (.dup 1)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 1)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .effect .caller 0, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .effect .sload 1, + .op (.stack (.dup 1)), + .op (.stack (.dup 1)), + .op (.stack .lt), + .jumpi 14, + .op (.stack (.dup 0)), + .op (.stack .not), + .op (.stack .iszero), + .jumpi 13, + .op (.stack (.dup 1)), + .op (.stack (.swap 0)), + .op (.stack .sub), + .op (.stack (.dup 2)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 1)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .effect .caller 0, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .effect .sstore 2, + .op (.stack (.push 0)), + .jump 13], + -- bb41 + [.op (.stack .pop), + .op (.stack (.dup 1)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 0)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .op (.stack (.dup 0)), + .effect .sload 1, + .op (.stack (.dup 2)), + .op (.stack (.dup 1)), + .op (.stack .lt), + .jumpi 1, + .op (.stack (.push 36)), + .effect .calldataload 1, + .op (.stack (.dup 3)), + .op (.stack (.swap 0)), + .op (.stack (.swap 1)), + .op (.stack .sub), + .op (.stack (.swap 0)), + .op (.stack (.swap 1)), + .effect .sstore 2, + .op (.stack (.dup 0)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .op (.stack (.dup 0)), + .effect .sload 1, + .op (.stack (.dup 3)), + .op (.stack (.dup 1)), + .op (.stack .add), + .op (.stack (.swap 0)), + .op (.stack (.dup 1)), + .op (.stack .lt), + .jumpi 15, + .op (.stack (.swap 0)), + .effect .sstore 2, + .op (.stack (.swap 0)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.swap 0)), + .op (.stack (.push 0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef)), + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .effect (.log 3) 5, + .op (.stack (.push 1)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb45 + [.op (.stack (.push 0x616c6c6f77616e6365)), + .op (.stack (.push 184)), + .op (.stack .shl), + .op (.stack (.push 9)), + .jump 10], + -- bb31 + [.op (.stack (.push 17)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 0x4e487b71)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 36)), + .op (.stack (.push 28)), + .revert]] } + +end SolarTV.Export.Token diff --git a/Certified/token/gen/Token/Evm7.lean b/Certified/token/gen/Token/Evm7.lean new file mode 100644 index 00000000..a7040c2a --- /dev/null +++ b/Certified/token/gen/Token/Evm7.lean @@ -0,0 +1,484 @@ +-- solar-lean-stage: kind=evm index=7 pass=tail-merge +import SolarTV.EVMIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `Token`; do not edit. -/ + +namespace SolarTV.Export.Token + +/-- The runtime EVM IR after `tail-merge`. -/ +def evm7 : EVM.Program.Program := + { blocks := [ + -- bb0 + [.effect .callvalue 0, + .jumpi 1, + .op (.stack (.push 0)), + .effect .calldataload 1, + .op (.stack (.push 224)), + .op (.stack .shr), + .op (.stack (.dup 0)), + .op (.stack (.push 0x8d1fdf2f)), + .op (.stack .gt), + .jumpi 2, + .op (.stack (.dup 0)), + .op (.stack (.push 0x8d1fdf2f)), + .op (.stack .eq), + .jumpi 7, + .op (.stack (.dup 0)), + .op (.stack (.push 0xa9059cbb)), + .op (.stack .eq), + .jumpi 8, + .op (.stack (.dup 0)), + .op (.stack (.push 0xdd62ed3e)), + .op (.stack .eq), + .jumpi 4, + .op (.stack (.dup 0)), + .op (.stack (.push 0xe5839836)), + .op (.stack .eq), + .jumpi 6, + .jump 1], + -- bb11 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb2 + [.op (.stack (.dup 0)), + .op (.stack (.push 0x95ea7b3)), + .op (.stack .eq), + .jumpi 11, + .op (.stack (.dup 0)), + .op (.stack (.push 0x23b872dd)), + .op (.stack .eq), + .jumpi 12, + .op (.stack (.dup 0)), + .op (.stack (.push 0x70a08231)), + .op (.stack .eq), + .jumpi 3, + .op (.stack (.dup 0)), + .op (.stack (.push 0x893d20e8)), + .op (.stack .eq), + .jumpi 5, + .jump 1], + -- bb12 + [.op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 160)), + .op (.stack .shr), + .op (.stack (.push 36)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack .or), + .jumpi 1, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 0)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .effect .sload 1, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb15 + [.op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 160)), + .op (.stack .shr), + .op (.stack (.push 68)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack .or), + .op (.stack (.push 36)), + .effect .calldataload 1, + .op (.stack (.push 160)), + .op (.stack .shr), + .op (.stack .or), + .jumpi 1, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 1)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .op (.stack (.push 36)), + .effect .calldataload 1, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .effect .sload 1, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb18 + [.op (.stack (.push 4)), + .effect .sload 1, + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .op (.stack .and), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb19 + [.op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 160)), + .op (.stack .shr), + .op (.stack (.push 36)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack .or), + .jumpi 1, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 2)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .effect .sload 1, + .op (.stack (.push 255)), + .op (.stack .and), + .op (.stack (.push 0)), + .op (.stack .lt), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb22 + [.op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 160)), + .op (.stack .shr), + .op (.stack (.push 36)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack .or), + .jumpi 1, + .op (.stack (.push 4)), + .effect .sload 1, + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .op (.stack .and), + .effect .caller 0, + .op (.stack .sub), + .jumpi 1, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 2)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 1)), + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .effect .sstore 2, + .stop], + -- bb26 + [.op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 160)), + .op (.stack .shr), + .op (.stack (.push 68)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack .or), + .jumpi 1, + .effect .caller 0, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 2)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .effect .sload 1, + .op (.stack (.push 255)), + .op (.stack .and), + .jumpi 1, + .op (.stack (.push 36)), + .effect .calldataload 1, + .effect .caller 0, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 0)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .op (.stack (.dup 0)), + .effect .sload 1, + .op (.stack (.dup 2)), + .op (.stack (.dup 1)), + .op (.stack .lt), + .jumpi 9, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.dup 3)), + .op (.stack (.swap 0)), + .op (.stack (.swap 1)), + .op (.stack .sub), + .op (.stack (.swap 0)), + .op (.stack (.swap 1)), + .effect .sstore 2, + .op (.stack (.dup 0)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .op (.stack (.dup 0)), + .effect .sload 1, + .op (.stack (.dup 3)), + .op (.stack (.dup 1)), + .op (.stack .add), + .op (.stack (.swap 0)), + .op (.stack (.dup 1)), + .op (.stack .lt), + .jumpi 15, + .op (.stack (.swap 0)), + .effect .sstore 2, + .op (.stack (.swap 0)), + .op (.stack (.push 0)), + .op .store, + .effect .caller 0, + .jump 16], + -- bb32 + [.op (.stack (.push 0x62616c616e6365)), + .op (.stack (.push 200)), + .op (.stack .shl), + .op (.stack (.push 7)), + .jump 10], + -- bb47 + [.op (.stack (.push 32)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op .store, + .op (.stack (.push 96)), + .op .store, + .op (.stack (.push 0x8c379a0)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 100)), + .op (.stack (.push 28)), + .revert], + -- bb34 + [.op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 160)), + .op (.stack .shr), + .op (.stack (.push 68)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack .or), + .jumpi 1, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 36)), + .effect .calldataload 1, + .effect .caller 0, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 1)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .op (.stack (.dup 2)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op .store, + .op (.stack (.dup 0)), + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .effect .sstore 2, + .op (.stack (.push 0)), + .op .store, + .effect .caller 0, + .op (.stack (.push 0x8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925)), + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .effect (.log 3) 5, + .op (.stack (.push 1)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb37 + [.op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 160)), + .op (.stack .shr), + .op (.stack (.push 100)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack .or), + .op (.stack (.push 36)), + .effect .calldataload 1, + .op (.stack (.push 160)), + .op (.stack .shr), + .op (.stack .or), + .jumpi 1, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 68)), + .effect .calldataload 1, + .op (.stack (.dup 1)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 1)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .effect .caller 0, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .effect .sload 1, + .op (.stack (.dup 1)), + .op (.stack (.dup 1)), + .op (.stack .lt), + .jumpi 14, + .op (.stack (.dup 0)), + .op (.stack .not), + .op (.stack .iszero), + .jumpi 13, + .op (.stack (.dup 1)), + .op (.stack (.swap 0)), + .op (.stack .sub), + .op (.stack (.dup 2)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 1)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .effect .caller 0, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .effect .sstore 2, + .op (.stack (.push 0)), + .jump 13], + -- bb41 + [.op (.stack .pop), + .op (.stack (.dup 1)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 0)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .op (.stack (.dup 0)), + .effect .sload 1, + .op (.stack (.dup 2)), + .op (.stack (.dup 1)), + .op (.stack .lt), + .jumpi 1, + .op (.stack (.push 36)), + .effect .calldataload 1, + .op (.stack (.dup 3)), + .op (.stack (.swap 0)), + .op (.stack (.swap 1)), + .op (.stack .sub), + .op (.stack (.swap 0)), + .op (.stack (.swap 1)), + .effect .sstore 2, + .op (.stack (.dup 0)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .op (.stack (.dup 0)), + .effect .sload 1, + .op (.stack (.dup 3)), + .op (.stack (.dup 1)), + .op (.stack .add), + .op (.stack (.swap 0)), + .op (.stack (.dup 1)), + .op (.stack .lt), + .jumpi 15, + .op (.stack (.swap 0)), + .effect .sstore 2, + .op (.stack (.swap 0)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.swap 0)), + .jump 16], + -- bb45 + [.op (.stack (.push 0x616c6c6f77616e6365)), + .op (.stack (.push 184)), + .op (.stack .shl), + .op (.stack (.push 9)), + .jump 10], + -- bb31 + [.op (.stack (.push 17)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 0x4e487b71)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 36)), + .op (.stack (.push 28)), + .revert], + -- bb48 + [.op (.stack (.push 0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef)), + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .effect (.log 3) 5, + .op (.stack (.push 1)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret]] } + +end SolarTV.Export.Token diff --git a/Certified/token/gen/Token/Evm8.lean b/Certified/token/gen/Token/Evm8.lean new file mode 100644 index 00000000..f846c7c8 --- /dev/null +++ b/Certified/token/gen/Token/Evm8.lean @@ -0,0 +1,484 @@ +-- solar-lean-stage: kind=evm index=8 pass=block-cse +import SolarTV.EVMIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `Token`; do not edit. -/ + +namespace SolarTV.Export.Token + +/-- The runtime EVM IR after `block-cse`. -/ +def evm8 : EVM.Program.Program := + { blocks := [ + -- bb0 + [.effect .callvalue 0, + .jumpi 1, + .op (.stack (.push 0)), + .effect .calldataload 1, + .op (.stack (.push 224)), + .op (.stack .shr), + .op (.stack (.dup 0)), + .op (.stack (.push 0x8d1fdf2f)), + .op (.stack .gt), + .jumpi 2, + .op (.stack (.dup 0)), + .op (.stack (.push 0x8d1fdf2f)), + .op (.stack .eq), + .jumpi 7, + .op (.stack (.dup 0)), + .op (.stack (.push 0xa9059cbb)), + .op (.stack .eq), + .jumpi 8, + .op (.stack (.dup 0)), + .op (.stack (.push 0xdd62ed3e)), + .op (.stack .eq), + .jumpi 4, + .op (.stack (.dup 0)), + .op (.stack (.push 0xe5839836)), + .op (.stack .eq), + .jumpi 6, + .jump 1], + -- bb11 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb2 + [.op (.stack (.dup 0)), + .op (.stack (.push 0x95ea7b3)), + .op (.stack .eq), + .jumpi 11, + .op (.stack (.dup 0)), + .op (.stack (.push 0x23b872dd)), + .op (.stack .eq), + .jumpi 12, + .op (.stack (.dup 0)), + .op (.stack (.push 0x70a08231)), + .op (.stack .eq), + .jumpi 3, + .op (.stack (.dup 0)), + .op (.stack (.push 0x893d20e8)), + .op (.stack .eq), + .jumpi 5, + .jump 1], + -- bb12 + [.op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 160)), + .op (.stack .shr), + .op (.stack (.push 36)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack .or), + .jumpi 1, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 0)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .effect .sload 1, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb15 + [.op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 160)), + .op (.stack .shr), + .op (.stack (.push 68)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack .or), + .op (.stack (.push 36)), + .effect .calldataload 1, + .op (.stack (.push 160)), + .op (.stack .shr), + .op (.stack .or), + .jumpi 1, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 1)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .op (.stack (.push 36)), + .effect .calldataload 1, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .effect .sload 1, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb18 + [.op (.stack (.push 4)), + .effect .sload 1, + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .op (.stack .and), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb19 + [.op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 160)), + .op (.stack .shr), + .op (.stack (.push 36)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack .or), + .jumpi 1, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 2)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .effect .sload 1, + .op (.stack (.push 255)), + .op (.stack .and), + .op (.stack (.push 0)), + .op (.stack .lt), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb22 + [.op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 160)), + .op (.stack .shr), + .op (.stack (.push 36)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack .or), + .jumpi 1, + .op (.stack (.push 4)), + .effect .sload 1, + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .op (.stack .and), + .effect .caller 0, + .op (.stack .sub), + .jumpi 1, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 2)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 1)), + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .effect .sstore 2, + .stop], + -- bb26 + [.op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 160)), + .op (.stack .shr), + .op (.stack (.push 68)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack .or), + .jumpi 1, + .effect .caller 0, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 2)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .effect .sload 1, + .op (.stack (.push 255)), + .op (.stack .and), + .jumpi 1, + .op (.stack (.push 36)), + .effect .calldataload 1, + .effect .caller 0, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 0)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .op (.stack (.dup 0)), + .effect .sload 1, + .op (.stack (.dup 2)), + .op (.stack (.dup 1)), + .op (.stack .lt), + .jumpi 9, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.dup 3)), + .op (.stack (.swap 0)), + .op (.stack (.swap 1)), + .op (.stack .sub), + .op (.stack (.swap 0)), + .op (.stack (.swap 1)), + .effect .sstore 2, + .op (.stack (.dup 0)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .op (.stack (.dup 0)), + .effect .sload 1, + .op (.stack (.dup 3)), + .op (.stack (.dup 1)), + .op (.stack .add), + .op (.stack (.swap 0)), + .op (.stack (.dup 1)), + .op (.stack .lt), + .jumpi 15, + .op (.stack (.swap 0)), + .effect .sstore 2, + .op (.stack (.swap 0)), + .op (.stack (.push 0)), + .op .store, + .effect .caller 0, + .jump 16], + -- bb32 + [.op (.stack (.push 0x62616c616e6365)), + .op (.stack (.push 200)), + .op (.stack .shl), + .op (.stack (.push 7)), + .jump 10], + -- bb47 + [.op (.stack (.push 32)), + .op (.stack (.dup 0)), + .op .store, + .op (.stack (.push 64)), + .op .store, + .op (.stack (.push 96)), + .op .store, + .op (.stack (.push 0x8c379a0)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 100)), + .op (.stack (.push 28)), + .revert], + -- bb34 + [.op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 160)), + .op (.stack .shr), + .op (.stack (.push 68)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack .or), + .jumpi 1, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 36)), + .effect .calldataload 1, + .effect .caller 0, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 1)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .op (.stack (.dup 2)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op .store, + .op (.stack (.dup 0)), + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .effect .sstore 2, + .op (.stack (.push 0)), + .op .store, + .effect .caller 0, + .op (.stack (.push 0x8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925)), + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .effect (.log 3) 5, + .op (.stack (.push 1)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb37 + [.op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 160)), + .op (.stack .shr), + .op (.stack (.push 100)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack .or), + .op (.stack (.push 36)), + .effect .calldataload 1, + .op (.stack (.push 160)), + .op (.stack .shr), + .op (.stack .or), + .jumpi 1, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 68)), + .effect .calldataload 1, + .op (.stack (.dup 1)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 1)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .effect .caller 0, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .effect .sload 1, + .op (.stack (.dup 1)), + .op (.stack (.dup 1)), + .op (.stack .lt), + .jumpi 14, + .op (.stack (.dup 0)), + .op (.stack .not), + .op (.stack .iszero), + .jumpi 13, + .op (.stack (.dup 1)), + .op (.stack (.swap 0)), + .op (.stack .sub), + .op (.stack (.dup 2)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 1)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .effect .caller 0, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .effect .sstore 2, + .op (.stack (.push 0)), + .jump 13], + -- bb41 + [.op (.stack .pop), + .op (.stack (.dup 1)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 0)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .op (.stack (.dup 0)), + .effect .sload 1, + .op (.stack (.dup 2)), + .op (.stack (.dup 1)), + .op (.stack .lt), + .jumpi 1, + .op (.stack (.push 36)), + .effect .calldataload 1, + .op (.stack (.dup 3)), + .op (.stack (.swap 0)), + .op (.stack (.swap 1)), + .op (.stack .sub), + .op (.stack (.swap 0)), + .op (.stack (.swap 1)), + .effect .sstore 2, + .op (.stack (.dup 0)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .op (.stack (.dup 0)), + .effect .sload 1, + .op (.stack (.dup 3)), + .op (.stack (.dup 1)), + .op (.stack .add), + .op (.stack (.swap 0)), + .op (.stack (.dup 1)), + .op (.stack .lt), + .jumpi 15, + .op (.stack (.swap 0)), + .effect .sstore 2, + .op (.stack (.swap 0)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.swap 0)), + .jump 16], + -- bb45 + [.op (.stack (.push 0x616c6c6f77616e6365)), + .op (.stack (.push 184)), + .op (.stack .shl), + .op (.stack (.push 9)), + .jump 10], + -- bb31 + [.op (.stack (.push 17)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 0x4e487b71)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 36)), + .op (.stack (.push 28)), + .revert], + -- bb48 + [.op (.stack (.push 0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef)), + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .effect (.log 3) 5, + .op (.stack (.push 1)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret]] } + +end SolarTV.Export.Token diff --git a/Certified/token/gen/Token/Evm9.lean b/Certified/token/gen/Token/Evm9.lean new file mode 100644 index 00000000..0d18181b --- /dev/null +++ b/Certified/token/gen/Token/Evm9.lean @@ -0,0 +1,484 @@ +-- solar-lean-stage: kind=evm index=9 pass=block-layout +import SolarTV.EVMIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `Token`; do not edit. -/ + +namespace SolarTV.Export.Token + +/-- The runtime EVM IR after `block-layout`. -/ +def evm9 : EVM.Program.Program := + { blocks := [ + -- bb0 + [.effect .callvalue 0, + .jumpi 1, + .op (.stack (.push 0)), + .effect .calldataload 1, + .op (.stack (.push 224)), + .op (.stack .shr), + .op (.stack (.dup 0)), + .op (.stack (.push 0x8d1fdf2f)), + .op (.stack .gt), + .jumpi 3, + .op (.stack (.dup 0)), + .op (.stack (.push 0x8d1fdf2f)), + .op (.stack .eq), + .jumpi 8, + .op (.stack (.dup 0)), + .op (.stack (.push 0xa9059cbb)), + .op (.stack .eq), + .jumpi 9, + .op (.stack (.dup 0)), + .op (.stack (.push 0xdd62ed3e)), + .op (.stack .eq), + .jumpi 5, + .op (.stack (.dup 0)), + .op (.stack (.push 0xe5839836)), + .op (.stack .eq), + .jumpi 7, + .jump 1], + -- bb11 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb31 + [.op (.stack (.push 17)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 0x4e487b71)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 36)), + .op (.stack (.push 28)), + .revert], + -- bb2 + [.op (.stack (.dup 0)), + .op (.stack (.push 0x95ea7b3)), + .op (.stack .eq), + .jumpi 13, + .op (.stack (.dup 0)), + .op (.stack (.push 0x23b872dd)), + .op (.stack .eq), + .jumpi 14, + .op (.stack (.dup 0)), + .op (.stack (.push 0x70a08231)), + .op (.stack .eq), + .jumpi 4, + .op (.stack (.dup 0)), + .op (.stack (.push 0x893d20e8)), + .op (.stack .eq), + .jumpi 6, + .jump 1], + -- bb12 + [.op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 160)), + .op (.stack .shr), + .op (.stack (.push 36)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack .or), + .jumpi 1, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 0)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .effect .sload 1, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb15 + [.op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 160)), + .op (.stack .shr), + .op (.stack (.push 68)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack .or), + .op (.stack (.push 36)), + .effect .calldataload 1, + .op (.stack (.push 160)), + .op (.stack .shr), + .op (.stack .or), + .jumpi 1, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 1)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .op (.stack (.push 36)), + .effect .calldataload 1, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .effect .sload 1, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb18 + [.op (.stack (.push 4)), + .effect .sload 1, + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .op (.stack .and), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb19 + [.op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 160)), + .op (.stack .shr), + .op (.stack (.push 36)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack .or), + .jumpi 1, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 2)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .effect .sload 1, + .op (.stack (.push 255)), + .op (.stack .and), + .op (.stack (.push 0)), + .op (.stack .lt), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb22 + [.op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 160)), + .op (.stack .shr), + .op (.stack (.push 36)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack .or), + .jumpi 1, + .op (.stack (.push 4)), + .effect .sload 1, + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .op (.stack .and), + .effect .caller 0, + .op (.stack .sub), + .jumpi 1, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 2)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 1)), + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .effect .sstore 2, + .stop], + -- bb26 + [.op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 160)), + .op (.stack .shr), + .op (.stack (.push 68)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack .or), + .jumpi 1, + .effect .caller 0, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 2)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .effect .sload 1, + .op (.stack (.push 255)), + .op (.stack .and), + .jumpi 1, + .op (.stack (.push 36)), + .effect .calldataload 1, + .effect .caller 0, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 0)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .op (.stack (.dup 0)), + .effect .sload 1, + .op (.stack (.dup 2)), + .op (.stack (.dup 1)), + .op (.stack .lt), + .jumpi 11, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.dup 3)), + .op (.stack (.swap 0)), + .op (.stack (.swap 1)), + .op (.stack .sub), + .op (.stack (.swap 0)), + .op (.stack (.swap 1)), + .effect .sstore 2, + .op (.stack (.dup 0)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .op (.stack (.dup 0)), + .effect .sload 1, + .op (.stack (.dup 3)), + .op (.stack (.dup 1)), + .op (.stack .add), + .op (.stack (.swap 0)), + .op (.stack (.dup 1)), + .op (.stack .lt), + .jumpi 2, + .op (.stack (.swap 0)), + .effect .sstore 2, + .op (.stack (.swap 0)), + .op (.stack (.push 0)), + .op .store, + .effect .caller 0, + .jump 10], + -- bb48 + [.op (.stack (.push 0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef)), + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .effect (.log 3) 5, + .op (.stack (.push 1)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb32 + [.op (.stack (.push 0x62616c616e6365)), + .op (.stack (.push 200)), + .op (.stack .shl), + .op (.stack (.push 7)), + .jump 12], + -- bb47 + [.op (.stack (.push 32)), + .op (.stack (.dup 0)), + .op .store, + .op (.stack (.push 64)), + .op .store, + .op (.stack (.push 96)), + .op .store, + .op (.stack (.push 0x8c379a0)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 100)), + .op (.stack (.push 28)), + .revert], + -- bb34 + [.op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 160)), + .op (.stack .shr), + .op (.stack (.push 68)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack .or), + .jumpi 1, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 36)), + .effect .calldataload 1, + .effect .caller 0, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 1)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .op (.stack (.dup 2)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op .store, + .op (.stack (.dup 0)), + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .effect .sstore 2, + .op (.stack (.push 0)), + .op .store, + .effect .caller 0, + .op (.stack (.push 0x8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925)), + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .effect (.log 3) 5, + .op (.stack (.push 1)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb37 + [.op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 160)), + .op (.stack .shr), + .op (.stack (.push 100)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack .or), + .op (.stack (.push 36)), + .effect .calldataload 1, + .op (.stack (.push 160)), + .op (.stack .shr), + .op (.stack .or), + .jumpi 1, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 68)), + .effect .calldataload 1, + .op (.stack (.dup 1)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 1)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .effect .caller 0, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .effect .sload 1, + .op (.stack (.dup 1)), + .op (.stack (.dup 1)), + .op (.stack .lt), + .jumpi 16, + .op (.stack (.dup 0)), + .op (.stack .not), + .op (.stack .iszero), + .jumpi 15, + .op (.stack (.dup 1)), + .op (.stack (.swap 0)), + .op (.stack .sub), + .op (.stack (.dup 2)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 1)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .effect .caller 0, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .effect .sstore 2, + .op (.stack (.push 0)), + .jump 15], + -- bb41 + [.op (.stack .pop), + .op (.stack (.dup 1)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 0)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .op (.stack (.dup 0)), + .effect .sload 1, + .op (.stack (.dup 2)), + .op (.stack (.dup 1)), + .op (.stack .lt), + .jumpi 1, + .op (.stack (.push 36)), + .effect .calldataload 1, + .op (.stack (.dup 3)), + .op (.stack (.swap 0)), + .op (.stack (.swap 1)), + .op (.stack .sub), + .op (.stack (.swap 0)), + .op (.stack (.swap 1)), + .effect .sstore 2, + .op (.stack (.dup 0)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .op (.stack (.dup 0)), + .effect .sload 1, + .op (.stack (.dup 3)), + .op (.stack (.dup 1)), + .op (.stack .add), + .op (.stack (.swap 0)), + .op (.stack (.dup 1)), + .op (.stack .lt), + .jumpi 2, + .op (.stack (.swap 0)), + .effect .sstore 2, + .op (.stack (.swap 0)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.swap 0)), + .jump 10], + -- bb45 + [.op (.stack (.push 0x616c6c6f77616e6365)), + .op (.stack (.push 184)), + .op (.stack .shl), + .op (.stack (.push 9)), + .jump 12]] } + +end SolarTV.Export.Token diff --git a/Certified/token/gen/Token/Manifest.lean b/Certified/token/gen/Token/Manifest.lean new file mode 100644 index 00000000..f8f6fcae --- /dev/null +++ b/Certified/token/gen/Token/Manifest.lean @@ -0,0 +1,53 @@ +-- solar-lean-stage: kind=manifest index=0 pass=none +/-! Generated by `solar -Zemit-lean-stages` for `Token`; do not edit. + +What the stages of this directory were compiled from and by. `stages` lists each +stage's file, its definition, the pass whose output it is, and the SHA-256 of the file. +-/ + +namespace SolarTV.Export.Token.Manifest + +def sources : List (String × String) := + [("solar-tv/milestone/token/token.sol", "bcaef611c02d565045174ebd565915bb263dee0051ae1ed9c3f201a7b379ba49")] + +def compiler : String := "0.8.38+commit.3ca8f483.solar.0.3.0-dev" + +def arguments : List String := + ["solar-tv/milestone/token/token.sol", + "-Zcheck-analyses=false", + "-Ogas", + "--evm-version", + "osaka", + "--emit=bin-runtime", + "-Zemit-lean-stages=solar-tv/milestone/token/gen"] + +def evmVersion : String := "osaka" + +def optimization : String := "Gas" + +def stages : List (String × String × String × String) := + [("Stage0", "stage0", "lower-evm-shaped", "ee5ac4da11360b8a720da813980026173daf36a950c8bff96dfe04fd096f3dae"), + ("Mir1", "mir1", "place-reads", "f5714ae419249883c2bd3fae0ee5267adbc1aa22690598e6c14af4e5cf1254f6"), + ("Mir2", "mir2", "dce", "0007c3dcab3c1def1f9b6b5cc82d8fc63caade8c33abd011cd1ef6efa35cd69c"), + ("Mir3", "mir3", "spell-width-tests", "9a158109c011f9766516e98e4604efdaa16a67ffdd0ff27ad796ae81c232b125"), + ("Mir4", "mir4", "evm-inst-schedule", "5cd8c51fba856102b03c9226dc274ba35b7cbc927d411af54f3db29f33507aed"), + ("Sched", "sched", "stack-schedule", "c4b9d1fe5e4638eb10dc3df4b0fc22e4e4cb8bb1b8a5e385b323a6be6d928083"), + ("Evm1", "evm1", "peephole-early", "11b76b2099bbc1423db31e2474b2f286de92c9136a05ff529656bb8877015402"), + ("Evm2", "evm2", "cfg-simplify-early", "0a859fb8bcb2d2710ddc2b95fec963aee15b614e150450c7871cbb9c6940362e"), + ("Evm3", "evm3", "compact-pushes", "a29749e0fd010f50692f610c32166c21fcf9c3e38cc2bfdfa973993a44477066"), + ("Evm4", "evm4", "block-layout", "771c03b44c4591af745bc39f7457a4dcfcb08f08e0e931cd9ad5ea8dee85a741"), + ("Evm5", "evm5", "terminal-dedup", "0bfecc06a0c31f1b7af8127cb6539ce472c24d20990ee1e4644d651ed57d9d35"), + ("Evm6", "evm6", "cfg-simplify-early", "372d04f924adf83eb02b18aec69d7da55fca4a4284c6c00c0f1d075fd6e42c03"), + ("Evm7", "evm7", "tail-merge", "a24d14ce51d3ad577aa4137b3411769bd800660cf686f76d9d1587d81a90aa4e"), + ("Evm8", "evm8", "block-cse", "57502e10fe2ca03c518197e933f775c534a9df631838e10f7e4a4bac4f868437"), + ("Evm9", "evm9", "block-layout", "2d4aacefe0e2d239ba16713a5ec11532c96f7aeb88cfb596989fc1df0e3b80aa"), + ("Evm10", "evm10", "inline-returns", "8be69fbd3957fcf9778243c6e11494863ee2e49be3679c42735f36f4fe16483e"), + ("Evm11", "evm11", "late-word", "0d4543ec8e2fbc48bb8a138716f4001a82c2fd93c6ed640e4de61e009dd92dfc"), + ("Bytecode", "bytecode", "assemble", "76a07c0351a33c21912a45d1cd1db48b2ec7a089d12f1d12c2e77b2041f94c9e")] + +def bytecodeHex : String := + "34603d575f3560e01c80638d1fdf2f1160535780638d1fdf2f14610114578063a9059cbb14610143578063dd62ed3e1460a4578063e58398361460eb575b5f5ffd5b6011602052634e487b715f526024601cfd5b8063095ea7b3146101f157806323b872dd1461024e57806370a08231146081578063893d20e81460db575f5ffd5b60043560a01c6024361017603d576004355f525f60205260405f20545f5260205ff35b60043560a01c604436101760243560a01c17603d576004355f52600160205260405f206024355f5260205260405f20545f5260205ff35b60045460601b60601c5f5260205ff35b60043560a01c6024361017603d576004355f52600260205260405f205460ff165f105f5260205ff35b60043560a01c6024361017603d5760045460601b60601c3303603d576004355f526002602052600160405f2055005b60043560a01c6044361017603d57335f52600260205260405f205460ff16603d57602435335f525f60205260405f2080548281106101cc5760043583909103909155805f5260405f2080548381019081106041579055905f52335b7fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef60205fa360015f5260205ff35b6662616c616e636560c81b60075b602080526040526060526308c379a05f526064601cfd5b60043560a01c6044361017603d57600435602435335f52600160205260405f20825f526020528060405f20555f52337f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b92560205fa360015f5260205ff35b60043560a01c606436101760243560a01c17603d57600435604435815f52600160205260405f20335f5260205260405f20548181106102e5578019156102aa57819003825f52600160205260405f20335f5260205260405f20555f5b50815f525f60205260405f208054828110603d5760243583909103909155805f5260405f2080548381019081106041579055905f529061019e565b68616c6c6f77616e636560b81b60096101da56" + +def bytecodeSha256 : String := "b6f1c3ab69651bb080d1ac406be62499ca6ba82de76bb1d203a7619404b2c799" + +end SolarTV.Export.Token.Manifest diff --git a/Certified/token/gen/Token/Mir1.lean b/Certified/token/gen/Token/Mir1.lean new file mode 100644 index 00000000..3a9cf9e5 --- /dev/null +++ b/Certified/token/gen/Token/Mir1.lean @@ -0,0 +1,369 @@ +-- solar-lean-stage: kind=mir index=1 pass=place-reads +import SolarTV.MIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `Token`; do not edit. -/ + +namespace SolarTV.Export.Token + +/-- The lowered MIR module after `place-reads`. -/ +def mir1 : MIR.Lowered.Module := + { entry := 9, + functions := [ + -- @balanceOf + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 7) .calldatasize [], + .pure 9 .lt [.value 7, .const 36], + .effect (some 11) .calldataload [.const 4], + .pure 13 .gt [.value 11, .const 0xffffffffffffffffffffffffffffffffffffffff], + .pure 25 .or [.value 9, .value 13]], + .branch (.value 25) 1 2⟩, + -- bb1 + ⟨[], + [], + .revert (.const 0) (.const 0)⟩, + -- bb2 + ⟨[], + [.effect (some 26) .calldataload [.const 4], + .effect none .mstore [.const 0, .value 26], + .effect none .mstore [.const 32, .const 0], + .effect (some 22) .keccak256 [.const 0, .const 64], + .effect (some 5) .sload [.value 22], + .effect none .mstore [.const 0, .value 5]], + .ret (.const 0) (.const 32)⟩] }, + -- @allowance + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 10) .calldatasize [], + .pure 12 .lt [.value 10, .const 68], + .effect (some 14) .calldataload [.const 4], + .pure 16 .gt [.value 14, .const 0xffffffffffffffffffffffffffffffffffffffff], + .pure 40 .or [.value 12, .value 16], + .effect (some 18) .calldataload [.const 36], + .pure 20 .gt [.value 18, .const 0xffffffffffffffffffffffffffffffffffffffff], + .pure 41 .or [.value 40, .value 20]], + .branch (.value 41) 1 2⟩, + -- bb1 + ⟨[], + [], + .revert (.const 0) (.const 0)⟩, + -- bb2 + ⟨[], + [.effect (some 43) .calldataload [.const 36], + .effect (some 42) .calldataload [.const 4], + .effect none .mstore [.const 0, .value 42], + .effect none .mstore [.const 32, .const 1], + .effect (some 30) .keccak256 [.const 0, .const 64], + .effect none .mstore [.const 0, .value 43], + .effect none .mstore [.const 32, .value 30], + .effect (some 35) .keccak256 [.const 0, .const 64], + .effect (some 8) .sload [.value 35], + .effect none .mstore [.const 0, .value 8]], + .ret (.const 0) (.const 32)⟩] }, + -- @getOwner + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 2) .sload [.const 4], + .pure 8 .and [.value 2, .const 0xffffffffffffffffffffffffffffffffffffffff], + .effect none .mstore [.const 0, .value 8]], + .ret (.const 0) (.const 32)⟩] }, + -- @isFrozen + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 10) .calldatasize [], + .pure 12 .lt [.value 10, .const 36], + .effect (some 14) .calldataload [.const 4], + .pure 16 .gt [.value 14, .const 0xffffffffffffffffffffffffffffffffffffffff], + .pure 33 .or [.value 12, .value 16]], + .branch (.value 33) 1 2⟩, + -- bb1 + ⟨[], + [], + .revert (.const 0) (.const 0)⟩, + -- bb2 + ⟨[], + [.effect (some 34) .calldataload [.const 4], + .effect none .mstore [.const 0, .value 34], + .effect none .mstore [.const 32, .const 2], + .effect (some 28) .keccak256 [.const 0, .const 64], + .effect (some 5) .sload [.value 28], + .pure 32 .and [.value 5, .const 255], + .ne 8 (.value 32) (.const 0), + .word 22 (.value 8), + .effect none .mstore [.const 0, .value 22]], + .ret (.const 0) (.const 32)⟩] }, + -- @freeze + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 17) .calldatasize [], + .pure 19 .lt [.value 17, .const 36], + .effect (some 21) .calldataload [.const 4], + .pure 23 .gt [.value 21, .const 0xffffffffffffffffffffffffffffffffffffffff], + .pure 35 .or [.value 19, .value 23]], + .branch (.value 35) 1 3⟩, + -- bb1 + ⟨[], + [], + .revert (.const 0) (.const 0)⟩, + -- bb2 + ⟨[], + [.effect (some 36) .calldataload [.const 4], + .effect none .mstore [.const 0, .value 36], + .effect none .mstore [.const 32, .const 2], + .effect (some 30) .keccak256 [.const 0, .const 64], + .effect none .sstore [.value 30, .const 1]], + .stop⟩, + -- bb3 + ⟨[], + [.effect (some 1) .caller [], + .effect (some 3) .sload [.const 4], + .pure 34 .and [.value 3, .const 0xffffffffffffffffffffffffffffffffffffffff], + .pure 5 .eq [.value 1, .value 34]], + .branch (.value 5) 2 1⟩] }, + -- @transfer + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 54) .calldatasize [], + .pure 56 .lt [.value 54, .const 68], + .effect (some 58) .calldataload [.const 4], + .pure 60 .gt [.value 58, .const 0xffffffffffffffffffffffffffffffffffffffff], + .pure 91 .or [.value 56, .value 60]], + .branch (.value 91) 1 7⟩, + -- bb1 + ⟨[], + [], + .revert (.const 0) (.const 0)⟩, + -- bb2 + ⟨[], + [.effect (some 93) .calldataload [.const 36], + .effect none .mstore [.const 0, .value 3], + .effect none .mstore [.const 32, .const 0], + .effect (some 76) .keccak256 [.const 0, .const 64], + .effect (some 18) .sload [.value 76], + .pure 19 .lt [.value 18, .value 93]], + .branch (.value 19) 3 4⟩, + -- bb3 + ⟨[], + [], + .tailCall 8 [.const 7, .const 0x62616c616e636500000000000000000000000000000000000000000000000000]⟩, + -- bb4 + ⟨[], + [.effect (some 92) .calldataload [.const 4], + .pure 29 .sub [.value 18, .value 93], + .effect none .sstore [.value 76, .value 29], + .effect none .mstore [.const 0, .value 92], + .effect (some 81) .keccak256 [.const 0, .const 64], + .effect (some 33) .sload [.value 81], + .pure 45 .add [.value 33, .value 93], + .pure 46 .lt [.value 45, .value 33]], + .branch (.value 46) 5 6⟩, + -- bb5 + ⟨[], + [.effect none .mstore [.const 32, .const 17], + .effect none .mstore [.const 0, .const 0x4e487b71]], + .revert (.const 28) (.const 36)⟩, + -- bb6 + ⟨[], + [.effect none .sstore [.value 81, .value 45], + .effect none .mstore [.const 0, .value 93], + .effect none (.log 3) [.const 0, .const 32, .const 0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef, .value 3, .value 92], + .effect none .mstore [.const 0, .const 1]], + .ret (.const 0) (.const 32)⟩, + -- bb7 + ⟨[], + [.effect (some 62) .calldataload [.const 36], + .effect (some 3) .caller [], + .effect none .mstore [.const 0, .value 3], + .effect none .mstore [.const 32, .const 2], + .effect (some 86) .keccak256 [.const 0, .const 64], + .effect (some 6) .sload [.value 86], + .pure 90 .and [.value 6, .const 255], + .ne 9 (.value 90) (.const 0)], + .branch (.value 9) 1 2⟩] }, + -- @approve + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 18) .calldatasize [], + .pure 20 .lt [.value 18, .const 68], + .effect (some 22) .calldataload [.const 4], + .pure 24 .gt [.value 22, .const 0xffffffffffffffffffffffffffffffffffffffff], + .pure 48 .or [.value 20, .value 24]], + .branch (.value 48) 1 2⟩, + -- bb1 + ⟨[], + [], + .revert (.const 0) (.const 0)⟩, + -- bb2 + ⟨[], + [.effect (some 49) .calldataload [.const 4], + .effect (some 26) .calldataload [.const 36], + .effect (some 3) .caller [], + .effect none .mstore [.const 0, .value 3], + .effect none .mstore [.const 32, .const 1], + .effect (some 40) .keccak256 [.const 0, .const 64], + .effect none .mstore [.const 0, .value 49], + .effect none .mstore [.const 32, .value 40], + .effect (some 45) .keccak256 [.const 0, .const 64], + .effect none .sstore [.value 45, .value 26], + .effect none .mstore [.const 0, .value 26], + .effect none (.log 3) [.const 0, .const 32, .const 0x8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925, .value 3, .value 49], + .effect none .mstore [.const 0, .const 1]], + .ret (.const 0) (.const 32)⟩] }, + -- @transferFrom + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 60) .calldatasize [], + .pure 62 .lt [.value 60, .const 100], + .effect (some 64) .calldataload [.const 4], + .pure 66 .gt [.value 64, .const 0xffffffffffffffffffffffffffffffffffffffff], + .pure 122 .or [.value 62, .value 66], + .effect (some 68) .calldataload [.const 36], + .pure 70 .gt [.value 68, .const 0xffffffffffffffffffffffffffffffffffffffff], + .pure 123 .or [.value 122, .value 70]], + .branch (.value 123) 5 9⟩, + -- bb1 + ⟨[], + [.pure 83 .not [.value 9], + .ne 16 (.value 83) (.const 0)], + .branch (.value 16) 3 2⟩, + -- bb2 + ⟨[], + [.effect none .mstore [.const 0, .value 124], + .effect none .mstore [.const 32, .const 0], + .effect (some 91) .keccak256 [.const 0, .const 64], + .effect (some 27) .sload [.value 91], + .pure 28 .lt [.value 27, .value 72]], + .branch (.value 28) 5 6⟩, + -- bb3 + ⟨[], + [.pure 17 .sub [.value 9, .value 72], + .effect none .mstore [.const 0, .value 124], + .effect none .mstore [.const 32, .const 1], + .effect (some 96) .keccak256 [.const 0, .const 64], + .effect none .mstore [.const 0, .value 6], + .effect none .mstore [.const 32, .value 96], + .effect (some 101) .keccak256 [.const 0, .const 64], + .effect none .sstore [.value 101, .value 17]], + .jump 2⟩, + -- bb4 + ⟨[], + [], + .tailCall 8 [.const 9, .const 0x616c6c6f77616e63650000000000000000000000000000000000000000000000]⟩, + -- bb5 + ⟨[], + [], + .revert (.const 0) (.const 0)⟩, + -- bb6 + ⟨[], + [.effect (some 125) .calldataload [.const 36], + .pure 37 .sub [.value 27, .value 72], + .effect none .sstore [.value 91, .value 37], + .effect none .mstore [.const 0, .value 125], + .effect (some 106) .keccak256 [.const 0, .const 64], + .effect (some 41) .sload [.value 106], + .pure 51 .add [.value 41, .value 72], + .pure 52 .lt [.value 51, .value 41]], + .branch (.value 52) 7 8⟩, + -- bb7 + ⟨[], + [.effect none .mstore [.const 32, .const 17], + .effect none .mstore [.const 0, .const 0x4e487b71]], + .revert (.const 28) (.const 36)⟩, + -- bb8 + ⟨[], + [.effect none .sstore [.value 106, .value 51], + .effect none .mstore [.const 0, .value 72], + .effect none (.log 3) [.const 0, .const 32, .const 0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef, .value 124, .value 125], + .effect none .mstore [.const 0, .const 1]], + .ret (.const 0) (.const 32)⟩, + -- bb9 + ⟨[], + [.effect (some 124) .calldataload [.const 4], + .effect (some 72) .calldataload [.const 68], + .effect none .mstore [.const 0, .value 124], + .effect none .mstore [.const 32, .const 1], + .effect (some 111) .keccak256 [.const 0, .const 64], + .effect (some 6) .caller [], + .effect none .mstore [.const 0, .value 6], + .effect none .mstore [.const 32, .value 111], + .effect (some 116) .keccak256 [.const 0, .const 64], + .effect (some 9) .sload [.value 116], + .pure 10 .lt [.value 9, .value 72]], + .branch (.value 10) 4 1⟩] }, + -- @revert_error + { params := [0, 1], + blocks := [ + -- bb0 + ⟨[], + [.effect none .mstore [.const 32, .const 32], + .effect none .mstore [.const 64, .value 0], + .effect none .mstore [.const 96, .value 1], + .effect none .mstore [.const 0, .const 0x8c379a0]], + .revert (.const 28) (.const 100)⟩] }, + -- @entry + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 0) .callvalue [], + .ne 2 (.value 0) (.const 0)], + .branch (.value 2) 10 1⟩, + -- bb1 + ⟨[], + [.effect (some 4) .calldataload [.const 0], + .pure 6 .shr [.const 224, .value 4]], + .switch (.value 6) 10 [(.const 0x95ea7b3, 2), (.const 0x23b872dd, 3), (.const 0x70a08231, 4), (.const 0x893d20e8, 5), (.const 0x8d1fdf2f, 6), (.const 0xa9059cbb, 7), (.const 0xdd62ed3e, 8), (.const 0xe5839836, 9)]⟩, + -- bb2 + ⟨[], + [], + .tailCall 6 []⟩, + -- bb3 + ⟨[], + [], + .tailCall 7 []⟩, + -- bb4 + ⟨[], + [], + .tailCall 0 []⟩, + -- bb5 + ⟨[], + [], + .tailCall 2 []⟩, + -- bb6 + ⟨[], + [], + .tailCall 4 []⟩, + -- bb7 + ⟨[], + [], + .tailCall 5 []⟩, + -- bb8 + ⟨[], + [], + .tailCall 1 []⟩, + -- bb9 + ⟨[], + [], + .tailCall 3 []⟩, + -- bb10 + ⟨[], + [], + .revert (.const 0) (.const 0)⟩] }] } + +end SolarTV.Export.Token diff --git a/Certified/token/gen/Token/Mir2.lean b/Certified/token/gen/Token/Mir2.lean new file mode 100644 index 00000000..7c56605f --- /dev/null +++ b/Certified/token/gen/Token/Mir2.lean @@ -0,0 +1,368 @@ +-- solar-lean-stage: kind=mir index=2 pass=dce +import SolarTV.MIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `Token`; do not edit. -/ + +namespace SolarTV.Export.Token + +/-- The lowered MIR module after `dce`. -/ +def mir2 : MIR.Lowered.Module := + { entry := 9, + functions := [ + -- @balanceOf + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 7) .calldatasize [], + .pure 9 .lt [.value 7, .const 36], + .effect (some 11) .calldataload [.const 4], + .pure 13 .gt [.value 11, .const 0xffffffffffffffffffffffffffffffffffffffff], + .pure 25 .or [.value 9, .value 13]], + .branch (.value 25) 1 2⟩, + -- bb1 + ⟨[], + [], + .revert (.const 0) (.const 0)⟩, + -- bb2 + ⟨[], + [.effect (some 26) .calldataload [.const 4], + .effect none .mstore [.const 0, .value 26], + .effect none .mstore [.const 32, .const 0], + .effect (some 22) .keccak256 [.const 0, .const 64], + .effect (some 5) .sload [.value 22], + .effect none .mstore [.const 0, .value 5]], + .ret (.const 0) (.const 32)⟩] }, + -- @allowance + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 10) .calldatasize [], + .pure 12 .lt [.value 10, .const 68], + .effect (some 14) .calldataload [.const 4], + .pure 16 .gt [.value 14, .const 0xffffffffffffffffffffffffffffffffffffffff], + .pure 40 .or [.value 12, .value 16], + .effect (some 18) .calldataload [.const 36], + .pure 20 .gt [.value 18, .const 0xffffffffffffffffffffffffffffffffffffffff], + .pure 41 .or [.value 40, .value 20]], + .branch (.value 41) 1 2⟩, + -- bb1 + ⟨[], + [], + .revert (.const 0) (.const 0)⟩, + -- bb2 + ⟨[], + [.effect (some 43) .calldataload [.const 36], + .effect (some 42) .calldataload [.const 4], + .effect none .mstore [.const 0, .value 42], + .effect none .mstore [.const 32, .const 1], + .effect (some 30) .keccak256 [.const 0, .const 64], + .effect none .mstore [.const 0, .value 43], + .effect none .mstore [.const 32, .value 30], + .effect (some 35) .keccak256 [.const 0, .const 64], + .effect (some 8) .sload [.value 35], + .effect none .mstore [.const 0, .value 8]], + .ret (.const 0) (.const 32)⟩] }, + -- @getOwner + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 2) .sload [.const 4], + .pure 8 .and [.value 2, .const 0xffffffffffffffffffffffffffffffffffffffff], + .effect none .mstore [.const 0, .value 8]], + .ret (.const 0) (.const 32)⟩] }, + -- @isFrozen + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 10) .calldatasize [], + .pure 12 .lt [.value 10, .const 36], + .effect (some 14) .calldataload [.const 4], + .pure 16 .gt [.value 14, .const 0xffffffffffffffffffffffffffffffffffffffff], + .pure 33 .or [.value 12, .value 16]], + .branch (.value 33) 1 2⟩, + -- bb1 + ⟨[], + [], + .revert (.const 0) (.const 0)⟩, + -- bb2 + ⟨[], + [.effect (some 34) .calldataload [.const 4], + .effect none .mstore [.const 0, .value 34], + .effect none .mstore [.const 32, .const 2], + .effect (some 28) .keccak256 [.const 0, .const 64], + .effect (some 5) .sload [.value 28], + .pure 32 .and [.value 5, .const 255], + .ne 8 (.value 32) (.const 0), + .word 22 (.value 8), + .effect none .mstore [.const 0, .value 22]], + .ret (.const 0) (.const 32)⟩] }, + -- @freeze + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 17) .calldatasize [], + .pure 19 .lt [.value 17, .const 36], + .effect (some 21) .calldataload [.const 4], + .pure 23 .gt [.value 21, .const 0xffffffffffffffffffffffffffffffffffffffff], + .pure 35 .or [.value 19, .value 23]], + .branch (.value 35) 1 3⟩, + -- bb1 + ⟨[], + [], + .revert (.const 0) (.const 0)⟩, + -- bb2 + ⟨[], + [.effect (some 36) .calldataload [.const 4], + .effect none .mstore [.const 0, .value 36], + .effect none .mstore [.const 32, .const 2], + .effect (some 30) .keccak256 [.const 0, .const 64], + .effect none .sstore [.value 30, .const 1]], + .stop⟩, + -- bb3 + ⟨[], + [.effect (some 1) .caller [], + .effect (some 3) .sload [.const 4], + .pure 34 .and [.value 3, .const 0xffffffffffffffffffffffffffffffffffffffff], + .pure 5 .eq [.value 1, .value 34]], + .branch (.value 5) 2 1⟩] }, + -- @transfer + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 54) .calldatasize [], + .pure 56 .lt [.value 54, .const 68], + .effect (some 58) .calldataload [.const 4], + .pure 60 .gt [.value 58, .const 0xffffffffffffffffffffffffffffffffffffffff], + .pure 91 .or [.value 56, .value 60]], + .branch (.value 91) 1 7⟩, + -- bb1 + ⟨[], + [], + .revert (.const 0) (.const 0)⟩, + -- bb2 + ⟨[], + [.effect (some 93) .calldataload [.const 36], + .effect none .mstore [.const 0, .value 3], + .effect none .mstore [.const 32, .const 0], + .effect (some 76) .keccak256 [.const 0, .const 64], + .effect (some 18) .sload [.value 76], + .pure 19 .lt [.value 18, .value 93]], + .branch (.value 19) 3 4⟩, + -- bb3 + ⟨[], + [], + .tailCall 8 [.const 7, .const 0x62616c616e636500000000000000000000000000000000000000000000000000]⟩, + -- bb4 + ⟨[], + [.effect (some 92) .calldataload [.const 4], + .pure 29 .sub [.value 18, .value 93], + .effect none .sstore [.value 76, .value 29], + .effect none .mstore [.const 0, .value 92], + .effect (some 81) .keccak256 [.const 0, .const 64], + .effect (some 33) .sload [.value 81], + .pure 45 .add [.value 33, .value 93], + .pure 46 .lt [.value 45, .value 33]], + .branch (.value 46) 5 6⟩, + -- bb5 + ⟨[], + [.effect none .mstore [.const 32, .const 17], + .effect none .mstore [.const 0, .const 0x4e487b71]], + .revert (.const 28) (.const 36)⟩, + -- bb6 + ⟨[], + [.effect none .sstore [.value 81, .value 45], + .effect none .mstore [.const 0, .value 93], + .effect none (.log 3) [.const 0, .const 32, .const 0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef, .value 3, .value 92], + .effect none .mstore [.const 0, .const 1]], + .ret (.const 0) (.const 32)⟩, + -- bb7 + ⟨[], + [.effect (some 3) .caller [], + .effect none .mstore [.const 0, .value 3], + .effect none .mstore [.const 32, .const 2], + .effect (some 86) .keccak256 [.const 0, .const 64], + .effect (some 6) .sload [.value 86], + .pure 90 .and [.value 6, .const 255], + .ne 9 (.value 90) (.const 0)], + .branch (.value 9) 1 2⟩] }, + -- @approve + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 18) .calldatasize [], + .pure 20 .lt [.value 18, .const 68], + .effect (some 22) .calldataload [.const 4], + .pure 24 .gt [.value 22, .const 0xffffffffffffffffffffffffffffffffffffffff], + .pure 48 .or [.value 20, .value 24]], + .branch (.value 48) 1 2⟩, + -- bb1 + ⟨[], + [], + .revert (.const 0) (.const 0)⟩, + -- bb2 + ⟨[], + [.effect (some 49) .calldataload [.const 4], + .effect (some 26) .calldataload [.const 36], + .effect (some 3) .caller [], + .effect none .mstore [.const 0, .value 3], + .effect none .mstore [.const 32, .const 1], + .effect (some 40) .keccak256 [.const 0, .const 64], + .effect none .mstore [.const 0, .value 49], + .effect none .mstore [.const 32, .value 40], + .effect (some 45) .keccak256 [.const 0, .const 64], + .effect none .sstore [.value 45, .value 26], + .effect none .mstore [.const 0, .value 26], + .effect none (.log 3) [.const 0, .const 32, .const 0x8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925, .value 3, .value 49], + .effect none .mstore [.const 0, .const 1]], + .ret (.const 0) (.const 32)⟩] }, + -- @transferFrom + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 60) .calldatasize [], + .pure 62 .lt [.value 60, .const 100], + .effect (some 64) .calldataload [.const 4], + .pure 66 .gt [.value 64, .const 0xffffffffffffffffffffffffffffffffffffffff], + .pure 122 .or [.value 62, .value 66], + .effect (some 68) .calldataload [.const 36], + .pure 70 .gt [.value 68, .const 0xffffffffffffffffffffffffffffffffffffffff], + .pure 123 .or [.value 122, .value 70]], + .branch (.value 123) 5 9⟩, + -- bb1 + ⟨[], + [.pure 83 .not [.value 9], + .ne 16 (.value 83) (.const 0)], + .branch (.value 16) 3 2⟩, + -- bb2 + ⟨[], + [.effect none .mstore [.const 0, .value 124], + .effect none .mstore [.const 32, .const 0], + .effect (some 91) .keccak256 [.const 0, .const 64], + .effect (some 27) .sload [.value 91], + .pure 28 .lt [.value 27, .value 72]], + .branch (.value 28) 5 6⟩, + -- bb3 + ⟨[], + [.pure 17 .sub [.value 9, .value 72], + .effect none .mstore [.const 0, .value 124], + .effect none .mstore [.const 32, .const 1], + .effect (some 96) .keccak256 [.const 0, .const 64], + .effect none .mstore [.const 0, .value 6], + .effect none .mstore [.const 32, .value 96], + .effect (some 101) .keccak256 [.const 0, .const 64], + .effect none .sstore [.value 101, .value 17]], + .jump 2⟩, + -- bb4 + ⟨[], + [], + .tailCall 8 [.const 9, .const 0x616c6c6f77616e63650000000000000000000000000000000000000000000000]⟩, + -- bb5 + ⟨[], + [], + .revert (.const 0) (.const 0)⟩, + -- bb6 + ⟨[], + [.effect (some 125) .calldataload [.const 36], + .pure 37 .sub [.value 27, .value 72], + .effect none .sstore [.value 91, .value 37], + .effect none .mstore [.const 0, .value 125], + .effect (some 106) .keccak256 [.const 0, .const 64], + .effect (some 41) .sload [.value 106], + .pure 51 .add [.value 41, .value 72], + .pure 52 .lt [.value 51, .value 41]], + .branch (.value 52) 7 8⟩, + -- bb7 + ⟨[], + [.effect none .mstore [.const 32, .const 17], + .effect none .mstore [.const 0, .const 0x4e487b71]], + .revert (.const 28) (.const 36)⟩, + -- bb8 + ⟨[], + [.effect none .sstore [.value 106, .value 51], + .effect none .mstore [.const 0, .value 72], + .effect none (.log 3) [.const 0, .const 32, .const 0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef, .value 124, .value 125], + .effect none .mstore [.const 0, .const 1]], + .ret (.const 0) (.const 32)⟩, + -- bb9 + ⟨[], + [.effect (some 124) .calldataload [.const 4], + .effect (some 72) .calldataload [.const 68], + .effect none .mstore [.const 0, .value 124], + .effect none .mstore [.const 32, .const 1], + .effect (some 111) .keccak256 [.const 0, .const 64], + .effect (some 6) .caller [], + .effect none .mstore [.const 0, .value 6], + .effect none .mstore [.const 32, .value 111], + .effect (some 116) .keccak256 [.const 0, .const 64], + .effect (some 9) .sload [.value 116], + .pure 10 .lt [.value 9, .value 72]], + .branch (.value 10) 4 1⟩] }, + -- @revert_error + { params := [0, 1], + blocks := [ + -- bb0 + ⟨[], + [.effect none .mstore [.const 32, .const 32], + .effect none .mstore [.const 64, .value 0], + .effect none .mstore [.const 96, .value 1], + .effect none .mstore [.const 0, .const 0x8c379a0]], + .revert (.const 28) (.const 100)⟩] }, + -- @entry + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 0) .callvalue [], + .ne 2 (.value 0) (.const 0)], + .branch (.value 2) 10 1⟩, + -- bb1 + ⟨[], + [.effect (some 4) .calldataload [.const 0], + .pure 6 .shr [.const 224, .value 4]], + .switch (.value 6) 10 [(.const 0x95ea7b3, 2), (.const 0x23b872dd, 3), (.const 0x70a08231, 4), (.const 0x893d20e8, 5), (.const 0x8d1fdf2f, 6), (.const 0xa9059cbb, 7), (.const 0xdd62ed3e, 8), (.const 0xe5839836, 9)]⟩, + -- bb2 + ⟨[], + [], + .tailCall 6 []⟩, + -- bb3 + ⟨[], + [], + .tailCall 7 []⟩, + -- bb4 + ⟨[], + [], + .tailCall 0 []⟩, + -- bb5 + ⟨[], + [], + .tailCall 2 []⟩, + -- bb6 + ⟨[], + [], + .tailCall 4 []⟩, + -- bb7 + ⟨[], + [], + .tailCall 5 []⟩, + -- bb8 + ⟨[], + [], + .tailCall 1 []⟩, + -- bb9 + ⟨[], + [], + .tailCall 3 []⟩, + -- bb10 + ⟨[], + [], + .revert (.const 0) (.const 0)⟩] }] } + +end SolarTV.Export.Token diff --git a/Certified/token/gen/Token/Mir3.lean b/Certified/token/gen/Token/Mir3.lean new file mode 100644 index 00000000..49a33974 --- /dev/null +++ b/Certified/token/gen/Token/Mir3.lean @@ -0,0 +1,382 @@ +-- solar-lean-stage: kind=mir index=3 pass=spell-width-tests +import SolarTV.MIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `Token`; do not edit. -/ + +namespace SolarTV.Export.Token + +/-- The lowered MIR module after `spell-width-tests`. -/ +def mir3 : MIR.Lowered.Module := + { entry := 9, + functions := [ + -- @balanceOf + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 7) .calldatasize [], + .pure 9 .lt [.value 7, .const 36], + .effect (some 11) .calldataload [.const 4], + .pure 28 .shr [.const 160, .value 11], + .word 31 (.value 9), + .pure 32 .or [.value 28, .value 31], + .ne 25 (.value 32) (.const 0)], + .branch (.value 25) 1 2⟩, + -- bb1 + ⟨[], + [], + .revert (.const 0) (.const 0)⟩, + -- bb2 + ⟨[], + [.effect (some 26) .calldataload [.const 4], + .effect none .mstore [.const 0, .value 26], + .effect none .mstore [.const 32, .const 0], + .effect (some 22) .keccak256 [.const 0, .const 64], + .effect (some 5) .sload [.value 22], + .effect none .mstore [.const 0, .value 5]], + .ret (.const 0) (.const 32)⟩] }, + -- @allowance + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 10) .calldatasize [], + .pure 12 .lt [.value 10, .const 68], + .effect (some 14) .calldataload [.const 4], + .pure 45 .shr [.const 160, .value 14], + .word 48 (.value 12), + .pure 49 .or [.value 45, .value 48], + .effect (some 18) .calldataload [.const 36], + .pure 53 .shr [.const 160, .value 18], + .pure 56 .or [.value 49, .value 53], + .ne 41 (.value 56) (.const 0)], + .branch (.value 41) 1 2⟩, + -- bb1 + ⟨[], + [], + .revert (.const 0) (.const 0)⟩, + -- bb2 + ⟨[], + [.effect (some 43) .calldataload [.const 36], + .effect (some 42) .calldataload [.const 4], + .effect none .mstore [.const 0, .value 42], + .effect none .mstore [.const 32, .const 1], + .effect (some 30) .keccak256 [.const 0, .const 64], + .effect none .mstore [.const 0, .value 43], + .effect none .mstore [.const 32, .value 30], + .effect (some 35) .keccak256 [.const 0, .const 64], + .effect (some 8) .sload [.value 35], + .effect none .mstore [.const 0, .value 8]], + .ret (.const 0) (.const 32)⟩] }, + -- @getOwner + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 2) .sload [.const 4], + .pure 8 .and [.value 2, .const 0xffffffffffffffffffffffffffffffffffffffff], + .effect none .mstore [.const 0, .value 8]], + .ret (.const 0) (.const 32)⟩] }, + -- @isFrozen + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 10) .calldatasize [], + .pure 12 .lt [.value 10, .const 36], + .effect (some 14) .calldataload [.const 4], + .pure 36 .shr [.const 160, .value 14], + .word 39 (.value 12), + .pure 40 .or [.value 36, .value 39], + .ne 33 (.value 40) (.const 0)], + .branch (.value 33) 1 2⟩, + -- bb1 + ⟨[], + [], + .revert (.const 0) (.const 0)⟩, + -- bb2 + ⟨[], + [.effect (some 34) .calldataload [.const 4], + .effect none .mstore [.const 0, .value 34], + .effect none .mstore [.const 32, .const 2], + .effect (some 28) .keccak256 [.const 0, .const 64], + .effect (some 5) .sload [.value 28], + .pure 32 .and [.value 5, .const 255], + .ne 8 (.value 32) (.const 0), + .word 22 (.value 8), + .effect none .mstore [.const 0, .value 22]], + .ret (.const 0) (.const 32)⟩] }, + -- @freeze + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 17) .calldatasize [], + .pure 19 .lt [.value 17, .const 36], + .effect (some 21) .calldataload [.const 4], + .pure 38 .shr [.const 160, .value 21], + .word 41 (.value 19), + .pure 42 .or [.value 38, .value 41], + .ne 35 (.value 42) (.const 0)], + .branch (.value 35) 1 3⟩, + -- bb1 + ⟨[], + [], + .revert (.const 0) (.const 0)⟩, + -- bb2 + ⟨[], + [.effect (some 36) .calldataload [.const 4], + .effect none .mstore [.const 0, .value 36], + .effect none .mstore [.const 32, .const 2], + .effect (some 30) .keccak256 [.const 0, .const 64], + .effect none .sstore [.value 30, .const 1]], + .stop⟩, + -- bb3 + ⟨[], + [.effect (some 1) .caller [], + .effect (some 3) .sload [.const 4], + .pure 34 .and [.value 3, .const 0xffffffffffffffffffffffffffffffffffffffff], + .pure 5 .eq [.value 1, .value 34]], + .branch (.value 5) 2 1⟩] }, + -- @transfer + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 54) .calldatasize [], + .pure 56 .lt [.value 54, .const 68], + .effect (some 58) .calldataload [.const 4], + .pure 95 .shr [.const 160, .value 58], + .word 98 (.value 56), + .pure 99 .or [.value 95, .value 98], + .ne 91 (.value 99) (.const 0)], + .branch (.value 91) 1 7⟩, + -- bb1 + ⟨[], + [], + .revert (.const 0) (.const 0)⟩, + -- bb2 + ⟨[], + [.effect (some 93) .calldataload [.const 36], + .effect none .mstore [.const 0, .value 3], + .effect none .mstore [.const 32, .const 0], + .effect (some 76) .keccak256 [.const 0, .const 64], + .effect (some 18) .sload [.value 76], + .pure 19 .lt [.value 18, .value 93]], + .branch (.value 19) 3 4⟩, + -- bb3 + ⟨[], + [], + .tailCall 8 [.const 7, .const 0x62616c616e636500000000000000000000000000000000000000000000000000]⟩, + -- bb4 + ⟨[], + [.effect (some 92) .calldataload [.const 4], + .pure 29 .sub [.value 18, .value 93], + .effect none .sstore [.value 76, .value 29], + .effect none .mstore [.const 0, .value 92], + .effect (some 81) .keccak256 [.const 0, .const 64], + .effect (some 33) .sload [.value 81], + .pure 45 .add [.value 33, .value 93], + .pure 46 .lt [.value 45, .value 33]], + .branch (.value 46) 5 6⟩, + -- bb5 + ⟨[], + [.effect none .mstore [.const 32, .const 17], + .effect none .mstore [.const 0, .const 0x4e487b71]], + .revert (.const 28) (.const 36)⟩, + -- bb6 + ⟨[], + [.effect none .sstore [.value 81, .value 45], + .effect none .mstore [.const 0, .value 93], + .effect none (.log 3) [.const 0, .const 32, .const 0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef, .value 3, .value 92], + .effect none .mstore [.const 0, .const 1]], + .ret (.const 0) (.const 32)⟩, + -- bb7 + ⟨[], + [.effect (some 3) .caller [], + .effect none .mstore [.const 0, .value 3], + .effect none .mstore [.const 32, .const 2], + .effect (some 86) .keccak256 [.const 0, .const 64], + .effect (some 6) .sload [.value 86], + .pure 90 .and [.value 6, .const 255], + .ne 9 (.value 90) (.const 0)], + .branch (.value 9) 1 2⟩] }, + -- @approve + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 18) .calldatasize [], + .pure 20 .lt [.value 18, .const 68], + .effect (some 22) .calldataload [.const 4], + .pure 51 .shr [.const 160, .value 22], + .word 54 (.value 20), + .pure 55 .or [.value 51, .value 54], + .ne 48 (.value 55) (.const 0)], + .branch (.value 48) 1 2⟩, + -- bb1 + ⟨[], + [], + .revert (.const 0) (.const 0)⟩, + -- bb2 + ⟨[], + [.effect (some 49) .calldataload [.const 4], + .effect (some 26) .calldataload [.const 36], + .effect (some 3) .caller [], + .effect none .mstore [.const 0, .value 3], + .effect none .mstore [.const 32, .const 1], + .effect (some 40) .keccak256 [.const 0, .const 64], + .effect none .mstore [.const 0, .value 49], + .effect none .mstore [.const 32, .value 40], + .effect (some 45) .keccak256 [.const 0, .const 64], + .effect none .sstore [.value 45, .value 26], + .effect none .mstore [.const 0, .value 26], + .effect none (.log 3) [.const 0, .const 32, .const 0x8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925, .value 3, .value 49], + .effect none .mstore [.const 0, .const 1]], + .ret (.const 0) (.const 32)⟩] }, + -- @transferFrom + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 60) .calldatasize [], + .pure 62 .lt [.value 60, .const 100], + .effect (some 64) .calldataload [.const 4], + .pure 127 .shr [.const 160, .value 64], + .word 130 (.value 62), + .pure 131 .or [.value 127, .value 130], + .effect (some 68) .calldataload [.const 36], + .pure 135 .shr [.const 160, .value 68], + .pure 138 .or [.value 131, .value 135], + .ne 123 (.value 138) (.const 0)], + .branch (.value 123) 5 9⟩, + -- bb1 + ⟨[], + [.pure 83 .not [.value 9], + .ne 16 (.value 83) (.const 0)], + .branch (.value 16) 3 2⟩, + -- bb2 + ⟨[], + [.effect none .mstore [.const 0, .value 124], + .effect none .mstore [.const 32, .const 0], + .effect (some 91) .keccak256 [.const 0, .const 64], + .effect (some 27) .sload [.value 91], + .pure 28 .lt [.value 27, .value 72]], + .branch (.value 28) 5 6⟩, + -- bb3 + ⟨[], + [.pure 17 .sub [.value 9, .value 72], + .effect none .mstore [.const 0, .value 124], + .effect none .mstore [.const 32, .const 1], + .effect (some 96) .keccak256 [.const 0, .const 64], + .effect none .mstore [.const 0, .value 6], + .effect none .mstore [.const 32, .value 96], + .effect (some 101) .keccak256 [.const 0, .const 64], + .effect none .sstore [.value 101, .value 17]], + .jump 2⟩, + -- bb4 + ⟨[], + [], + .tailCall 8 [.const 9, .const 0x616c6c6f77616e63650000000000000000000000000000000000000000000000]⟩, + -- bb5 + ⟨[], + [], + .revert (.const 0) (.const 0)⟩, + -- bb6 + ⟨[], + [.effect (some 125) .calldataload [.const 36], + .pure 37 .sub [.value 27, .value 72], + .effect none .sstore [.value 91, .value 37], + .effect none .mstore [.const 0, .value 125], + .effect (some 106) .keccak256 [.const 0, .const 64], + .effect (some 41) .sload [.value 106], + .pure 51 .add [.value 41, .value 72], + .pure 52 .lt [.value 51, .value 41]], + .branch (.value 52) 7 8⟩, + -- bb7 + ⟨[], + [.effect none .mstore [.const 32, .const 17], + .effect none .mstore [.const 0, .const 0x4e487b71]], + .revert (.const 28) (.const 36)⟩, + -- bb8 + ⟨[], + [.effect none .sstore [.value 106, .value 51], + .effect none .mstore [.const 0, .value 72], + .effect none (.log 3) [.const 0, .const 32, .const 0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef, .value 124, .value 125], + .effect none .mstore [.const 0, .const 1]], + .ret (.const 0) (.const 32)⟩, + -- bb9 + ⟨[], + [.effect (some 124) .calldataload [.const 4], + .effect (some 72) .calldataload [.const 68], + .effect none .mstore [.const 0, .value 124], + .effect none .mstore [.const 32, .const 1], + .effect (some 111) .keccak256 [.const 0, .const 64], + .effect (some 6) .caller [], + .effect none .mstore [.const 0, .value 6], + .effect none .mstore [.const 32, .value 111], + .effect (some 116) .keccak256 [.const 0, .const 64], + .effect (some 9) .sload [.value 116], + .pure 10 .lt [.value 9, .value 72]], + .branch (.value 10) 4 1⟩] }, + -- @revert_error + { params := [0, 1], + blocks := [ + -- bb0 + ⟨[], + [.effect none .mstore [.const 32, .const 32], + .effect none .mstore [.const 64, .value 0], + .effect none .mstore [.const 96, .value 1], + .effect none .mstore [.const 0, .const 0x8c379a0]], + .revert (.const 28) (.const 100)⟩] }, + -- @entry + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 0) .callvalue [], + .ne 2 (.value 0) (.const 0)], + .branch (.value 2) 10 1⟩, + -- bb1 + ⟨[], + [.effect (some 4) .calldataload [.const 0], + .pure 6 .shr [.const 224, .value 4]], + .switch (.value 6) 10 [(.const 0x95ea7b3, 2), (.const 0x23b872dd, 3), (.const 0x70a08231, 4), (.const 0x893d20e8, 5), (.const 0x8d1fdf2f, 6), (.const 0xa9059cbb, 7), (.const 0xdd62ed3e, 8), (.const 0xe5839836, 9)]⟩, + -- bb2 + ⟨[], + [], + .tailCall 6 []⟩, + -- bb3 + ⟨[], + [], + .tailCall 7 []⟩, + -- bb4 + ⟨[], + [], + .tailCall 0 []⟩, + -- bb5 + ⟨[], + [], + .tailCall 2 []⟩, + -- bb6 + ⟨[], + [], + .tailCall 4 []⟩, + -- bb7 + ⟨[], + [], + .tailCall 5 []⟩, + -- bb8 + ⟨[], + [], + .tailCall 1 []⟩, + -- bb9 + ⟨[], + [], + .tailCall 3 []⟩, + -- bb10 + ⟨[], + [], + .revert (.const 0) (.const 0)⟩] }] } + +end SolarTV.Export.Token diff --git a/Certified/token/gen/Token/Mir4.lean b/Certified/token/gen/Token/Mir4.lean new file mode 100644 index 00000000..afcb57b1 --- /dev/null +++ b/Certified/token/gen/Token/Mir4.lean @@ -0,0 +1,382 @@ +-- solar-lean-stage: kind=mir index=4 pass=evm-inst-schedule +import SolarTV.MIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `Token`; do not edit. -/ + +namespace SolarTV.Export.Token + +/-- The lowered MIR module after `evm-inst-schedule`. -/ +def mir4 : MIR.Lowered.Module := + { entry := 9, + functions := [ + -- @balanceOf + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 11) .calldataload [.const 4], + .pure 28 .shr [.const 160, .value 11], + .effect (some 7) .calldatasize [], + .pure 9 .lt [.value 7, .const 36], + .word 31 (.value 9), + .pure 32 .or [.value 28, .value 31], + .ne 25 (.value 32) (.const 0)], + .branch (.value 25) 1 2⟩, + -- bb1 + ⟨[], + [], + .revert (.const 0) (.const 0)⟩, + -- bb2 + ⟨[], + [.effect (some 26) .calldataload [.const 4], + .effect none .mstore [.const 0, .value 26], + .effect none .mstore [.const 32, .const 0], + .effect (some 22) .keccak256 [.const 0, .const 64], + .effect (some 5) .sload [.value 22], + .effect none .mstore [.const 0, .value 5]], + .ret (.const 0) (.const 32)⟩] }, + -- @allowance + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 14) .calldataload [.const 4], + .pure 45 .shr [.const 160, .value 14], + .effect (some 10) .calldatasize [], + .pure 12 .lt [.value 10, .const 68], + .word 48 (.value 12), + .pure 49 .or [.value 45, .value 48], + .effect (some 18) .calldataload [.const 36], + .pure 53 .shr [.const 160, .value 18], + .pure 56 .or [.value 49, .value 53], + .ne 41 (.value 56) (.const 0)], + .branch (.value 41) 1 2⟩, + -- bb1 + ⟨[], + [], + .revert (.const 0) (.const 0)⟩, + -- bb2 + ⟨[], + [.effect (some 43) .calldataload [.const 36], + .effect (some 42) .calldataload [.const 4], + .effect none .mstore [.const 0, .value 42], + .effect none .mstore [.const 32, .const 1], + .effect (some 30) .keccak256 [.const 0, .const 64], + .effect none .mstore [.const 0, .value 43], + .effect none .mstore [.const 32, .value 30], + .effect (some 35) .keccak256 [.const 0, .const 64], + .effect (some 8) .sload [.value 35], + .effect none .mstore [.const 0, .value 8]], + .ret (.const 0) (.const 32)⟩] }, + -- @getOwner + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 2) .sload [.const 4], + .pure 8 .and [.value 2, .const 0xffffffffffffffffffffffffffffffffffffffff], + .effect none .mstore [.const 0, .value 8]], + .ret (.const 0) (.const 32)⟩] }, + -- @isFrozen + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 14) .calldataload [.const 4], + .pure 36 .shr [.const 160, .value 14], + .effect (some 10) .calldatasize [], + .pure 12 .lt [.value 10, .const 36], + .word 39 (.value 12), + .pure 40 .or [.value 36, .value 39], + .ne 33 (.value 40) (.const 0)], + .branch (.value 33) 1 2⟩, + -- bb1 + ⟨[], + [], + .revert (.const 0) (.const 0)⟩, + -- bb2 + ⟨[], + [.effect (some 34) .calldataload [.const 4], + .effect none .mstore [.const 0, .value 34], + .effect none .mstore [.const 32, .const 2], + .effect (some 28) .keccak256 [.const 0, .const 64], + .effect (some 5) .sload [.value 28], + .pure 32 .and [.value 5, .const 255], + .ne 8 (.value 32) (.const 0), + .word 22 (.value 8), + .effect none .mstore [.const 0, .value 22]], + .ret (.const 0) (.const 32)⟩] }, + -- @freeze + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 21) .calldataload [.const 4], + .pure 38 .shr [.const 160, .value 21], + .effect (some 17) .calldatasize [], + .pure 19 .lt [.value 17, .const 36], + .word 41 (.value 19), + .pure 42 .or [.value 38, .value 41], + .ne 35 (.value 42) (.const 0)], + .branch (.value 35) 1 3⟩, + -- bb1 + ⟨[], + [], + .revert (.const 0) (.const 0)⟩, + -- bb2 + ⟨[], + [.effect (some 36) .calldataload [.const 4], + .effect none .mstore [.const 0, .value 36], + .effect none .mstore [.const 32, .const 2], + .effect (some 30) .keccak256 [.const 0, .const 64], + .effect none .sstore [.value 30, .const 1]], + .stop⟩, + -- bb3 + ⟨[], + [.effect (some 1) .caller [], + .effect (some 3) .sload [.const 4], + .pure 34 .and [.value 3, .const 0xffffffffffffffffffffffffffffffffffffffff], + .pure 5 .eq [.value 1, .value 34]], + .branch (.value 5) 2 1⟩] }, + -- @transfer + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 58) .calldataload [.const 4], + .pure 95 .shr [.const 160, .value 58], + .effect (some 54) .calldatasize [], + .pure 56 .lt [.value 54, .const 68], + .word 98 (.value 56), + .pure 99 .or [.value 95, .value 98], + .ne 91 (.value 99) (.const 0)], + .branch (.value 91) 1 7⟩, + -- bb1 + ⟨[], + [], + .revert (.const 0) (.const 0)⟩, + -- bb2 + ⟨[], + [.effect (some 93) .calldataload [.const 36], + .effect none .mstore [.const 0, .value 3], + .effect none .mstore [.const 32, .const 0], + .effect (some 76) .keccak256 [.const 0, .const 64], + .effect (some 18) .sload [.value 76], + .pure 19 .lt [.value 18, .value 93]], + .branch (.value 19) 3 4⟩, + -- bb3 + ⟨[], + [], + .tailCall 8 [.const 7, .const 0x62616c616e636500000000000000000000000000000000000000000000000000]⟩, + -- bb4 + ⟨[], + [.effect (some 92) .calldataload [.const 4], + .pure 29 .sub [.value 18, .value 93], + .effect none .sstore [.value 76, .value 29], + .effect none .mstore [.const 0, .value 92], + .effect (some 81) .keccak256 [.const 0, .const 64], + .effect (some 33) .sload [.value 81], + .pure 45 .add [.value 33, .value 93], + .pure 46 .lt [.value 45, .value 33]], + .branch (.value 46) 5 6⟩, + -- bb5 + ⟨[], + [.effect none .mstore [.const 32, .const 17], + .effect none .mstore [.const 0, .const 0x4e487b71]], + .revert (.const 28) (.const 36)⟩, + -- bb6 + ⟨[], + [.effect none .sstore [.value 81, .value 45], + .effect none .mstore [.const 0, .value 93], + .effect none (.log 3) [.const 0, .const 32, .const 0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef, .value 3, .value 92], + .effect none .mstore [.const 0, .const 1]], + .ret (.const 0) (.const 32)⟩, + -- bb7 + ⟨[], + [.effect (some 3) .caller [], + .effect none .mstore [.const 0, .value 3], + .effect none .mstore [.const 32, .const 2], + .effect (some 86) .keccak256 [.const 0, .const 64], + .effect (some 6) .sload [.value 86], + .pure 90 .and [.value 6, .const 255], + .ne 9 (.value 90) (.const 0)], + .branch (.value 9) 1 2⟩] }, + -- @approve + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 22) .calldataload [.const 4], + .pure 51 .shr [.const 160, .value 22], + .effect (some 18) .calldatasize [], + .pure 20 .lt [.value 18, .const 68], + .word 54 (.value 20), + .pure 55 .or [.value 51, .value 54], + .ne 48 (.value 55) (.const 0)], + .branch (.value 48) 1 2⟩, + -- bb1 + ⟨[], + [], + .revert (.const 0) (.const 0)⟩, + -- bb2 + ⟨[], + [.effect (some 49) .calldataload [.const 4], + .effect (some 26) .calldataload [.const 36], + .effect (some 3) .caller [], + .effect none .mstore [.const 0, .value 3], + .effect none .mstore [.const 32, .const 1], + .effect (some 40) .keccak256 [.const 0, .const 64], + .effect none .mstore [.const 0, .value 49], + .effect none .mstore [.const 32, .value 40], + .effect (some 45) .keccak256 [.const 0, .const 64], + .effect none .sstore [.value 45, .value 26], + .effect none .mstore [.const 0, .value 26], + .effect none (.log 3) [.const 0, .const 32, .const 0x8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925, .value 3, .value 49], + .effect none .mstore [.const 0, .const 1]], + .ret (.const 0) (.const 32)⟩] }, + -- @transferFrom + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 64) .calldataload [.const 4], + .pure 127 .shr [.const 160, .value 64], + .effect (some 60) .calldatasize [], + .pure 62 .lt [.value 60, .const 100], + .word 130 (.value 62), + .pure 131 .or [.value 127, .value 130], + .effect (some 68) .calldataload [.const 36], + .pure 135 .shr [.const 160, .value 68], + .pure 138 .or [.value 131, .value 135], + .ne 123 (.value 138) (.const 0)], + .branch (.value 123) 5 9⟩, + -- bb1 + ⟨[], + [.pure 83 .not [.value 9], + .ne 16 (.value 83) (.const 0)], + .branch (.value 16) 3 2⟩, + -- bb2 + ⟨[], + [.effect none .mstore [.const 0, .value 124], + .effect none .mstore [.const 32, .const 0], + .effect (some 91) .keccak256 [.const 0, .const 64], + .effect (some 27) .sload [.value 91], + .pure 28 .lt [.value 27, .value 72]], + .branch (.value 28) 5 6⟩, + -- bb3 + ⟨[], + [.pure 17 .sub [.value 9, .value 72], + .effect none .mstore [.const 0, .value 124], + .effect none .mstore [.const 32, .const 1], + .effect (some 96) .keccak256 [.const 0, .const 64], + .effect none .mstore [.const 0, .value 6], + .effect none .mstore [.const 32, .value 96], + .effect (some 101) .keccak256 [.const 0, .const 64], + .effect none .sstore [.value 101, .value 17]], + .jump 2⟩, + -- bb4 + ⟨[], + [], + .tailCall 8 [.const 9, .const 0x616c6c6f77616e63650000000000000000000000000000000000000000000000]⟩, + -- bb5 + ⟨[], + [], + .revert (.const 0) (.const 0)⟩, + -- bb6 + ⟨[], + [.effect (some 125) .calldataload [.const 36], + .pure 37 .sub [.value 27, .value 72], + .effect none .sstore [.value 91, .value 37], + .effect none .mstore [.const 0, .value 125], + .effect (some 106) .keccak256 [.const 0, .const 64], + .effect (some 41) .sload [.value 106], + .pure 51 .add [.value 41, .value 72], + .pure 52 .lt [.value 51, .value 41]], + .branch (.value 52) 7 8⟩, + -- bb7 + ⟨[], + [.effect none .mstore [.const 32, .const 17], + .effect none .mstore [.const 0, .const 0x4e487b71]], + .revert (.const 28) (.const 36)⟩, + -- bb8 + ⟨[], + [.effect none .sstore [.value 106, .value 51], + .effect none .mstore [.const 0, .value 72], + .effect none (.log 3) [.const 0, .const 32, .const 0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef, .value 124, .value 125], + .effect none .mstore [.const 0, .const 1]], + .ret (.const 0) (.const 32)⟩, + -- bb9 + ⟨[], + [.effect (some 124) .calldataload [.const 4], + .effect (some 72) .calldataload [.const 68], + .effect none .mstore [.const 0, .value 124], + .effect none .mstore [.const 32, .const 1], + .effect (some 111) .keccak256 [.const 0, .const 64], + .effect (some 6) .caller [], + .effect none .mstore [.const 0, .value 6], + .effect none .mstore [.const 32, .value 111], + .effect (some 116) .keccak256 [.const 0, .const 64], + .effect (some 9) .sload [.value 116], + .pure 10 .lt [.value 9, .value 72]], + .branch (.value 10) 4 1⟩] }, + -- @revert_error + { params := [0, 1], + blocks := [ + -- bb0 + ⟨[], + [.effect none .mstore [.const 32, .const 32], + .effect none .mstore [.const 64, .value 0], + .effect none .mstore [.const 96, .value 1], + .effect none .mstore [.const 0, .const 0x8c379a0]], + .revert (.const 28) (.const 100)⟩] }, + -- @entry + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 0) .callvalue [], + .ne 2 (.value 0) (.const 0)], + .branch (.value 2) 10 1⟩, + -- bb1 + ⟨[], + [.effect (some 4) .calldataload [.const 0], + .pure 6 .shr [.const 224, .value 4]], + .switch (.value 6) 10 [(.const 0x95ea7b3, 2), (.const 0x23b872dd, 3), (.const 0x70a08231, 4), (.const 0x893d20e8, 5), (.const 0x8d1fdf2f, 6), (.const 0xa9059cbb, 7), (.const 0xdd62ed3e, 8), (.const 0xe5839836, 9)]⟩, + -- bb2 + ⟨[], + [], + .tailCall 6 []⟩, + -- bb3 + ⟨[], + [], + .tailCall 7 []⟩, + -- bb4 + ⟨[], + [], + .tailCall 0 []⟩, + -- bb5 + ⟨[], + [], + .tailCall 2 []⟩, + -- bb6 + ⟨[], + [], + .tailCall 4 []⟩, + -- bb7 + ⟨[], + [], + .tailCall 5 []⟩, + -- bb8 + ⟨[], + [], + .tailCall 1 []⟩, + -- bb9 + ⟨[], + [], + .tailCall 3 []⟩, + -- bb10 + ⟨[], + [], + .revert (.const 0) (.const 0)⟩] }] } + +end SolarTV.Export.Token diff --git a/Certified/token/gen/Token/Sched.lean b/Certified/token/gen/Token/Sched.lean new file mode 100644 index 00000000..bcd63bc0 --- /dev/null +++ b/Certified/token/gen/Token/Sched.lean @@ -0,0 +1,568 @@ +-- solar-lean-stage: kind=sched index=0 pass=stack-schedule +import SolarTV.EVMIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `Token`; do not edit. -/ + +namespace SolarTV.Export.Token + +/-- The runtime EVM IR as stack scheduling emits it. -/ +def sched : EVM.Program.Program := + { blocks := [ + -- bb0 + [.effect .callvalue 0, + .jumpi 11, + .jump 1], + -- bb1 + [.op (.stack (.push 0)), + .effect .calldataload 1, + .op (.stack (.push 224)), + .op (.stack .shr), + .op (.stack (.dup 0)), + .op (.stack (.push 0x8d1fdf2f)), + .op (.stack .gt), + .jumpi 2, + .op (.stack (.dup 0)), + .op (.stack (.push 0x8d1fdf2f)), + .op (.stack .eq), + .jumpi 6, + .op (.stack (.dup 0)), + .op (.stack (.push 0xa9059cbb)), + .op (.stack .eq), + .jumpi 5, + .op (.stack (.dup 0)), + .op (.stack (.push 0xdd62ed3e)), + .op (.stack .eq), + .jumpi 4, + .op (.stack (.dup 0)), + .op (.stack (.push 0xe5839836)), + .op (.stack .eq), + .jumpi 3, + .jump 11], + -- bb2 + [.op (.stack (.dup 0)), + .op (.stack (.push 0x95ea7b3)), + .op (.stack .eq), + .jumpi 10, + .op (.stack (.dup 0)), + .op (.stack (.push 0x23b872dd)), + .op (.stack .eq), + .jumpi 9, + .op (.stack (.dup 0)), + .op (.stack (.push 0x70a08231)), + .op (.stack .eq), + .jumpi 8, + .op (.stack (.dup 0)), + .op (.stack (.push 0x893d20e8)), + .op (.stack .eq), + .jumpi 7, + .jump 11], + -- bb3 + [.jump 19], + -- bb4 + [.jump 15], + -- bb5 + [.jump 26], + -- bb6 + [.jump 22], + -- bb7 + [.jump 18], + -- bb8 + [.jump 12], + -- bb9 + [.jump 37], + -- bb10 + [.jump 34], + -- bb11 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb12 + [.op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 160)), + .op (.stack .shr), + .op (.stack (.push 36)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack .or), + .jumpi 14, + .jump 13], + -- bb13 + [.op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 0)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .effect .sload 1, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb14 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb15 + [.op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 160)), + .op (.stack .shr), + .op (.stack (.push 68)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack .or), + .op (.stack (.push 36)), + .effect .calldataload 1, + .op (.stack (.push 160)), + .op (.stack .shr), + .op (.stack .or), + .jumpi 17, + .jump 16], + -- bb16 + [.op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 1)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .op (.stack (.push 36)), + .effect .calldataload 1, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .effect .sload 1, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb17 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb18 + [.op (.stack (.push 4)), + .effect .sload 1, + .op (.stack (.push 0xffffffffffffffffffffffffffffffffffffffff)), + .op (.stack .and), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb19 + [.op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 160)), + .op (.stack .shr), + .op (.stack (.push 36)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack .or), + .jumpi 21, + .jump 20], + -- bb20 + [.op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 2)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .effect .sload 1, + .op (.stack (.push 255)), + .op (.stack .and), + .op (.stack (.push 0)), + .op (.stack .lt), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb21 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb22 + [.op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 160)), + .op (.stack .shr), + .op (.stack (.push 36)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack .or), + .jumpi 25, + .jump 23], + -- bb23 + [.op (.stack (.push 4)), + .effect .sload 1, + .op (.stack (.push 0xffffffffffffffffffffffffffffffffffffffff)), + .op (.stack .and), + .effect .caller 0, + .op (.stack .eq), + .op (.stack .iszero), + .jumpi 25, + .jump 24], + -- bb24 + [.op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 2)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 1)), + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .effect .sstore 2, + .stop], + -- bb25 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb26 + [.op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 160)), + .op (.stack .shr), + .op (.stack (.push 68)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack .or), + .jumpi 33, + .jump 27], + -- bb27 + [.effect .caller 0, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 2)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .effect .sload 1, + .op (.stack (.push 255)), + .op (.stack .and), + .jumpi 33, + .jump 28], + -- bb28 + [.op (.stack (.push 36)), + .effect .calldataload 1, + .effect .caller 0, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 0)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .op (.stack (.dup 0)), + .effect .sload 1, + .op (.stack (.dup 2)), + .op (.stack (.dup 1)), + .op (.stack .lt), + .jumpi 32, + .jump 29], + -- bb29 + [.op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.dup 3)), + .op (.stack (.swap 0)), + .op (.stack (.swap 1)), + .op (.stack .sub), + .op (.stack (.swap 0)), + .op (.stack (.swap 1)), + .effect .sstore 2, + .op (.stack (.dup 0)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .op (.stack (.dup 0)), + .effect .sload 1, + .op (.stack (.dup 3)), + .op (.stack (.dup 1)), + .op (.stack .add), + .op (.stack (.swap 0)), + .op (.stack (.dup 1)), + .op (.stack .lt), + .jumpi 31, + .jump 30], + -- bb30 + [.op (.stack (.swap 0)), + .effect .sstore 2, + .op (.stack (.swap 0)), + .op (.stack (.push 0)), + .op .store, + .effect .caller 0, + .op (.stack (.push 0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef)), + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .effect (.log 3) 5, + .op (.stack (.push 1)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb31 + [.op (.stack (.push 17)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 0x4e487b71)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 36)), + .op (.stack (.push 28)), + .revert], + -- bb32 + [.op (.stack (.push 0x62616c616e636500000000000000000000000000000000000000000000000000)), + .op (.stack (.push 7)), + .jump 47], + -- bb33 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb34 + [.op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 160)), + .op (.stack .shr), + .op (.stack (.push 68)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack .or), + .jumpi 36, + .jump 35], + -- bb35 + [.op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 36)), + .effect .calldataload 1, + .effect .caller 0, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 1)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .op (.stack (.dup 2)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op .store, + .op (.stack (.dup 0)), + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .effect .sstore 2, + .op (.stack (.push 0)), + .op .store, + .effect .caller 0, + .op (.stack (.push 0x8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925)), + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .effect (.log 3) 5, + .op (.stack (.push 1)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb36 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb37 + [.op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 160)), + .op (.stack .shr), + .op (.stack (.push 100)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack .or), + .op (.stack (.push 36)), + .effect .calldataload 1, + .op (.stack (.push 160)), + .op (.stack .shr), + .op (.stack .or), + .jumpi 46, + .jump 38], + -- bb38 + [.op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 68)), + .effect .calldataload 1, + .op (.stack (.dup 1)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 1)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .effect .caller 0, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .effect .sload 1, + .op (.stack (.dup 1)), + .op (.stack (.dup 1)), + .op (.stack .lt), + .jumpi 45, + .jump 39], + -- bb39 + [.op (.stack (.dup 0)), + .op (.stack .not), + .op (.stack .iszero), + .jumpi 41, + .jump 40], + -- bb40 + [.op (.stack (.dup 1)), + .op (.stack (.swap 0)), + .op (.stack .sub), + .op (.stack (.dup 2)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 1)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .effect .caller 0, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .effect .sstore 2, + .op (.stack (.push 0)), + .jump 41], + -- bb41 + [.op (.stack .pop), + .op (.stack (.dup 1)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 0)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .op (.stack (.dup 0)), + .effect .sload 1, + .op (.stack (.dup 2)), + .op (.stack (.dup 1)), + .op (.stack .lt), + .jumpi 46, + .jump 42], + -- bb42 + [.op (.stack (.push 36)), + .effect .calldataload 1, + .op (.stack (.dup 3)), + .op (.stack (.swap 0)), + .op (.stack (.swap 1)), + .op (.stack .sub), + .op (.stack (.swap 0)), + .op (.stack (.swap 1)), + .effect .sstore 2, + .op (.stack (.dup 0)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .op (.stack (.dup 0)), + .effect .sload 1, + .op (.stack (.dup 3)), + .op (.stack (.dup 1)), + .op (.stack .add), + .op (.stack (.swap 0)), + .op (.stack (.dup 1)), + .op (.stack .lt), + .jumpi 44, + .jump 43], + -- bb43 + [.op (.stack (.swap 0)), + .effect .sstore 2, + .op (.stack (.swap 0)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.swap 0)), + .op (.stack (.push 0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef)), + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .effect (.log 3) 5, + .op (.stack (.push 1)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb44 + [.op (.stack (.push 17)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 0x4e487b71)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 36)), + .op (.stack (.push 28)), + .revert], + -- bb45 + [.op (.stack (.push 0x616c6c6f77616e63650000000000000000000000000000000000000000000000)), + .op (.stack (.push 9)), + .jump 47], + -- bb46 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb47 + [.op (.stack (.push 32)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op .store, + .op (.stack (.push 96)), + .op .store, + .op (.stack (.push 0x8c379a0)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 100)), + .op (.stack (.push 28)), + .revert]] } + +end SolarTV.Export.Token diff --git a/Certified/token/gen/Token/Stage0.lean b/Certified/token/gen/Token/Stage0.lean new file mode 100644 index 00000000..06961bad --- /dev/null +++ b/Certified/token/gen/Token/Stage0.lean @@ -0,0 +1,359 @@ +-- solar-lean-stage: kind=mir index=0 pass=lower-evm-shaped +import SolarTV.MIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `Token`; do not edit. -/ + +namespace SolarTV.Export.Token + +/-- The first lowered MIR module, after `lower-evm-shaped` advanced the phase. -/ +def stage0 : MIR.Lowered.Module := + { entry := 9, + functions := [ + -- @balanceOf + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 7) .calldatasize [], + .pure 9 .lt [.value 7, .const 36], + .effect (some 11) .calldataload [.const 4], + .pure 13 .gt [.value 11, .const 0xffffffffffffffffffffffffffffffffffffffff], + .pure 25 .or [.value 9, .value 13]], + .branch (.value 25) 1 2⟩, + -- bb1 + ⟨[], + [], + .revert (.const 0) (.const 0)⟩, + -- bb2 + ⟨[], + [.effect none .mstore [.const 0, .value 11], + .effect none .mstore [.const 32, .const 0], + .effect (some 22) .keccak256 [.const 0, .const 64], + .effect (some 5) .sload [.value 22], + .effect none .mstore [.const 0, .value 5]], + .ret (.const 0) (.const 32)⟩] }, + -- @allowance + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 10) .calldatasize [], + .pure 12 .lt [.value 10, .const 68], + .effect (some 14) .calldataload [.const 4], + .pure 16 .gt [.value 14, .const 0xffffffffffffffffffffffffffffffffffffffff], + .pure 40 .or [.value 12, .value 16], + .effect (some 18) .calldataload [.const 36], + .pure 20 .gt [.value 18, .const 0xffffffffffffffffffffffffffffffffffffffff], + .pure 41 .or [.value 40, .value 20]], + .branch (.value 41) 1 2⟩, + -- bb1 + ⟨[], + [], + .revert (.const 0) (.const 0)⟩, + -- bb2 + ⟨[], + [.effect none .mstore [.const 0, .value 14], + .effect none .mstore [.const 32, .const 1], + .effect (some 30) .keccak256 [.const 0, .const 64], + .effect none .mstore [.const 0, .value 18], + .effect none .mstore [.const 32, .value 30], + .effect (some 35) .keccak256 [.const 0, .const 64], + .effect (some 8) .sload [.value 35], + .effect none .mstore [.const 0, .value 8]], + .ret (.const 0) (.const 32)⟩] }, + -- @getOwner + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 2) .sload [.const 4], + .pure 8 .and [.value 2, .const 0xffffffffffffffffffffffffffffffffffffffff], + .effect none .mstore [.const 0, .value 8]], + .ret (.const 0) (.const 32)⟩] }, + -- @isFrozen + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 10) .calldatasize [], + .pure 12 .lt [.value 10, .const 36], + .effect (some 14) .calldataload [.const 4], + .pure 16 .gt [.value 14, .const 0xffffffffffffffffffffffffffffffffffffffff], + .pure 33 .or [.value 12, .value 16]], + .branch (.value 33) 1 2⟩, + -- bb1 + ⟨[], + [], + .revert (.const 0) (.const 0)⟩, + -- bb2 + ⟨[], + [.effect none .mstore [.const 0, .value 14], + .effect none .mstore [.const 32, .const 2], + .effect (some 28) .keccak256 [.const 0, .const 64], + .effect (some 5) .sload [.value 28], + .pure 32 .and [.value 5, .const 255], + .ne 8 (.value 32) (.const 0), + .word 22 (.value 8), + .effect none .mstore [.const 0, .value 22]], + .ret (.const 0) (.const 32)⟩] }, + -- @freeze + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 17) .calldatasize [], + .pure 19 .lt [.value 17, .const 36], + .effect (some 21) .calldataload [.const 4], + .pure 23 .gt [.value 21, .const 0xffffffffffffffffffffffffffffffffffffffff], + .pure 35 .or [.value 19, .value 23]], + .branch (.value 35) 1 3⟩, + -- bb1 + ⟨[], + [], + .revert (.const 0) (.const 0)⟩, + -- bb2 + ⟨[], + [.effect none .mstore [.const 0, .value 21], + .effect none .mstore [.const 32, .const 2], + .effect (some 30) .keccak256 [.const 0, .const 64], + .effect none .sstore [.value 30, .const 1]], + .stop⟩, + -- bb3 + ⟨[], + [.effect (some 1) .caller [], + .effect (some 3) .sload [.const 4], + .pure 34 .and [.value 3, .const 0xffffffffffffffffffffffffffffffffffffffff], + .pure 5 .eq [.value 1, .value 34]], + .branch (.value 5) 2 1⟩] }, + -- @transfer + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 54) .calldatasize [], + .pure 56 .lt [.value 54, .const 68], + .effect (some 58) .calldataload [.const 4], + .pure 60 .gt [.value 58, .const 0xffffffffffffffffffffffffffffffffffffffff], + .pure 91 .or [.value 56, .value 60]], + .branch (.value 91) 1 7⟩, + -- bb1 + ⟨[], + [], + .revert (.const 0) (.const 0)⟩, + -- bb2 + ⟨[], + [.effect none .mstore [.const 0, .value 3], + .effect none .mstore [.const 32, .const 0], + .effect (some 76) .keccak256 [.const 0, .const 64], + .effect (some 18) .sload [.value 76], + .pure 19 .lt [.value 18, .value 62]], + .branch (.value 19) 3 4⟩, + -- bb3 + ⟨[], + [], + .tailCall 8 [.const 7, .const 0x62616c616e636500000000000000000000000000000000000000000000000000]⟩, + -- bb4 + ⟨[], + [.pure 29 .sub [.value 18, .value 62], + .effect none .sstore [.value 76, .value 29], + .effect none .mstore [.const 0, .value 58], + .effect (some 81) .keccak256 [.const 0, .const 64], + .effect (some 33) .sload [.value 81], + .pure 45 .add [.value 33, .value 62], + .pure 46 .lt [.value 45, .value 33]], + .branch (.value 46) 5 6⟩, + -- bb5 + ⟨[], + [.effect none .mstore [.const 32, .const 17], + .effect none .mstore [.const 0, .const 0x4e487b71]], + .revert (.const 28) (.const 36)⟩, + -- bb6 + ⟨[], + [.effect none .sstore [.value 81, .value 45], + .effect none .mstore [.const 0, .value 62], + .effect none (.log 3) [.const 0, .const 32, .const 0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef, .value 3, .value 58], + .effect none .mstore [.const 0, .const 1]], + .ret (.const 0) (.const 32)⟩, + -- bb7 + ⟨[], + [.effect (some 62) .calldataload [.const 36], + .effect (some 3) .caller [], + .effect none .mstore [.const 0, .value 3], + .effect none .mstore [.const 32, .const 2], + .effect (some 86) .keccak256 [.const 0, .const 64], + .effect (some 6) .sload [.value 86], + .pure 90 .and [.value 6, .const 255], + .ne 9 (.value 90) (.const 0)], + .branch (.value 9) 1 2⟩] }, + -- @approve + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 18) .calldatasize [], + .pure 20 .lt [.value 18, .const 68], + .effect (some 22) .calldataload [.const 4], + .pure 24 .gt [.value 22, .const 0xffffffffffffffffffffffffffffffffffffffff], + .pure 48 .or [.value 20, .value 24]], + .branch (.value 48) 1 2⟩, + -- bb1 + ⟨[], + [], + .revert (.const 0) (.const 0)⟩, + -- bb2 + ⟨[], + [.effect (some 26) .calldataload [.const 36], + .effect (some 3) .caller [], + .effect none .mstore [.const 0, .value 3], + .effect none .mstore [.const 32, .const 1], + .effect (some 40) .keccak256 [.const 0, .const 64], + .effect none .mstore [.const 0, .value 22], + .effect none .mstore [.const 32, .value 40], + .effect (some 45) .keccak256 [.const 0, .const 64], + .effect none .sstore [.value 45, .value 26], + .effect none .mstore [.const 0, .value 26], + .effect none (.log 3) [.const 0, .const 32, .const 0x8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925, .value 3, .value 22], + .effect none .mstore [.const 0, .const 1]], + .ret (.const 0) (.const 32)⟩] }, + -- @transferFrom + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 60) .calldatasize [], + .pure 62 .lt [.value 60, .const 100], + .effect (some 64) .calldataload [.const 4], + .pure 66 .gt [.value 64, .const 0xffffffffffffffffffffffffffffffffffffffff], + .pure 122 .or [.value 62, .value 66], + .effect (some 68) .calldataload [.const 36], + .pure 70 .gt [.value 68, .const 0xffffffffffffffffffffffffffffffffffffffff], + .pure 123 .or [.value 122, .value 70]], + .branch (.value 123) 5 9⟩, + -- bb1 + ⟨[], + [.pure 83 .not [.value 9], + .ne 16 (.value 83) (.const 0)], + .branch (.value 16) 3 2⟩, + -- bb2 + ⟨[], + [.effect none .mstore [.const 0, .value 64], + .effect none .mstore [.const 32, .const 0], + .effect (some 91) .keccak256 [.const 0, .const 64], + .effect (some 27) .sload [.value 91], + .pure 28 .lt [.value 27, .value 72]], + .branch (.value 28) 5 6⟩, + -- bb3 + ⟨[], + [.pure 17 .sub [.value 9, .value 72], + .effect none .mstore [.const 0, .value 64], + .effect none .mstore [.const 32, .const 1], + .effect (some 96) .keccak256 [.const 0, .const 64], + .effect none .mstore [.const 0, .value 6], + .effect none .mstore [.const 32, .value 96], + .effect (some 101) .keccak256 [.const 0, .const 64], + .effect none .sstore [.value 101, .value 17]], + .jump 2⟩, + -- bb4 + ⟨[], + [], + .tailCall 8 [.const 9, .const 0x616c6c6f77616e63650000000000000000000000000000000000000000000000]⟩, + -- bb5 + ⟨[], + [], + .revert (.const 0) (.const 0)⟩, + -- bb6 + ⟨[], + [.pure 37 .sub [.value 27, .value 72], + .effect none .sstore [.value 91, .value 37], + .effect none .mstore [.const 0, .value 68], + .effect (some 106) .keccak256 [.const 0, .const 64], + .effect (some 41) .sload [.value 106], + .pure 51 .add [.value 41, .value 72], + .pure 52 .lt [.value 51, .value 41]], + .branch (.value 52) 7 8⟩, + -- bb7 + ⟨[], + [.effect none .mstore [.const 32, .const 17], + .effect none .mstore [.const 0, .const 0x4e487b71]], + .revert (.const 28) (.const 36)⟩, + -- bb8 + ⟨[], + [.effect none .sstore [.value 106, .value 51], + .effect none .mstore [.const 0, .value 72], + .effect none (.log 3) [.const 0, .const 32, .const 0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef, .value 64, .value 68], + .effect none .mstore [.const 0, .const 1]], + .ret (.const 0) (.const 32)⟩, + -- bb9 + ⟨[], + [.effect (some 72) .calldataload [.const 68], + .effect none .mstore [.const 0, .value 64], + .effect none .mstore [.const 32, .const 1], + .effect (some 111) .keccak256 [.const 0, .const 64], + .effect (some 6) .caller [], + .effect none .mstore [.const 0, .value 6], + .effect none .mstore [.const 32, .value 111], + .effect (some 116) .keccak256 [.const 0, .const 64], + .effect (some 9) .sload [.value 116], + .pure 10 .lt [.value 9, .value 72]], + .branch (.value 10) 4 1⟩] }, + -- @revert_error + { params := [0, 1], + blocks := [ + -- bb0 + ⟨[], + [.effect none .mstore [.const 32, .const 32], + .effect none .mstore [.const 64, .value 0], + .effect none .mstore [.const 96, .value 1], + .effect none .mstore [.const 0, .const 0x8c379a0]], + .revert (.const 28) (.const 100)⟩] }, + -- @entry + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 0) .callvalue [], + .ne 2 (.value 0) (.const 0)], + .branch (.value 2) 10 1⟩, + -- bb1 + ⟨[], + [.effect (some 4) .calldataload [.const 0], + .pure 6 .shr [.const 224, .value 4]], + .switch (.value 6) 10 [(.const 0x95ea7b3, 2), (.const 0x23b872dd, 3), (.const 0x70a08231, 4), (.const 0x893d20e8, 5), (.const 0x8d1fdf2f, 6), (.const 0xa9059cbb, 7), (.const 0xdd62ed3e, 8), (.const 0xe5839836, 9)]⟩, + -- bb2 + ⟨[], + [], + .tailCall 6 []⟩, + -- bb3 + ⟨[], + [], + .tailCall 7 []⟩, + -- bb4 + ⟨[], + [], + .tailCall 0 []⟩, + -- bb5 + ⟨[], + [], + .tailCall 2 []⟩, + -- bb6 + ⟨[], + [], + .tailCall 4 []⟩, + -- bb7 + ⟨[], + [], + .tailCall 5 []⟩, + -- bb8 + ⟨[], + [], + .tailCall 1 []⟩, + -- bb9 + ⟨[], + [], + .tailCall 3 []⟩, + -- bb10 + ⟨[], + [], + .revert (.const 0) (.const 0)⟩] }] } + +end SolarTV.Export.Token diff --git a/Certified/token/gen/Token/manifest.json b/Certified/token/gen/Token/manifest.json new file mode 100644 index 00000000..6bbd825c --- /dev/null +++ b/Certified/token/gen/Token/manifest.json @@ -0,0 +1,170 @@ +{ + "arguments": [ + "solar-tv/milestone/token/token.sol", + "-Zcheck-analyses=false", + "-Ogas", + "--evm-version", + "osaka", + "--emit=bin-runtime", + "-Zemit-lean-stages=solar-tv/milestone/token/gen" + ], + "bytecode": "34603d575f3560e01c80638d1fdf2f1160535780638d1fdf2f14610114578063a9059cbb14610143578063dd62ed3e1460a4578063e58398361460eb575b5f5ffd5b6011602052634e487b715f526024601cfd5b8063095ea7b3146101f157806323b872dd1461024e57806370a08231146081578063893d20e81460db575f5ffd5b60043560a01c6024361017603d576004355f525f60205260405f20545f5260205ff35b60043560a01c604436101760243560a01c17603d576004355f52600160205260405f206024355f5260205260405f20545f5260205ff35b60045460601b60601c5f5260205ff35b60043560a01c6024361017603d576004355f52600260205260405f205460ff165f105f5260205ff35b60043560a01c6024361017603d5760045460601b60601c3303603d576004355f526002602052600160405f2055005b60043560a01c6044361017603d57335f52600260205260405f205460ff16603d57602435335f525f60205260405f2080548281106101cc5760043583909103909155805f5260405f2080548381019081106041579055905f52335b7fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef60205fa360015f5260205ff35b6662616c616e636560c81b60075b602080526040526060526308c379a05f526064601cfd5b60043560a01c6044361017603d57600435602435335f52600160205260405f20825f526020528060405f20555f52337f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b92560205fa360015f5260205ff35b60043560a01c606436101760243560a01c17603d57600435604435815f52600160205260405f20335f5260205260405f20548181106102e5578019156102aa57819003825f52600160205260405f20335f5260205260405f20555f5b50815f525f60205260405f208054828110603d5760243583909103909155805f5260405f2080548381019081106041579055905f529061019e565b68616c6c6f77616e636560b81b60096101da56", + "bytecode_sha256": "b6f1c3ab69651bb080d1ac406be62499ca6ba82de76bb1d203a7619404b2c799", + "compiler": "0.8.38+commit.3ca8f483.solar.0.3.0-dev", + "contract": "Token", + "evm_version": "osaka", + "optimization": "Gas", + "options": "CompileOpts { input: [\"solar-tv/milestone/token/token.sol\"], import_remappings: [], base_path: None, include_paths: [], allow_paths: [], no_import_callback: false, language: Solidity, threads: 4, evm_version: Osaka, stop_after: None, optimization: Gas, optimizer_runs: None, revert_strings: Default, libraries: [], out_dir: None, emit: [BinRuntime], standard_json: false, color: Auto, verbose: false, pretty_json: false, pretty_json_err: false, error_format: Human, error_format_human: Unicode, diagnostic_width: None, no_warnings: false, allow: [], _unstable: [\"check-analyses=false\", \"emit-lean-stages=solar-tv/milestone/token/gen\"], unstable: UnstableOpts { ui_testing: false, track_diagnostics: false, parse_yul: false, no_resolve_imports: false, recover_incomplete_input: false, dump: None, ast_stats: false, hir_stats: false, standard_json_stats: false, span_visitor: false, print_max_storage_sizes: false, print_natspec: false, mir_pipeline: None, evm_ir_pipeline: None, print_after_each: false, pass_diff: false, debugify: None, debugify_output: None, solar_tv: None, validate_ir: None, time_passes: false, codegen_all_functions: false, switch_lowering: Auto, switch_max_gas_code_growth: None, switch_max_bit_slice_gas_code_growth: None, tune: None, pack_wide_jump_tables: false, check_analyses: Some(false), prove_analyses: None, validate_passes: None, validate_passes_fault: None, validate_backend: None, validate_backend_fault: None, validate_evm_ir_passes: None, validate_assembly: false, validate_assembly_fault: None, emit_lean_stages: Some(\"solar-tv/milestone/token/gen\"), forget_gcx: true, help: (), _non_exhaustive: () }, _non_exhaustive: () }", + "sources": [ + { + "path": "solar-tv/milestone/token/token.sol", + "sha256": "bcaef611c02d565045174ebd565915bb263dee0051ae1ed9c3f201a7b379ba49" + } + ], + "stages": [ + { + "definition": "stage0", + "file": "Stage0.lean", + "index": 0, + "kind": "mir", + "pass": "lower-evm-shaped", + "sha256": "ee5ac4da11360b8a720da813980026173daf36a950c8bff96dfe04fd096f3dae" + }, + { + "definition": "mir1", + "file": "Mir1.lean", + "index": 1, + "kind": "mir", + "pass": "place-reads", + "sha256": "f5714ae419249883c2bd3fae0ee5267adbc1aa22690598e6c14af4e5cf1254f6" + }, + { + "definition": "mir2", + "file": "Mir2.lean", + "index": 2, + "kind": "mir", + "pass": "dce", + "sha256": "0007c3dcab3c1def1f9b6b5cc82d8fc63caade8c33abd011cd1ef6efa35cd69c" + }, + { + "definition": "mir3", + "file": "Mir3.lean", + "index": 3, + "kind": "mir", + "pass": "spell-width-tests", + "sha256": "9a158109c011f9766516e98e4604efdaa16a67ffdd0ff27ad796ae81c232b125" + }, + { + "definition": "mir4", + "file": "Mir4.lean", + "index": 4, + "kind": "mir", + "pass": "evm-inst-schedule", + "sha256": "5cd8c51fba856102b03c9226dc274ba35b7cbc927d411af54f3db29f33507aed" + }, + { + "definition": "sched", + "file": "Sched.lean", + "index": 0, + "kind": "sched", + "pass": "stack-schedule", + "sha256": "c4b9d1fe5e4638eb10dc3df4b0fc22e4e4cb8bb1b8a5e385b323a6be6d928083" + }, + { + "definition": "evm1", + "file": "Evm1.lean", + "index": 1, + "kind": "evm", + "pass": "peephole-early", + "sha256": "11b76b2099bbc1423db31e2474b2f286de92c9136a05ff529656bb8877015402" + }, + { + "definition": "evm2", + "file": "Evm2.lean", + "index": 2, + "kind": "evm", + "pass": "cfg-simplify-early", + "sha256": "0a859fb8bcb2d2710ddc2b95fec963aee15b614e150450c7871cbb9c6940362e" + }, + { + "definition": "evm3", + "file": "Evm3.lean", + "index": 3, + "kind": "evm", + "pass": "compact-pushes", + "sha256": "a29749e0fd010f50692f610c32166c21fcf9c3e38cc2bfdfa973993a44477066" + }, + { + "definition": "evm4", + "file": "Evm4.lean", + "index": 4, + "kind": "evm", + "pass": "block-layout", + "sha256": "771c03b44c4591af745bc39f7457a4dcfcb08f08e0e931cd9ad5ea8dee85a741" + }, + { + "definition": "evm5", + "file": "Evm5.lean", + "index": 5, + "kind": "evm", + "pass": "terminal-dedup", + "sha256": "0bfecc06a0c31f1b7af8127cb6539ce472c24d20990ee1e4644d651ed57d9d35" + }, + { + "definition": "evm6", + "file": "Evm6.lean", + "index": 6, + "kind": "evm", + "pass": "cfg-simplify-early", + "sha256": "372d04f924adf83eb02b18aec69d7da55fca4a4284c6c00c0f1d075fd6e42c03" + }, + { + "definition": "evm7", + "file": "Evm7.lean", + "index": 7, + "kind": "evm", + "pass": "tail-merge", + "sha256": "a24d14ce51d3ad577aa4137b3411769bd800660cf686f76d9d1587d81a90aa4e" + }, + { + "definition": "evm8", + "file": "Evm8.lean", + "index": 8, + "kind": "evm", + "pass": "block-cse", + "sha256": "57502e10fe2ca03c518197e933f775c534a9df631838e10f7e4a4bac4f868437" + }, + { + "definition": "evm9", + "file": "Evm9.lean", + "index": 9, + "kind": "evm", + "pass": "block-layout", + "sha256": "2d4aacefe0e2d239ba16713a5ec11532c96f7aeb88cfb596989fc1df0e3b80aa" + }, + { + "definition": "evm10", + "file": "Evm10.lean", + "index": 10, + "kind": "evm", + "pass": "inline-returns", + "sha256": "8be69fbd3957fcf9778243c6e11494863ee2e49be3679c42735f36f4fe16483e" + }, + { + "definition": "evm11", + "file": "Evm11.lean", + "index": 11, + "kind": "evm", + "pass": "late-word", + "sha256": "0d4543ec8e2fbc48bb8a138716f4001a82c2fd93c6ed640e4de61e009dd92dfc" + }, + { + "definition": "bytecode", + "file": "Bytecode.lean", + "index": 0, + "kind": "bytecode", + "pass": "assemble", + "sha256": "76a07c0351a33c21912a45d1cd1db48b2ec7a089d12f1d12c2e77b2041f94c9e" + } + ] +} diff --git a/Certified/token/options b/Certified/token/options new file mode 100644 index 00000000..db0d7d53 --- /dev/null +++ b/Certified/token/options @@ -0,0 +1,4 @@ +-Zcheck-analyses=false +-Ogas +--evm-version +osaka diff --git a/Certified/token/token.sol b/Certified/token/token.sol new file mode 100644 index 00000000..cb5efea6 --- /dev/null +++ b/Certified/token/token.sol @@ -0,0 +1,60 @@ +contract Token { + mapping(address => uint256) balances; + mapping(address => mapping(address => uint256)) allowances; + mapping(address => bool) frozen; + uint256 totalSupply; + address owner; + + event Transfer(address indexed from, address indexed to, uint256 value); + event Approval(address indexed owner, address indexed spender, uint256 value); + + function balanceOf(address who) external view returns (uint256) { + return balances[who]; + } + + function allowance(address holder, address spender) external view returns (uint256) { + return allowances[holder][spender]; + } + + function getOwner() external view returns (address) { + return owner; + } + + function isFrozen(address who) external view returns (bool) { + return frozen[who]; + } + + function freeze(address who) external { + require(msg.sender == owner); + frozen[who] = true; + } + + function transfer(address to, uint256 value) external returns (bool) { + require(!frozen[msg.sender]); + require(balances[msg.sender] >= value, "balance"); + balances[msg.sender] -= value; + balances[to] += value; + emit Transfer(msg.sender, to, value); + return true; + } + + function approve(address spender, uint256 value) external returns (bool) { + allowances[msg.sender][spender] = value; + emit Approval(msg.sender, spender, value); + return true; + } + + function transferFrom(address from, address to, uint256 value) external returns (bool) { + uint256 a = allowances[from][msg.sender]; + if (a < value) { + revert("allowance"); + } else if (a != type(uint256).max) { + allowances[from][msg.sender] = a - value; + } + require(balances[from] >= value); + balances[from] -= value; + balances[to] += value; + emit Transfer(from, to, value); + return true; + } +} diff --git a/Certified/w1/W1.lean b/Certified/w1/W1.lean new file mode 100644 index 00000000..401f3b38 --- /dev/null +++ b/Certified/w1/W1.lean @@ -0,0 +1,2 @@ +import gen.Stages +import W1.Sanity diff --git a/Certified/w1/W1/Sanity.lean b/Certified/w1/W1/Sanity.lean new file mode 100644 index 00000000..bd070472 --- /dev/null +++ b/Certified/w1/W1/Sanity.lean @@ -0,0 +1,110 @@ +import gen.Stages + +/-! Each exported artifact of w1 run in Lean on concrete calls. + +Every artifact, from the first lowered MIR to the final EVM IR, observes the same result on +each call below: a valid addition returns the sum, an overflowing one reverts with +`Panic(0x11)`, a call with value, an unknown selector and short calldata revert empty. The +results are checked by the kernel (`decide +kernel`), with no native evaluation; the oracle is +irrelevant here, since w1 reads nothing from it. -/ + +namespace SolarTV.Milestone.W1.Sanity + +open SolarTV Machine EvmRules + +/-- An oracle that answers zero, for solidity-lean's test caller. -/ +def oracle : Oracle := + ⟨fun _ _ _ => 0, fun _ => 0, fun _ _ => 0, fun _ _ => 0, fun _ => 0, + BitVec.ofNat 160 environment.caller⟩ + +/-- The big-endian 32 bytes of a word. -/ +def word (n : Nat) : List UInt8 := (List.range 32).map fun i => UInt8.ofNat (n / 256 ^ (31 - i)) + +/-- A call of `f(a, b)`, selector `0x13d1aa2e`, with `value` wei and the selector `selector`. -/ +def call (a b : Nat) (value : Nat := 0) (selector : List UInt8 := [0x13, 0xd1, 0xaa, 0x2e]) : + Call := + ⟨⟨(selector ++ word a ++ word b).toArray⟩, value, []⟩ + +/-- A call whose calldata is only the selector and one argument. -/ +def short : Call := ⟨⟨([0x13, 0xd1, 0xaa, 0x2e] ++ word 1).toArray⟩, 0, []⟩ + +/-- Success and output of an end, as `observe` gives them. -/ +def outcome (c : Call) : Option (Halt × State) → Option (Bool × List Nat) + | some r => some ((observe c r.2 r.1).success, (observe c r.2 r.1).output) + | none => none + +def mir (m : MIR.Lowered.Module) (c : Call) : Option (Bool × List Nat) := + outcome c (MIR.Lowered.Module.run oracle m c 16) + +def evm (p : EVM.Program.Program) (c : Call) : Option (Bool × List Nat) := + outcome c (EVM.Program.run oracle p c 32) + +def sum : Option (Bool × List Nat) := some (true, List.replicate 31 0 ++ [3]) + +def panic : Option (Bool × List Nat) := + some (false, [0x4e, 0x48, 0x7b, 0x71] ++ List.replicate 31 0 ++ [0x11]) + +def empty : Option (Bool × List Nat) := some (false, []) + +def max : Nat := 2 ^ 256 - 1 + +/-! The first lowered MIR. -/ + +theorem stage0_sum : mir Export.Main.stage0 (call 1 2) = sum := by decide +kernel +theorem stage0_overflow : mir Export.Main.stage0 (call max 1) = panic := by decide +kernel +theorem stage0_value : mir Export.Main.stage0 (call 1 2 (value := 1)) = empty := by decide +kernel +theorem stage0_selector : + mir Export.Main.stage0 (call 1 2 (selector := [0, 0, 0, 0])) = empty := by decide +kernel +theorem stage0_short : mir Export.Main.stage0 short = empty := by decide +kernel + +/-! The scheduled EVM IR and the output of every EVM IR pass. -/ + +theorem sched_sum : evm Export.Main.sched (call 1 2) = sum := by decide +kernel +theorem sched_overflow : evm Export.Main.sched (call max 1) = panic := by decide +kernel +theorem sched_value : evm Export.Main.sched (call 1 2 (value := 1)) = empty := by decide +kernel +theorem sched_selector : + evm Export.Main.sched (call 1 2 (selector := [0, 0, 0, 0])) = empty := by decide +kernel +theorem sched_short : evm Export.Main.sched short = empty := by decide +kernel + +theorem evm1_sum : evm Export.Main.evm1 (call 1 2) = sum := by decide +kernel +theorem evm1_overflow : evm Export.Main.evm1 (call max 1) = panic := by decide +kernel +theorem evm2_sum : evm Export.Main.evm2 (call 1 2) = sum := by decide +kernel +theorem evm2_overflow : evm Export.Main.evm2 (call max 1) = panic := by decide +kernel +theorem evm3_sum : evm Export.Main.evm3 (call 1 2) = sum := by decide +kernel +theorem evm3_overflow : evm Export.Main.evm3 (call max 1) = panic := by decide +kernel +theorem evm4_sum : evm Export.Main.evm4 (call 1 2) = sum := by decide +kernel +theorem evm4_overflow : evm Export.Main.evm4 (call max 1) = panic := by decide +kernel +theorem evm4_value : evm Export.Main.evm4 (call 1 2 (value := 1)) = empty := by decide +kernel +theorem evm4_selector : + evm Export.Main.evm4 (call 1 2 (selector := [0, 0, 0, 0])) = empty := by decide +kernel +theorem evm4_short : evm Export.Main.evm4 short = empty := by decide +kernel + +/-! The checks tell programs apart: entering `@f` directly skips the value and selector +checks, and dropping the panic block makes an overflow stop with success instead. -/ + +/-- `stage0` entered at `@f` instead of the dispatcher. -/ +def withoutDispatch : MIR.Lowered.Module := { Export.Main.stage0 with entry := 0 } + +theorem withoutDispatch_value : mir withoutDispatch (call 1 2 (value := 1)) = sum := by + decide +kernel + +/-- `evm4` without its last block, the panic. -/ +def withoutPanic : EVM.Program.Program := ⟨Export.Main.evm4.blocks.take 2⟩ + +theorem withoutPanic_overflow : evm withoutPanic (call max 1) = some (true, []) := by + decide +kernel + +/-! The bytecode is the manifest's. -/ + +theorem bytecode_manifest : Export.Main.bytecodeHex = Export.Main.Manifest.bytecodeHex := rfl + +/-- info: 'SolarTV.Milestone.W1.Sanity.stage0_overflow' depends on axioms: [propext, Quot.sound] -/ +#guard_msgs in +#print axioms stage0_overflow + +/-- info: 'SolarTV.Milestone.W1.Sanity.evm4_overflow' depends on axioms: [propext, Quot.sound] -/ +#guard_msgs in +#print axioms evm4_overflow + +end SolarTV.Milestone.W1.Sanity + diff --git a/Certified/w1/gen/Main/Bytecode.lean b/Certified/w1/gen/Main/Bytecode.lean new file mode 100644 index 00000000..4308d748 --- /dev/null +++ b/Certified/w1/gen/Main/Bytecode.lean @@ -0,0 +1,18 @@ +-- solar-lean-stage: kind=bytecode index=0 pass=assemble +/-! Generated by `solar -Zemit-lean-stages` for `Main`; do not edit. -/ + +namespace SolarTV.Export.Main + +/-- The runtime bytecode, byte by byte. -/ +def bytecode : List Nat := + [0x34, 0x60, 0x2e, 0x57, 0x5f, 0x35, 0x60, 0xe0, 0x1c, 0x80, 0x63, 0x13, 0xd1, 0xaa, 0x2e, 0x03, + 0x60, 0x2e, 0x57, 0x60, 0x44, 0x36, 0x10, 0x60, 0x2e, 0x57, 0x60, 0x04, 0x35, 0x60, 0x24, 0x35, + 0x81, 0x01, 0x90, 0x81, 0x10, 0x60, 0x32, 0x57, 0x5f, 0x52, 0x60, 0x20, 0x5f, 0xf3, 0x5b, 0x5f, + 0x5f, 0xfd, 0x5b, 0x60, 0x11, 0x60, 0x20, 0x52, 0x63, 0x4e, 0x48, 0x7b, 0x71, 0x5f, 0x52, 0x60, + 0x24, 0x60, 0x1c, 0xfd] + +/-- The runtime bytecode in hex, as `--emit=bin-runtime` prints it. -/ +def bytecodeHex : String := + "34602e575f3560e01c806313d1aa2e03602e5760443610602e5760043560243581019081106032575f5260205ff35b5f5ffd5b6011602052634e487b715f526024601cfd" + +end SolarTV.Export.Main diff --git a/Certified/w1/gen/Main/Evm1.lean b/Certified/w1/gen/Main/Evm1.lean new file mode 100644 index 00000000..ea4696ca --- /dev/null +++ b/Certified/w1/gen/Main/Evm1.lean @@ -0,0 +1,62 @@ +-- solar-lean-stage: kind=evm index=1 pass=cfg-simplify-early +import SolarTV.EVMIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `Main`; do not edit. -/ + +namespace SolarTV.Export.Main + +/-- The runtime EVM IR after `cfg-simplify-early`. -/ +def evm1 : EVM.Program.Program := + { blocks := [ + -- bb0 + [.effect .callvalue 0, + .jumpi 1, + .op (.stack (.push 0)), + .effect .calldataload 1, + .op (.stack (.push 224)), + .op (.stack .shr), + .op (.stack (.dup 0)), + .op (.stack (.push 0x13d1aa2e)), + .op (.stack .eq), + .jumpi 2, + .jump 1], + -- bb3 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb4 + [.op (.stack (.push 68)), + .op (.stack .calldatasize), + .op (.stack .lt), + .jumpi 4, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 36)), + .effect .calldataload 1, + .op (.stack (.dup 1)), + .op (.stack .add), + .op (.stack (.swap 0)), + .op (.stack (.dup 1)), + .op (.stack .lt), + .jumpi 3, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb7 + [.op (.stack (.push 17)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 0x4e487b71)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 36)), + .op (.stack (.push 28)), + .revert], + -- bb8 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert]] } + +end SolarTV.Export.Main diff --git a/Certified/w1/gen/Main/Evm2.lean b/Certified/w1/gen/Main/Evm2.lean new file mode 100644 index 00000000..ebf688d4 --- /dev/null +++ b/Certified/w1/gen/Main/Evm2.lean @@ -0,0 +1,62 @@ +-- solar-lean-stage: kind=evm index=2 pass=share-reverts +import SolarTV.EVMIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `Main`; do not edit. -/ + +namespace SolarTV.Export.Main + +/-- The runtime EVM IR after `share-reverts`. -/ +def evm2 : EVM.Program.Program := + { blocks := [ + -- bb0 + [.effect .callvalue 0, + .jumpi 1, + .op (.stack (.push 0)), + .effect .calldataload 1, + .op (.stack (.push 224)), + .op (.stack .shr), + .op (.stack (.dup 0)), + .op (.stack (.push 0x13d1aa2e)), + .op (.stack .sub), + .jumpi 1, + .jump 2], + -- bb3 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb4 + [.op (.stack (.push 68)), + .op (.stack .calldatasize), + .op (.stack .lt), + .jumpi 4, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 36)), + .effect .calldataload 1, + .op (.stack (.dup 1)), + .op (.stack .add), + .op (.stack (.swap 0)), + .op (.stack (.dup 1)), + .op (.stack .lt), + .jumpi 3, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb7 + [.op (.stack (.push 17)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 0x4e487b71)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 36)), + .op (.stack (.push 28)), + .revert], + -- bb8 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert]] } + +end SolarTV.Export.Main diff --git a/Certified/w1/gen/Main/Evm3.lean b/Certified/w1/gen/Main/Evm3.lean new file mode 100644 index 00000000..62217667 --- /dev/null +++ b/Certified/w1/gen/Main/Evm3.lean @@ -0,0 +1,60 @@ +-- solar-lean-stage: kind=evm index=3 pass=terminal-dedup +import SolarTV.EVMIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `Main`; do not edit. -/ + +namespace SolarTV.Export.Main + +/-- The runtime EVM IR after `terminal-dedup`. -/ +def evm3 : EVM.Program.Program := + { blocks := [ + -- bb0 + [.effect .callvalue 0, + .jumpi 1, + .op (.stack (.push 0)), + .effect .calldataload 1, + .op (.stack (.push 224)), + .op (.stack .shr), + .op (.stack (.dup 0)), + .op (.stack (.push 0x13d1aa2e)), + .op (.stack .sub), + .jumpi 1, + .jump 2], + -- bb3 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb4 + [.op (.stack (.push 68)), + .op (.stack .calldatasize), + .op (.stack .lt), + .jumpi 4, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 36)), + .effect .calldataload 1, + .op (.stack (.dup 1)), + .op (.stack .add), + .op (.stack (.swap 0)), + .op (.stack (.dup 1)), + .op (.stack .lt), + .jumpi 3, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb7 + [.op (.stack (.push 17)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 0x4e487b71)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 36)), + .op (.stack (.push 28)), + .revert], + -- bb8 + [.jump 1]] } + +end SolarTV.Export.Main diff --git a/Certified/w1/gen/Main/Evm4.lean b/Certified/w1/gen/Main/Evm4.lean new file mode 100644 index 00000000..2c9e6e8f --- /dev/null +++ b/Certified/w1/gen/Main/Evm4.lean @@ -0,0 +1,56 @@ +-- solar-lean-stage: kind=evm index=4 pass=cfg-simplify-early +import SolarTV.EVMIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `Main`; do not edit. -/ + +namespace SolarTV.Export.Main + +/-- The runtime EVM IR after `cfg-simplify-early`. -/ +def evm4 : EVM.Program.Program := + { blocks := [ + -- bb0 + [.effect .callvalue 0, + .jumpi 1, + .op (.stack (.push 0)), + .effect .calldataload 1, + .op (.stack (.push 224)), + .op (.stack .shr), + .op (.stack (.dup 0)), + .op (.stack (.push 0x13d1aa2e)), + .op (.stack .sub), + .jumpi 1, + .op (.stack (.push 68)), + .op (.stack .calldatasize), + .op (.stack .lt), + .jumpi 1, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 36)), + .effect .calldataload 1, + .op (.stack (.dup 1)), + .op (.stack .add), + .op (.stack (.swap 0)), + .op (.stack (.dup 1)), + .op (.stack .lt), + .jumpi 2, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb3 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb7 + [.op (.stack (.push 17)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 0x4e487b71)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 36)), + .op (.stack (.push 28)), + .revert]] } + +end SolarTV.Export.Main diff --git a/Certified/w1/gen/Main/Manifest.lean b/Certified/w1/gen/Main/Manifest.lean new file mode 100644 index 00000000..3c6b5e67 --- /dev/null +++ b/Certified/w1/gen/Main/Manifest.lean @@ -0,0 +1,41 @@ +-- solar-lean-stage: kind=manifest index=0 pass=none +/-! Generated by `solar -Zemit-lean-stages` for `Main`; do not edit. + +What the stages of this directory were compiled from and by. `stages` lists each +stage's file, its definition, the pass whose output it is, and the SHA-256 of the file. +-/ + +namespace SolarTV.Export.Main.Manifest + +def sources : List (String × String) := + [("solar-tv/milestone/w1/w1.sol", "e117e9ffe35bad0e8f1c0968146f9f99c8a4e5822787334f2591f0b1f6a46947")] + +def compiler : String := "0.8.38+commit.3ca8f483.solar.0.3.0-dev" + +def arguments : List String := + ["solar-tv/milestone/w1/w1.sol", + "-Ogas", + "--evm-version", + "osaka", + "--emit=bin-runtime", + "-Zemit-lean-stages=solar-tv/milestone/w1/gen"] + +def evmVersion : String := "osaka" + +def optimization : String := "Gas" + +def stages : List (String × String × String × String) := + [("Stage0", "stage0", "lower-evm-shaped", "fdf061c02c61572edabc120fbbae3199153ef03ff8dd1ba8f595732d915b2393"), + ("Sched", "sched", "stack-schedule", "c71694c03284f20688a387320b8274e1170d77e0144f942367063144aaf99b1c"), + ("Evm1", "evm1", "cfg-simplify-early", "9e2485b2fe109ce18c3a766cf61c72feb289ad77047d412a52c547f593851894"), + ("Evm2", "evm2", "share-reverts", "d48b6f1604cfa19d47510ea36cc03a0d6aab015d3116b3a2d876997018d9276a"), + ("Evm3", "evm3", "terminal-dedup", "67e313735720516f937146b9c9e6ac89ef731521eb34d66410a0945ac815bf43"), + ("Evm4", "evm4", "cfg-simplify-early", "6b1aace8993d2a8e277f8a60f7a9053df13f8d86e2e1b4416b639bbac7647529"), + ("Bytecode", "bytecode", "assemble", "d3e9cc2eda568f223b58d3c4cb380fc2929a0c0fb4dfa2277f570cf65c35b50a")] + +def bytecodeHex : String := + "34602e575f3560e01c806313d1aa2e03602e5760443610602e5760043560243581019081106032575f5260205ff35b5f5ffd5b6011602052634e487b715f526024601cfd" + +def bytecodeSha256 : String := "24d2438e4d77b39b2530aac7af63774b10576eabc3c093d282620ab44403778b" + +end SolarTV.Export.Main.Manifest diff --git a/Certified/w1/gen/Main/Sched.lean b/Certified/w1/gen/Main/Sched.lean new file mode 100644 index 00000000..7aa00560 --- /dev/null +++ b/Certified/w1/gen/Main/Sched.lean @@ -0,0 +1,70 @@ +-- solar-lean-stage: kind=sched index=0 pass=stack-schedule +import SolarTV.EVMIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `Main`; do not edit. -/ + +namespace SolarTV.Export.Main + +/-- The runtime EVM IR as stack scheduling emits it. -/ +def sched : EVM.Program.Program := + { blocks := [ + -- bb0 + [.effect .callvalue 0, + .jumpi 3, + .jump 1], + -- bb1 + [.op (.stack (.push 0)), + .effect .calldataload 1, + .op (.stack (.push 224)), + .op (.stack .shr), + .op (.stack (.dup 0)), + .op (.stack (.push 0x13d1aa2e)), + .op (.stack .eq), + .jumpi 2, + .jump 3], + -- bb2 + [.jump 4], + -- bb3 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb4 + [.op (.stack (.push 68)), + .op (.stack .calldatasize), + .op (.stack .lt), + .jumpi 8, + .jump 5], + -- bb5 + [.op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 36)), + .effect .calldataload 1, + .op (.stack (.dup 1)), + .op (.stack .add), + .op (.stack (.swap 0)), + .op (.stack (.dup 1)), + .op (.stack .lt), + .jumpi 7, + .jump 6], + -- bb6 + [.op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb7 + [.op (.stack (.push 17)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 0x4e487b71)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 36)), + .op (.stack (.push 28)), + .revert], + -- bb8 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert]] } + +end SolarTV.Export.Main diff --git a/Certified/w1/gen/Main/Stage0.lean b/Certified/w1/gen/Main/Stage0.lean new file mode 100644 index 00000000..0f88c77c --- /dev/null +++ b/Certified/w1/gen/Main/Stage0.lean @@ -0,0 +1,62 @@ +-- solar-lean-stage: kind=mir index=0 pass=lower-evm-shaped +import SolarTV.MIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `Main`; do not edit. -/ + +namespace SolarTV.Export.Main + +/-- The first lowered MIR module, after `lower-evm-shaped` advanced the phase. -/ +def stage0 : MIR.Lowered.Module := + { entry := 1, + functions := [ + -- @f + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 13) .calldatasize [], + .pure 15 .lt [.value 13, .const 68]], + .branch (.value 15) 3 4⟩, + -- bb1 + ⟨[], + [.effect none .mstore [.const 32, .const 17], + .effect none .mstore [.const 0, .const 0x4e487b71]], + .revert (.const 28) (.const 36)⟩, + -- bb2 + ⟨[], + [.effect none .mstore [.const 0, .value 4]], + .ret (.const 0) (.const 32)⟩, + -- bb3 + ⟨[], + [], + .revert (.const 0) (.const 0)⟩, + -- bb4 + ⟨[], + [.effect (some 17) .calldataload [.const 4], + .effect (some 19) .calldataload [.const 36], + .pure 4 .add [.value 17, .value 19], + .pure 5 .lt [.value 4, .value 17]], + .branch (.value 5) 1 2⟩] }, + -- @entry + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 0) .callvalue [], + .ne 2 (.value 0) (.const 0)], + .branch (.value 2) 3 1⟩, + -- bb1 + ⟨[], + [.effect (some 4) .calldataload [.const 0], + .pure 6 .shr [.const 224, .value 4]], + .switch (.value 6) 3 [(.const 0x13d1aa2e, 2)]⟩, + -- bb2 + ⟨[], + [], + .tailCall 0 []⟩, + -- bb3 + ⟨[], + [], + .revert (.const 0) (.const 0)⟩] }] } + +end SolarTV.Export.Main diff --git a/Certified/w1/gen/Main/manifest.json b/Certified/w1/gen/Main/manifest.json new file mode 100644 index 00000000..54e35418 --- /dev/null +++ b/Certified/w1/gen/Main/manifest.json @@ -0,0 +1,81 @@ +{ + "arguments": [ + "solar-tv/milestone/w1/w1.sol", + "-Ogas", + "--evm-version", + "osaka", + "--emit=bin-runtime", + "-Zemit-lean-stages=solar-tv/milestone/w1/gen" + ], + "bytecode": "34602e575f3560e01c806313d1aa2e03602e5760443610602e5760043560243581019081106032575f5260205ff35b5f5ffd5b6011602052634e487b715f526024601cfd", + "bytecode_sha256": "24d2438e4d77b39b2530aac7af63774b10576eabc3c093d282620ab44403778b", + "compiler": "0.8.38+commit.3ca8f483.solar.0.3.0-dev", + "contract": "Main", + "evm_version": "osaka", + "optimization": "Gas", + "options": "CompileOpts { input: [\"solar-tv/milestone/w1/w1.sol\"], import_remappings: [], base_path: None, include_paths: [], allow_paths: [], no_import_callback: false, language: Solidity, threads: 4, evm_version: Osaka, stop_after: None, optimization: Gas, optimizer_runs: None, revert_strings: Default, libraries: [], out_dir: None, emit: [BinRuntime], standard_json: false, color: Auto, verbose: false, pretty_json: false, pretty_json_err: false, error_format: Human, error_format_human: Unicode, diagnostic_width: None, no_warnings: false, allow: [], _unstable: [\"emit-lean-stages=solar-tv/milestone/w1/gen\"], unstable: UnstableOpts { ui_testing: false, track_diagnostics: false, parse_yul: false, no_resolve_imports: false, recover_incomplete_input: false, dump: None, ast_stats: false, hir_stats: false, standard_json_stats: false, span_visitor: false, print_max_storage_sizes: false, print_natspec: false, mir_pipeline: None, evm_ir_pipeline: None, print_after_each: false, pass_diff: false, debugify: None, debugify_output: None, solar_tv: None, validate_ir: None, time_passes: false, codegen_all_functions: false, switch_lowering: Auto, switch_max_gas_code_growth: None, switch_max_bit_slice_gas_code_growth: None, tune: None, pack_wide_jump_tables: false, check_analyses: None, prove_analyses: None, validate_passes: None, validate_passes_fault: None, validate_backend: None, validate_backend_fault: None, validate_evm_ir_passes: None, validate_assembly: false, validate_assembly_fault: None, emit_lean_stages: Some(\"solar-tv/milestone/w1/gen\"), forget_gcx: true, help: (), _non_exhaustive: () }, _non_exhaustive: () }", + "sources": [ + { + "path": "solar-tv/milestone/w1/w1.sol", + "sha256": "e117e9ffe35bad0e8f1c0968146f9f99c8a4e5822787334f2591f0b1f6a46947" + } + ], + "stages": [ + { + "definition": "stage0", + "file": "Stage0.lean", + "index": 0, + "kind": "mir", + "pass": "lower-evm-shaped", + "sha256": "fdf061c02c61572edabc120fbbae3199153ef03ff8dd1ba8f595732d915b2393" + }, + { + "definition": "sched", + "file": "Sched.lean", + "index": 0, + "kind": "sched", + "pass": "stack-schedule", + "sha256": "c71694c03284f20688a387320b8274e1170d77e0144f942367063144aaf99b1c" + }, + { + "definition": "evm1", + "file": "Evm1.lean", + "index": 1, + "kind": "evm", + "pass": "cfg-simplify-early", + "sha256": "9e2485b2fe109ce18c3a766cf61c72feb289ad77047d412a52c547f593851894" + }, + { + "definition": "evm2", + "file": "Evm2.lean", + "index": 2, + "kind": "evm", + "pass": "share-reverts", + "sha256": "d48b6f1604cfa19d47510ea36cc03a0d6aab015d3116b3a2d876997018d9276a" + }, + { + "definition": "evm3", + "file": "Evm3.lean", + "index": 3, + "kind": "evm", + "pass": "terminal-dedup", + "sha256": "67e313735720516f937146b9c9e6ac89ef731521eb34d66410a0945ac815bf43" + }, + { + "definition": "evm4", + "file": "Evm4.lean", + "index": 4, + "kind": "evm", + "pass": "cfg-simplify-early", + "sha256": "6b1aace8993d2a8e277f8a60f7a9053df13f8d86e2e1b4416b639bbac7647529" + }, + { + "definition": "bytecode", + "file": "Bytecode.lean", + "index": 0, + "kind": "bytecode", + "pass": "assemble", + "sha256": "d3e9cc2eda568f223b58d3c4cb380fc2929a0c0fb4dfa2277f570cf65c35b50a" + } + ] +} diff --git a/Certified/w1/gen/Stages.lean b/Certified/w1/gen/Stages.lean new file mode 100644 index 00000000..f319dccc --- /dev/null +++ b/Certified/w1/gen/Stages.lean @@ -0,0 +1,9 @@ +-- Generated by gen.sh from Main/manifest.json; do not edit. +import gen.Main.Stage0 +import gen.Main.Sched +import gen.Main.Evm1 +import gen.Main.Evm2 +import gen.Main.Evm3 +import gen.Main.Evm4 +import gen.Main.Bytecode +import gen.Main.Manifest diff --git a/Certified/w1/w1.sol b/Certified/w1/w1.sol new file mode 100644 index 00000000..1b9e73ed --- /dev/null +++ b/Certified/w1/w1.sol @@ -0,0 +1,3 @@ +// SPDX-License-Identifier: UNLICENSED +pragma solidity ^0.8.28; +contract Main { function f(uint256 a, uint256 b) external pure returns (uint256) { return a + b; } } diff --git a/Certified/w4/Proofs.lean b/Certified/w4/Proofs.lean new file mode 100644 index 00000000..93ea22d3 --- /dev/null +++ b/Certified/w4/Proofs.lean @@ -0,0 +1,3 @@ +-- Generated by solar-tv/milestone/certify.py; do not edit. +import w4.Proofs.Stages +import w4.Proofs.Assembly diff --git a/Certified/w4/Proofs/Assembly.lean b/Certified/w4/Proofs/Assembly.lean new file mode 100644 index 00000000..7eec049c --- /dev/null +++ b/Certified/w4/Proofs/Assembly.lean @@ -0,0 +1,42 @@ +-- Generated by solar-tv/milestone/certify.py; do not edit. +import W1Proofs.Items +import w4.gen.Main.Evm4 +import w4.gen.Main.Bytecode + +/-! The final EVM IR of `Main` against its bytecode, by the assembly checker's walk: the bytecode decodes, linearly from offset 0, to exactly the program's instructions, each jumped-to block at its `JUMPDEST`. -/ + +namespace SolarTV.Milestone.W4 + +open SolarTV.Assembly SolarTV.Export.Main SolarTV.Milestone.W1 + +set_option maxRecDepth 100000 + +/-- The items of the final EVM IR. -/ +def items : List Item := (itemsOf evm4).getD [] + +theorem items_eq : itemsOf evm4 = some items := by decide + +/-- The layout: each jumped-to block at the bytecode's next `JUMPDEST`. The walk checks it. -/ +def offset (label : Nat) : Nat := if label = 1 then 0x20 else 0 + +/-- The instructions the walk reaches, each at its offset. -/ +def stream : List (Nat × Instr) := (walk bytecode offset 0 items).getD [] + +/-- The checker's walk accepts the exported bytecode against the final EVM IR. -/ +theorem walk_eq : walk bytecode offset 0 items = some stream := by decide +kernel + +theorem checked : Walk bytecode offset 0 items stream := walk_sound walk_eq + +/-- The bytecode's linear decoding is the final EVM IR's instructions at the layout. -/ +theorem decodes : decodeFrom bytecode (bytecode.length + 1) 0 = stream := + walk_decodes checked _ (by have := walk_length checked; omega) + +/-- info: 'SolarTV.Milestone.W4.walk_eq' depends on axioms: [propext, Quot.sound] -/ +#guard_msgs in +#print axioms walk_eq + +/-- info: 'SolarTV.Milestone.W4.decodes' depends on axioms: [propext, Quot.sound] -/ +#guard_msgs in +#print axioms decodes + +end SolarTV.Milestone.W4 diff --git a/Certified/w4/Proofs/Runs/Evm1.lean b/Certified/w4/Proofs/Runs/Evm1.lean new file mode 100644 index 00000000..48c70b19 --- /dev/null +++ b/Certified/w4/Proofs/Runs/Evm1.lean @@ -0,0 +1,22 @@ +-- Generated by solar-tv/milestone/certify.py; do not edit. +import W1Proofs.Tactic +import W1Proofs.Axioms +import w4.gen.Main.Evm1 +import w4.gen.Main.Sched + +/-! `cfg-simplify-early`: its input and output end in the same result on every call. -/ + +namespace SolarTV.Milestone.W4 + +open Machine SolarTV.Export.Main SolarTV.Milestone.W1 + +set_option maxHeartbeats 2000000 in +theorem evm1_run (o : Oracle) (call : Call) : + EVM.Program.run o sched call 7 = EVM.Program.run o evm1 call 4 := by + sym_exec + +/-- info: 'SolarTV.Milestone.W4.evm1_run' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within evm1_run + +end SolarTV.Milestone.W4 diff --git a/Certified/w4/Proofs/Runs/Evm2.lean b/Certified/w4/Proofs/Runs/Evm2.lean new file mode 100644 index 00000000..67918531 --- /dev/null +++ b/Certified/w4/Proofs/Runs/Evm2.lean @@ -0,0 +1,22 @@ +-- Generated by solar-tv/milestone/certify.py; do not edit. +import W1Proofs.Tactic +import W1Proofs.Axioms +import w4.gen.Main.Evm2 +import w4.gen.Main.Evm1 + +/-! `share-reverts`: its input and output end in the same result on every call. -/ + +namespace SolarTV.Milestone.W4 + +open Machine SolarTV.Export.Main SolarTV.Milestone.W1 + +set_option maxHeartbeats 2000000 in +theorem evm2_run (o : Oracle) (call : Call) : + EVM.Program.run o evm1 call 4 = EVM.Program.run o evm2 call 4 := by + sym_exec + +/-- info: 'SolarTV.Milestone.W4.evm2_run' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within evm2_run + +end SolarTV.Milestone.W4 diff --git a/Certified/w4/Proofs/Runs/Evm3.lean b/Certified/w4/Proofs/Runs/Evm3.lean new file mode 100644 index 00000000..52f1c048 --- /dev/null +++ b/Certified/w4/Proofs/Runs/Evm3.lean @@ -0,0 +1,22 @@ +-- Generated by solar-tv/milestone/certify.py; do not edit. +import W1Proofs.Tactic +import W1Proofs.Axioms +import w4.gen.Main.Evm3 +import w4.gen.Main.Evm2 + +/-! `terminal-dedup`: its input and output end in the same result on every call. -/ + +namespace SolarTV.Milestone.W4 + +open Machine SolarTV.Export.Main SolarTV.Milestone.W1 + +set_option maxHeartbeats 2000000 in +theorem evm3_run (o : Oracle) (call : Call) : + EVM.Program.run o evm2 call 4 = EVM.Program.run o evm3 call 4 := by + sym_exec + +/-- info: 'SolarTV.Milestone.W4.evm3_run' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within evm3_run + +end SolarTV.Milestone.W4 diff --git a/Certified/w4/Proofs/Runs/Evm4.lean b/Certified/w4/Proofs/Runs/Evm4.lean new file mode 100644 index 00000000..c18f6ed3 --- /dev/null +++ b/Certified/w4/Proofs/Runs/Evm4.lean @@ -0,0 +1,22 @@ +-- Generated by solar-tv/milestone/certify.py; do not edit. +import W1Proofs.Tactic +import W1Proofs.Axioms +import w4.gen.Main.Evm4 +import w4.gen.Main.Evm3 + +/-! `cfg-simplify-early`: its input and output end in the same result on every call. -/ + +namespace SolarTV.Milestone.W4 + +open Machine SolarTV.Export.Main SolarTV.Milestone.W1 + +set_option maxHeartbeats 2000000 in +theorem evm4_run (o : Oracle) (call : Call) : + EVM.Program.run o evm3 call 4 = EVM.Program.run o evm4 call 2 := by + sym_exec + +/-- info: 'SolarTV.Milestone.W4.evm4_run' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within evm4_run + +end SolarTV.Milestone.W4 diff --git a/Certified/w4/Proofs/Runs/Sched.lean b/Certified/w4/Proofs/Runs/Sched.lean new file mode 100644 index 00000000..f1631f4e --- /dev/null +++ b/Certified/w4/Proofs/Runs/Sched.lean @@ -0,0 +1,22 @@ +-- Generated by solar-tv/milestone/certify.py; do not edit. +import W1Proofs.Tactic +import W1Proofs.Axioms +import w4.gen.Main.Sched +import w4.gen.Main.Stage0 + +/-! Stack scheduling: the last lowered MIR and the scheduled EVM IR end in the same result on every call. -/ + +namespace SolarTV.Milestone.W4 + +open Machine SolarTV.Export.Main SolarTV.Milestone.W1 + +set_option maxHeartbeats 2000000 in +theorem sched_run (o : Oracle) (call : Call) : + MIR.Lowered.Module.run o stage0 call 7 = EVM.Program.run o sched call 7 := by + sym_exec + +/-- info: 'SolarTV.Milestone.W4.sched_run' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within sched_run + +end SolarTV.Milestone.W4 diff --git a/Certified/w4/Proofs/Runs/Stage0.lean b/Certified/w4/Proofs/Runs/Stage0.lean new file mode 100644 index 00000000..77a270e1 --- /dev/null +++ b/Certified/w4/Proofs/Runs/Stage0.lean @@ -0,0 +1,21 @@ +-- Generated by solar-tv/milestone/certify.py; do not edit. +import W1Proofs.Tactic +import W1Proofs.Axioms +import w4.gen.Main.Stage0 + +/-! The first lowered MIR ends on every call within 7 blocks, the number of its blocks. -/ + +namespace SolarTV.Milestone.W4 + +open Machine SolarTV.Export.Main SolarTV.Milestone.W1 + +set_option maxHeartbeats 2000000 in +theorem stage0_ends (o : Oracle) (call : Call) : + (MIR.Lowered.Module.run o stage0 call 7).isSome = true := by + sym_exec + +/-- info: 'SolarTV.Milestone.W4.stage0_ends' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within stage0_ends + +end SolarTV.Milestone.W4 diff --git a/Certified/w4/Proofs/Stages.lean b/Certified/w4/Proofs/Stages.lean new file mode 100644 index 00000000..66a10a06 --- /dev/null +++ b/Certified/w4/Proofs/Stages.lean @@ -0,0 +1,99 @@ +-- Generated by solar-tv/milestone/certify.py; do not edit. +import w4.Proofs.Runs.Stage0 +import w4.Proofs.Runs.Sched +import w4.Proofs.Runs.Evm1 +import w4.Proofs.Runs.Evm2 +import w4.Proofs.Runs.Evm3 +import w4.Proofs.Runs.Evm4 +import W1Proofs.Stage +import SolarTV.Composition + +/-! The backend stages of `Main`, each proved on every call (`anyCall`: any calldata, call value and storage) under every oracle, and chained from the first lowered MIR `stage0` to the final EVM IR `evm4`. Fuels are the programs' block counts. -/ + +namespace SolarTV.Milestone.W4 + +open Machine SolarTV.Export.Main SolarTV.Milestone.W1 + +/-- `stack-schedule`: stage0 to sched. -/ +theorem stage_sched (o : Oracle) : Stage (mirSem o) (evmirSem o) stage0 sched anyCall := + stage_of_runs (A := MIR.Lowered.moduleLayer) (B := EVM.Program.layer) 7 7 (fun call _ => stage0_ends o call) + (fun call _ => sched_run o call) + +theorem sched_ends (o : Oracle) : ∀ call, anyCall call → + (EVM.Program.run o sched call 7).isSome = true := + ends_of_runs (A := MIR.Lowered.moduleLayer) (B := EVM.Program.layer) + (o := o) (p := stage0) (q := sched) (n := 7) (m := 7) (fun call _ => stage0_ends o call) + (fun call _ => sched_run o call) + +/-- `cfg-simplify-early`: sched to evm1. -/ +theorem stage_evm1 (o : Oracle) : Stage (evmirSem o) (evmirSem o) sched evm1 anyCall := + stage_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) 7 4 (sched_ends o) + (fun call _ => evm1_run o call) + +theorem evm1_ends (o : Oracle) : ∀ call, anyCall call → + (EVM.Program.run o evm1 call 4).isSome = true := + ends_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) + (o := o) (p := sched) (q := evm1) (n := 7) (m := 4) (sched_ends o) + (fun call _ => evm1_run o call) + +/-- `share-reverts`: evm1 to evm2. -/ +theorem stage_evm2 (o : Oracle) : Stage (evmirSem o) (evmirSem o) evm1 evm2 anyCall := + stage_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) 4 4 (evm1_ends o) + (fun call _ => evm2_run o call) + +theorem evm2_ends (o : Oracle) : ∀ call, anyCall call → + (EVM.Program.run o evm2 call 4).isSome = true := + ends_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) + (o := o) (p := evm1) (q := evm2) (n := 4) (m := 4) (evm1_ends o) + (fun call _ => evm2_run o call) + +/-- `terminal-dedup`: evm2 to evm3. -/ +theorem stage_evm3 (o : Oracle) : Stage (evmirSem o) (evmirSem o) evm2 evm3 anyCall := + stage_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) 4 4 (evm2_ends o) + (fun call _ => evm3_run o call) + +theorem evm3_ends (o : Oracle) : ∀ call, anyCall call → + (EVM.Program.run o evm3 call 4).isSome = true := + ends_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) + (o := o) (p := evm2) (q := evm3) (n := 4) (m := 4) (evm2_ends o) + (fun call _ => evm3_run o call) + +/-- `cfg-simplify-early`: evm3 to evm4. -/ +theorem stage_evm4 (o : Oracle) : Stage (evmirSem o) (evmirSem o) evm3 evm4 anyCall := + stage_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) 4 2 (evm3_ends o) + (fun call _ => evm4_run o call) + +/-- The compilation from the first lowered MIR to the final EVM IR. -/ +def compilation : Compilation := + ⟨stage0, [], sched, [evm1, evm2, evm3, evm4]⟩ + +/-- Every stage from the first lowered MIR to the final EVM IR, chained by the library's composition, on every call. -/ +theorem w4_mir_to_evmir (o : Oracle) : Stage (mirSem o) (evmirSem o) stage0 evm4 anyCall := + mir_to_evmir o anyCall compilation trivial (stage_sched o) + ⟨stage_evm1 o, stage_evm2 o, stage_evm3 o, stage_evm4 o, trivial⟩ + +/-- info: 'SolarTV.Milestone.W4.stage_sched' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms stage_sched + +/-- info: 'SolarTV.Milestone.W4.stage_evm1' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms stage_evm1 + +/-- info: 'SolarTV.Milestone.W4.stage_evm2' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms stage_evm2 + +/-- info: 'SolarTV.Milestone.W4.stage_evm3' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms stage_evm3 + +/-- info: 'SolarTV.Milestone.W4.stage_evm4' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms stage_evm4 + +/-- info: 'SolarTV.Milestone.W4.w4_mir_to_evmir' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms w4_mir_to_evmir + +end SolarTV.Milestone.W4 diff --git a/Certified/w4/bytecode.hex b/Certified/w4/bytecode.hex new file mode 100644 index 00000000..da2948a4 --- /dev/null +++ b/Certified/w4/bytecode.hex @@ -0,0 +1 @@ +346020575f3560e01c806360fe47b103602057602436106020576004355f55005b5f5ffd diff --git a/Certified/w4/gen/Main/Bytecode.lean b/Certified/w4/gen/Main/Bytecode.lean new file mode 100644 index 00000000..4e7384ba --- /dev/null +++ b/Certified/w4/gen/Main/Bytecode.lean @@ -0,0 +1,16 @@ +-- solar-lean-stage: kind=bytecode index=0 pass=assemble +/-! Generated by `solar -Zemit-lean-stages` for `Main`; do not edit. -/ + +namespace SolarTV.Export.Main + +/-- The runtime bytecode, byte by byte. -/ +def bytecode : List Nat := + [0x34, 0x60, 0x20, 0x57, 0x5f, 0x35, 0x60, 0xe0, 0x1c, 0x80, 0x63, 0x60, 0xfe, 0x47, 0xb1, 0x03, + 0x60, 0x20, 0x57, 0x60, 0x24, 0x36, 0x10, 0x60, 0x20, 0x57, 0x60, 0x04, 0x35, 0x5f, 0x55, 0x00, + 0x5b, 0x5f, 0x5f, 0xfd] + +/-- The runtime bytecode in hex, as `--emit=bin-runtime` prints it. -/ +def bytecodeHex : String := + "346020575f3560e01c806360fe47b103602057602436106020576004355f55005b5f5ffd" + +end SolarTV.Export.Main diff --git a/Certified/w4/gen/Main/Evm1.lean b/Certified/w4/gen/Main/Evm1.lean new file mode 100644 index 00000000..28f58e8a --- /dev/null +++ b/Certified/w4/gen/Main/Evm1.lean @@ -0,0 +1,42 @@ +-- solar-lean-stage: kind=evm index=1 pass=cfg-simplify-early +import SolarTV.EVMIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `Main`; do not edit. -/ + +namespace SolarTV.Export.Main + +/-- The runtime EVM IR after `cfg-simplify-early`. -/ +def evm1 : EVM.Program.Program := + { blocks := [ + -- bb0 + [.effect .callvalue 0, + .jumpi 1, + .op (.stack (.push 0)), + .effect .calldataload 1, + .op (.stack (.push 224)), + .op (.stack .shr), + .op (.stack (.dup 0)), + .op (.stack (.push 0x60fe47b1)), + .op (.stack .eq), + .jumpi 2, + .jump 1], + -- bb3 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb4 + [.op (.stack (.push 36)), + .op (.stack .calldatasize), + .op (.stack .lt), + .jumpi 3, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 0)), + .effect .sstore 2, + .stop], + -- bb6 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert]] } + +end SolarTV.Export.Main diff --git a/Certified/w4/gen/Main/Evm2.lean b/Certified/w4/gen/Main/Evm2.lean new file mode 100644 index 00000000..652f443a --- /dev/null +++ b/Certified/w4/gen/Main/Evm2.lean @@ -0,0 +1,42 @@ +-- solar-lean-stage: kind=evm index=2 pass=share-reverts +import SolarTV.EVMIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `Main`; do not edit. -/ + +namespace SolarTV.Export.Main + +/-- The runtime EVM IR after `share-reverts`. -/ +def evm2 : EVM.Program.Program := + { blocks := [ + -- bb0 + [.effect .callvalue 0, + .jumpi 1, + .op (.stack (.push 0)), + .effect .calldataload 1, + .op (.stack (.push 224)), + .op (.stack .shr), + .op (.stack (.dup 0)), + .op (.stack (.push 0x60fe47b1)), + .op (.stack .sub), + .jumpi 1, + .jump 2], + -- bb3 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb4 + [.op (.stack (.push 36)), + .op (.stack .calldatasize), + .op (.stack .lt), + .jumpi 3, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 0)), + .effect .sstore 2, + .stop], + -- bb6 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert]] } + +end SolarTV.Export.Main diff --git a/Certified/w4/gen/Main/Evm3.lean b/Certified/w4/gen/Main/Evm3.lean new file mode 100644 index 00000000..49d91be3 --- /dev/null +++ b/Certified/w4/gen/Main/Evm3.lean @@ -0,0 +1,40 @@ +-- solar-lean-stage: kind=evm index=3 pass=terminal-dedup +import SolarTV.EVMIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `Main`; do not edit. -/ + +namespace SolarTV.Export.Main + +/-- The runtime EVM IR after `terminal-dedup`. -/ +def evm3 : EVM.Program.Program := + { blocks := [ + -- bb0 + [.effect .callvalue 0, + .jumpi 1, + .op (.stack (.push 0)), + .effect .calldataload 1, + .op (.stack (.push 224)), + .op (.stack .shr), + .op (.stack (.dup 0)), + .op (.stack (.push 0x60fe47b1)), + .op (.stack .sub), + .jumpi 1, + .jump 2], + -- bb3 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb4 + [.op (.stack (.push 36)), + .op (.stack .calldatasize), + .op (.stack .lt), + .jumpi 3, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 0)), + .effect .sstore 2, + .stop], + -- bb6 + [.jump 1]] } + +end SolarTV.Export.Main diff --git a/Certified/w4/gen/Main/Evm4.lean b/Certified/w4/gen/Main/Evm4.lean new file mode 100644 index 00000000..0c46121e --- /dev/null +++ b/Certified/w4/gen/Main/Evm4.lean @@ -0,0 +1,36 @@ +-- solar-lean-stage: kind=evm index=4 pass=cfg-simplify-early +import SolarTV.EVMIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `Main`; do not edit. -/ + +namespace SolarTV.Export.Main + +/-- The runtime EVM IR after `cfg-simplify-early`. -/ +def evm4 : EVM.Program.Program := + { blocks := [ + -- bb0 + [.effect .callvalue 0, + .jumpi 1, + .op (.stack (.push 0)), + .effect .calldataload 1, + .op (.stack (.push 224)), + .op (.stack .shr), + .op (.stack (.dup 0)), + .op (.stack (.push 0x60fe47b1)), + .op (.stack .sub), + .jumpi 1, + .op (.stack (.push 36)), + .op (.stack .calldatasize), + .op (.stack .lt), + .jumpi 1, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 0)), + .effect .sstore 2, + .stop], + -- bb3 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert]] } + +end SolarTV.Export.Main diff --git a/Certified/w4/gen/Main/Manifest.lean b/Certified/w4/gen/Main/Manifest.lean new file mode 100644 index 00000000..f7a39202 --- /dev/null +++ b/Certified/w4/gen/Main/Manifest.lean @@ -0,0 +1,41 @@ +-- solar-lean-stage: kind=manifest index=0 pass=none +/-! Generated by `solar -Zemit-lean-stages` for `Main`; do not edit. + +What the stages of this directory were compiled from and by. `stages` lists each +stage's file, its definition, the pass whose output it is, and the SHA-256 of the file. +-/ + +namespace SolarTV.Export.Main.Manifest + +def sources : List (String × String) := + [("solar-tv/milestone/w4/w4.sol", "942f34d659aeb6e6809054e007c8201ad58d6ddb4ac748444eb9442dc317f02d")] + +def compiler : String := "0.8.38+commit.7817979b.solar.0.3.0-dev" + +def arguments : List String := + ["solar-tv/milestone/w4/w4.sol", + "-Ogas", + "--evm-version", + "osaka", + "--emit=bin-runtime", + "-Zemit-lean-stages=solar-tv/milestone/w4/gen"] + +def evmVersion : String := "osaka" + +def optimization : String := "Gas" + +def stages : List (String × String × String × String) := + [("Stage0", "stage0", "lower-evm-shaped", "ad2808b449e47195d6e928b2f07d7345c6fd85e2e1f66c6e8a4d85be6e9aee01"), + ("Sched", "sched", "stack-schedule", "7f3aa6e29328784877d834249d0d9c4ca0b91a2ffa502b499cb54ee7079d7146"), + ("Evm1", "evm1", "cfg-simplify-early", "ba810a9908a18e0fab7fa8c84b8e468f71fc28872422e237e8f7c74ddb98123e"), + ("Evm2", "evm2", "share-reverts", "aaf0fa85179f3ee35481eaf6ebbbce3a9d55b10f568a398acdcd1ebba33d15df"), + ("Evm3", "evm3", "terminal-dedup", "c43f40fbc2bae9fa15dda374eddbc74ecc567d460eacb90eb8ec9dce3963aef6"), + ("Evm4", "evm4", "cfg-simplify-early", "e71c69daa0aa1e6b065784c4401c964795416ef7afb30a48723f2c97f369aabb"), + ("Bytecode", "bytecode", "assemble", "6752a6cf2de90dc563c1c70b55e2e5d1edf7940c357c651bb767a5f7d5d33e03")] + +def bytecodeHex : String := + "346020575f3560e01c806360fe47b103602057602436106020576004355f55005b5f5ffd" + +def bytecodeSha256 : String := "4ac6a427e10e54ab60dbae0bd734633543eafea6ea38440d53363c8fa50018ee" + +end SolarTV.Export.Main.Manifest diff --git a/Certified/w4/gen/Main/Sched.lean b/Certified/w4/gen/Main/Sched.lean new file mode 100644 index 00000000..6cc14795 --- /dev/null +++ b/Certified/w4/gen/Main/Sched.lean @@ -0,0 +1,48 @@ +-- solar-lean-stage: kind=sched index=0 pass=stack-schedule +import SolarTV.EVMIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `Main`; do not edit. -/ + +namespace SolarTV.Export.Main + +/-- The runtime EVM IR as stack scheduling emits it. -/ +def sched : EVM.Program.Program := + { blocks := [ + -- bb0 + [.effect .callvalue 0, + .jumpi 3, + .jump 1], + -- bb1 + [.op (.stack (.push 0)), + .effect .calldataload 1, + .op (.stack (.push 224)), + .op (.stack .shr), + .op (.stack (.dup 0)), + .op (.stack (.push 0x60fe47b1)), + .op (.stack .eq), + .jumpi 2, + .jump 3], + -- bb2 + [.jump 4], + -- bb3 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb4 + [.op (.stack (.push 36)), + .op (.stack .calldatasize), + .op (.stack .lt), + .jumpi 6, + .jump 5], + -- bb5 + [.op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 0)), + .effect .sstore 2, + .stop], + -- bb6 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert]] } + +end SolarTV.Export.Main diff --git a/Certified/w4/gen/Main/Stage0.lean b/Certified/w4/gen/Main/Stage0.lean new file mode 100644 index 00000000..865b23ba --- /dev/null +++ b/Certified/w4/gen/Main/Stage0.lean @@ -0,0 +1,51 @@ +-- solar-lean-stage: kind=mir index=0 pass=lower-evm-shaped +import SolarTV.MIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `Main`; do not edit. -/ + +namespace SolarTV.Export.Main + +/-- The first lowered MIR module, after `lower-evm-shaped` advanced the phase. -/ +def stage0 : MIR.Lowered.Module := + { entry := 1, + functions := [ + -- @set + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 3) .calldatasize [], + .pure 5 .lt [.value 3, .const 36]], + .branch (.value 5) 1 2⟩, + -- bb1 + ⟨[], + [], + .revert (.const 0) (.const 0)⟩, + -- bb2 + ⟨[], + [.effect (some 7) .calldataload [.const 4], + .effect none .sstore [.const 0, .value 7]], + .stop⟩] }, + -- @entry + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 0) .callvalue [], + .ne 2 (.value 0) (.const 0)], + .branch (.value 2) 3 1⟩, + -- bb1 + ⟨[], + [.effect (some 4) .calldataload [.const 0], + .pure 6 .shr [.const 224, .value 4]], + .switch (.value 6) 3 [(.const 0x60fe47b1, 2)]⟩, + -- bb2 + ⟨[], + [], + .tailCall 0 []⟩, + -- bb3 + ⟨[], + [], + .revert (.const 0) (.const 0)⟩] }] } + +end SolarTV.Export.Main diff --git a/Certified/w4/gen/Main/manifest.json b/Certified/w4/gen/Main/manifest.json new file mode 100644 index 00000000..dcd74eab --- /dev/null +++ b/Certified/w4/gen/Main/manifest.json @@ -0,0 +1,81 @@ +{ + "arguments": [ + "solar-tv/milestone/w4/w4.sol", + "-Ogas", + "--evm-version", + "osaka", + "--emit=bin-runtime", + "-Zemit-lean-stages=solar-tv/milestone/w4/gen" + ], + "bytecode": "346020575f3560e01c806360fe47b103602057602436106020576004355f55005b5f5ffd", + "bytecode_sha256": "4ac6a427e10e54ab60dbae0bd734633543eafea6ea38440d53363c8fa50018ee", + "compiler": "0.8.38+commit.7817979b.solar.0.3.0-dev", + "contract": "Main", + "evm_version": "osaka", + "optimization": "Gas", + "options": "CompileOpts { input: [\"solar-tv/milestone/w4/w4.sol\"], import_remappings: [], base_path: None, include_paths: [], allow_paths: [], no_import_callback: false, language: Solidity, threads: 4, evm_version: Osaka, stop_after: None, optimization: Gas, optimizer_runs: None, revert_strings: Default, libraries: [], out_dir: None, emit: [BinRuntime], standard_json: false, color: Auto, verbose: false, pretty_json: false, pretty_json_err: false, error_format: Human, error_format_human: Unicode, diagnostic_width: None, no_warnings: false, allow: [], _unstable: [\"emit-lean-stages=solar-tv/milestone/w4/gen\"], unstable: UnstableOpts { ui_testing: false, track_diagnostics: false, parse_yul: false, no_resolve_imports: false, recover_incomplete_input: false, dump: None, ast_stats: false, hir_stats: false, standard_json_stats: false, span_visitor: false, print_max_storage_sizes: false, print_natspec: false, mir_pipeline: None, evm_ir_pipeline: None, print_after_each: false, pass_diff: false, debugify: None, debugify_output: None, solar_tv: None, validate_ir: None, time_passes: false, codegen_all_functions: false, switch_lowering: Auto, switch_max_gas_code_growth: None, switch_max_bit_slice_gas_code_growth: None, tune: None, pack_wide_jump_tables: false, check_analyses: None, prove_analyses: None, validate_passes: None, validate_passes_fault: None, validate_backend: None, validate_backend_fault: None, validate_evm_ir_passes: None, validate_assembly: false, validate_assembly_fault: None, emit_lean_stages: Some(\"solar-tv/milestone/w4/gen\"), forget_gcx: true, help: (), _non_exhaustive: () }, _non_exhaustive: () }", + "sources": [ + { + "path": "solar-tv/milestone/w4/w4.sol", + "sha256": "942f34d659aeb6e6809054e007c8201ad58d6ddb4ac748444eb9442dc317f02d" + } + ], + "stages": [ + { + "definition": "stage0", + "file": "Stage0.lean", + "index": 0, + "kind": "mir", + "pass": "lower-evm-shaped", + "sha256": "ad2808b449e47195d6e928b2f07d7345c6fd85e2e1f66c6e8a4d85be6e9aee01" + }, + { + "definition": "sched", + "file": "Sched.lean", + "index": 0, + "kind": "sched", + "pass": "stack-schedule", + "sha256": "7f3aa6e29328784877d834249d0d9c4ca0b91a2ffa502b499cb54ee7079d7146" + }, + { + "definition": "evm1", + "file": "Evm1.lean", + "index": 1, + "kind": "evm", + "pass": "cfg-simplify-early", + "sha256": "ba810a9908a18e0fab7fa8c84b8e468f71fc28872422e237e8f7c74ddb98123e" + }, + { + "definition": "evm2", + "file": "Evm2.lean", + "index": 2, + "kind": "evm", + "pass": "share-reverts", + "sha256": "aaf0fa85179f3ee35481eaf6ebbbce3a9d55b10f568a398acdcd1ebba33d15df" + }, + { + "definition": "evm3", + "file": "Evm3.lean", + "index": 3, + "kind": "evm", + "pass": "terminal-dedup", + "sha256": "c43f40fbc2bae9fa15dda374eddbc74ecc567d460eacb90eb8ec9dce3963aef6" + }, + { + "definition": "evm4", + "file": "Evm4.lean", + "index": 4, + "kind": "evm", + "pass": "cfg-simplify-early", + "sha256": "e71c69daa0aa1e6b065784c4401c964795416ef7afb30a48723f2c97f369aabb" + }, + { + "definition": "bytecode", + "file": "Bytecode.lean", + "index": 0, + "kind": "bytecode", + "pass": "assemble", + "sha256": "6752a6cf2de90dc563c1c70b55e2e5d1edf7940c357c651bb767a5f7d5d33e03" + } + ] +} diff --git a/Certified/w4/options b/Certified/w4/options new file mode 100644 index 00000000..da38913c --- /dev/null +++ b/Certified/w4/options @@ -0,0 +1,3 @@ +-Ogas +--evm-version +osaka diff --git a/Certified/w4/w4.sol b/Certified/w4/w4.sol new file mode 100644 index 00000000..2451a811 --- /dev/null +++ b/Certified/w4/w4.sol @@ -0,0 +1,8 @@ +// SPDX-License-Identifier: UNLICENSED +pragma solidity ^0.8.28; +contract Main { + uint256 x; + function set(uint256 v) external { + x = v; + } +} diff --git a/SolidCore/Refinement/Solar/Assemble.lean b/SolidCore/Refinement/Solar/Assemble.lean index 0ffd56ee..e13c353b 100644 --- a/SolidCore/Refinement/Solar/Assemble.lean +++ b/SolidCore/Refinement/Solar/Assemble.lean @@ -103,7 +103,9 @@ 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. -/ +/-- The opcode of each stack operation of the fragment. `dup` and `swap` take a `Fin 256` position, +as SolarTV's EVM IR does; only DUP1 to DUP16 and SWAP1 to SWAP16 are one-byte opcodes, so a deeper +position (DUPN and SWAPN, which take an immediate) is outside the fragment. -/ def opByte : SolarTV.EVM.Op → Option Nat | .add => some 0x01 | .mul => some 0x02 | .sub => some 0x03 | .div => some 0x04 | .mod => some 0x06 | .lt => some 0x10 | .gt => some 0x11 @@ -111,7 +113,8 @@ def opByte : SolarTV.EVM.Op → Option Nat | .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) + | .dup i => if i.val < 16 then some (0x80 + i.val) else none + | .swap i => if i.val < 16 then some (0x90 + i.val) else none | _ => none /-- The assembly items of an instruction. Outside the fragment it is INVALID, which the check @@ -224,8 +227,8 @@ def stackNeed : SolarTV.EVM.Op → Option (Nat × Int) | .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) + | .dup i => if i.val < 16 then some (i.val + 1, 1) else none + | .swap i => if i.val < 16 then some (i.val + 2, 0) else none | _ => none /-- A jump to block `t` with a stack of at least `h` words typed `ty` and potential `k` left: `t` is a @@ -261,9 +264,10 @@ def blockStep (p : Program) (c : Cert) (ok : Nat → List Word → List Ty → N | 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) && + | .dup i => decide (1 ≤ k) && decide (i.val < 16) && decide (i.val + 1 ≤ h) && ok (h + 1) (dupKnown known i.val) (tyAt ty i.val :: ty) (k - 1) - | .swap i => decide (1 ≤ k) && decide (i.val + 2 ≤ h) && ok h [] (tySwap ty i.val) (k - 1) + | .swap i => decide (1 ≤ k) && decide (i.val < 16) && decide (i.val + 2 ≤ h) && + ok h [] (tySwap ty i.val) (k - 1) | .pop => decide (1 ≤ k) && decide (1 ≤ h) && ok (h - 1) [] ty.tail (k - 1) | op => match stackNeed op with @@ -773,7 +777,7 @@ theorem stack_rule_cheap {op : SolarTV.EVM.Op} {byte : Nat} {stack next : List W (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 + cases op <;> simp only [opByte, reduceCtorEq, Option.some.injEq] at hb <;> try subst hb case mod | mul | div => simp [low] at hm case add => bin_rule add_agree case sub => bin_rule sub_agree @@ -798,15 +802,25 @@ theorem stack_rule_cheap {op : SolarTV.EVM.Op} {byte : Nat} {stack next : List W 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 + split at hb + · rename_i hi + simp only [Option.some.injEq] at hb + subst hb + simp only [SolarTV.EVM.step, Option.map_eq_some_iff] at hstep obtain ⟨x, hx, rfl⟩ := hstep - exact ⟨_, le_refl _, swap_of_decode hlt hcode (decode_swap i) hx hgas⟩ + exact ⟨_, le_refl _, dup (⟨i.val, hi⟩ : Fin 16) hlt hcode hx hgas hlen⟩ + · simp at hb + case swap i => + split at hb + · rename_i hi + simp only [Option.some.injEq] at hb + subst hb + rcases stack with _ | ⟨top, rest⟩ + · simp [SolarTV.EVM.step] at hstep + · simp only [SolarTV.EVM.step, Option.map_eq_some_iff] at hstep + obtain ⟨x, hx, rfl⟩ := hstep + exact ⟨_, le_refl _, swap_of_decode hlt hcode (decode_swap ⟨i.val, hi⟩) hx hgas⟩ + · simp at hb /-- A stack operation of the fragment, at its opcode, does what SolarTV's semantics does, for at most 5 gas (the price of MUL, DIV and MOD; the rest cost 3). -/ diff --git a/SolidCore/Refinement/Solar/AssembleSim.lean b/SolidCore/Refinement/Solar/AssembleSim.lean index 121b1d1b..d0e1e63f 100644 --- a/SolidCore/Refinement/Solar/AssembleSim.lean +++ b/SolidCore/Refinement/Solar/AssembleSim.lean @@ -483,17 +483,17 @@ theorem stack_sim {p : Program} {c : Cert} {ok : Nat → List Word → List Ty by_cases hd : ∃ i, op = .dup i · obtain ⟨i, rfl⟩ := hd simp only [blockStep, Bool.and_eq_true, decide_eq_true_eq] at hok - obtain ⟨⟨hk1, hi⟩, hok⟩ := hok + obtain ⟨⟨⟨hk1, h16⟩, hi⟩, hok⟩ := hok have hiS : i.val < S.length := by omega have hiT : i.val < T.length := by omega - refine ⟨hk1, _, rfl, h + 1, _, _, _, ?_, ?_, SR.dup hR hiS hiT, by simp; omega, by simp, _, + refine ⟨hk1, 0x80 + i.val, by simp [opByte, h16], h + 1, _, _, _, ?_, ?_, SR.dup hR hiS hiT, by simp; omega, by simp, _, dupKnown_prefix hk hiS, hok⟩ · simp [SolarTV.EVM.step, List.getElem?_eq_getElem hiS] · simp [SolarTV.EVM.step, List.getElem?_eq_getElem hiT] by_cases hs : ∃ i, op = .swap i · obtain ⟨i, rfl⟩ := hs simp only [blockStep, Bool.and_eq_true, decide_eq_true_eq] at hok - obtain ⟨⟨hk1, hi⟩, hok⟩ := hok + obtain ⟨⟨⟨hk1, h16⟩, hi⟩, hok⟩ := hok rcases S with _ | ⟨a, S⟩ · simp at hh; omega rcases T with _ | ⟨b, T⟩ @@ -501,7 +501,7 @@ theorem stack_sim {p : Program} {c : Cert} {ok : Nat → List Word → List Ty simp only [List.length_cons] at hh hL have hiS : i.val < S.length := by omega have hiT : i.val < T.length := by omega - refine ⟨hk1, _, rfl, h, _, _, _, ?_, ?_, SR.swap hR hiS hiT, by simp; omega, by simp, [], + refine ⟨hk1, 0x90 + i.val, by simp [opByte, h16], h, _, _, _, ?_, ?_, SR.swap hR hiS hiT, by simp; omega, by simp, [], List.nil_prefix, hok⟩ · simp [SolarTV.EVM.step, List.getElem?_eq_getElem hiS] · simp [SolarTV.EVM.step, List.getElem?_eq_getElem hiT] diff --git a/lake-manifest.json b/lake-manifest.json index a831f685..5c50c94a 100644 --- a/lake-manifest.json +++ b/lake-manifest.json @@ -1,7 +1,9 @@ -{"version": "1.3.0", +{ + "version": "1.3.0", "packagesDir": ".lake/packages", - "packages": - [{"url": "https://github.com/leanprover-community/mathlib4", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4", "type": "git", "subDir": null, "scope": "leanprover-community", @@ -10,34 +12,30 @@ "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", + "configFile": "lakefile.lean" + }, + { + "type": "path", "scope": "", - "rev": "2144dccb0984e6df238cc2e5e9d741e2e52e722d", - "name": "solar_tv", - "manifestFile": "lake-manifest.json", - "inputRev": "2144dccb0984e6df238cc2e5e9d741e2e52e722d", - "inherited": false, - "configFile": "lakefile.toml"}, - {"type": "path", - "scope": "", - "name": "«evm-interaction»", + "name": "\u00abevm-interaction\u00bb", "manifestFile": "lake-manifest.json", "inherited": false, "dir": "vendor/evm-interaction", "copy": false, - "configFile": "lakefile.lean"}, - {"type": "path", + "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", + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/ethereum/EthLib.git", "type": "git", "subDir": null, "scope": "", @@ -46,8 +44,10 @@ "manifestFile": "lake-manifest.json", "inputRev": "2cd5d14a6a2f6fd22ef6b68423e45cfa3a21001a", "inherited": false, - "configFile": "lakefile.lean"}, - {"url": "https://github.com/leanprover-community/plausible", + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", "type": "git", "subDir": null, "scope": "leanprover-community", @@ -56,8 +56,10 @@ "manifestFile": "lake-manifest.json", "inputRev": "main", "inherited": true, - "configFile": "lakefile.toml"}, - {"url": "https://github.com/leanprover-community/LeanSearchClient", + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", "type": "git", "subDir": null, "scope": "leanprover-community", @@ -66,8 +68,10 @@ "manifestFile": "lake-manifest.json", "inputRev": "main", "inherited": true, - "configFile": "lakefile.toml"}, - {"url": "https://github.com/leanprover-community/import-graph", + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", "type": "git", "subDir": null, "scope": "leanprover-community", @@ -76,8 +80,10 @@ "manifestFile": "lake-manifest.json", "inputRev": "main", "inherited": true, - "configFile": "lakefile.toml"}, - {"url": "https://github.com/leanprover-community/ProofWidgets4", + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", "type": "git", "subDir": null, "scope": "leanprover-community", @@ -86,8 +92,10 @@ "manifestFile": "lake-manifest.json", "inputRev": "main", "inherited": true, - "configFile": "lakefile.lean"}, - {"url": "https://github.com/leanprover-community/aesop", + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", "type": "git", "subDir": null, "scope": "leanprover-community", @@ -96,8 +104,10 @@ "manifestFile": "lake-manifest.json", "inputRev": "master", "inherited": true, - "configFile": "lakefile.toml"}, - {"url": "https://github.com/leanprover-community/quote4", + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", "type": "git", "subDir": null, "scope": "leanprover-community", @@ -106,8 +116,10 @@ "manifestFile": "lake-manifest.json", "inputRev": "master", "inherited": true, - "configFile": "lakefile.toml"}, - {"url": "https://github.com/leanprover-community/batteries", + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", "type": "git", "subDir": null, "scope": "leanprover-community", @@ -116,16 +128,10 @@ "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", + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/Verified-zkEVM/VCVio.git", "type": "git", "subDir": null, "scope": "", @@ -134,8 +140,10 @@ "manifestFile": "lake-manifest.json", "inputRev": "bbf05eeeedf84c5f98baaf5ab846f2d2479cc8ab", "inherited": true, - "configFile": "lakefile.lean"}, - {"url": "https://github.com/leanprover/lean4-cli", + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover/lean4-cli", "type": "git", "subDir": null, "scope": "leanprover", @@ -144,8 +152,10 @@ "manifestFile": "lake-manifest.json", "inputRev": "v4.35.0", "inherited": true, - "configFile": "lakefile.toml"}, - {"url": "https://github.com/lean-crypto-foundations/QuantumFoundations", + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/lean-crypto-foundations/QuantumFoundations", "type": "git", "subDir": null, "scope": "", @@ -154,8 +164,10 @@ "manifestFile": "lake-manifest.json", "inputRev": "901aaab7967ceecd2240d0b38bbde7cf3e2c14ac", "inherited": true, - "configFile": "lakefile.toml"}, - {"url": "https://github.com/Verified-zkEVM/PolyFun", + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/Verified-zkEVM/PolyFun", "type": "git", "subDir": null, "scope": "", @@ -164,8 +176,10 @@ "manifestFile": "lake-manifest.json", "inputRev": "4181c82238142d9b73403fbf4c4b13e1a801e400", "inherited": true, - "configFile": "lakefile.toml"}, - {"url": "https://github.com/leanprover/cslib", + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/cslib", "type": "git", "subDir": null, "scope": "leanprover", @@ -174,7 +188,10 @@ "manifestFile": "lake-manifest.json", "inputRev": "v4.35.0", "inherited": true, - "configFile": "lakefile.toml"}], - "name": "«solidity-lean»", + "configFile": "lakefile.toml" + } + ], + "name": "\u00absolidity-lean\u00bb", "lakeDir": ".lake", - "fixedToolchain": false} + "fixedToolchain": false +} diff --git a/lakefile.lean b/lakefile.lean index 0ec14fa1..8d441779 100644 --- a/lakefile.lean +++ b/lakefile.lean @@ -13,15 +13,6 @@ require evmyul from "vendor" / "evmyul" -- 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" @@ -161,3 +152,112 @@ lean_lib SolidCoreSolarBankSource where lean_lib SolidCoreSolarToken where roots := #[`SolidCore.Refinement.Solar.Token.Lowering, `SolidCore.Refinement.Solar.Token.Assembly, `SolidCore.Refinement.Solar.Token.Mutants, `SolidCore.Refinement.Solar.Token.Certified] + +/-! solar's translation validation (formerly solar's `solar-tv` Lean package, moved here so that +every Lean source of the certified translation lives in this repository; solar keeps only the +stage exporter and the drivers that generate Lean against a pinned commit of this repository). +These libraries keep Lean's default options (as their own package had), not the ones above. -/ + +/-- The option defaults of solar's former `solar_tv` package. -/ +def solarTVOptions : Array LeanOption := #[ + ⟨`maxHeartbeats, (200000 : Nat)⟩, + ⟨`backward.do.legacy, false⟩ +] + +/-- solar's word semantics and rewrite-rule lemmas (`EvmRules`), vendored from solar's +scripts/evm-rules/lean at the commit vendor/evm-rules/README.md names. -/ +lean_lib EvmRules where + srcDir := "vendor/evm-rules" + globs := #[.andSubmodules `EvmRules] + leanOptions := solarTVOptions + +/-- MIR and EVM IR semantics, the stages and their refinement, assembly walk, cut points and +symbolic memory laws. -/ +lean_lib SolarTV where + srcDir := "tv" + globs := #[.andSubmodules `SolarTV] + leanOptions := solarTVOptions + +/-- The symbolic-execution procedures and assembly items that the generated per-contract proofs +use, and w1's own stage proofs. Symbolic execution is heavy: fail on running out of memory rather +than exhaust the machine. -/ +lean_lib W1Proofs where + srcDir := "tv" + globs := #[.andSubmodules `W1Proofs] + leanOptions := solarTVOptions + moreLeanArgs := #["-M", "3000"] + +/-! Generated per-contract stages and proofs that the headline theorems import, as solar's +exporter and certify driver write them (Certified//gen and Certified//Proofs, module +names without a `Certified` prefix). Regenerate with solar's certify driver; see +Certified/README.md. -/ + +/-- w1's exported stages and their checks. -/ +lean_lib W1 where + srcDir := "Certified/w1" + roots := #[`W1] + globs := #[.andSubmodules `W1, .submodules `gen] + leanOptions := solarTVOptions + +lean_lib counter where + srcDir := "Certified" + roots := #[`counter.Proofs] + globs := #[.andSubmodules `counter] + leanOptions := solarTVOptions + moreLeanArgs := #["-M", "3000"] + +lean_lib w4 where + srcDir := "Certified" + roots := #[`w4.Proofs] + globs := #[.andSubmodules `w4] + leanOptions := solarTVOptions + moreLeanArgs := #["-M", "3000"] + +lean_lib masks where + srcDir := "Certified" + roots := #[`masks.Proofs] + globs := #[.andSubmodules `masks] + leanOptions := solarTVOptions + moreLeanArgs := #["-M", "3000"] + +lean_lib bank where + srcDir := "Certified" + roots := #[`bank.Proofs] + globs := #[.andSubmodules `bank] + leanOptions := solarTVOptions + moreLeanArgs := #["-M", "3000"] + +lean_lib c4 where + srcDir := "Certified" + roots := #[`c4.Proofs] + globs := #[.andSubmodules `c4] + leanOptions := solarTVOptions + moreLeanArgs := #["-M", "3000"] + +lean_lib mulx where + srcDir := "Certified" + roots := #[`mulx.Proofs] + globs := #[.andSubmodules `mulx] + leanOptions := solarTVOptions + moreLeanArgs := #["-M", "3000"] + +lean_lib events where + srcDir := "Certified" + roots := #[`events.Proofs] + globs := #[.andSubmodules `events] + leanOptions := solarTVOptions + moreLeanArgs := #["-M", "3000"] + +lean_lib reader where + srcDir := "Certified" + roots := #[`reader.Proofs] + globs := #[.andSubmodules `reader] + leanOptions := solarTVOptions + moreLeanArgs := #["-M", "3000"] + +lean_lib token where + srcDir := "Certified" + roots := #[`token.Proofs] + globs := #[.andSubmodules `token] + leanOptions := solarTVOptions + moreLeanArgs := #["-M", "3000"] diff --git a/scripts/check-evm-rules-vendor.sh b/scripts/check-evm-rules-vendor.sh new file mode 100755 index 00000000..b2f46017 --- /dev/null +++ b/scripts/check-evm-rules-vendor.sh @@ -0,0 +1,9 @@ +#!/usr/bin/env bash +# Compare the vendored EvmRules library with a solar checkout's scripts/evm-rules/lean. +# Usage: scripts/check-evm-rules-vendor.sh SOLAR_DIR +set -euo pipefail +root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +solar="${1:?usage: check-evm-rules-vendor.sh SOLAR_DIR}" +diff -r "$solar/scripts/evm-rules/lean/EvmRules.lean" "$root/vendor/evm-rules/EvmRules.lean" +diff -r "$solar/scripts/evm-rules/lean/EvmRules" "$root/vendor/evm-rules/EvmRules" +echo "vendor/evm-rules matches $solar" diff --git a/tv/SolarTV.lean b/tv/SolarTV.lean new file mode 100644 index 00000000..5ebe119d --- /dev/null +++ b/tv/SolarTV.lean @@ -0,0 +1,255 @@ +import SolarTV.MIR.Transforms.DCE +import SolarTV.MIR.Transforms.Casts +import SolarTV.MIR.Transforms.CheckElim +import SolarTV.MIR.Transforms.TrimSwitchDefaults +import SolarTV.MIR.Transforms.RenamePhiPredecessors +import SolarTV.EVMIR.Transforms.EqIszeroJumpi +import SolarTV.EVMIR.Transforms.StackPeephole +import SolarTV.EVMIR.StackSafety +import SolarTV.EVMIR.Memory +import SolarTV.MIR.Transforms.DeadStore +import SolarTV.MemorySafety +import SolarTV.MemorySymbolic +import SolarTV.MemorySymbolicSafety +import SolarTV.EVMIR.GasSafety +import SolarTV.EVMIR.Transforms.GasSwapAdd +import SolarTV.Stages.Assembly +import SolarTV.Stages.Link +import SolarTV.Stages.Entries + +import SolarTV.Agreement.Encoder +import SolarTV.Composition +import SolarTV.CutPoint +import SolarTV.CutPointExamples +import SolarTV.MIR.Validation.AddZero + +import SolarTV.State.StorageSafety +import SolarTV.State.Calls +import SolarTV.KeccakSafety +import SolarTV.WordSafety + +import SolarTV.EVMIR.State.Normalize +import SolarTV.EVMIR.State.Observe +import SolarTV.EVMIR.State.Safety +import SolarTV.EVMIR.Precompiles.Observe +import SolarTV.EVMIR.Precompiles.Safety +import SolarTV.MIR.State.Observe +import SolarTV.MIR.State.Safety +import SolarTV.MIR.State.Normalize + +-- Keep the transitive axiom sets visible on the pinned toolchain. An admitted +-- proof introduces sorryAx and fails the build even if it lives in an import. +/-- info: 'SolarTV.CutPoint.Sim.ends' depends on axioms: [propext, Quot.sound] -/ +#guard_msgs in +#print axioms SolarTV.CutPoint.Sim.ends + +/-- info: 'SolarTV.CutPoint.Sim.diverges_iff' depends on axioms: [propext, Quot.sound] -/ +#guard_msgs in +#print axioms SolarTV.CutPoint.Sim.diverges_iff + +/-- info: 'SolarTV.CutPoint.LayerSim.certified' depends on axioms: [propext, Quot.sound] -/ +#guard_msgs in +#print axioms SolarTV.CutPoint.LayerSim.certified + +/-- info: 'SolarTV.CutPoint.LayerSim.certified_back' depends on axioms: [propext, Quot.sound] -/ +#guard_msgs in +#print axioms SolarTV.CutPoint.LayerSim.certified_back + +/-- info: 'SolarTV.CutPoint.seg_ne_fuel' depends on axioms: [propext, Quot.sound] -/ +#guard_msgs in +#print axioms SolarTV.CutPoint.seg_ne_fuel + +/-- info: 'SolarTV.MIR.simplify_switch' depends on axioms: [propext] -/ +#guard_msgs in +#print axioms SolarTV.MIR.simplify_switch + +/-- info: 'SolarTV.EVM.eq_iszero_jumpi' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms SolarTV.EVM.eq_iszero_jumpi + +/-- info: 'SolarTV.MIR.erase_unused' depends on axioms: [propext, Quot.sound] -/ +#guard_msgs in +#print axioms SolarTV.MIR.erase_unused + +/-- info: 'SolarTV.MIR.rename_phi_predecessors' depends on axioms: [propext] -/ +#guard_msgs in +#print axioms SolarTV.MIR.rename_phi_predecessors + +/-- info: 'SolarTV.MIR.truncate_extended_address' depends on axioms: [propext, Quot.sound] -/ +#guard_msgs in +#print axioms SolarTV.MIR.truncate_extended_address + +/-- info: 'SolarTV.MIR.increment_below_bound' depends on axioms: [propext, Quot.sound] -/ +#guard_msgs in +#print axioms SolarTV.MIR.increment_below_bound + +/-- info: 'SolarTV.MIR.cannot_drop_overflow' depends on axioms: [propext, Quot.sound] -/ +#guard_msgs in +#print axioms SolarTV.MIR.cannot_drop_overflow + +/-- info: 'SolarTV.EVM.swap_add' depends on axioms: [propext, Quot.sound] -/ +#guard_msgs in +#print axioms SolarTV.EVM.swap_add + +/-- info: 'SolarTV.EVM.dropping_full_push_pop_changes_outcome' depends on axioms: [propext, Quot.sound] -/ +#guard_msgs in +#print axioms SolarTV.EVM.dropping_full_push_pop_changes_outcome + +/-- info: 'SolarTV.MIR.dead_store' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms SolarTV.MIR.dead_store + +/-- info: 'SolarTV.EVM.Gas.swap_add_refines' depends on axioms: [propext, Quot.sound] -/ +#guard_msgs in +#print axioms SolarTV.EVM.Gas.swap_add_refines + +/-- info: 'SolarTV.Assembly.stage' depends on axioms: [propext, Quot.sound] -/ +#guard_msgs in +#print axioms SolarTV.Assembly.stage + +/-- info: 'SolarTV.Assembly.example_fault' depends on axioms: [propext, Quot.sound] -/ +#guard_msgs in +#print axioms SolarTV.Assembly.example_fault + +/-- info: 'SolarTV.Entries.to_bytecode' does not depend on any axioms -/ +#guard_msgs in +#print axioms SolarTV.Entries.to_bytecode + +-- The agreement theorems that the pass validation encoder's terms are the Lean semantics. +-- They are kernel proofs: none bit-blasts, so none depends on a natively evaluated check. +/-- info: 'SolarTV.Agreement.step_sdiv' depends on axioms: [propext, Quot.sound] -/ +#guard_msgs in +#print axioms SolarTV.Agreement.step_sdiv + +/-- info: 'SolarTV.Agreement.abstract_mulmod' depends on axioms: [propext, Quot.sound] -/ +#guard_msgs in +#print axioms SolarTV.Agreement.abstract_mulmod + +/-- +info: 'SolarTV.Agreement.word_signextend' depends on axioms: [propext, Classical.choice, Quot.sound] +-/ +#guard_msgs in +#print axioms SolarTV.Agreement.word_signextend + +/-- +info: 'SolarTV.Agreement.mir_add_i160' depends on axioms: [propext, Classical.choice, Quot.sound] +-/ +#guard_msgs in +#print axioms SolarTV.Agreement.mir_add_i160 +/-- +info: 'SolarTV.Agreement.word_byte' depends on axioms: [propext, Quot.sound] +-/ +#guard_msgs in +#print axioms SolarTV.Agreement.word_byte + +/-- +info: 'SolarTV.Agreement.mir_shl_i160' depends on axioms: [propext, Classical.choice, Quot.sound] +-/ +#guard_msgs in +#print axioms SolarTV.Agreement.mir_shl_i160 + +/-- +info: 'SolarTV.Agreement.mir_lt_i1' depends on axioms: [propext, Classical.choice, Quot.sound] +-/ +#guard_msgs in +#print axioms SolarTV.Agreement.mir_lt_i1 + +/-- +info: 'SolarTV.Agreement.mir_sext_i160_i256' depends on axioms: [propext, Classical.choice, Quot.sound] +-/ +#guard_msgs in +#print axioms SolarTV.Agreement.mir_sext_i160_i256 +-- Contract semantics and the composition of stages. +/-- info: 'SolarTV.mir_to_evmir_certified' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms SolarTV.mir_to_evmir_certified + +/-- info: 'SolarTV.mir_to_bytecode' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms SolarTV.mir_to_bytecode + +/-- +info: 'SolarTV.MIR.Lowered.failureConvention' depends on axioms: [propext, Classical.choice, Quot.sound] +-/ +#guard_msgs in +#print axioms SolarTV.MIR.Lowered.failureConvention + +/-- +info: 'SolarTV.MIR.Lowered.moduleFailureConvention' depends on axioms: [propext, Classical.choice, Quot.sound] +-/ +#guard_msgs in +#print axioms SolarTV.MIR.Lowered.moduleFailureConvention + +/-- +info: 'SolarTV.EVM.Program.failureConvention' depends on axioms: [propext, Classical.choice, Quot.sound] +-/ +#guard_msgs in +#print axioms SolarTV.EVM.Program.failureConvention + +/-- +info: 'SolarTV.EVM.Program.stepOp_project' depends on axioms: [propext, Classical.choice, Quot.sound] +-/ +#guard_msgs in +#print axioms SolarTV.EVM.Program.stepOp_project +-- One pass validation query lifted to a stage. +/-- +info: 'SolarTV.MIR.Validation.AddZero.stage' depends on axioms: [propext, Classical.choice, Quot.sound] +-/ +#guard_msgs in +#print axioms SolarTV.MIR.Validation.AddZero.stage + +/-- info: 'SolarTV.Word.power_eq_pow' depends on axioms: [propext, Quot.sound] -/ +#guard_msgs in +#print axioms SolarTV.Word.power_eq_pow + +/-- info: 'SolarTV.Keccak.empty' depends on axioms: [propext, Quot.sound] -/ +#guard_msgs in +#print axioms SolarTV.Keccak.empty + +/-- info: 'SolarTV.Storage.overwrite' depends on axioms: [propext, Quot.sound] -/ +#guard_msgs in +#print axioms SolarTV.Storage.overwrite + +/-- info: 'SolarTV.Storage.sentry_rejects' depends on axioms: [propext, Quot.sound] -/ +#guard_msgs in +#print axioms SolarTV.Storage.sentry_rejects + +/-- info: 'SolarTV.Calls.reverted_restores_journal' does not depend on any axioms -/ +#guard_msgs in +#print axioms SolarTV.Calls.reverted_restores_journal + +/-- info: 'SolarTV.MIR.State.simultaneous_phis' depends on axioms: [propext, Quot.sound] -/ +#guard_msgs in +#print axioms SolarTV.MIR.State.simultaneous_phis + +/-- info: 'SolarTV.MIR.State.work_limit_is_not_equivalence' depends on axioms: [propext] -/ +#guard_msgs in +#print axioms SolarTV.MIR.State.work_limit_is_not_equivalence + +/-- info: 'SolarTV.Execution.slotsWrite_overwrite' depends on axioms: [propext, Quot.sound] -/ +#guard_msgs in +#print axioms SolarTV.Execution.slotsWrite_overwrite + +/-- info: 'SolarTV.Execution.flatten_wordBytes' depends on axioms: [propext, Quot.sound] -/ +#guard_msgs in +#print axioms SolarTV.Execution.flatten_wordBytes + +/-- info: 'SolarTV.Execution.readWord_writeWord' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms SolarTV.Execution.readWord_writeWord + +/-- info: 'SolarTV.MIR.State.run_next' depends on axioms: [propext, Quot.sound] -/ +#guard_msgs in +#print axioms SolarTV.MIR.State.run_next + +/-- info: 'SolarTV.MIR.State.live_return_data_is_observable' depends on axioms: [propext] -/ +#guard_msgs in +#print axioms SolarTV.MIR.State.live_return_data_is_observable + +/-- info: 'SolarTV.MIR.State.project_inserted_field' depends on axioms: [propext] -/ +#guard_msgs in +#print axioms SolarTV.MIR.State.project_inserted_field + +/-- info: 'SolarTV.MIR.State.uninitialized_neighbor' depends on axioms: [propext] -/ +#guard_msgs in +#print axioms SolarTV.MIR.State.uninitialized_neighbor diff --git a/tv/SolarTV/Agreement/Encoder.lean b/tv/SolarTV/Agreement/Encoder.lean new file mode 100644 index 00000000..fe45194a --- /dev/null +++ b/tv/SolarTV/Agreement/Encoder.lean @@ -0,0 +1,768 @@ +import SolarTV.Agreement.Tactic + +/-! Agreement of the pass validation encoder with the Lean semantics. + +Generated by the `lean_agreement` test in +`crates/codegen/src/mir/transform/validate_passes.rs`: do not edit by hand. Each term is +the one the encoder (`Encoder::pure`, `low_bits`, `sign_extend`, `not_equal` and +`select`) gives an operation on symbolic operands, translated to Lean by the certifier's +`word_term`, so a mistranslation of either fails these proofs. + +- `word_X` and `step_X`: the term of each pure opcode the encoder models exactly is its + `EvmRules.Evm` definition, and so the result `SolarTV.EVM.step` pushes. +- `exp_X`: the constant shapes of `EXP` the encoder computes exactly. +- `abstract_X`: the abstract tier's laws hold of the exact operation, so replacing it + with an uninterpreted function constrained by them only allows more models. +- `mir_X_iN`: the term of each MIR operation on `iN` operands, which the encoder keeps + as zero-extended words and masks to their width, is the zero-extended result of its + `SolarTV.MIR` definition. Signed operations read the sign bit of a word, so the + encoder rejects them on narrow integers and they appear at `i256` only. +-/ + +namespace SolarTV.Agreement + +open EvmRules + +set_option linter.unusedSimpArgs false + +theorem word_add («$a» «$b» : Word) : + («$a» + «$b») = + Evm.add «$a» «$b» := by + agree_word + +theorem step_add (ctx : EVM.Context) («$a» «$b» : Word) (rest : EVM.Stack) : + EVM.step ctx .add («$a» :: «$b» :: rest) = + some ((«$a» + «$b») :: rest) := by + rw [word_add]; rfl + +theorem word_mul («$a» «$b» : Word) : + («$a» * «$b») = + Evm.mul «$a» «$b» := by + agree_word + +theorem step_mul (ctx : EVM.Context) («$a» «$b» : Word) (rest : EVM.Stack) : + EVM.step ctx .mul («$a» :: «$b» :: rest) = + some ((«$a» * «$b») :: rest) := by + rw [word_mul]; rfl + +theorem word_sub («$a» «$b» : Word) : + («$a» - «$b») = + Evm.sub «$a» «$b» := by + agree_word + +theorem step_sub (ctx : EVM.Context) («$a» «$b» : Word) (rest : EVM.Stack) : + EVM.step ctx .sub («$a» :: «$b» :: rest) = + some ((«$a» - «$b») :: rest) := by + rw [word_sub]; rfl + +theorem word_div («$a» «$b» : Word) : + (if («$b» = (0x0000000000000000000000000000000000000000000000000000000000000000#256)) then (0x0000000000000000000000000000000000000000000000000000000000000000#256) else (BitVec.smtUDiv «$a» «$b»)) = + Evm.div «$a» «$b» := by + agree_word + +theorem step_div (ctx : EVM.Context) («$a» «$b» : Word) (rest : EVM.Stack) : + EVM.step ctx .div («$a» :: «$b» :: rest) = + some ((if («$b» = (0x0000000000000000000000000000000000000000000000000000000000000000#256)) then (0x0000000000000000000000000000000000000000000000000000000000000000#256) else (BitVec.smtUDiv «$a» «$b»)) :: rest) := by + rw [word_div]; rfl + +theorem word_sdiv («$a» «$b» : Word) : + (if («$b» = (0x0000000000000000000000000000000000000000000000000000000000000000#256)) then (0x0000000000000000000000000000000000000000000000000000000000000000#256) else (BitVec.smtSDiv «$a» «$b»)) = + Evm.sdiv «$a» «$b» := by + agree_word + +theorem step_sdiv (ctx : EVM.Context) («$a» «$b» : Word) (rest : EVM.Stack) : + EVM.step ctx .sdiv («$a» :: «$b» :: rest) = + some ((if («$b» = (0x0000000000000000000000000000000000000000000000000000000000000000#256)) then (0x0000000000000000000000000000000000000000000000000000000000000000#256) else (BitVec.smtSDiv «$a» «$b»)) :: rest) := by + rw [word_sdiv]; rfl + +theorem word_mod («$a» «$b» : Word) : + (if («$b» = (0x0000000000000000000000000000000000000000000000000000000000000000#256)) then (0x0000000000000000000000000000000000000000000000000000000000000000#256) else (BitVec.umod «$a» «$b»)) = + Evm.mod «$a» «$b» := by + agree_word + +theorem step_mod (ctx : EVM.Context) («$a» «$b» : Word) (rest : EVM.Stack) : + EVM.step ctx .mod («$a» :: «$b» :: rest) = + some ((if («$b» = (0x0000000000000000000000000000000000000000000000000000000000000000#256)) then (0x0000000000000000000000000000000000000000000000000000000000000000#256) else (BitVec.umod «$a» «$b»)) :: rest) := by + rw [word_mod]; rfl + +theorem word_smod («$a» «$b» : Word) : + (if («$b» = (0x0000000000000000000000000000000000000000000000000000000000000000#256)) then (0x0000000000000000000000000000000000000000000000000000000000000000#256) else (BitVec.srem «$a» «$b»)) = + Evm.smod «$a» «$b» := by + agree_word + +theorem step_smod (ctx : EVM.Context) («$a» «$b» : Word) (rest : EVM.Stack) : + EVM.step ctx .smod («$a» :: «$b» :: rest) = + some ((if («$b» = (0x0000000000000000000000000000000000000000000000000000000000000000#256)) then (0x0000000000000000000000000000000000000000000000000000000000000000#256) else (BitVec.srem «$a» «$b»)) :: rest) := by + rw [word_smod]; rfl + +theorem word_addmod («$a» «$b» «$c» : Word) : + (if («$c» = (0x0000000000000000000000000000000000000000000000000000000000000000#256)) then (0x0000000000000000000000000000000000000000000000000000000000000000#256) else (BitVec.extractLsb' 0 256 (BitVec.umod ((BitVec.setWidth 257 «$a») + (BitVec.setWidth 257 «$b»)) (BitVec.setWidth 257 «$c»)))) = + Evm.addmod «$a» «$b» «$c» := by + agree_word + +theorem step_addmod (ctx : EVM.Context) («$a» «$b» «$c» : Word) (rest : EVM.Stack) : + EVM.step ctx .addmod («$a» :: «$b» :: «$c» :: rest) = + some ((if («$c» = (0x0000000000000000000000000000000000000000000000000000000000000000#256)) then (0x0000000000000000000000000000000000000000000000000000000000000000#256) else (BitVec.extractLsb' 0 256 (BitVec.umod ((BitVec.setWidth 257 «$a») + (BitVec.setWidth 257 «$b»)) (BitVec.setWidth 257 «$c»)))) :: rest) := by + rw [word_addmod]; rfl + +theorem word_mulmod («$a» «$b» «$c» : Word) : + (if («$c» = (0x0000000000000000000000000000000000000000000000000000000000000000#256)) then (0x0000000000000000000000000000000000000000000000000000000000000000#256) else (BitVec.extractLsb' 0 256 (BitVec.umod ((BitVec.setWidth 512 «$a») * (BitVec.setWidth 512 «$b»)) (BitVec.setWidth 512 «$c»)))) = + Evm.mulmod «$a» «$b» «$c» := by + agree_word + +theorem step_mulmod (ctx : EVM.Context) («$a» «$b» «$c» : Word) (rest : EVM.Stack) : + EVM.step ctx .mulmod («$a» :: «$b» :: «$c» :: rest) = + some ((if («$c» = (0x0000000000000000000000000000000000000000000000000000000000000000#256)) then (0x0000000000000000000000000000000000000000000000000000000000000000#256) else (BitVec.extractLsb' 0 256 (BitVec.umod ((BitVec.setWidth 512 «$a») * (BitVec.setWidth 512 «$b»)) (BitVec.setWidth 512 «$c»)))) :: rest) := by + rw [word_mulmod]; rfl + +theorem word_signextend («$a» «$b» : Word) : + (if («$a» ≥ (0x000000000000000000000000000000000000000000000000000000000000001f#256)) then «$b» else (BitVec.sshiftRight' («$b» <<< ((0x00000000000000000000000000000000000000000000000000000000000000f8#256) - ((0x0000000000000000000000000000000000000000000000000000000000000008#256) * «$a»))) ((0x00000000000000000000000000000000000000000000000000000000000000f8#256) - ((0x0000000000000000000000000000000000000000000000000000000000000008#256) * «$a»)))) = + Evm.signextend «$a» «$b» := by + agree_word + +theorem step_signextend (ctx : EVM.Context) («$a» «$b» : Word) (rest : EVM.Stack) : + EVM.step ctx .signextend («$a» :: «$b» :: rest) = + some ((if («$a» ≥ (0x000000000000000000000000000000000000000000000000000000000000001f#256)) then «$b» else (BitVec.sshiftRight' («$b» <<< ((0x00000000000000000000000000000000000000000000000000000000000000f8#256) - ((0x0000000000000000000000000000000000000000000000000000000000000008#256) * «$a»))) ((0x00000000000000000000000000000000000000000000000000000000000000f8#256) - ((0x0000000000000000000000000000000000000000000000000000000000000008#256) * «$a»)))) :: rest) := by + rw [word_signextend]; rfl + +theorem word_lt («$a» «$b» : Word) : + (if («$a» < «$b») then (0x0000000000000000000000000000000000000000000000000000000000000001#256) else (0x0000000000000000000000000000000000000000000000000000000000000000#256)) = + Evm.lt «$a» «$b» := by + agree_word + +theorem step_lt (ctx : EVM.Context) («$a» «$b» : Word) (rest : EVM.Stack) : + EVM.step ctx .lt («$a» :: «$b» :: rest) = + some ((if («$a» < «$b») then (0x0000000000000000000000000000000000000000000000000000000000000001#256) else (0x0000000000000000000000000000000000000000000000000000000000000000#256)) :: rest) := by + rw [word_lt]; rfl + +theorem word_gt («$a» «$b» : Word) : + (if («$a» > «$b») then (0x0000000000000000000000000000000000000000000000000000000000000001#256) else (0x0000000000000000000000000000000000000000000000000000000000000000#256)) = + Evm.gt «$a» «$b» := by + agree_word + +theorem step_gt (ctx : EVM.Context) («$a» «$b» : Word) (rest : EVM.Stack) : + EVM.step ctx .gt («$a» :: «$b» :: rest) = + some ((if («$a» > «$b») then (0x0000000000000000000000000000000000000000000000000000000000000001#256) else (0x0000000000000000000000000000000000000000000000000000000000000000#256)) :: rest) := by + rw [word_gt]; rfl + +theorem word_slt («$a» «$b» : Word) : + (if ((BitVec.slt «$a» «$b») = true) then (0x0000000000000000000000000000000000000000000000000000000000000001#256) else (0x0000000000000000000000000000000000000000000000000000000000000000#256)) = + Evm.slt «$a» «$b» := by + agree_word + +theorem step_slt (ctx : EVM.Context) («$a» «$b» : Word) (rest : EVM.Stack) : + EVM.step ctx .slt («$a» :: «$b» :: rest) = + some ((if ((BitVec.slt «$a» «$b») = true) then (0x0000000000000000000000000000000000000000000000000000000000000001#256) else (0x0000000000000000000000000000000000000000000000000000000000000000#256)) :: rest) := by + rw [word_slt]; rfl + +theorem word_sgt («$a» «$b» : Word) : + (if ((BitVec.slt «$b» «$a») = true) then (0x0000000000000000000000000000000000000000000000000000000000000001#256) else (0x0000000000000000000000000000000000000000000000000000000000000000#256)) = + Evm.sgt «$a» «$b» := by + agree_word + +theorem step_sgt (ctx : EVM.Context) («$a» «$b» : Word) (rest : EVM.Stack) : + EVM.step ctx .sgt («$a» :: «$b» :: rest) = + some ((if ((BitVec.slt «$b» «$a») = true) then (0x0000000000000000000000000000000000000000000000000000000000000001#256) else (0x0000000000000000000000000000000000000000000000000000000000000000#256)) :: rest) := by + rw [word_sgt]; rfl + +theorem word_eq («$a» «$b» : Word) : + (if («$a» = «$b») then (0x0000000000000000000000000000000000000000000000000000000000000001#256) else (0x0000000000000000000000000000000000000000000000000000000000000000#256)) = + Evm.eq «$a» «$b» := by + agree_word + +theorem step_eq (ctx : EVM.Context) («$a» «$b» : Word) (rest : EVM.Stack) : + EVM.step ctx .eq («$a» :: «$b» :: rest) = + some ((if («$a» = «$b») then (0x0000000000000000000000000000000000000000000000000000000000000001#256) else (0x0000000000000000000000000000000000000000000000000000000000000000#256)) :: rest) := by + rw [word_eq]; rfl + +theorem word_iszero («$a» : Word) : + (if («$a» = (0x0000000000000000000000000000000000000000000000000000000000000000#256)) then (0x0000000000000000000000000000000000000000000000000000000000000001#256) else (0x0000000000000000000000000000000000000000000000000000000000000000#256)) = + Evm.iszero «$a» := by + agree_word + +theorem step_iszero (ctx : EVM.Context) («$a» : Word) (rest : EVM.Stack) : + EVM.step ctx .iszero («$a» :: rest) = + some ((if («$a» = (0x0000000000000000000000000000000000000000000000000000000000000000#256)) then (0x0000000000000000000000000000000000000000000000000000000000000001#256) else (0x0000000000000000000000000000000000000000000000000000000000000000#256)) :: rest) := by + rw [word_iszero]; rfl + +theorem word_and («$a» «$b» : Word) : + («$a» &&& «$b») = + Evm.and «$a» «$b» := by + agree_word + +theorem step_and (ctx : EVM.Context) («$a» «$b» : Word) (rest : EVM.Stack) : + EVM.step ctx .and («$a» :: «$b» :: rest) = + some ((«$a» &&& «$b») :: rest) := by + rw [word_and]; rfl + +theorem word_or («$a» «$b» : Word) : + («$a» ||| «$b») = + Evm.or «$a» «$b» := by + agree_word + +theorem step_or (ctx : EVM.Context) («$a» «$b» : Word) (rest : EVM.Stack) : + EVM.step ctx .or («$a» :: «$b» :: rest) = + some ((«$a» ||| «$b») :: rest) := by + rw [word_or]; rfl + +theorem word_xor («$a» «$b» : Word) : + («$a» ^^^ «$b») = + Evm.xor «$a» «$b» := by + agree_word + +theorem step_xor (ctx : EVM.Context) («$a» «$b» : Word) (rest : EVM.Stack) : + EVM.step ctx .xor («$a» :: «$b» :: rest) = + some ((«$a» ^^^ «$b») :: rest) := by + rw [word_xor]; rfl + +theorem word_not («$a» : Word) : + (~~~«$a») = + Evm.not «$a» := by + agree_word + +theorem step_not (ctx : EVM.Context) («$a» : Word) (rest : EVM.Stack) : + EVM.step ctx .not («$a» :: rest) = + some ((~~~«$a») :: rest) := by + rw [word_not]; rfl + +theorem word_byte («$a» «$b» : Word) : + (if («$a» ≥ (0x0000000000000000000000000000000000000000000000000000000000000020#256)) then (0x0000000000000000000000000000000000000000000000000000000000000000#256) else ((«$b» >>> (((0x000000000000000000000000000000000000000000000000000000000000001f#256) - «$a») * (0x0000000000000000000000000000000000000000000000000000000000000008#256))) &&& (0x00000000000000000000000000000000000000000000000000000000000000ff#256))) = + Evm.byte «$a» «$b» := by + agree_word + +theorem step_byte (ctx : EVM.Context) («$a» «$b» : Word) (rest : EVM.Stack) : + EVM.step ctx .byte («$a» :: «$b» :: rest) = + some ((if («$a» ≥ (0x0000000000000000000000000000000000000000000000000000000000000020#256)) then (0x0000000000000000000000000000000000000000000000000000000000000000#256) else ((«$b» >>> (((0x000000000000000000000000000000000000000000000000000000000000001f#256) - «$a») * (0x0000000000000000000000000000000000000000000000000000000000000008#256))) &&& (0x00000000000000000000000000000000000000000000000000000000000000ff#256))) :: rest) := by + rw [word_byte]; rfl + +theorem word_shl («$a» «$b» : Word) : + (if («$a» ≥ (0x0000000000000000000000000000000000000000000000000000000000000100#256)) then (0x0000000000000000000000000000000000000000000000000000000000000000#256) else («$b» <<< «$a»)) = + Evm.shl «$a» «$b» := by + agree_word + +theorem step_shl (ctx : EVM.Context) («$a» «$b» : Word) (rest : EVM.Stack) : + EVM.step ctx .shl («$a» :: «$b» :: rest) = + some ((if («$a» ≥ (0x0000000000000000000000000000000000000000000000000000000000000100#256)) then (0x0000000000000000000000000000000000000000000000000000000000000000#256) else («$b» <<< «$a»)) :: rest) := by + rw [word_shl]; rfl + +theorem word_shr («$a» «$b» : Word) : + (if («$a» ≥ (0x0000000000000000000000000000000000000000000000000000000000000100#256)) then (0x0000000000000000000000000000000000000000000000000000000000000000#256) else («$b» >>> «$a»)) = + Evm.shr «$a» «$b» := by + agree_word + +theorem step_shr (ctx : EVM.Context) («$a» «$b» : Word) (rest : EVM.Stack) : + EVM.step ctx .shr («$a» :: «$b» :: rest) = + some ((if («$a» ≥ (0x0000000000000000000000000000000000000000000000000000000000000100#256)) then (0x0000000000000000000000000000000000000000000000000000000000000000#256) else («$b» >>> «$a»)) :: rest) := by + rw [word_shr]; rfl + +theorem word_sar («$a» «$b» : Word) : + (if («$a» ≥ (0x0000000000000000000000000000000000000000000000000000000000000100#256)) then (BitVec.sshiftRight' «$b» (0x00000000000000000000000000000000000000000000000000000000000000ff#256)) else (BitVec.sshiftRight' «$b» «$a»)) = + Evm.sar «$a» «$b» := by + agree_word + +theorem step_sar (ctx : EVM.Context) («$a» «$b» : Word) (rest : EVM.Stack) : + EVM.step ctx .sar («$a» :: «$b» :: rest) = + some ((if («$a» ≥ (0x0000000000000000000000000000000000000000000000000000000000000100#256)) then (BitVec.sshiftRight' «$b» (0x00000000000000000000000000000000000000000000000000000000000000ff#256)) else (BitVec.sshiftRight' «$b» «$a»)) :: rest) := by + rw [word_sar]; rfl + +theorem exp_base_0 («$e» : Word) : + (if («$e» = (0x0000000000000000000000000000000000000000000000000000000000000000#256)) then (0x0000000000000000000000000000000000000000000000000000000000000001#256) else (0x0000000000000000000000000000000000000000000000000000000000000000#256)) = + Evm.exp 0#256 «$e» := by + agree_exp + +theorem exp_base_1 («$e» : Word) : + (0x0000000000000000000000000000000000000000000000000000000000000001#256) = + Evm.exp 1#256 «$e» := by + agree_exp + +theorem exp_base_2 («$e» : Word) : + (if («$e» ≥ (0x0000000000000000000000000000000000000000000000000000000000000100#256)) then (0x0000000000000000000000000000000000000000000000000000000000000000#256) else ((0x0000000000000000000000000000000000000000000000000000000000000001#256) <<< («$e» * (0x0000000000000000000000000000000000000000000000000000000000000001#256)))) = + Evm.exp 2#256 «$e» := by + agree_exp + +theorem exp_base_16 («$e» : Word) : + (if («$e» ≥ (0x0000000000000000000000000000000000000000000000000000000000000040#256)) then (0x0000000000000000000000000000000000000000000000000000000000000000#256) else ((0x0000000000000000000000000000000000000000000000000000000000000001#256) <<< («$e» * (0x0000000000000000000000000000000000000000000000000000000000000004#256)))) = + Evm.exp 16#256 «$e» := by + agree_exp + +theorem exp_base_256 («$e» : Word) : + (if («$e» ≥ (0x0000000000000000000000000000000000000000000000000000000000000020#256)) then (0x0000000000000000000000000000000000000000000000000000000000000000#256) else ((0x0000000000000000000000000000000000000000000000000000000000000001#256) <<< («$e» * (0x0000000000000000000000000000000000000000000000000000000000000008#256)))) = + Evm.exp 256#256 «$e» := by + agree_exp + +theorem exp_power_0 («$a» : Word) : + (0x0000000000000000000000000000000000000000000000000000000000000001#256) = + Evm.exp «$a» 0#256 := by + agree_exp + +theorem exp_power_1 («$a» : Word) : + ((0x0000000000000000000000000000000000000000000000000000000000000001#256) * «$a») = + Evm.exp «$a» 1#256 := by + agree_exp + +theorem exp_power_2 («$a» : Word) : + (((0x0000000000000000000000000000000000000000000000000000000000000001#256) * «$a») * «$a») = + Evm.exp «$a» 2#256 := by + agree_exp + +theorem exp_power_8 («$a» : Word) : + (((((((((0x0000000000000000000000000000000000000000000000000000000000000001#256) * «$a») * «$a») * «$a») * «$a») * «$a») * «$a») * «$a») * «$a») = + Evm.exp «$a» 8#256 := by + agree_exp + +theorem abstract_mul («$a» «$b» «$t» : Word) («$umul» : Word → Word → Word) + (hf : ∀ p q, «$umul» p q = Evm.mul p q) + (ht : «$t» = Evm.mul «$a» «$b») : + ((«$t» = («$umul» «$a» «$b»)) ∧ ((((«$a» = (0x0000000000000000000000000000000000000000000000000000000000000000#256)) ∨ («$b» = (0x0000000000000000000000000000000000000000000000000000000000000000#256))) → («$t» = (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ∧ (((«$a» = (0x0000000000000000000000000000000000000000000000000000000000000001#256)) → («$t» = «$b»)) ∧ (((«$b» = (0x0000000000000000000000000000000000000000000000000000000000000001#256)) → («$t» = «$a»)) ∧ («$t» = («$umul» «$b» «$a»)))))) := by + agree_abstract + +theorem abstract_div («$a» «$b» «$t» : Word) («$udiv» : Word → Word → Word) + (hf : ∀ p q, «$udiv» p q = Evm.div p q) + (ht : «$t» = Evm.div «$a» «$b») : + ((«$t» = («$udiv» «$a» «$b»)) ∧ (((«$b» = (0x0000000000000000000000000000000000000000000000000000000000000000#256)) → («$t» = (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ∧ ((«$t» ≤ «$a») ∧ ((«$b» = (0x0000000000000000000000000000000000000000000000000000000000000001#256)) → («$t» = «$a»))))) := by + agree_abstract + +theorem abstract_mod («$a» «$b» «$t» : Word) («$umod» : Word → Word → Word) + (hf : ∀ p q, «$umod» p q = Evm.mod p q) + (ht : «$t» = Evm.mod «$a» «$b») : + ((«$t» = («$umod» «$a» «$b»)) ∧ (((«$b» = (0x0000000000000000000000000000000000000000000000000000000000000000#256)) → («$t» = (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ∧ (((¬(«$b» = (0x0000000000000000000000000000000000000000000000000000000000000000#256))) → («$t» < «$b»)) ∧ ((«$t» ≤ «$a») ∧ ((«$a» < «$b») → («$t» = «$a»)))))) := by + agree_abstract + +theorem abstract_addmod («$a» «$b» «$c» «$t» : Word) («$addmod3» : Word → Word → Word → Word) + (hf : ∀ p q r, «$addmod3» p q r = Evm.addmod p q r) + (ht : «$t» = Evm.addmod «$a» «$b» «$c») : + ((«$t» = («$addmod3» «$a» «$b» «$c»)) ∧ (((«$c» = (0x0000000000000000000000000000000000000000000000000000000000000000#256)) → («$t» = (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ∧ ((¬(«$c» = (0x0000000000000000000000000000000000000000000000000000000000000000#256))) → («$t» < «$c»)))) := by + agree_abstract + +theorem abstract_mulmod («$a» «$b» «$c» «$t» : Word) («$mulmod3» : Word → Word → Word → Word) + (hf : ∀ p q r, «$mulmod3» p q r = Evm.mulmod p q r) + (ht : «$t» = Evm.mulmod «$a» «$b» «$c») : + ((«$t» = («$mulmod3» «$a» «$b» «$c»)) ∧ (((«$c» = (0x0000000000000000000000000000000000000000000000000000000000000000#256)) → («$t» = (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ∧ ((¬(«$c» = (0x0000000000000000000000000000000000000000000000000000000000000000#256))) → («$t» < «$c»)))) := by + agree_abstract + +theorem mir_add_i1 (x : BitVec 1) (y : BitVec 1) («$a» «$b» : Word) + (ha : «$a» = x.setWidth 256) + (hb : «$b» = y.setWidth 256) : + ((«$a» + «$b») &&& (0x0000000000000000000000000000000000000000000000000000000000000001#256)) = + (MIR.eval .add x y).setWidth 256 := by + agree_mir + +theorem mir_sub_i1 (x : BitVec 1) (y : BitVec 1) («$a» «$b» : Word) + (ha : «$a» = x.setWidth 256) + (hb : «$b» = y.setWidth 256) : + ((«$a» - «$b») &&& (0x0000000000000000000000000000000000000000000000000000000000000001#256)) = + (MIR.eval .sub x y).setWidth 256 := by + agree_mir + +theorem mir_mul_i1 (x : BitVec 1) (y : BitVec 1) («$a» «$b» : Word) + (ha : «$a» = x.setWidth 256) + (hb : «$b» = y.setWidth 256) : + ((«$a» * «$b») &&& (0x0000000000000000000000000000000000000000000000000000000000000001#256)) = + (MIR.eval .mul x y).setWidth 256 := by + agree_mir + +theorem mir_and_i1 (x : BitVec 1) (y : BitVec 1) («$a» «$b» : Word) + (ha : «$a» = x.setWidth 256) + (hb : «$b» = y.setWidth 256) : + ((«$a» &&& «$b») &&& (0x0000000000000000000000000000000000000000000000000000000000000001#256)) = + (MIR.eval .and x y).setWidth 256 := by + agree_mir + +theorem mir_or_i1 (x : BitVec 1) (y : BitVec 1) («$a» «$b» : Word) + (ha : «$a» = x.setWidth 256) + (hb : «$b» = y.setWidth 256) : + ((«$a» ||| «$b») &&& (0x0000000000000000000000000000000000000000000000000000000000000001#256)) = + (MIR.eval .or x y).setWidth 256 := by + agree_mir + +theorem mir_xor_i1 (x : BitVec 1) (y : BitVec 1) («$a» «$b» : Word) + (ha : «$a» = x.setWidth 256) + (hb : «$b» = y.setWidth 256) : + ((«$a» ^^^ «$b») &&& (0x0000000000000000000000000000000000000000000000000000000000000001#256)) = + (MIR.eval .xor x y).setWidth 256 := by + agree_mir + +theorem mir_div_i1 (x : BitVec 1) (y : BitVec 1) («$a» «$b» : Word) + (ha : «$a» = x.setWidth 256) + (hb : «$b» = y.setWidth 256) : + ((if («$b» = (0x0000000000000000000000000000000000000000000000000000000000000000#256)) then (0x0000000000000000000000000000000000000000000000000000000000000000#256) else (BitVec.smtUDiv «$a» «$b»)) &&& (0x0000000000000000000000000000000000000000000000000000000000000001#256)) = + (MIR.eval .div x y).setWidth 256 := by + agree_mir + +theorem mir_mod_i1 (x : BitVec 1) (y : BitVec 1) («$a» «$b» : Word) + (ha : «$a» = x.setWidth 256) + (hb : «$b» = y.setWidth 256) : + ((if («$b» = (0x0000000000000000000000000000000000000000000000000000000000000000#256)) then (0x0000000000000000000000000000000000000000000000000000000000000000#256) else (BitVec.umod «$a» «$b»)) &&& (0x0000000000000000000000000000000000000000000000000000000000000001#256)) = + (MIR.eval .mod x y).setWidth 256 := by + agree_mir + +theorem mir_shl_i1 (x : BitVec 1) (y : BitVec 1) («$a» «$b» : Word) + (ha : «$a» = x.setWidth 256) + (hb : «$b» = y.setWidth 256) : + ((if («$a» ≥ (0x0000000000000000000000000000000000000000000000000000000000000100#256)) then (0x0000000000000000000000000000000000000000000000000000000000000000#256) else («$b» <<< «$a»)) &&& (0x0000000000000000000000000000000000000000000000000000000000000001#256)) = + (MIR.eval .shl x y).setWidth 256 := by + agree_mir + +theorem mir_shr_i1 (x : BitVec 1) (y : BitVec 1) («$a» «$b» : Word) + (ha : «$a» = x.setWidth 256) + (hb : «$b» = y.setWidth 256) : + ((if («$a» ≥ (0x0000000000000000000000000000000000000000000000000000000000000100#256)) then (0x0000000000000000000000000000000000000000000000000000000000000000#256) else («$b» >>> «$a»)) &&& (0x0000000000000000000000000000000000000000000000000000000000000001#256)) = + (MIR.eval .shr x y).setWidth 256 := by + agree_mir + +theorem mir_not_i1 (x : BitVec 1) («$a» : Word) + (ha : «$a» = x.setWidth 256) : + ((~~~«$a») &&& (0x0000000000000000000000000000000000000000000000000000000000000001#256)) = + (MIR.not x).setWidth 256 := by + agree_mir + +theorem mir_lt_i1 (x : BitVec 1) (y : BitVec 1) («$a» «$b» : Word) + (ha : «$a» = x.setWidth 256) + (hb : «$b» = y.setWidth 256) : + ((if («$a» < «$b») then (0x0000000000000000000000000000000000000000000000000000000000000001#256) else (0x0000000000000000000000000000000000000000000000000000000000000000#256)) &&& (0x0000000000000000000000000000000000000000000000000000000000000001#256)) = + (MIR.compare .lt x y).setWidth 256 := by + agree_mir + +theorem mir_gt_i1 (x : BitVec 1) (y : BitVec 1) («$a» «$b» : Word) + (ha : «$a» = x.setWidth 256) + (hb : «$b» = y.setWidth 256) : + ((if («$a» > «$b») then (0x0000000000000000000000000000000000000000000000000000000000000001#256) else (0x0000000000000000000000000000000000000000000000000000000000000000#256)) &&& (0x0000000000000000000000000000000000000000000000000000000000000001#256)) = + (MIR.compare .gt x y).setWidth 256 := by + agree_mir + +theorem mir_eq_i1 (x : BitVec 1) (y : BitVec 1) («$a» «$b» : Word) + (ha : «$a» = x.setWidth 256) + (hb : «$b» = y.setWidth 256) : + ((if («$a» = «$b») then (0x0000000000000000000000000000000000000000000000000000000000000001#256) else (0x0000000000000000000000000000000000000000000000000000000000000000#256)) &&& (0x0000000000000000000000000000000000000000000000000000000000000001#256)) = + (MIR.compare .eq x y).setWidth 256 := by + agree_mir + +theorem mir_ne_i1 (x : BitVec 1) (y : BitVec 1) («$a» «$b» : Word) + (ha : «$a» = x.setWidth 256) + (hb : «$b» = y.setWidth 256) : + (if («$a» = «$b») then (0x0000000000000000000000000000000000000000000000000000000000000000#256) else (0x0000000000000000000000000000000000000000000000000000000000000001#256)) = + (MIR.compare .ne x y).setWidth 256 := by + agree_mir + +theorem mir_select_i1 (x : BitVec 1) (y : BitVec 1) (z : BitVec 1) («$a» «$b» «$c» : Word) + (ha : «$a» = x.setWidth 256) + (hb : «$b» = y.setWidth 256) + (hc : «$c» = z.setWidth 256) : + (if («$a» = (0x0000000000000000000000000000000000000000000000000000000000000000#256)) then «$c» else «$b») = + (MIR.select x y z).setWidth 256 := by + agree_mir + +theorem mir_add_i160 (x : BitVec 160) (y : BitVec 160) («$a» «$b» : Word) + (ha : «$a» = x.setWidth 256) + (hb : «$b» = y.setWidth 256) : + ((«$a» + «$b») &&& (0x000000000000000000000000ffffffffffffffffffffffffffffffffffffffff#256)) = + (MIR.eval .add x y).setWidth 256 := by + agree_mir + +theorem mir_sub_i160 (x : BitVec 160) (y : BitVec 160) («$a» «$b» : Word) + (ha : «$a» = x.setWidth 256) + (hb : «$b» = y.setWidth 256) : + ((«$a» - «$b») &&& (0x000000000000000000000000ffffffffffffffffffffffffffffffffffffffff#256)) = + (MIR.eval .sub x y).setWidth 256 := by + agree_mir + +theorem mir_mul_i160 (x : BitVec 160) (y : BitVec 160) («$a» «$b» : Word) + (ha : «$a» = x.setWidth 256) + (hb : «$b» = y.setWidth 256) : + ((«$a» * «$b») &&& (0x000000000000000000000000ffffffffffffffffffffffffffffffffffffffff#256)) = + (MIR.eval .mul x y).setWidth 256 := by + agree_mir + +theorem mir_and_i160 (x : BitVec 160) (y : BitVec 160) («$a» «$b» : Word) + (ha : «$a» = x.setWidth 256) + (hb : «$b» = y.setWidth 256) : + ((«$a» &&& «$b») &&& (0x000000000000000000000000ffffffffffffffffffffffffffffffffffffffff#256)) = + (MIR.eval .and x y).setWidth 256 := by + agree_mir + +theorem mir_or_i160 (x : BitVec 160) (y : BitVec 160) («$a» «$b» : Word) + (ha : «$a» = x.setWidth 256) + (hb : «$b» = y.setWidth 256) : + ((«$a» ||| «$b») &&& (0x000000000000000000000000ffffffffffffffffffffffffffffffffffffffff#256)) = + (MIR.eval .or x y).setWidth 256 := by + agree_mir + +theorem mir_xor_i160 (x : BitVec 160) (y : BitVec 160) («$a» «$b» : Word) + (ha : «$a» = x.setWidth 256) + (hb : «$b» = y.setWidth 256) : + ((«$a» ^^^ «$b») &&& (0x000000000000000000000000ffffffffffffffffffffffffffffffffffffffff#256)) = + (MIR.eval .xor x y).setWidth 256 := by + agree_mir + +theorem mir_div_i160 (x : BitVec 160) (y : BitVec 160) («$a» «$b» : Word) + (ha : «$a» = x.setWidth 256) + (hb : «$b» = y.setWidth 256) : + ((if («$b» = (0x0000000000000000000000000000000000000000000000000000000000000000#256)) then (0x0000000000000000000000000000000000000000000000000000000000000000#256) else (BitVec.smtUDiv «$a» «$b»)) &&& (0x000000000000000000000000ffffffffffffffffffffffffffffffffffffffff#256)) = + (MIR.eval .div x y).setWidth 256 := by + agree_mir + +theorem mir_mod_i160 (x : BitVec 160) (y : BitVec 160) («$a» «$b» : Word) + (ha : «$a» = x.setWidth 256) + (hb : «$b» = y.setWidth 256) : + ((if («$b» = (0x0000000000000000000000000000000000000000000000000000000000000000#256)) then (0x0000000000000000000000000000000000000000000000000000000000000000#256) else (BitVec.umod «$a» «$b»)) &&& (0x000000000000000000000000ffffffffffffffffffffffffffffffffffffffff#256)) = + (MIR.eval .mod x y).setWidth 256 := by + agree_mir + +theorem mir_shl_i160 (x : BitVec 160) (y : BitVec 160) («$a» «$b» : Word) + (ha : «$a» = x.setWidth 256) + (hb : «$b» = y.setWidth 256) : + ((if («$a» ≥ (0x0000000000000000000000000000000000000000000000000000000000000100#256)) then (0x0000000000000000000000000000000000000000000000000000000000000000#256) else («$b» <<< «$a»)) &&& (0x000000000000000000000000ffffffffffffffffffffffffffffffffffffffff#256)) = + (MIR.eval .shl x y).setWidth 256 := by + agree_mir + +theorem mir_shr_i160 (x : BitVec 160) (y : BitVec 160) («$a» «$b» : Word) + (ha : «$a» = x.setWidth 256) + (hb : «$b» = y.setWidth 256) : + ((if («$a» ≥ (0x0000000000000000000000000000000000000000000000000000000000000100#256)) then (0x0000000000000000000000000000000000000000000000000000000000000000#256) else («$b» >>> «$a»)) &&& (0x000000000000000000000000ffffffffffffffffffffffffffffffffffffffff#256)) = + (MIR.eval .shr x y).setWidth 256 := by + agree_mir + +theorem mir_not_i160 (x : BitVec 160) («$a» : Word) + (ha : «$a» = x.setWidth 256) : + ((~~~«$a») &&& (0x000000000000000000000000ffffffffffffffffffffffffffffffffffffffff#256)) = + (MIR.not x).setWidth 256 := by + agree_mir + +theorem mir_lt_i160 (x : BitVec 160) (y : BitVec 160) («$a» «$b» : Word) + (ha : «$a» = x.setWidth 256) + (hb : «$b» = y.setWidth 256) : + ((if («$a» < «$b») then (0x0000000000000000000000000000000000000000000000000000000000000001#256) else (0x0000000000000000000000000000000000000000000000000000000000000000#256)) &&& (0x0000000000000000000000000000000000000000000000000000000000000001#256)) = + (MIR.compare .lt x y).setWidth 256 := by + agree_mir + +theorem mir_gt_i160 (x : BitVec 160) (y : BitVec 160) («$a» «$b» : Word) + (ha : «$a» = x.setWidth 256) + (hb : «$b» = y.setWidth 256) : + ((if («$a» > «$b») then (0x0000000000000000000000000000000000000000000000000000000000000001#256) else (0x0000000000000000000000000000000000000000000000000000000000000000#256)) &&& (0x0000000000000000000000000000000000000000000000000000000000000001#256)) = + (MIR.compare .gt x y).setWidth 256 := by + agree_mir + +theorem mir_eq_i160 (x : BitVec 160) (y : BitVec 160) («$a» «$b» : Word) + (ha : «$a» = x.setWidth 256) + (hb : «$b» = y.setWidth 256) : + ((if («$a» = «$b») then (0x0000000000000000000000000000000000000000000000000000000000000001#256) else (0x0000000000000000000000000000000000000000000000000000000000000000#256)) &&& (0x0000000000000000000000000000000000000000000000000000000000000001#256)) = + (MIR.compare .eq x y).setWidth 256 := by + agree_mir + +theorem mir_ne_i160 (x : BitVec 160) (y : BitVec 160) («$a» «$b» : Word) + (ha : «$a» = x.setWidth 256) + (hb : «$b» = y.setWidth 256) : + (if («$a» = «$b») then (0x0000000000000000000000000000000000000000000000000000000000000000#256) else (0x0000000000000000000000000000000000000000000000000000000000000001#256)) = + (MIR.compare .ne x y).setWidth 256 := by + agree_mir + +theorem mir_select_i160 (x : BitVec 1) (y : BitVec 160) (z : BitVec 160) («$a» «$b» «$c» : Word) + (ha : «$a» = x.setWidth 256) + (hb : «$b» = y.setWidth 256) + (hc : «$c» = z.setWidth 256) : + (if («$a» = (0x0000000000000000000000000000000000000000000000000000000000000000#256)) then «$c» else «$b») = + (MIR.select x y z).setWidth 256 := by + agree_mir + +theorem mir_add_i256 (x : BitVec 256) (y : BitVec 256) («$a» «$b» : Word) + (ha : «$a» = x.setWidth 256) + (hb : «$b» = y.setWidth 256) : + («$a» + «$b») = + (MIR.eval .add x y).setWidth 256 := by + agree_mir + +theorem mir_sub_i256 (x : BitVec 256) (y : BitVec 256) («$a» «$b» : Word) + (ha : «$a» = x.setWidth 256) + (hb : «$b» = y.setWidth 256) : + («$a» - «$b») = + (MIR.eval .sub x y).setWidth 256 := by + agree_mir + +theorem mir_mul_i256 (x : BitVec 256) (y : BitVec 256) («$a» «$b» : Word) + (ha : «$a» = x.setWidth 256) + (hb : «$b» = y.setWidth 256) : + («$a» * «$b») = + (MIR.eval .mul x y).setWidth 256 := by + agree_mir + +theorem mir_and_i256 (x : BitVec 256) (y : BitVec 256) («$a» «$b» : Word) + (ha : «$a» = x.setWidth 256) + (hb : «$b» = y.setWidth 256) : + («$a» &&& «$b») = + (MIR.eval .and x y).setWidth 256 := by + agree_mir + +theorem mir_or_i256 (x : BitVec 256) (y : BitVec 256) («$a» «$b» : Word) + (ha : «$a» = x.setWidth 256) + (hb : «$b» = y.setWidth 256) : + («$a» ||| «$b») = + (MIR.eval .or x y).setWidth 256 := by + agree_mir + +theorem mir_xor_i256 (x : BitVec 256) (y : BitVec 256) («$a» «$b» : Word) + (ha : «$a» = x.setWidth 256) + (hb : «$b» = y.setWidth 256) : + («$a» ^^^ «$b») = + (MIR.eval .xor x y).setWidth 256 := by + agree_mir + +theorem mir_div_i256 (x : BitVec 256) (y : BitVec 256) («$a» «$b» : Word) + (ha : «$a» = x.setWidth 256) + (hb : «$b» = y.setWidth 256) : + (if («$b» = (0x0000000000000000000000000000000000000000000000000000000000000000#256)) then (0x0000000000000000000000000000000000000000000000000000000000000000#256) else (BitVec.smtUDiv «$a» «$b»)) = + (MIR.eval .div x y).setWidth 256 := by + agree_mir + +theorem mir_mod_i256 (x : BitVec 256) (y : BitVec 256) («$a» «$b» : Word) + (ha : «$a» = x.setWidth 256) + (hb : «$b» = y.setWidth 256) : + (if («$b» = (0x0000000000000000000000000000000000000000000000000000000000000000#256)) then (0x0000000000000000000000000000000000000000000000000000000000000000#256) else (BitVec.umod «$a» «$b»)) = + (MIR.eval .mod x y).setWidth 256 := by + agree_mir + +theorem mir_sdiv_i256 (x : BitVec 256) (y : BitVec 256) («$a» «$b» : Word) + (ha : «$a» = x.setWidth 256) + (hb : «$b» = y.setWidth 256) : + (if («$b» = (0x0000000000000000000000000000000000000000000000000000000000000000#256)) then (0x0000000000000000000000000000000000000000000000000000000000000000#256) else (BitVec.smtSDiv «$a» «$b»)) = + (MIR.eval .sdiv x y).setWidth 256 := by + agree_mir + +theorem mir_smod_i256 (x : BitVec 256) (y : BitVec 256) («$a» «$b» : Word) + (ha : «$a» = x.setWidth 256) + (hb : «$b» = y.setWidth 256) : + (if («$b» = (0x0000000000000000000000000000000000000000000000000000000000000000#256)) then (0x0000000000000000000000000000000000000000000000000000000000000000#256) else (BitVec.srem «$a» «$b»)) = + (MIR.eval .smod x y).setWidth 256 := by + agree_mir + +theorem mir_shl_i256 (x : BitVec 256) (y : BitVec 256) («$a» «$b» : Word) + (ha : «$a» = x.setWidth 256) + (hb : «$b» = y.setWidth 256) : + (if («$a» ≥ (0x0000000000000000000000000000000000000000000000000000000000000100#256)) then (0x0000000000000000000000000000000000000000000000000000000000000000#256) else («$b» <<< «$a»)) = + (MIR.eval .shl x y).setWidth 256 := by + agree_mir + +theorem mir_shr_i256 (x : BitVec 256) (y : BitVec 256) («$a» «$b» : Word) + (ha : «$a» = x.setWidth 256) + (hb : «$b» = y.setWidth 256) : + (if («$a» ≥ (0x0000000000000000000000000000000000000000000000000000000000000100#256)) then (0x0000000000000000000000000000000000000000000000000000000000000000#256) else («$b» >>> «$a»)) = + (MIR.eval .shr x y).setWidth 256 := by + agree_mir + +theorem mir_sar_i256 (x : BitVec 256) (y : BitVec 256) («$a» «$b» : Word) + (ha : «$a» = x.setWidth 256) + (hb : «$b» = y.setWidth 256) : + (if («$a» ≥ (0x0000000000000000000000000000000000000000000000000000000000000100#256)) then (BitVec.sshiftRight' «$b» (0x00000000000000000000000000000000000000000000000000000000000000ff#256)) else (BitVec.sshiftRight' «$b» «$a»)) = + (MIR.eval .sar x y).setWidth 256 := by + agree_mir + +theorem mir_not_i256 (x : BitVec 256) («$a» : Word) + (ha : «$a» = x.setWidth 256) : + (~~~«$a») = + (MIR.not x).setWidth 256 := by + agree_mir + +theorem mir_lt_i256 (x : BitVec 256) (y : BitVec 256) («$a» «$b» : Word) + (ha : «$a» = x.setWidth 256) + (hb : «$b» = y.setWidth 256) : + ((if («$a» < «$b») then (0x0000000000000000000000000000000000000000000000000000000000000001#256) else (0x0000000000000000000000000000000000000000000000000000000000000000#256)) &&& (0x0000000000000000000000000000000000000000000000000000000000000001#256)) = + (MIR.compare .lt x y).setWidth 256 := by + agree_mir + +theorem mir_gt_i256 (x : BitVec 256) (y : BitVec 256) («$a» «$b» : Word) + (ha : «$a» = x.setWidth 256) + (hb : «$b» = y.setWidth 256) : + ((if («$a» > «$b») then (0x0000000000000000000000000000000000000000000000000000000000000001#256) else (0x0000000000000000000000000000000000000000000000000000000000000000#256)) &&& (0x0000000000000000000000000000000000000000000000000000000000000001#256)) = + (MIR.compare .gt x y).setWidth 256 := by + agree_mir + +theorem mir_slt_i256 (x : BitVec 256) (y : BitVec 256) («$a» «$b» : Word) + (ha : «$a» = x.setWidth 256) + (hb : «$b» = y.setWidth 256) : + ((if ((BitVec.slt «$a» «$b») = true) then (0x0000000000000000000000000000000000000000000000000000000000000001#256) else (0x0000000000000000000000000000000000000000000000000000000000000000#256)) &&& (0x0000000000000000000000000000000000000000000000000000000000000001#256)) = + (MIR.compare .slt x y).setWidth 256 := by + agree_mir + +theorem mir_sgt_i256 (x : BitVec 256) (y : BitVec 256) («$a» «$b» : Word) + (ha : «$a» = x.setWidth 256) + (hb : «$b» = y.setWidth 256) : + ((if ((BitVec.slt «$b» «$a») = true) then (0x0000000000000000000000000000000000000000000000000000000000000001#256) else (0x0000000000000000000000000000000000000000000000000000000000000000#256)) &&& (0x0000000000000000000000000000000000000000000000000000000000000001#256)) = + (MIR.compare .sgt x y).setWidth 256 := by + agree_mir + +theorem mir_eq_i256 (x : BitVec 256) (y : BitVec 256) («$a» «$b» : Word) + (ha : «$a» = x.setWidth 256) + (hb : «$b» = y.setWidth 256) : + ((if («$a» = «$b») then (0x0000000000000000000000000000000000000000000000000000000000000001#256) else (0x0000000000000000000000000000000000000000000000000000000000000000#256)) &&& (0x0000000000000000000000000000000000000000000000000000000000000001#256)) = + (MIR.compare .eq x y).setWidth 256 := by + agree_mir + +theorem mir_ne_i256 (x : BitVec 256) (y : BitVec 256) («$a» «$b» : Word) + (ha : «$a» = x.setWidth 256) + (hb : «$b» = y.setWidth 256) : + (if («$a» = «$b») then (0x0000000000000000000000000000000000000000000000000000000000000000#256) else (0x0000000000000000000000000000000000000000000000000000000000000001#256)) = + (MIR.compare .ne x y).setWidth 256 := by + agree_mir + +theorem mir_select_i256 (x : BitVec 1) (y : BitVec 256) (z : BitVec 256) («$a» «$b» «$c» : Word) + (ha : «$a» = x.setWidth 256) + (hb : «$b» = y.setWidth 256) + (hc : «$c» = z.setWidth 256) : + (if («$a» = (0x0000000000000000000000000000000000000000000000000000000000000000#256)) then «$c» else «$b») = + (MIR.select x y z).setWidth 256 := by + agree_mir + +theorem mir_zext_i1_i160 (x : BitVec 1) («$a» : Word) + (ha : «$a» = x.setWidth 256) : + «$a» = + (MIR.cast .zext 160 x).setWidth 256 := by + agree_mir + +theorem mir_sext_i1_i160 (x : BitVec 1) («$a» : Word) + (ha : «$a» = x.setWidth 256) : + ((BitVec.signExtend 256 (BitVec.extractLsb' 0 1 «$a»)) &&& (0x000000000000000000000000ffffffffffffffffffffffffffffffffffffffff#256)) = + (MIR.cast .sext 160 x).setWidth 256 := by + agree_mir + +theorem mir_zext_i1_i256 (x : BitVec 1) («$a» : Word) + (ha : «$a» = x.setWidth 256) : + «$a» = + (MIR.cast .zext 256 x).setWidth 256 := by + agree_mir + +theorem mir_sext_i1_i256 (x : BitVec 1) («$a» : Word) + (ha : «$a» = x.setWidth 256) : + ((BitVec.signExtend 256 (BitVec.extractLsb' 0 1 «$a»)) &&& (0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff#256)) = + (MIR.cast .sext 256 x).setWidth 256 := by + agree_mir + +theorem mir_trunc_i160_i1 (x : BitVec 160) («$a» : Word) + (ha : «$a» = x.setWidth 256) : + («$a» &&& (0x0000000000000000000000000000000000000000000000000000000000000001#256)) = + (MIR.cast .trunc 1 x).setWidth 256 := by + agree_mir + +theorem mir_zext_i160_i256 (x : BitVec 160) («$a» : Word) + (ha : «$a» = x.setWidth 256) : + «$a» = + (MIR.cast .zext 256 x).setWidth 256 := by + agree_mir + +theorem mir_sext_i160_i256 (x : BitVec 160) («$a» : Word) + (ha : «$a» = x.setWidth 256) : + ((BitVec.signExtend 256 (BitVec.extractLsb' 0 160 «$a»)) &&& (0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff#256)) = + (MIR.cast .sext 256 x).setWidth 256 := by + agree_mir + +theorem mir_trunc_i256_i1 (x : BitVec 256) («$a» : Word) + (ha : «$a» = x.setWidth 256) : + («$a» &&& (0x0000000000000000000000000000000000000000000000000000000000000001#256)) = + (MIR.cast .trunc 1 x).setWidth 256 := by + agree_mir + +theorem mir_trunc_i256_i160 (x : BitVec 256) («$a» : Word) + (ha : «$a» = x.setWidth 256) : + («$a» &&& (0x000000000000000000000000ffffffffffffffffffffffffffffffffffffffff#256)) = + (MIR.cast .trunc 160 x).setWidth 256 := by + agree_mir + +end SolarTV.Agreement diff --git a/tv/SolarTV/Agreement/Tactic.lean b/tv/SolarTV/Agreement/Tactic.lean new file mode 100644 index 00000000..356ec5c9 --- /dev/null +++ b/tv/SolarTV/Agreement/Tactic.lean @@ -0,0 +1,552 @@ +import SolarTV.MIR.Ops +import SolarTV.EVMIR.Ops +import EvmRules.Tactic +import EvmRules.Reference + +/-! Tactics for the generated agreement theorems of `Encoder.lean`. + +Every theorem is proved by rewriting with the lemmas below and checked by the kernel alone: +no SAT solver, and `decide +kernel` only on closed terms. The EVM opcodes go through the +second transcription of `EvmRules.Reference`, the MIR operations through lemmas about +zero-extended operands, and divisions, remainders, products and the powers of `EXP` through +`BitVec.toNat`, as do the abstract tier's laws. -/ + +namespace SolarTV.Agreement + +open EvmRules + +/-- SMT-LIB's unsigned division by zero gives all ones; the guard the encoder puts +around it gives zero, as `DIV` does. -/ +theorem guarded_div (a b : Word) : + (if b = 0#256 then 0#256 else BitVec.smtUDiv a b) = Evm.div a b := by + by_cases h : b = 0#256 <;> simp [h, BitVec.smtUDiv, Evm.div] + +theorem guarded_sdiv (a b : Word) : + (if b = 0#256 then 0#256 else BitVec.smtSDiv a b) = Evm.sdiv a b := by + by_cases h : b = 0#256 + · simp [h, Evm.sdiv] + · have h' : -b ≠ 0#256 := by simpa using h + simp only [h, ite_false, BitVec.smtSDiv, BitVec.sdiv, BitVec.smtUDiv, Evm.sdiv] + split <;> simp_all + +theorem guarded_mod (a b : Word) : + (if b = 0#256 then 0#256 else BitVec.umod a b) = Evm.mod a b := by + by_cases h : b = 0#256 <;> simp [h, Evm.mod, BitVec.umod_eq] + +theorem guarded_smod (a b : Word) : + (if b = 0#256 then 0#256 else BitVec.srem a b) = Evm.smod a b := by + by_cases h : b = 0#256 <;> simp [h, Evm.smod] + +set_option exponentiation.threshold 512 in +theorem guarded_addmod (a b n : Word) : + (if n = 0#256 then 0#256 else BitVec.extractLsb' 0 256 + (BitVec.umod (BitVec.setWidth 257 a + BitVec.setWidth 257 b) (BitVec.setWidth 257 n))) = + Evm.addmod a b n := by + rw [← BitVec.setWidth_eq_extractLsb' (by decide)] + by_cases h : n = 0#256 + · simp [h, Evm.addmod] + · have h0 : ¬n = 0 := h + simp only [h, h0, ite_false, Evm.addmod, beq_iff_eq, Bool.cond_eq_ite, BitVec.umod_eq] + apply BitVec.eq_of_toNat_eq + have ha := a.isLt + have hb := b.isLt + have hn := n.isLt + have h1 : (2:Nat) ^ 257 = 2 * 2 ^ 256 := by rw [Nat.pow_succ, Nat.mul_comm] + have h2 : (2:Nat) ^ 512 = 2 ^ 256 * 2 ^ 256 := by rw [← Nat.pow_add] + have h3 : 2 ≤ (2:Nat) ^ 256 := Nat.le_self_pow (by decide) 2 + have h4 : 2 * 2 ^ 256 ≤ (2:Nat) ^ 256 * 2 ^ 256 := Nat.mul_le_mul_right _ h3 + simp only [BitVec.toNat_setWidth, BitVec.toNat_umod, BitVec.toNat_add, + Nat.mod_eq_of_lt (show a.toNat < 2 ^ 512 by omega), + Nat.mod_eq_of_lt (show b.toNat < 2 ^ 512 by omega), + Nat.mod_eq_of_lt (show n.toNat < 2 ^ 512 by omega), + Nat.mod_eq_of_lt (show a.toNat < 2 ^ 257 by omega), + Nat.mod_eq_of_lt (show b.toNat < 2 ^ 257 by omega), + Nat.mod_eq_of_lt (show n.toNat < 2 ^ 257 by omega), + Nat.mod_eq_of_lt (show a.toNat + b.toNat < 2 ^ 512 by omega), + Nat.mod_eq_of_lt (show a.toNat + b.toNat < 2 ^ 257 by omega)] + +theorem guarded_mulmod (a b n : Word) : + (if n = 0#256 then 0#256 else BitVec.extractLsb' 0 256 + (BitVec.umod (BitVec.setWidth 512 a * BitVec.setWidth 512 b) (BitVec.setWidth 512 n))) = + Evm.mulmod a b n := by + rw [← BitVec.setWidth_eq_extractLsb' (by decide)] + by_cases h : n = 0#256 + · simp [h, Evm.mulmod] + · simp [h, Evm.mulmod, BitVec.umod_eq] + +/-- The value of a power, which `BitVec` defines by repeated multiplication. -/ +theorem toNat_pow {w : Nat} (x : BitVec w) (n : Nat) : (x ^ n).toNat = x.toNat ^ n % 2 ^ w := by + induction n with + | zero => simp [BitVec.pow_zero, BitVec.toNat_ofNat] + | succ n ih => rw [BitVec.pow_succ, BitVec.toNat_mul, ih, Nat.pow_succ, Nat.mod_mul_mod] + +/-- A base `2^k` raised to `e` is `1 <<< (e k)`, zero once `e k` reaches the width: the +encoder's limit `L` is the least exponent with `L k ≥ 256`, below which `e k` cannot wrap. -/ +theorem exp_power_of_two (k L : Nat) (e : Word) (hk : k < 256) (hL : 256 ≤ L * k) + (hL' : (L - 1) * k < 256) (hL256 : L ≤ 256) : + (if e ≥ BitVec.ofNat 256 L then 0#256 else 1#256 <<< (e * BitVec.ofNat 256 k)) = + Evm.exp (BitVec.ofNat 256 (2 ^ k)) e := by + apply BitVec.eq_of_toNat_eq + have h256 : 256 < 2 ^ 256 := Nat.lt_two_pow_self + have hpow : 2 ^ k < 2 ^ 256 := Nat.pow_lt_pow_right (by decide) hk + have hL2 : L < 2 ^ 256 := by omega + have hk2 : k < 2 ^ 256 := by omega + simp only [Evm.exp, toNat_pow, BitVec.toNat_ofNat, Nat.mod_eq_of_lt hpow, ← Nat.pow_mul] + simp only [GE.ge, BitVec.le_def, BitVec.toNat_ofNat, Nat.mod_eq_of_lt hL2] + by_cases he : L ≤ e.toNat + · simp only [he, ↓reduceIte] + have : L * k ≤ e.toNat * k := Nat.mul_le_mul_right k he + obtain ⟨d, hd⟩ : ∃ d, k * e.toNat = 256 + d := ⟨k * e.toNat - 256, by + rw [Nat.mul_comm k]; omega⟩ + rw [hd, Nat.pow_add, Nat.mul_mod_right] + rfl + · simp only [he, ↓reduceIte] + have : e.toNat ≤ L - 1 := by omega + have hsmall : e.toNat * k < 256 := Nat.lt_of_le_of_lt (Nat.mul_le_mul_right k this) hL' + rw [BitVec.shiftLeft_eq', BitVec.toNat_shiftLeft, BitVec.toNat_mul, BitVec.toNat_ofNat, + BitVec.toNat_ofNat, Nat.mod_eq_of_lt hk2, Nat.mod_eq_of_lt (by omega : e.toNat * k < 2 ^ 256), + Nat.shiftLeft_eq, Nat.mul_comm (e.toNat) k] + simp + +theorem exp_zero_base (e : Word) : + (if e = 0#256 then 1#256 else 0#256) = Evm.exp 0#256 e := by + apply BitVec.eq_of_toNat_eq + by_cases hz : e = 0#256 + · simp [hz, Evm.exp] + · have : e.toNat ≠ 0 := fun hn => hz (BitVec.eq_of_toNat_eq (by simp [hn])) + simp [hz, Evm.exp, toNat_pow, Nat.zero_pow (Nat.pos_of_ne_zero this)] + +theorem exp_one_base (e : Word) : 1#256 = Evm.exp 1#256 e := by + apply BitVec.eq_of_toNat_eq + simp [Evm.exp, toNat_pow] + +/-- Low bits as the mask the encoder applies, for the narrow widths. -/ +theorem mask_160 (t : Word) : + t &&& 0x000000000000000000000000ffffffffffffffffffffffffffffffffffffffff#256 = + (t.setWidth 160).setWidth 256 := by + apply BitVec.eq_of_toNat_eq + rw [BitVec.toNat_and, BitVec.toNat_setWidth, BitVec.toNat_setWidth, + show (0x000000000000000000000000ffffffffffffffffffffffffffffffffffffffff#256).toNat = + 2 ^ 160 - 1 from rfl, + Nat.and_two_pow_sub_one_eq_mod, Nat.mod_eq_of_lt (a := t.toNat % 2 ^ 160)] + exact Nat.lt_of_lt_of_le (Nat.mod_lt _ (by decide)) (Nat.pow_le_pow_right (by decide) (by decide)) + +theorem mask_1 (t : Word) : + t &&& 0x0000000000000000000000000000000000000000000000000000000000000001#256 = + (t.setWidth 1).setWidth 256 := by + apply BitVec.eq_of_toNat_eq + rw [BitVec.toNat_and, BitVec.toNat_setWidth, BitVec.toNat_setWidth, + show (0x0000000000000000000000000000000000000000000000000000000000000001#256).toNat = + 2 ^ 1 - 1 from rfl, + Nat.and_two_pow_sub_one_eq_mod, Nat.mod_eq_of_lt (a := t.toNat % 2 ^ 1)] + exact Nat.lt_of_lt_of_le (Nat.mod_lt _ (by decide)) (Nat.pow_le_pow_right (by decide) (by decide)) + +theorem setWidth_div {w : Nat} (x y : BitVec w) (h : w ≤ 256) : + x.setWidth 256 / y.setWidth 256 = (x / y).setWidth 256 := by + apply BitVec.eq_of_toNat_eq + have hx := x.isLt + have hy := y.isLt + have : 2 ^ w ≤ 2 ^ 256 := Nat.pow_le_pow_right (by omega) h + have hq : x.toNat / y.toNat < 2 ^ w := Nat.lt_of_le_of_lt (Nat.div_le_self _ _) hx + simp only [BitVec.toNat_udiv, BitVec.toNat_setWidth, + Nat.mod_eq_of_lt (show x.toNat < 2 ^ 256 by omega), + Nat.mod_eq_of_lt (show y.toNat < 2 ^ 256 by omega), + Nat.mod_eq_of_lt (show x.toNat / y.toNat < 2 ^ 256 by omega)] + +theorem setWidth_mod {w : Nat} (x y : BitVec w) (h : w ≤ 256) : + x.setWidth 256 % y.setWidth 256 = (x % y).setWidth 256 := by + apply BitVec.eq_of_toNat_eq + have hx := x.isLt + have hy := y.isLt + have : 2 ^ w ≤ 2 ^ 256 := Nat.pow_le_pow_right (by omega) h + have hr : x.toNat % y.toNat < 2 ^ w := Nat.lt_of_le_of_lt (Nat.mod_le _ _) hx + simp only [BitVec.toNat_umod, BitVec.toNat_setWidth, + Nat.mod_eq_of_lt (show x.toNat < 2 ^ 256 by omega), + Nat.mod_eq_of_lt (show y.toNat < 2 ^ 256 by omega), + Nat.mod_eq_of_lt (show x.toNat % y.toNat < 2 ^ 256 by omega)] + +theorem setWidth_mul {w : Nat} (x y : BitVec w) (h : w ≤ 256) : + ((x.setWidth 256 * y.setWidth 256).setWidth w).setWidth 256 = (x * y).setWidth 256 := by + rw [BitVec.setWidth_mul _ _ h, BitVec.setWidth_setWidth_of_le _ h, + BitVec.setWidth_setWidth_of_le _ h, BitVec.setWidth_eq, BitVec.setWidth_eq] + +/-- `SIGNEXTEND`'s shift is eight times the byte index; as a shift it bit-blasts cheaply. -/ +theorem mul_eight (a : Word) : + 0x0000000000000000000000000000000000000000000000000000000000000008#256 * a = a <<< 3 := by + apply BitVec.eq_of_toNat_eq + rw [BitVec.toNat_mul, BitVec.toNat_shiftLeft, Nat.shiftLeft_eq] + simp only [BitVec.toNat_ofNat] + rw [Nat.mul_comm] + +theorem beq_zero {a : Word} (h : ¬a = 0#256) : (a == 0) = false := by + simpa using h + +theorem toNat_ne_zero {a : Word} (h : ¬a = 0#256) : a.toNat ≠ 0 := + fun hn => h (BitVec.eq_of_toNat_eq (by simp [hn])) + +theorem mul_comm (a b : Word) : Evm.mul a b = Evm.mul b a := BitVec.mul_comm _ _ + +theorem div_le (a b : Word) : Evm.div a b ≤ a := by + simp only [Evm.div, BitVec.le_def, BitVec.toNat_udiv] + exact Nat.div_le_self _ _ + +theorem mod_lt (a b : Word) : ¬b = 0#256 → Evm.mod a b < b := by + intro h + simp only [Evm.mod, beq_zero h, Bool.cond_false, BitVec.lt_def, BitVec.toNat_umod] + exact Nat.mod_lt _ (Nat.pos_of_ne_zero (toNat_ne_zero h)) + +theorem mod_le (a b : Word) : Evm.mod a b ≤ a := by + by_cases h : b = 0#256 + · subst h; simp [Evm.mod, BitVec.le_def] + · simp only [Evm.mod, beq_zero h, Bool.cond_false, BitVec.le_def, BitVec.toNat_umod] + exact Nat.mod_le _ _ + +theorem mod_of_lt (a b : Word) : a < b → Evm.mod a b = a := by + intro h + have hb : ¬b = 0#256 := by + intro hb; subst hb; simp [BitVec.lt_def] at h + simp only [Evm.mod, beq_zero hb, Bool.cond_false] + apply BitVec.eq_of_toNat_eq + simp only [BitVec.toNat_umod] + exact Nat.mod_eq_of_lt (BitVec.lt_def.mp h) + +set_option exponentiation.threshold 512 in +theorem setWidth_umod_lt (x n : BitVec 512) (h : n.toNat ≠ 0) : + (BitVec.setWidth 256 (x % n)).toNat < n.toNat := by + simp only [BitVec.toNat_setWidth, BitVec.toNat_umod] + exact Nat.lt_of_le_of_lt (Nat.mod_le _ _) (Nat.mod_lt _ (Nat.pos_of_ne_zero h)) + +set_option exponentiation.threshold 512 in +theorem addmod_lt (a b n : Word) : ¬n = 0#256 → Evm.addmod a b n < n := by + intro h + have : (2:Nat) ^ 256 ≤ 2 ^ 512 := Nat.pow_le_pow_right (by decide) (by decide) + have hn : (n.setWidth 512).toNat = n.toNat := by + simp only [BitVec.toNat_setWidth]; exact Nat.mod_eq_of_lt (by have := n.isLt; omega) + simp only [Evm.addmod, beq_zero h, Bool.cond_false, BitVec.lt_def] + have := setWidth_umod_lt (BitVec.setWidth 512 a + BitVec.setWidth 512 b) (n.setWidth 512) + (by rw [hn]; exact toNat_ne_zero h) + rwa [hn] at this + +set_option exponentiation.threshold 512 in +theorem mulmod_lt (a b n : Word) : ¬n = 0#256 → Evm.mulmod a b n < n := by + intro h + have : (2:Nat) ^ 256 ≤ 2 ^ 512 := Nat.pow_le_pow_right (by decide) (by decide) + have hn : (n.setWidth 512).toNat = n.toNat := by + simp only [BitVec.toNat_setWidth]; exact Nat.mod_eq_of_lt (by have := n.isLt; omega) + simp only [Evm.mulmod, beq_zero h, Bool.cond_false, BitVec.lt_def] + have := setWidth_umod_lt (BitVec.setWidth 512 a * BitVec.setWidth 512 b) (n.setWidth 512) + (by rw [hn]; exact toNat_ne_zero h) + rwa [hn] at this + +theorem addmod_zero (a b n : Word) : n = 0#256 → Evm.addmod a b n = 0#256 := by + intro h; subst h; rfl + +theorem mulmod_zero (a b n : Word) : n = 0#256 → Evm.mulmod a b n = 0#256 := by + intro h; subst h; rfl + +/-! Kernel proofs of the remaining terms, without a SAT solver: the EVM opcodes through the +second transcription of `EvmRules.Reference`, and the MIR operations at the operand width +through the zero-extension lemmas below. An `i1` operand takes two values, so those +theorems split on them and the kernel evaluates each closed case. -/ + +theorem bv1_cases (x : BitVec 1) : x = 0#1 ∨ x = 1#1 := by + have h := x.isLt + have : x.toNat = 0 ∨ x.toNat = 1 := by omega + rcases this with h | h + · exact Or.inl (BitVec.eq_of_toNat_eq (by simp [h])) + · exact Or.inr (BitVec.eq_of_toNat_eq (by simp [h])) + +theorem enc_lt (a b : Word) : + (if a < b then 1#256 else 0#256) = Evm.lt a b := by + rw [lt_agrees]; rfl + +theorem enc_gt (a b : Word) : + (if a > b then 1#256 else 0#256) = Evm.gt a b := by + rw [gt_agrees]; rfl + +theorem enc_slt (a b : Word) : + (if (BitVec.slt a b = true) then 1#256 else 0#256) = Evm.slt a b := by + rw [slt_agrees]; rfl + +theorem enc_sgt (a b : Word) : + (if (BitVec.slt b a = true) then 1#256 else 0#256) = Evm.sgt a b := by + rw [sgt_agrees]; rfl + +theorem enc_eq (a b : Word) : + (if a = b then 1#256 else 0#256) = Evm.eq a b := by + rw [eq_agrees]; rfl + +theorem enc_iszero (a : Word) : + (if a = 0#256 then 1#256 else 0#256) = Evm.iszero a := by + rw [iszero_agrees]; rfl + +theorem enc_shl (a b : Word) : + (if a ≥ 256#256 then 0#256 else b <<< a) = Evm.shl a b := by + rw [shl_agrees] + unfold Reference.shl + by_cases h : a ≥ 256#256 + · rw [ite_eq_left h, ite_eq_right (by simpa [BitVec.le_def, BitVec.lt_def] using h)] + · rw [ite_eq_right h, ite_eq_left (by simpa [BitVec.le_def, BitVec.lt_def] using h), BitVec.shiftLeft_eq'] + +theorem enc_shr (a b : Word) : + (if a ≥ 256#256 then 0#256 else b >>> a) = Evm.shr a b := by + rw [shr_agrees] + unfold Reference.shr + by_cases h : a ≥ 256#256 + · rw [ite_eq_left h, ite_eq_right (by simpa [BitVec.le_def, BitVec.lt_def] using h)] + · rw [ite_eq_right h, ite_eq_left (by simpa [BitVec.le_def, BitVec.lt_def] using h), BitVec.ushiftRight_eq'] + +/-- Shifting by 255 already copies the sign bit into every bit. -/ +theorem sshiftRight_255 (b : Word) : b.sshiftRight 255 = b.sshiftRight 256 := by + apply BitVec.eq_of_getLsbD_eq + intro i hi + simp only [BitVec.getLsbD_sshiftRight, BitVec.msb_eq_getLsbD_last] + by_cases h0 : i = 0 + · subst h0; simp + · simp [show ¬255 + i < 256 by omega, show ¬256 + i < 256 by omega] + +theorem enc_sar (a b : Word) : + (if a ≥ 256#256 then BitVec.sshiftRight' b 255#256 else BitVec.sshiftRight' b a) = + Evm.sar a b := by + rw [sar_agrees] + unfold Reference.sar + by_cases h : a ≥ 256#256 + · rw [ite_eq_left h, ite_eq_right (by simpa [BitVec.le_def, BitVec.lt_def] using h), + BitVec.sshiftRight_eq'] + exact sshiftRight_255 b + · rw [ite_eq_right h, ite_eq_left (by simpa [BitVec.le_def, BitVec.lt_def] using h), + BitVec.sshiftRight_eq'] + +theorem enc_byte (a b : Word) : + (if a ≥ 32#256 then 0#256 else (b >>> ((31#256 - a) * 8#256)) &&& 255#256) = + Evm.byte a b := by + rw [byte_agrees] + unfold Reference.byte + by_cases h : a ≥ 32#256 + · rw [ite_eq_left h, ite_eq_right (by simpa [BitVec.le_def, BitVec.lt_def] using h)] + · have hc : ((31#256 - a) * 8#256).toNat < 256 := by + simp only [GE.ge, BitVec.le_def, BitVec.toNat_ofNat] at h + bv_omega + rw [ite_eq_right h, ite_eq_left (by simpa [BitVec.le_def, BitVec.lt_def] using h), Reference.shr, + ite_eq_left (by simpa [BitVec.lt_def] using hc), BitVec.ushiftRight_eq'] + +theorem enc_signextend (a b : Word) : + (if a ≥ 31#256 then b else + BitVec.sshiftRight' (b <<< (248#256 - 8#256 * a)) (248#256 - 8#256 * a)) = + Evm.signextend a b := by + rw [signextend_agrees] + unfold Reference.signextend + by_cases h : a ≥ 31#256 + · rw [ite_eq_left h, ite_eq_right (by simpa [BitVec.le_def, BitVec.lt_def] using h)] + · have hc : (248#256 - a * 8#256).toNat < 256 := by + simp only [GE.ge, BitVec.le_def, BitVec.toNat_ofNat] at h + bv_omega + rw [ite_eq_right h, ite_eq_left (by simpa [BitVec.le_def, BitVec.lt_def] using h), Reference.sar, + Reference.shl, ite_eq_left (by simpa [BitVec.lt_def] using hc), + ite_eq_left (by simpa [BitVec.lt_def] using hc), BitVec.mul_comm 8#256 a, + BitVec.sshiftRight_eq', BitVec.shiftLeft_eq'] + +theorem toNat_setWidth_256 {w : Nat} (x : BitVec w) (h : w ≤ 256) : + (x.setWidth 256).toNat = x.toNat := by + rw [BitVec.toNat_setWidth, + Nat.mod_eq_of_lt (Nat.lt_of_lt_of_le x.isLt (Nat.pow_le_pow_right (by decide) h))] + +theorem setWidth_256_inj {w : Nat} {x y : BitVec w} (h : w ≤ 256) : + x.setWidth 256 = y.setWidth 256 ↔ x = y := by + constructor + · intro e + apply BitVec.eq_of_toNat_eq + have := congrArg BitVec.toNat e + rwa [toNat_setWidth_256 _ h, toNat_setWidth_256 _ h] at this + · intro e; rw [e] + +theorem setWidth_256_lt {w : Nat} {x y : BitVec w} (h : w ≤ 256) : + x.setWidth 256 < y.setWidth 256 ↔ x < y := by + simp only [BitVec.lt_def, toNat_setWidth_256 _ h] + +theorem setWidth_256_ge {w : Nat} {x : BitVec w} (h : w ≤ 256) : + x.setWidth 256 ≥ 256#256 ↔ 256 ≤ x.toNat := by + simp only [GE.ge, BitVec.le_def, toNat_setWidth_256 _ h, BitVec.toNat_ofNat] + +theorem low_ext {w : Nat} (x : BitVec w) (h : w ≤ 256) : (x.setWidth 256).setWidth w = x := by + rw [BitVec.setWidth_setWidth_of_le _ h, BitVec.setWidth_eq] + +theorem low_add {w : Nat} (x y : BitVec w) (h : w ≤ 256) : + (x.setWidth 256 + y.setWidth 256).setWidth w = x + y := by + rw [BitVec.setWidth_add _ _ h, low_ext _ h, low_ext _ h] + +theorem low_sub {w : Nat} (x y : BitVec w) (h : w ≤ 256) : + (x.setWidth 256 - y.setWidth 256).setWidth w = x - y := by + rw [BitVec.sub_eq_add_neg, BitVec.setWidth_add _ _ h, BitVec.setWidth_neg_of_le h, + low_ext _ h, low_ext _ h, ← BitVec.sub_eq_add_neg] + +theorem low_and {w : Nat} (x y : BitVec w) (h : w ≤ 256) : + (x.setWidth 256 &&& y.setWidth 256).setWidth w = x &&& y := by + rw [BitVec.setWidth_and, low_ext _ h, low_ext _ h] + +theorem low_or {w : Nat} (x y : BitVec w) (h : w ≤ 256) : + (x.setWidth 256 ||| y.setWidth 256).setWidth w = x ||| y := by + rw [BitVec.setWidth_or, low_ext _ h, low_ext _ h] + +theorem low_xor {w : Nat} (x y : BitVec w) (h : w ≤ 256) : + (x.setWidth 256 ^^^ y.setWidth 256).setWidth w = x ^^^ y := by + rw [BitVec.setWidth_xor, low_ext _ h, low_ext _ h] + +theorem low_not {w : Nat} (x : BitVec w) (h : w ≤ 256) : + (~~~x.setWidth 256).setWidth w = ~~~x := by + rw [BitVec.setWidth_not h, low_ext _ h] + +theorem low_mod {w : Nat} (x y : BitVec w) (h : w ≤ 256) : + (bif y.setWidth 256 == 0 then 0 else (x % y).setWidth 256).setWidth w = + if y = 0 then 0 else x % y := by + by_cases hy : y = 0 + · subst hy; simp + · have : (y.setWidth 256 == 0) = false := by + rw [beq_eq_false_iff_ne, ne_eq] + intro e + exact hy ((setWidth_256_inj h).mp (e.trans (BitVec.setWidth_zero 256 w).symm)) + rw [this, Bool.cond_false, ite_eq_right hy, low_ext _ h] + +theorem low_shl {w : Nat} (x y : BitVec w) (h : w ≤ 256) : + (if x.setWidth 256 ≥ 256#256 then 0#256 else y.setWidth 256 <<< x.setWidth 256).setWidth w = + y <<< x.toNat := by + rw [BitVec.shiftLeft_eq', toNat_setWidth_256 _ h] + by_cases hx : x.setWidth 256 ≥ 256#256 + · rw [ite_eq_left hx, BitVec.shiftLeft_eq_zero (by have := (setWidth_256_ge h).mp hx; omega)] + simp + · rw [ite_eq_right hx, BitVec.setWidth_shiftLeft_of_le h, low_ext _ h] + +theorem low_shr {w : Nat} (x y : BitVec w) (h : w ≤ 256) : + (if x.setWidth 256 ≥ 256#256 then 0#256 else y.setWidth 256 >>> x.setWidth 256).setWidth w = + y >>> x.toNat := by + rw [BitVec.ushiftRight_eq', toNat_setWidth_256 _ h] + by_cases hx : x.setWidth 256 ≥ 256#256 + · rw [ite_eq_left hx, BitVec.ushiftRight_eq_zero (by have := (setWidth_256_ge h).mp hx; omega)] + simp + · rw [ite_eq_right hx, ← BitVec.setWidth_ushiftRight h, low_ext _ h] + +theorem word_mod_guard (x y : Word) : + (bif y == 0 then 0 else x % y) = if y = 0 then 0 else x % y := by + by_cases hy : y = 0 <;> simp [hy] + +theorem word_smod_guard (x y : Word) : + (bif y == 0 then 0 else x.srem y) = if y = 0 then 0 else x.srem y := by + by_cases hy : y = 0 <;> simp [hy] + +theorem word_shl_guard (x y : Word) : + (if x ≥ 256#256 then 0#256 else y <<< x) = y <<< x.toNat := by + rw [enc_shl, shl_agrees]; unfold Reference.shl + by_cases hx : x < 256#256 + · rw [ite_eq_left hx] + · rw [ite_eq_right hx, BitVec.shiftLeft_eq_zero (by simp [BitVec.lt_def] at hx; omega)] + +theorem word_shr_guard (x y : Word) : + (if x ≥ 256#256 then 0#256 else y >>> x) = y >>> x.toNat := by + rw [enc_shr, shr_agrees]; unfold Reference.shr + by_cases hx : x < 256#256 + · rw [ite_eq_left hx] + · rw [ite_eq_right hx, BitVec.ushiftRight_eq_zero (by simp [BitVec.lt_def] at hx; omega)] + +theorem word_sar_guard (x y : Word) : + (if x ≥ 256#256 then y.sshiftRight' 255#256 else y.sshiftRight' x) = + y.sshiftRight x.toNat := by + rw [enc_sar, sar_agrees]; unfold Reference.sar + by_cases hx : x < 256#256 + · rw [ite_eq_left hx] + · rw [ite_eq_right hx] + exact BitVec.sshiftRight_eq_sshiftRight_of_le (by decide) + (by simp [BitVec.lt_def] at hx; omega) + +theorem sext_160_256 (x : BitVec 160) : + BitVec.signExtend 256 (BitVec.extractLsb' 0 160 (BitVec.setWidth 256 x)) &&& + 115792089237316195423570985008687907853269984665640564039457584007913129639935#256 = + BitVec.signExtend 256 x := by + rw [← BitVec.setWidth_eq_extractLsb' (by decide), low_ext _ (by decide), + show (115792089237316195423570985008687907853269984665640564039457584007913129639935#256) = + BitVec.allOnes 256 from by decide +kernel, BitVec.and_allOnes] + +/-- The abstract tier's laws of the exact operation: the uninterpreted function is the +operation, so the first law holds by definition and each other one by a lemma above. -/ +macro "agree_abstract" : tactic => + `(tactic| ( + subst_vars + simp only [*, true_and] + repeat' apply And.intro + all_goals first + | with_reducible exact mul_comm _ _ + | with_reducible exact div_le _ _ + | with_reducible exact mod_le _ _ + | with_reducible exact mod_lt _ _ + | with_reducible exact mod_of_lt _ _ + | with_reducible exact addmod_lt _ _ _ + | with_reducible exact mulmod_lt _ _ _ + | with_reducible exact addmod_zero _ _ _ + | with_reducible exact mulmod_zero _ _ _ + | (rintro (h | h) <;> simp [h, Evm.mul]) + | (intro h; subst h; simp [Evm.mul, Evm.div, Evm.mod, Evm.addmod, Evm.mulmod]))) + +/-- The term of a pure opcode is its EVM definition: by definition, through the division +guards, or through the opcode's lemma above. -/ +macro "agree_word" : tactic => + `(tactic| first + | rfl + | simp only [guarded_div, guarded_sdiv, guarded_mod, guarded_smod, guarded_addmod, + guarded_mulmod]; done + | exact enc_lt _ _ + | exact enc_gt _ _ + | exact enc_slt _ _ + | exact enc_sgt _ _ + | exact enc_eq _ _ + | exact enc_iszero _ + | exact enc_byte _ _ + | exact enc_shl _ _ + | exact enc_shr _ _ + | exact enc_sar _ _ + | exact enc_signextend _ _) + +/-- The constant shapes of `EXP`. -/ +macro "agree_exp" : tactic => + `(tactic| first + | exact exp_zero_base _ + | exact exp_one_base _ + | (apply exp_power_of_two <;> decide) + | (simp only [Evm.exp, BitVec.toNat_ofNat, BitVec.pow_succ, BitVec.pow_zero]; done) + | (simp [Evm.exp, BitVec.pow_succ, BitVec.pow_zero]; done)) + +set_option hygiene false in +/-- A MIR operation's term: substitute the zero-extended operands, rewrite masks as low +bits and divisions, remainders and products at the operand width, then each operation at the +operand width by its lemma above. Comparisons split on their condition. An `i1` operand +(`x`, `y` or `z`, the generated theorems' names, hence the unhygienic macro) is split into +its two values, and the kernel evaluates what is then closed. -/ +macro "agree_mir" : tactic => + `(tactic| ( + subst_vars + try simp only [guarded_div, guarded_sdiv, guarded_mod, guarded_smod, mask_160, mask_1, + Evm.div, Evm.mod, Evm.sdiv, Evm.smod, MIR.eval, Word.binary, MIR.not, MIR.select, + MIR.compare, + MIR.cast, BitVec.setWidth_eq, setWidth_div _ _ (by decide : 160 ≤ 256), + setWidth_div _ _ (by decide : 1 ≤ 256), setWidth_mod _ _ (by decide : 160 ≤ 256), + setWidth_mod _ _ (by decide : 1 ≤ 256), setWidth_mul _ _ (by decide : 160 ≤ 256), + setWidth_mul _ _ (by decide : 1 ≤ 256)] + all_goals first + | rfl + | (simp only [low_add _ _ (by decide : 160 ≤ 256), low_sub _ _ (by decide : 160 ≤ 256), + low_and _ _ (by decide : 160 ≤ 256), low_or _ _ (by decide : 160 ≤ 256), + low_xor _ _ (by decide : 160 ≤ 256), low_not _ (by decide : 160 ≤ 256), + low_ext _ (by decide : 160 ≤ 256), low_mod _ _ (by decide : 160 ≤ 256), + low_shl _ _ (by decide : 160 ≤ 256), low_shr _ _ (by decide : 160 ≤ 256), + word_mod_guard, word_smod_guard, word_shl_guard, word_shr_guard, word_sar_guard, + sext_160_256]; done) + | rw [low_shl _ _ (by decide : 160 ≤ 256)] + | rw [low_shr _ _ (by decide : 160 ≤ 256)] + | (rcases bv1_cases x with rfl | rfl <;> + (try rcases bv1_cases y with rfl | rfl) <;> + (try rcases bv1_cases z with rfl | rfl) <;> + first | decide +kernel | simp) + | (try simp only [gt_iff_lt, setWidth_256_lt (by decide : 160 ≤ 256), + setWidth_256_inj (by decide : 160 ≤ 256), BitVec.ult_eq_decide_lt, decide_eq_true_eq, + beq_iff_eq, bne_iff_ne, ne_eq] + split <;> (try split) <;> first | decide +kernel | (exfalso; simp_all)))) + +end SolarTV.Agreement diff --git a/tv/SolarTV/Composition.lean b/tv/SolarTV/Composition.lean new file mode 100644 index 00000000..c042fe89 --- /dev/null +++ b/tv/SolarTV/Composition.lean @@ -0,0 +1,112 @@ +import SolarTV.MIR.Program +import SolarTV.EVMIR.Program + +/-! Composing the stages of the backend into one stage from lowered MIR to EVM IR. + +A compilation is the lowered MIR module, the output of each MIR pass after it, the +scheduled EVM IR program and the output of each EVM IR pass. Each MIR pass and each EVM IR +pass is a stage of its layer's semantics, which `-Zvalidate-passes` and +`-Zvalidate-evm-ir-passes` check pass by pass, and scheduling is a stage between the two +layers, which `-Zvalidate-backend` checks. Chaining them gives a stage from the MIR the +pipeline starts with to the EVM IR it ends with (`mir_to_evmir`), or from certificates +(`mir_to_evmir_certified`). The MIR semantics is at the lowered phase, so `lower-abi` and +`lower-dispatch` are outside these stages. `AssemblyStage` is the stage from EVM IR to +bytecode, which solidity-lean's bytecode semantics states, and `mir_to_bytecode` composes +it. -/ + +namespace SolarTV + +open Machine + +noncomputable def mirSem (o : Oracle) : Sem := MIR.Lowered.moduleSem o + +noncomputable def evmirSem (o : Oracle) : Sem := EVM.Program.sem o + +/-- Each program is a stage of the one before it. -/ +def Steps (S : Sem) (scope : Call → Prop) : List S.Prog → Prop + | [] | [_] => True + | p :: q :: rest => Stage S S p q scope ∧ Steps S scope (q :: rest) + +/-- Each program is certified against the one before it. -/ +def CertifiedSteps (L : Layer) (o : Oracle) (scope : Call → Prop) : List L.Prog → Prop + | [] | [_] => True + | p :: q :: rest => Certified L L o p q scope ∧ CertifiedSteps L o scope (q :: rest) + +theorem Steps.stage {S : Sem} {scope : Call → Prop} : + ∀ (p : S.Prog) (ps : List S.Prog), Steps S scope (p :: ps) → + Stage S S p ((p :: ps).getLast (List.cons_ne_nil p ps)) scope + | p, [], _ => Stage.refl S p scope + | p, q :: rest, ⟨first, steps⟩ => by + rw [List.getLast_cons_cons] + exact first.trans (Steps.stage q rest steps) + +theorem CertifiedSteps.certified {L : Layer} {o : Oracle} {scope : Call → Prop} : + ∀ (p : L.Prog) (ps : List L.Prog), CertifiedSteps L o scope (p :: ps) → + Certified L L o p ((p :: ps).getLast (List.cons_ne_nil p ps)) scope + | p, [], _ => Certified.refl L o p scope + | p, q :: rest, ⟨first, steps⟩ => by + rw [List.getLast_cons_cons] + exact first.trans (CertifiedSteps.certified q rest steps) + +theorem CertifiedSteps.steps {L : Layer} {o : Oracle} {scope : Call → Prop} : + ∀ (ps : List L.Prog), CertifiedSteps L o scope ps → Steps (L.sem o) scope ps + | [], _ | [_], _ => trivial + | _ :: q :: rest, ⟨first, steps⟩ => + ⟨stage_of_certified first, CertifiedSteps.steps (q :: rest) steps⟩ + +structure Compilation where + mir : MIR.Lowered.Module + mirPasses : List MIR.Lowered.Module + scheduled : EVM.Program.Program + evmirPasses : List EVM.Program.Program + +/-- The MIR the backend schedules: the output of the last MIR pass. -/ +def Compilation.scheduledFrom (p : Compilation) : MIR.Lowered.Module := + (p.mir :: p.mirPasses).getLast (List.cons_ne_nil _ _) + +/-- The EVM IR the pipeline ends with: the output of the last EVM IR pass. -/ +def Compilation.evmir (p : Compilation) : EVM.Program.Program := + (p.scheduled :: p.evmirPasses).getLast (List.cons_ne_nil _ _) + +theorem mir_to_evmir (o : Oracle) (scope : Call → Prop) (p : Compilation) + (mirPasses : Steps (mirSem o) scope (p.mir :: p.mirPasses)) + (scheduling : Stage (mirSem o) (evmirSem o) p.scheduledFrom p.scheduled scope) + (evmirPasses : Steps (evmirSem o) scope (p.scheduled :: p.evmirPasses)) : + Stage (mirSem o) (evmirSem o) p.mir p.evmir scope := + ((Steps.stage _ _ mirPasses).trans scheduling).trans (Steps.stage _ _ evmirPasses) + +theorem mir_to_evmir_certified (o : Oracle) (scope : Call → Prop) (p : Compilation) + (mirPasses : CertifiedSteps MIR.Lowered.moduleLayer o scope (p.mir :: p.mirPasses)) + (scheduling : Certified MIR.Lowered.moduleLayer EVM.Program.layer o p.scheduledFrom p.scheduled + scope) + (evmirPasses : CertifiedSteps EVM.Program.layer o scope (p.scheduled :: p.evmirPasses)) : + Stage (mirSem o) (evmirSem o) p.mir p.evmir scope := + mir_to_evmir o scope p (CertifiedSteps.steps _ mirPasses) (stage_of_certified scheduling) + (CertifiedSteps.steps _ evmirPasses) + +/-- The stage from scheduled EVM IR to bytecode under a bytecode semantics, which this +library takes as a hypothesis. -/ +def AssemblyStage (bytecode : Sem) (o : Oracle) (q : EVM.Program.Program) + (code : bytecode.Prog) (scope : Call → Prop) : Prop := + Stage (evmirSem o) bytecode q code scope + +theorem mir_to_bytecode (o : Oracle) (scope : Call → Prop) (p : Compilation) + (bytecode : Sem) (code : bytecode.Prog) + (mirPasses : CertifiedSteps MIR.Lowered.moduleLayer o scope (p.mir :: p.mirPasses)) + (scheduling : Certified MIR.Lowered.moduleLayer EVM.Program.layer o p.scheduledFrom p.scheduled + scope) + (evmirPasses : CertifiedSteps EVM.Program.layer o scope (p.scheduled :: p.evmirPasses)) + (assembly : AssemblyStage bytecode o p.evmir code scope) : + Stage (mirSem o) bytecode p.mir code scope := + (mir_to_evmir_certified o scope p mirPasses scheduling evmirPasses).trans assembly + +/-- One MIR pass, the backend and one EVM IR pass, each certified. -/ +theorem pipeline {o : Oracle} {scope : Call → Prop} {f g : MIR.Lowered.Module} + {q r : EVM.Program.Program} + (mirPass : Certified MIR.Lowered.moduleLayer MIR.Lowered.moduleLayer o f g scope) + (scheduling : Certified MIR.Lowered.moduleLayer EVM.Program.layer o g q scope) + (evmirPass : Certified EVM.Program.layer EVM.Program.layer o q r scope) : + Stage (mirSem o) (evmirSem o) f r scope := + stage_of_certified ((mirPass.trans scheduling).trans evmirPass) + +end SolarTV diff --git a/tv/SolarTV/CutPoint.lean b/tv/SolarTV/CutPoint.lean new file mode 100644 index 00000000..ecfeb17b --- /dev/null +++ b/tv/SolarTV/CutPoint.lean @@ -0,0 +1,533 @@ +import SolarTV.Machine + +/-! Whole runs from loop-free segments between cut points. + +A stage whose programs loop cannot be proved by running both on a call to their ends, as the +loop-free stages are: a loop runs as many times as its data says. Instead, each program gets +cut points, configurations such as the headers of its loops, so that every cycle of its control +flow passes through one, and the two programs get a relation between their configurations at +cut points. A segment runs a program from a configuration for at least one step and on until it +reaches a cut point, ends, or is stuck (\`seg\`); it is loop-free, so symbolic execution runs it +to the end with fuel the number of blocks (\`seg_ne_fuel\` shows such fuel suffices when every +cycle passes through a cut point). \`Sim\` asks that from every related pair of configurations, +both segments end alike: in results that agree, at cut points that are related again, or both +stuck. Running out of a segment's fuel matches nothing, so a segment that does not end where the +procedure expects fails the proof, by mismatch. + +From that alone, whole runs are related for any number of loop iterations (\`Sim.ends\`, +\`Sim.ends_back\`): every end of one program at some fuel is matched by an agreeing end of the +other at some fuel, in both directions, so one program ends exactly when the other does +(\`Sim.ends_iff\`); one is stuck exactly when the other is (\`Sim.stuck_iff\`); and one runs forever +exactly when the other does (\`Sim.diverges_iff\`). None of these holds vacuously: the segment +obligation has no case for running out of fuel, and each segment takes at least one step, so +an infinite run of one program is matched step for step by an infinite run of the other. + +Nothing here depends on what a configuration is, so the same theorem serves every stage whose +programs run as a step function with fuel (\`Machine.iterate\`): MIR to MIR, MIR to EVM IR and EVM +IR to EVM IR, and EVM IR to any bytecode semantics given as a step function. The relation is the +exporter's: it derives it from what the compiler records at each cut point (the values that +correspond, the phis, the stack layout of a loop header); this file proves no invariant of its +own. \`certified\` and \`certified_back\` state the result for layers. -/ + +namespace SolarTV.CutPoint + +universe u v u' v' + +/-- A machine of configurations \`σ\` and results \`R\`: one step ends in a result, continues from +a new configuration, or is stuck (\`none\`). -/ +abbrev Step (σ : Type u) (R : Type v) := σ → Option (R ⊕ σ) + +variable {σ : Type u} {R : Type v} {τ : Type u'} {R' : Type v'} + +/-- A run with fuel, one unit per step, as \`Machine.iterate\` runs: the result, or \`none\` when the +fuel runs out or the machine is stuck. -/ +def run (step : Step σ R) : Nat → σ → Option R + | 0, _ => none + | n + 1, x => + match step x with + | some (.inl r) => some r + | some (.inr y) => run step n y + | none => none + +/-- \`k\` steps from a configuration: the result reached on the way, the configuration after +them, or \`none\` when the machine is stuck on the way. -/ +def steps (step : Step σ R) : Nat → σ → Option (R ⊕ σ) + | 0, x => some (.inr x) + | k + 1, x => + match step x with + | some (.inl r) => some (.inl r) + | some (.inr y) => steps step k y + | none => none + +/-- A configuration from which the machine runs forever. -/ +def Diverges (step : Step σ R) (x : σ) : Prop := ∀ k, ∃ y, steps step k x = some (.inr y) + +/-- A configuration from which the machine gets stuck. -/ +def Stuck (step : Step σ R) (x : σ) : Prop := ∃ k, steps step k x = none + +/-- How a segment ends: in a result, at a cut point, stuck, or out of its fuel. -/ +inductive Seg (R : Type v) (σ : Type u) where + | done (r : R) + | cut (y : σ) + | stuck + | fuel + +/-- A segment from \`x\`: one step, then on until a cut point, an end or a stuck step, for at most +\`k\` steps in all. -/ +def seg (step : Step σ R) (cut : σ → Bool) : Nat → σ → Seg R σ + | 0, _ => .fuel + | k + 1, x => + match step x with + | none => .stuck + | some (.inl r) => .done r + | some (.inr y) => if cut y then .cut y else seg step cut k y + +/-- Two segments that end alike: in agreeing results, at related cut points, or both stuck. +Running out of fuel matches nothing. -/ +def SegRel (Ag : R → R' → Prop) (Rel : σ → τ → Prop) : Seg R σ → Seg R' τ → Prop + | .done r, .done r' => Ag r r' + | .cut y, .cut y' => Rel y y' + | .stuck, .stuck => True + | _, _ => False + +theorem SegRel.flip {Ag : R → R' → Prop} {Rel : σ → τ → Prop} : + ∀ {a : Seg R σ} {b : Seg R' τ}, SegRel Ag Rel a b → + SegRel (fun r' r => Ag r r') (fun y' y => Rel y y') b a + | .done _, .done _, h | .cut _, .cut _, h | .stuck, .stuck, h => h + | .done _, .cut _, h | .done _, .stuck, h | .done _, .fuel, h + | .cut _, .done _, h | .cut _, .stuck, h | .cut _, .fuel, h + | .stuck, .done _, h | .stuck, .cut _, h | .stuck, .fuel, h + | .fuel, _, h => h.elim + +/-! Runs and steps. -/ + +section Runs + +variable {step : Step σ R} + +theorem run_eq_steps : ∀ (n : Nat) (x : σ), + run step n x = match steps step n x with | some (.inl r) => some r | _ => none + | 0, _ => rfl + | n + 1, x => by + simp only [run, steps] + cases step x with + | none => rfl + | some v => + cases v with + | inl r => rfl + | inr y => exact run_eq_steps n y + +theorem run_of_steps {n : Nat} {x : σ} {r : R} (h : steps step n x = some (.inl r)) : + run step n x = some r := by + rw [run_eq_steps, h] + +theorem steps_of_run {n : Nat} {x : σ} {r : R} (h : run step n x = some r) : + steps step n x = some (.inl r) := by + rw [run_eq_steps] at h + split at h + · rename_i e; cases h; exact e + · cases h + +/-- Past an end or a stuck step, more steps change nothing. -/ +theorem steps_succ : ∀ {k : Nat} {x : σ}, (∀ y, steps step k x ≠ some (.inr y)) → + steps step (k + 1) x = steps step k x + | 0, x, h => absurd rfl (h x) + | k + 1, x, h => by + simp only [steps] at h ⊢ + cases e : step x with + | none => rfl + | some v => + cases v with + | inl r => rfl + | inr y => + rw [e] at h + exact steps_succ h + +theorem steps_le {k k' : Nat} {x : σ} (le : k ≤ k') (h : ∀ y, steps step k x ≠ some (.inr y)) : + steps step k' x = steps step k x := by + induction le with + | refl => rfl + | step _ ih => + rw [steps_succ (by rw [ih]; exact h), ih] + +theorem run_mono {n m : Nat} {x : σ} {r : R} (le : n ≤ m) (h : run step n x = some r) : + run step m x = some r := by + apply run_of_steps + rw [steps_le le (by rw [steps_of_run h]; intro y e; cases e)] + exact steps_of_run h + +/-- A run ends in at most one result, whatever its fuel. -/ +theorem run_unique {n m : Nat} {x : σ} {a b : R} (ha : run step n x = some a) + (hb : run step m x = some b) : a = b := by + have := run_mono (Nat.le_max_left n m) ha + rw [run_mono (Nat.le_max_right n m) hb] at this + exact (Option.some.inj this).symm + +theorem not_stuck_of_diverges {x : σ} (d : Diverges step x) : ¬Stuck step x := by + intro ⟨k, h⟩ + obtain ⟨y, e⟩ := d k + rw [h] at e + cases e + +theorem not_run_of_diverges {x : σ} (d : Diverges step x) (n : Nat) (r : R) : + run step n x ≠ some r := by + intro h + obtain ⟨y, e⟩ := d n + rw [steps_of_run h] at e + cases e + +/-- A run that neither ends nor gets stuck runs forever. -/ +theorem diverges_of {x : σ} (noEnd : ∀ n r, run step n x ≠ some r) (noStuck : ¬Stuck step x) : + Diverges step x := by + intro k + cases e : steps step k x with + | none => exact absurd ⟨k, e⟩ noStuck + | some v => + cases v with + | inl r => exact absurd (run_of_steps e) (noEnd k r) + | inr y => exact ⟨y, rfl⟩ + +theorem iterate_eq {ς : Type} (step : Step ς (Machine.Halt × Machine.State)) : + ∀ (n : Nat) (x : ς), Machine.iterate step n x = run step n x + | 0, _ => rfl + | n + 1, x => by + simp only [Machine.iterate, run] + cases step x with + | none => rfl + | some v => + cases v with + | inl r => rfl + | inr y => exact iterate_eq step n y + +end Runs + +/-! What a segment says about whole runs. -/ + +section Segments + +variable {step : Step σ R} {cut : σ → Bool} + +/-- A segment that reaches a cut point ran \`j ≥ 1\` steps to it. -/ +theorem seg_cut : ∀ {k : Nat} {x y : σ}, seg step cut k x = .cut y → + ∃ j, 1 ≤ j ∧ ∀ n, run step (n + j) x = run step n y ∧ steps step (n + j) x = steps step n y + | 0, _, _, h => by cases h + | k + 1, x, y, h => by + simp only [seg] at h + cases e : step x with + | none => rw [e] at h; cases h + | some v => + cases v with + | inl r => rw [e] at h; cases h + | inr z => + rw [e] at h + simp only at h + by_cases c : cut z = true + · simp only [c, ↓reduceIte] at h + cases h + refine ⟨1, Nat.le_refl 1, fun n => ⟨?_, ?_⟩⟩ <;> simp only [run, steps, e] + · simp only [c] at h + obtain ⟨j, pos, runs⟩ := seg_cut h + refine ⟨j + 1, by omega, fun n => ?_⟩ + rw [← Nat.add_assoc] + simp only [run, steps, e] + exact runs n + +/-- A segment that ends ran \`j ≥ 1\` steps to its result. -/ +theorem seg_done : ∀ {k : Nat} {x : σ} {r : R}, seg step cut k x = .done r → + ∃ j, 1 ≤ j ∧ ∀ n, run step (n + j) x = some r + | 0, _, _, h => by cases h + | k + 1, x, r, h => by + simp only [seg] at h + cases e : step x with + | none => rw [e] at h; cases h + | some v => + cases v with + | inl r' => + rw [e] at h + cases h + exact ⟨1, Nat.le_refl 1, fun n => by simp only [run, e]⟩ + | inr z => + rw [e] at h + simp only at h + by_cases c : cut z = true + · simp only [c, ↓reduceIte] at h; cases h + · simp only [c] at h + obtain ⟨j, pos, runs⟩ := seg_done h + refine ⟨j + 1, by omega, fun n => ?_⟩ + rw [← Nat.add_assoc] + simp only [run, e] + exact runs n + +/-- A segment that gets stuck never ends, and is stuck after \`j\` steps. -/ +theorem seg_stuck : ∀ {k : Nat} {x : σ}, seg step cut k x = .stuck → + (∀ n, run step n x = none) ∧ ∃ j, steps step j x = none + | 0, _, h => by cases h + | k + 1, x, h => by + simp only [seg] at h + cases e : step x with + | none => + refine ⟨fun n => ?_, 1, by simp only [steps, e]⟩ + cases n <;> simp only [run, e] + | some v => + cases v with + | inl r => rw [e] at h; cases h + | inr z => + rw [e] at h + simp only at h + by_cases c : cut z = true + · simp only [c, ↓reduceIte] at h; cases h + · simp only [c] at h + obtain ⟨runs, j, stuck⟩ := seg_stuck h + refine ⟨fun n => ?_, j + 1, by simp only [steps, e]; exact stuck⟩ + cases n with + | zero => rfl + | succ n => simp only [run, e]; exact runs n + +/-- Cut points that cover every cycle bound every segment: when every step to a configuration +that is no cut point climbs a rank bounded by \`N\` (a topological order of the control flow with +the edges into cut points removed, which is acyclic exactly when every cycle passes through a cut +point), a segment with more than \`N\` steps of fuel never runs out of it. -/ +theorem seg_ne_fuel (rank : σ → Nat) (N : Nat) (bound : ∀ x, rank x ≤ N) + (climbs : ∀ x y, step x = some (.inr y) → cut y = false → rank x < rank y) : + ∀ (k : Nat) (x : σ), N - rank x < k → seg step cut k x ≠ .fuel + | 0, _, h => absurd h (Nat.not_lt_zero _) + | k + 1, x, h => by + simp only [seg] + cases e : step x with + | none => simp + | some v => + cases v with + | inl r => simp + | inr y => + simp only + cases c : cut y with + | true => simp + | false => + simp only [Bool.false_eq_true, ↓reduceIte] + have := climbs x y e c + have := bound y + exact seg_ne_fuel rank N bound climbs k y (by omega) + +end Segments + +/-! The simulation. -/ + +/-- From every pair of related configurations, the two segments end alike. This is what symbolic +execution proves, segment by segment, at each pair of cut points; the relation holds of the two +programs' first configurations too, which need not be cut points. -/ +structure Sim (step : Step σ R) (cut : σ → Bool) (step' : Step τ R') (cut' : τ → Bool) + (Ag : R → R' → Prop) (Rel : σ → τ → Prop) : Prop where + segment : ∀ x x', Rel x x' → ∃ k k', SegRel Ag Rel (seg step cut k x) (seg step' cut' k' x') + +namespace Sim + +variable {step : Step σ R} {cut : σ → Bool} {step' : Step τ R'} {cut' : τ → Bool} + {Ag : R → R' → Prop} {Rel : σ → τ → Prop} + +/-- The simulation read backwards. -/ +theorem flip (S : Sim step cut step' cut' Ag Rel) : + Sim step' cut' step cut (fun r' r => Ag r r') (fun y' y => Rel y y') where + segment x' x rel := by + obtain ⟨k, k', h⟩ := S.segment x x' rel + exact ⟨k', k, h.flip⟩ + +/-- Every end of the first program, at any fuel, is matched by an agreeing end of the second. -/ +theorem ends (S : Sim step cut step' cut' Ag Rel) : + ∀ (n : Nat) (x : σ) (x' : τ) (r : R), Rel x x' → run step n x = some r → + ∃ m r', run step' m x' = some r' ∧ Ag r r' := by + intro n + induction n using Nat.strongRecOn with + | ind n ih => + intro x x' r rel ran + obtain ⟨k, k', h⟩ := S.segment x x' rel + cases hs : seg step cut k x with + | fuel => rw [hs] at h; exact h.elim + | stuck => + rw [(seg_stuck hs).1 n] at ran + cases ran + | done a => + cases hs' : seg step' cut' k' x' with + | done a' => + rw [hs, hs'] at h + obtain ⟨j, _, runs⟩ := seg_done hs + obtain ⟨j', _, runs'⟩ := seg_done hs' + have e : r = a := run_unique ran (runs 0) + subst e + exact ⟨0 + j', a', runs' 0, h⟩ + | cut _ | stuck | fuel => rw [hs, hs'] at h; exact h.elim + | cut y => + cases hs' : seg step' cut' k' x' with + | cut y' => + rw [hs, hs'] at h + obtain ⟨j, pos, runs⟩ := seg_cut hs + obtain ⟨j', _, runs'⟩ := seg_cut hs' + by_cases le : j ≤ n + · have e : n = (n - j) + j := by omega + rw [e, (runs (n - j)).1] at ran + obtain ⟨m, r', ran', ag⟩ := ih (n - j) (by omega) y y' r h ran + exact ⟨m + j', r', by rw [(runs' m).1]; exact ran', ag⟩ + · have := run_mono (Nat.le_of_lt (Nat.lt_of_not_le le)) ran + rw [show j = 0 + j from (Nat.zero_add j).symm, (runs 0).1] at this + cases this + | done _ | stuck | fuel => rw [hs, hs'] at h; exact h.elim + +/-- Every end of the second program is matched by an agreeing end of the first. -/ +theorem ends_back (S : Sim step cut step' cut' Ag Rel) (m : Nat) (x : σ) (x' : τ) (r' : R') + (rel : Rel x x') (ran : run step' m x' = some r') : + ∃ n r, run step n x = some r ∧ Ag r r' := + S.flip.ends m x' x r' rel ran + +/-- One program ends at some fuel exactly when the other does. -/ +theorem ends_iff (S : Sim step cut step' cut' Ag Rel) {x : σ} {x' : τ} (rel : Rel x x') : + (∃ n r, run step n x = some r) ↔ (∃ m r', run step' m x' = some r') := by + constructor + · intro ⟨n, r, ran⟩ + obtain ⟨m, r', ran', _⟩ := S.ends n x x' r rel ran + exact ⟨m, r', ran'⟩ + · intro ⟨m, r', ran'⟩ + obtain ⟨n, r, ran, _⟩ := S.ends_back m x x' r' rel ran' + exact ⟨n, r, ran⟩ + +/-- A stuck first program has a stuck second program. -/ +theorem stuck (S : Sim step cut step' cut' Ag Rel) : + ∀ (k : Nat) (x : σ) (x' : τ), Rel x x' → steps step k x = none → Stuck step' x' := by + intro k + induction k using Nat.strongRecOn with + | ind k ih => + intro x x' rel stuckAt + obtain ⟨k₁, k₁', h⟩ := S.segment x x' rel + cases hs : seg step cut k₁ x with + | fuel => rw [hs] at h; exact h.elim + | stuck => + cases hs' : seg step' cut' k₁' x' with + | stuck => exact (seg_stuck hs').2 + | done _ | cut _ | fuel => rw [hs, hs'] at h; exact h.elim + | done a => + obtain ⟨j, _, runs⟩ := seg_done hs + have ended := steps_of_run (runs 0) + have := steps_le (step := step) (x := x) (Nat.le_max_left (0 + j) k) + (by rw [ended]; intro y e; cases e) + rw [ended, steps_le (Nat.le_max_right (0 + j) k) (by rw [stuckAt]; intro y e; cases e), + stuckAt] at this + cases this + | cut y => + cases hs' : seg step' cut' k₁' x' with + | cut y' => + rw [hs, hs'] at h + obtain ⟨j, pos, runs⟩ := seg_cut hs + obtain ⟨j', _, runs'⟩ := seg_cut hs' + by_cases le : j ≤ k + · have e : k = (k - j) + j := by omega + rw [e, (runs (k - j)).2] at stuckAt + obtain ⟨i, si⟩ := ih (k - j) (by omega) y y' h stuckAt + exact ⟨i + j', by rw [(runs' i).2]; exact si⟩ + · -- Stuck before reaching the cut point, which it reaches: impossible. + have := steps_le (step := step) (x := x) (Nat.le_of_lt (Nat.lt_of_not_le le)) + (by rw [stuckAt]; intro y e; cases e) + rw [show j = 0 + j from (Nat.zero_add j).symm, (runs 0).2, stuckAt] at this + cases this + | done _ | stuck | fuel => rw [hs, hs'] at h; exact h.elim + +theorem stuck_iff (S : Sim step cut step' cut' Ag Rel) {x : σ} {x' : τ} (rel : Rel x x') : + Stuck step x ↔ Stuck step' x' := + ⟨fun ⟨k, h⟩ => S.stuck k x x' rel h, fun ⟨k, h⟩ => S.flip.stuck k x' x rel h⟩ + +/-- One program runs forever exactly when the other does: an infinite run is matched by an +infinite run, never by an end or a stuck step. -/ +theorem diverges_iff (S : Sim step cut step' cut' Ag Rel) {x : σ} {x' : τ} (rel : Rel x x') : + Diverges step x ↔ Diverges step' x' := by + constructor + · intro d + apply diverges_of + · intro m r' ran' + obtain ⟨n, r, ran, _⟩ := S.ends_back m x x' r' rel ran' + exact not_run_of_diverges d n r ran + · intro st + exact not_stuck_of_diverges d ((S.stuck_iff rel).2 st) + · intro d + apply diverges_of + · intro n r ran + obtain ⟨m, r', ran', _⟩ := S.ends n x x' r rel ran + exact not_run_of_diverges d m r' ran' + · intro st + exact not_stuck_of_diverges d ((S.stuck_iff rel).1 st) + +/-- A simulation from one obligation per pair of cut points: the relation is that one of the +pairs' relations holds, and each segment from a pair ends at a pair. -/ +theorem of_each {rels : List (σ → τ → Prop)} + (each : ∀ P ∈ rels, ∀ x x', P x x' → ∃ k k', + SegRel Ag (fun y y' => ∃ Q ∈ rels, Q y y') (seg step cut k x) (seg step' cut' k' x')) : + Sim step cut step' cut' Ag (fun x x' => ∃ P ∈ rels, P x x') where + segment x x' := fun ⟨P, mem, holds⟩ => each P mem x x' holds + +end Sim + +/-! Layers. -/ + +open Machine + +theorem Agree.symm {a b : Halt × State} (h : Agree a b) : Agree b a := by + obtain ⟨ha, sa⟩ := a + obtain ⟨hb, sb⟩ := b + cases ha <;> cases hb <;> simp_all [Agree] <;> (try exact h.symm) <;> (try omega) + all_goals (obtain ⟨k, st, tr, w⟩ := h; exact ⟨k.symm, st.symm, tr.symm, w.symm⟩) + +/-- Two programs of layers that run as step functions from each call's first configuration, +simulated through cut points on every call in scope. -/ +structure LayerSim (A B : Layer) (o : Oracle) (p : A.Prog) (q : B.Prog) (scope : Call → Prop) + where + σ : Type + τ : Type + step : Call → Step σ (Halt × State) + step' : Call → Step τ (Halt × State) + init : Call → σ + init' : Call → τ + runs : ∀ call n, A.run o p call n = Machine.iterate (step call) n (init call) + runs' : ∀ call n, B.run o q call n = Machine.iterate (step' call) n (init' call) + cut : σ → Bool + cut' : τ → Bool + Rel : Call → σ → τ → Prop + start : ∀ call, scope call → Rel call (init call) (init' call) + sim : ∀ call, scope call → Sim (step call) cut (step' call) cut' Agree (Rel call) + +namespace LayerSim + +variable {A B : Layer} {o : Oracle} {p : A.Prog} {q : B.Prog} {scope : Call → Prop} + +/-- Every end of \`p\` is matched by an agreeing end of \`q\`: a stage. -/ +theorem certified (S : LayerSim A B o p q scope) : Certified A B o p q scope := by + intro call inScope r ⟨n, ran⟩ + rw [S.runs, iterate_eq] at ran + obtain ⟨m, r', ran', ag⟩ := (S.sim call inScope).ends n _ _ r (S.start call inScope) ran + exact ⟨r', ⟨m, by rw [S.runs', iterate_eq]; exact ran'⟩, ag⟩ + +/-- Every end of \`q\` is matched by an agreeing end of \`p\`: the stage backwards, so \`q\` ends on a +call exactly when \`p\` does, and diverges exactly when \`p\` does. -/ +theorem certified_back (S : LayerSim A B o p q scope) : Certified B A o q p scope := by + intro call inScope r' ⟨m, ran'⟩ + rw [S.runs', iterate_eq] at ran' + obtain ⟨n, r, ran, ag⟩ := + (S.sim call inScope).ends_back m _ _ r' (S.start call inScope) ran' + exact ⟨r, ⟨n, by rw [S.runs, iterate_eq]; exact ran⟩, Agree.symm ag⟩ + +theorem ends_iff (S : LayerSim A B o p q scope) (call : Call) (inScope : scope call) : + (∃ r, A.Ends o p call r) ↔ (∃ r', B.Ends o q call r') := by + constructor + · intro ⟨r, e⟩ + obtain ⟨r', e', _⟩ := S.certified call inScope r e + exact ⟨r', e'⟩ + · intro ⟨r', e'⟩ + obtain ⟨r, e, _⟩ := S.certified_back call inScope r' e' + exact ⟨r, e⟩ + +theorem diverges_iff (S : LayerSim A B o p q scope) (call : Call) (inScope : scope call) : + Diverges (S.step call) (S.init call) ↔ Diverges (S.step' call) (S.init' call) := + (S.sim call inScope).diverges_iff (S.start call inScope) + +theorem stuck_iff (S : LayerSim A B o p q scope) (call : Call) (inScope : scope call) : + Stuck (S.step call) (S.init call) ↔ Stuck (S.step' call) (S.init' call) := + (S.sim call inScope).stuck_iff (S.start call inScope) + +end LayerSim + +end SolarTV.CutPoint diff --git a/tv/SolarTV/CutPointExamples.lean b/tv/SolarTV/CutPointExamples.lean new file mode 100644 index 00000000..9f021556 --- /dev/null +++ b/tv/SolarTV/CutPointExamples.lean @@ -0,0 +1,190 @@ +import SolarTV.CutPoint +import SolarTV.EVMIR.Program + +/-! The cut-point theorem on a loop whose trip count is the calldata's first word. + +\`countdown\` reads a word and subtracts one until it is zero; \`countdownAdd\` spells the +decrement as adding the all-ones word, as a peephole pass might. Their one cut point is the loop +header, block 1, and the relation there is that both configurations are the same, which is what +the exporter derives for a pass that leaves the header's stack layout alone. Each segment (the +entry, and one trip round the loop or out of it) is run symbolically, and \`LayerSim\` lifts them +to a stage in both directions for every call, however many times the loop runs, and to "one +diverges exactly when the other does". + +The negatives change the loop's body or its exit test; their segments from the header end at +configurations that differ, so the obligation is false, a mismatch at the cut point rather than a +proof that runs out of fuel. -/ + +namespace SolarTV.CutPoint.Examples + +open EvmRules Machine EVM.Program + +/-- Reads calldata word 0, then counts it down to zero. -/ +def countdown : Program := { blocks := [ + [.op (.stack (.push 0)), .effect .calldataload 1, .jump 1], + [.op (.stack (.dup 0)), .op (.stack .iszero), .jumpi 2, + .op (.stack (.push 1)), .op (.stack (.swap 0)), .op (.stack .sub), .jump 1], + [.op (.stack .pop), .stop]] } + +/-- The same loop, decrementing by adding the all-ones word. -/ +def countdownAdd : Program := { blocks := [ + [.op (.stack (.push 0)), .effect .calldataload 1, .jump 1], + [.op (.stack (.dup 0)), .op (.stack .iszero), .jumpi 2, + .op (.stack (.push (BitVec.allOnes 256))), .op (.stack .add), .jump 1], + [.op (.stack .pop), .stop]] } + +/-- The loop header. -/ +def header : Nat × EVM.Stack × State → Bool := fun x => x.1 == 1 + +/-- The first configuration of a call, and the loop header with its counter, each the same in +both programs. -/ +def rels (call : Call) : List (Nat × EVM.Stack × State → Nat × EVM.Stack × State → Prop) := + [fun x x' => x = (0, [], State.initial call) ∧ x' = x, + fun x x' => ∃ (w : BitVec 256) (s : State), x = (1, [w], s) ∧ x' = x] + + +/-- Adding the all-ones word subtracts one. -/ +theorem add_allOnes (w : BitVec 256) : + Evm.add 115792089237316195423570985008687907853269984665640564039457584007913129639935#256 w = + Evm.sub w 1#256 := by + unfold Evm.add Evm.sub + bv_omega + +theorem segments (o : Oracle) (call : Call) : + ∀ P ∈ rels call, ∀ x x', P x x' → ∃ k k', + SegRel Agree (fun y y' => ∃ Q ∈ rels call, Q y y') + (seg (block o call countdown) header k x) (seg (block o call countdownAdd) header k' x') := by + intro P mem x x' holds + simp only [rels, List.mem_cons, List.not_mem_nil, or_false] at mem + rcases mem with rfl | rfl + · obtain ⟨rfl, rfl⟩ := holds + refine ⟨1, 1, ?_⟩ + simp [seg, block, countdown, countdownAdd, exec, stepOp, EVM.stepChecked, EVM.step, Except.map, header, + Effect.apply, SegRel, rels] + · obtain ⟨w, s, rfl, rfl⟩ := holds + refine ⟨2, 2, ?_⟩ + by_cases hw : w = 0 + · simp [seg, block, countdown, countdownAdd, exec, stepOp, EVM.stepChecked, EVM.step, Except.map, header, + SegRel, hw, Evm.iszero] + exact Agree.refl _ + · have hw' : (w = 0#256) = False := propext ⟨hw, False.elim⟩ + simp [seg, block, countdown, countdownAdd, exec, stepOp, EVM.stepChecked, EVM.step, Except.map, header, + SegRel, rels, hw', Evm.iszero, add_allOnes] + +/-- The two loops, simulated through their header on every call. -/ +def sim (o : Oracle) : + LayerSim EVM.Program.layer EVM.Program.layer o countdown countdownAdd (fun _ => True) where + σ := Nat × EVM.Stack × State + τ := Nat × EVM.Stack × State + step call := block o call countdown + step' call := block o call countdownAdd + init call := (0, [], State.initial call) + init' call := (0, [], State.initial call) + runs _ _ := rfl + runs' _ _ := rfl + cut := header + cut' := header + Rel call := fun x x' => ∃ P ∈ rels call, P x x' + start _ _ := ⟨_, List.mem_cons_self, rfl, rfl⟩ + sim call _ := Sim.of_each (segments o call) + +/-- Every end of \`countdown\` is an end of \`countdownAdd\`, however many times the loop runs. -/ +theorem stage (o : Oracle) : + Stage (EVM.Program.sem o) (EVM.Program.sem o) countdown countdownAdd (fun _ => True) := + stage_of_certified (sim o).certified + +/-- And backwards. -/ +theorem stage_back (o : Oracle) : + Stage (EVM.Program.sem o) (EVM.Program.sem o) countdownAdd countdown (fun _ => True) := + stage_of_certified (sim o).certified_back + +/-- One runs forever on a call exactly when the other does. -/ +theorem diverges_iff (o : Oracle) (call : Call) : + Diverges (block o call countdown) (0, [], State.initial call) ↔ + Diverges (block o call countdownAdd) (0, [], State.initial call) := + (sim o).diverges_iff call trivial + +/-- The stage is not about runs that never end: on calldata whose first word is two, \`countdown\` +goes round its loop twice and stops. -/ +def two : Call := ⟨⟨(List.replicate 31 (0 : UInt8) ++ [2]).toArray⟩, 0, []⟩ + +theorem two_word : calldataWord two 0#256 = 2#256 := by decide +kernel + +theorem ends_on_two (o : Oracle) : (EVM.Program.run o countdown two 6).isSome = true := by + simp [EVM.Program.run, iterate, block, countdown, exec, stepOp, EVM.stepChecked, EVM.step, + Except.map, Effect.apply, two_word, Evm.iszero, Evm.sub] + +/-! Negatives: each mutation makes a segment from the header end differently, so no proof of the +obligation exists. -/ + +/-- The body subtracts two. -/ +def countdownBody : Program := { blocks := [ + [.op (.stack (.push 0)), .effect .calldataload 1, .jump 1], + [.op (.stack (.dup 0)), .op (.stack .iszero), .jumpi 2, + .op (.stack (.push 2)), .op (.stack (.swap 0)), .op (.stack .sub), .jump 1], + [.op (.stack .pop), .stop]] } + +/-- The exit test is inverted: the loop leaves while the counter is nonzero. -/ +def countdownExit : Program := { blocks := [ + [.op (.stack (.push 0)), .effect .calldataload 1, .jump 1], + [.op (.stack (.dup 0)), .jumpi 2, + .op (.stack (.push 1)), .op (.stack (.swap 0)), .op (.stack .sub), .jump 1], + [.op (.stack .pop), .stop]] } + +/-- From a counter of one, \`countdown\` comes back to the header with zero and \`countdownBody\` +with the all-ones word: the configurations at the cut point differ. -/ +theorem body_mismatch (o : Oracle) (call : Call) (s : State) : + ¬∃ k k', SegRel Agree (fun y y' => ∃ Q ∈ rels call, Q y y') + (seg (block o call countdown) header k (1, [1#256], s)) + (seg (block o call countdownBody) header k' (1, [1#256], s)) := by + rintro ⟨k, k', h⟩ + cases k with + | zero => simp [seg, SegRel] at h + | succ k => + cases k' with + | zero => simp [seg, SegRel] at h + | succ k' => + simp [seg, block, countdown, countdownBody, exec, stepOp, EVM.stepChecked, EVM.step, + Except.map, header, SegRel, rels, Evm.iszero, Evm.sub] at h + +/-- From a counter of one, \`countdown\` comes back to the header and \`countdownExit\` stops. -/ +theorem exit_mismatch (o : Oracle) (call : Call) (s : State) : + ¬∃ k k', SegRel Agree (fun y y' => ∃ Q ∈ rels call, Q y y') + (seg (block o call countdown) header k (1, [1#256], s)) + (seg (block o call countdownExit) header k' (1, [1#256], s)) := by + rintro ⟨k, k', h⟩ + cases k with + | zero => simp [seg, SegRel] at h + | succ k => + cases k' with + | zero => simp [seg, SegRel] at h + | succ k' => + cases k' with + | zero => + simp [seg, block, countdown, countdownExit, exec, stepOp, EVM.stepChecked, EVM.step, + Except.map, header, SegRel, Evm.iszero, Evm.sub] at h + | succ k' => + simp [seg, block, countdown, countdownExit, exec, stepOp, EVM.stepChecked, EVM.step, + Except.map, header, SegRel, Evm.iszero, Evm.sub] at h + +/-- info: 'SolarTV.CutPoint.Examples.stage' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms stage + +/-- info: 'SolarTV.CutPoint.Examples.diverges_iff' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms diverges_iff + +/-- info: 'SolarTV.CutPoint.Examples.body_mismatch' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms body_mismatch + +/-- info: 'SolarTV.CutPoint.Examples.exit_mismatch' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms exit_mismatch + +/-- info: 'SolarTV.CutPoint.Examples.ends_on_two' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms ends_on_two + +end SolarTV.CutPoint.Examples diff --git a/tv/SolarTV/EVMIR/Gas.lean b/tv/SolarTV/EVMIR/Gas.lean new file mode 100644 index 00000000..a064c405 --- /dev/null +++ b/tv/SolarTV/EVMIR/Gas.lean @@ -0,0 +1,143 @@ +import SolarTV.EVMIR.Memory +import SolarTV.State.Fork + +/-! Gas-aware execution of scheduled EVM IR windows. +The modeled costs follow EVMYulLean 047f630, EVM/Gas.lean:18-60, 87-90, +272-297 and GasConstants.lean:7-12, 40. They are unchanged for our opcode +subset from Cancun through Osaka. Memory charges use natural arithmetic. +Each instruction pays before executing; GAS returns the budget after its own +charge. Exceptions consume the remaining gas, whereas REVERT preserves it. + +The window starts after any entry JUMPDEST. Static terminals include the label +PUSH and JUMP/JUMPI, but not execution of the outgoing successor. Exact equality +is compositional for this projection. Resource refinement permits extra gas and +success where the original runs out; it requires a gas-insensitive continuation. +Calls, storage, refunds and transaction intrinsic gas are outside this fragment. -/ + +namespace SolarTV.EVM.Gas +open EvmRules + +inductive Op where + | instruction (op : Memory.Op) + | gas + +inductive Observation where + | execution (result : Memory.Execution) + | outOfGas + deriving DecidableEq + +structure Result where + observation : Observation + remaining : Nat + deriving DecidableEq + +def halted (result : Memory.Execution) (remaining : Nat) : Result := + match result with + | .failed _ => ⟨.execution result, 0⟩ + | _ => ⟨.execution result, remaining⟩ + +def exhausted : Result := ⟨.outOfGas, 0⟩ + +def memoryCost (words : Nat) : Nat := 3 * words + words * words / 512 + +def expansionCost (before after : SolarTV.Memory.State) : Nat := + memoryCost after.words.toNat - memoryCost before.words.toNat + +def pureCost (op : EVM.Op) (fork : Fork := .cancun) : Nat := + match op with + | .mul | .div | .sdiv | .mod | .smod | .signextend | .clz => 5 + | .addmod | .mulmod => 8 + | .exp => 10 + | .exchange _ _ => if fork.atLeast .amsterdam then 3 else 9 + | .pop | .calldatasize | .returndatasize => 2 + | .push value => if value = 0 && fork.atLeast .shanghai then 2 else 3 + | .eq | .sub | .add | .and | .or | .xor | .iszero | .not | .dup _ | .swap _ + | .lt | .gt | .slt | .sgt | .byte | .shl | .shr | .sar => 3 + +def baseCost (op : Memory.Op) (fork : Fork := .cancun) : Nat := + match op with + | .stack op => pureCost op fork + | .size => 2 + | .load | .store | .storeByte | .copy => 3 + | .hash => 30 + +def touched (op : Memory.Op) (stack : Stack) (memory : SolarTV.Memory.State) : + SolarTV.Memory.State := + match op, stack with + | .load, offset :: _ | .store, offset :: _ => SolarTV.Memory.expand memory offset.toNat 32 + | .storeByte, offset :: _ => SolarTV.Memory.expand memory offset.toNat 1 + | .copy, destination :: source :: count :: _ => + SolarTV.Memory.expand (SolarTV.Memory.expand memory source.toNat count.toNat) + destination.toNat count.toNat + | .hash, offset :: count :: _ => SolarTV.Memory.expand memory offset.toNat count.toNat + | _, _ => memory + +def cost (op : Memory.Op) (stack : Stack) (memory : SolarTV.Memory.State) + (fork : Fork := .cancun) : Nat := + let dynamic := match op, stack with + | .stack .exp, _ :: exponent :: _ => + (if fork.atLeast .spuriousDragon then 50 else 10) * ((256 - exponent.clz.toNat + 7) / 8) + | .copy, _ :: _ :: count :: _ => 3 * ((count.toNat + 31) / 32) + | .hash, _ :: count :: _ => 6 * ((count.toNat + 31) / 32) + | _, _ => 0 + baseCost op fork + dynamic + expansionCost memory (touched op stack memory) + +def finish (terminal : Memory.Terminal) (stack : Stack) (memory : SolarTV.Memory.State) + (gas : Nat) : Result := + match terminal with + | .control (.jump _) | .control (.branch _ _) | .control (.branchStop _) => + -- The label PUSH costs 3 and can fail before the transfer executes. + if gas < 3 then exhausted + else if stack.length + 1 > 1024 then halted (.failed .overflow) (gas - 3) + else + let transfer := match terminal with | .control (.jump _) => 8 | _ => 10 + if gas - 3 < transfer then exhausted + else halted (Memory.finish terminal stack memory) (gas - 3 - transfer) + | .output _ => + let expanded := match stack with + | offset :: size :: _ => SolarTV.Memory.expand memory offset.toNat size.toNat + | _ => memory + let charge := expansionCost memory expanded + if gas < charge then exhausted + else halted (Memory.finish terminal stack memory) (gas - charge) + | .control .stop | .control .invalid | .control .returnEmpty | .control .revertEmpty => + halted (Memory.finish terminal stack memory) gas + +def execute (ctx : Context) (ops : List Op) (terminal : Memory.Terminal) (stack : Stack) + (memory : SolarTV.Memory.State) (gas : Nat) (fork : Fork := .cancun) : Result := + match ops with + | [] => finish terminal stack memory gas + | .gas :: ops => + if gas < 2 then exhausted + else if stack.length + 1 > 1024 then halted (.failed .overflow) (gas - 2) + else execute ctx ops terminal (BitVec.ofNat 256 (gas - 2) :: stack) memory (gas - 2) fork + | .instruction op :: ops => + let charge := cost op stack memory fork + if gas < charge then exhausted + else match Memory.step ctx op stack memory with + | .error reason => halted (.failed reason) (gas - charge) + | .ok (stack, memory) => execute ctx ops terminal stack memory (gas - charge) fork +termination_by structural ops + +/-- This resource policy is deliberately weaker than exact EVM equivalence. +Only original out-of-gas is unconstrained; reverts and other failures stay defined. +An outgoing continuation must not distinguish extra remaining gas. -/ +def refines (original candidate : Result) : Prop := + original.observation = .outOfGas ∨ + (original.observation = candidate.observation ∧ original.remaining ≤ candidate.remaining) + +instance (original candidate : Result) : Decidable (refines original candidate) := + inferInstanceAs (Decidable (_ ∨ (_ ∧ _))) + +def code (result : Result) : List Word := + BitVec.ofNat 256 result.remaining :: (match result.observation with + | .outOfGas => [6] + | .execution result => Memory.code result) + +def describe (result : Result) : String := + let outcome := match result.observation with + | .outOfGas => "out-of-gas" + | .execution result => Memory.describe result + s!"{outcome}, gas={result.remaining}" + +end SolarTV.EVM.Gas diff --git a/tv/SolarTV/EVMIR/GasSafety.lean b/tv/SolarTV/EVMIR/GasSafety.lean new file mode 100644 index 00000000..a921554f --- /dev/null +++ b/tv/SolarTV/EVMIR/GasSafety.lean @@ -0,0 +1,42 @@ +import SolarTV.EVMIR.Gas + +/-! Kernel checks for opcode prices, debit order, expansion and exhaustion. +The quadratic boundary at 23 words pins the complete formula even though the +current importer admits accesses only within its 256-byte memory projection. -/ + +namespace SolarTV.EVM.Gas +open EvmRules +set_option maxRecDepth 4096 + +example : memoryCost 22 = 66 := by decide +example : memoryCost 23 = 70 := by decide +example : pureCost (.push 0) = 2 ∧ pureCost (.push 1) = 3 := by decide + +example : execute ⟨0, 0⟩ [.gas] (.control (.jump 1)) [] (SolarTV.Memory.initial [] 0) 13 = + ⟨.execution (.edge 1 [11] (SolarTV.Memory.initial [] 0)), 0⟩ := by decide + +example : execute ⟨0, 0⟩ [.gas] (.control .stop) [] (SolarTV.Memory.initial [] 0) 1 = + exhausted := by decide + +example : execute ⟨0, 0⟩ [.gas] (.control .stop) [] (SolarTV.Memory.initial [] 0) 2 = + ⟨.execution (.success []), 0⟩ := by decide + +example : finish (.control .invalid) [] (SolarTV.Memory.initial [] 0) 100 = + ⟨.execution (.failed .invalid), 0⟩ := by decide + +example : finish (.output true) [0, 32] (SolarTV.Memory.initial [] 0) 2 = exhausted := by decide +example : (finish (.output true) [0, 32] (SolarTV.Memory.initial [] 0) 10).remaining = 7 := by decide + +example : expansionCost (SolarTV.Memory.initial [] 22) + (SolarTV.Memory.expand (SolarTV.Memory.initial [] 22) 704 32) = 4 := by decide + +example : refines exhausted ⟨.execution (.success []), 10⟩ := by decide +example : ¬ refines ⟨.execution (.reverted []), 0⟩ ⟨.execution (.success []), 10⟩ := by decide + +example : execute ⟨0, 0⟩ + [.instruction (.stack (.push 0)), .instruction .load, .instruction (.stack .pop), + .instruction (.stack (.push 0)), .instruction .load, .instruction (.stack .pop)] + (.control .stop) [] (SolarTV.Memory.initial [] 0) 17 = + ⟨.execution (.success []), 0⟩ := by decide + +end SolarTV.EVM.Gas diff --git a/tv/SolarTV/EVMIR/Memory.lean b/tv/SolarTV/EVMIR/Memory.lean new file mode 100644 index 00000000..f58930f0 --- /dev/null +++ b/tv/SolarTV/EVMIR/Memory.lean @@ -0,0 +1,87 @@ +import SolarTV.Memory +import SolarTV.EVMIR.Ops + +/-! Scheduled EVM memory instructions and memory-backed terminal output. +The stack operand order is offset then value for stores, and offset then size +for RETURN/REVERT. All accesses expand active memory, including MLOAD. Terminal +halts discard private memory; outgoing edges retain the projected bytes and size. +Pure operations keep the existing stack-limit and first-exception semantics. -/ + +namespace SolarTV.EVM.Memory +open EvmRules + +inductive Op where + | stack (op : EVM.Op) + | load | store | storeByte | size | copy | hash + +inductive Terminal where + | control (terminal : EVM.Terminal) + | output (reverted : Bool) + +inductive Execution where + | edge (destination : Word) (stack : Stack) (memory : SolarTV.Memory.State) + | success (data : List SolarTV.Memory.Byte) + | reverted (data : List SolarTV.Memory.Byte) + | failed (reason : Failure) + deriving DecidableEq + +def step (ctx : Context) (op : Op) (stack : Stack) (memory : SolarTV.Memory.State) : + Except Failure (Stack × SolarTV.Memory.State) := + if stack.length > 1024 then .error .overflow + else match op, stack with + | .stack op, stack => (stepChecked ctx op stack).map (fun next => (next, memory)) + | .load, offset :: rest => .ok + (SolarTV.Memory.load memory offset.toNat :: rest, SolarTV.Memory.expand memory offset.toNat 32) + | .store, offset :: value :: rest => .ok (rest, SolarTV.Memory.store memory offset.toNat value) + | .storeByte, offset :: value :: rest => .ok (rest, SolarTV.Memory.storeByte memory offset.toNat value) + | .copy, destination :: source :: count :: rest => .ok + (rest, SolarTV.Memory.copy memory destination.toNat source.toNat count.toNat) + | .hash, offset :: count :: rest => .ok + (SolarTV.Memory.hash memory offset.toNat count.toNat :: rest, + SolarTV.Memory.expand memory offset.toNat count.toNat) + | .size, stack => + if stack.length + 1 > 1024 then .error .overflow + else .ok (SolarTV.Memory.msize memory :: stack, memory) + | _, _ => .error .underflow + +def finish (terminal : Terminal) (stack : Stack) (memory : SolarTV.Memory.State) : Execution := + if stack.length > 1024 then .failed .overflow + else match terminal with + | .control terminal => match EVM.finish terminal stack with + | .edge destination stack => .edge destination stack memory + | .success => .success [] + | .reverted => .reverted [] + | .failed reason => .failed reason + | .output reverted => match stack with + | offset :: size :: _ => + let memory := SolarTV.Memory.expand memory offset.toNat size.toNat + let data := SolarTV.Memory.read memory offset.toNat size.toNat + if reverted then .reverted data else .success data + | _ => .failed .underflow + +def execute (ctx : Context) : List Op → Terminal → Stack → SolarTV.Memory.State → Execution + | [], terminal, stack, memory => finish terminal stack memory + | op :: ops, terminal, stack, memory => match step ctx op stack memory with + | .error reason => .failed reason + | .ok (stack, memory) => execute ctx ops terminal stack memory + +def code : Execution → List Word + | .edge destination stack memory => + 0 :: destination :: BitVec.ofNat 256 stack.length :: stack ++ SolarTV.Memory.snapshot memory + | .success data => 1 :: data.map (fun b => b.setWidth 256) + | .reverted data => 2 :: data.map (fun b => b.setWidth 256) + | .failed .underflow => [3] + | .failed .overflow => [4] + | .failed .invalid => [5] + +def describe : Execution → String + | .edge destination stack memory => + let edge := if destination = 0 then "fallthrough" else s!"bb{destination.toNat}" + s!"{edge}, stack={stack.map BitVec.toNat}, {SolarTV.Memory.describe memory}" + | .success data => if data.isEmpty then "success(empty)" else s!"success(data={data.map BitVec.toNat})" + | .reverted data => if data.isEmpty then "revert(empty)" else s!"revert(data={data.map BitVec.toNat})" + | .failed .underflow => "exception(stack-underflow)" + | .failed .overflow => "exception(stack-overflow)" + | .failed .invalid => "exception(invalid-instruction)" + +end SolarTV.EVM.Memory diff --git a/tv/SolarTV/EVMIR/Ops.lean b/tv/SolarTV/EVMIR/Ops.lean new file mode 100644 index 00000000..c70cf136 --- /dev/null +++ b/tv/SolarTV/EVMIR/Ops.lean @@ -0,0 +1,159 @@ +import EvmRules.Word +import SolarTV.Word + +/-! Scheduled EVM IR word operations, bounded stacks and terminal outcomes. +Stack top is the head. The pure `step` gives operand semantics; `execute` adds +stack checks and preserves the first exception. Static transfers expose the +outgoing edge and live stack before the successor executes. Block references +stand for valid resolved destinations, independent of physical byte offsets. -/ + +namespace SolarTV.EVM + +open EvmRules + +inductive Op where + | eq | sub | add | mul | and | or | xor | iszero | not + | div | sdiv | mod | smod | exp | addmod | mulmod | signextend + | lt | gt | slt | sgt | byte | shl | shr | sar | clz + | calldatasize | returndatasize | push (value : Word) + | pop | dup (index : Fin 256) | swap (index : Fin 256) + | exchange (first second : Fin 32) + +structure Context where + calldataSize : Word + returndataSize : Word + +abbrev Stack := List Word + +def step (ctx : Context) : Op → Stack → Option Stack + | .add, a :: b :: rest => some (Evm.add a b :: rest) + | .mul, a :: b :: rest => some (Evm.mul a b :: rest) + | .and, a :: b :: rest => some (Evm.and a b :: rest) + | .or, a :: b :: rest => some (Evm.or a b :: rest) + | .xor, a :: b :: rest => some (Evm.xor a b :: rest) + | .not, a :: rest => some (Evm.not a :: rest) + | .div, a :: b :: rest => some (Evm.div a b :: rest) + | .sdiv, a :: b :: rest => some (Evm.sdiv a b :: rest) + | .mod, a :: b :: rest => some (Evm.mod a b :: rest) + | .smod, a :: b :: rest => some (Evm.smod a b :: rest) + | .exp, a :: b :: rest => some (Word.power a b.toNat :: rest) + | .addmod, a :: b :: n :: rest => some (Evm.addmod a b n :: rest) + | .mulmod, a :: b :: n :: rest => some (Evm.mulmod a b n :: rest) + | .signextend, a :: b :: rest => some (Evm.signextend a b :: rest) + | .byte, a :: b :: rest => some (Evm.byte a b :: rest) + | .shl, a :: b :: rest => some (Evm.shl a b :: rest) + | .shr, a :: b :: rest => some (Evm.shr a b :: rest) + | .sar, a :: b :: rest => some (Evm.sar a b :: rest) + | .lt, a :: b :: rest => some (Evm.lt a b :: rest) + | .gt, a :: b :: rest => some (Evm.gt a b :: rest) + | .slt, a :: b :: rest => some (Evm.slt a b :: rest) + | .sgt, a :: b :: rest => some (Evm.sgt a b :: rest) + | .clz, a :: rest => some (Evm.clz a :: rest) + | .exchange first second, stack => do + let a ← stack[first.val]? + let b ← stack[second.val]? + pure ((stack.set first.val b).set second.val a) + | .pop, _ :: rest => some rest + | .dup index, stack => (stack[index.val]?).map (fun value => value :: stack) + | .swap index, a :: rest => (rest[index.val]?).map (fun value => value :: rest.set index.val a) + | .eq, a :: b :: rest => some (Evm.eq a b :: rest) + | .sub, a :: b :: rest => some (Evm.sub a b :: rest) + | .iszero, a :: rest => some (Evm.iszero a :: rest) + | .calldatasize, rest => some (ctx.calldataSize :: rest) + | .returndatasize, rest => some (ctx.returndataSize :: rest) + | .push value, rest => some (value :: rest) + | _, _ => none + +/-! The bounded machine follows EVMYulLean 047f630, Data/Stack.lean and +EVM/Semantics.lean:450-471. The stack head is the next operand, underflow is +checked before executing an opcode, and the resulting height cannot exceed 1024. +Gas and memory expansion remain outside this fragment. Return/revert terminals +are admitted only when the importer proves the output length is zero. -/ + +inductive Failure where + | underflow | overflow | invalid + deriving DecidableEq + +inductive Execution where + | edge (destination : Word) (stack : Stack) + | success | reverted + | failed (reason : Failure) + deriving DecidableEq + +inductive Terminal where + | jump (destination : Word) + | branch (destination fallthrough : Word) + | branchStop (destination : Word) + | stop | returnEmpty | revertEmpty | invalid + +/-- Internal DUP/SWAP indices are zero-based; the importer accepts DUP1..16/SWAP1..16. -/ +def stepChecked (ctx : Context) (op : Op) (stack : Stack) : Except Failure Stack := + if stack.length > 1024 then .error .overflow + else match step ctx op stack with + | none => .error .underflow + | some next => if next.length > 1024 then .error .overflow else .ok next + +/-- Static transfers include the label PUSH and its peak height. Labels are valid, +resolved references supplied by the parser. A conditional transfer consumes its +condition only after the label push succeeds. -/ +def finish (terminal : Terminal) (stack : Stack) : Execution := + if stack.length > 1024 then .failed .overflow + else match terminal with + | .stop => .success + | .invalid => .failed .invalid + | .returnEmpty => match stack with + | _ :: _ :: _ => .success + | _ => .failed .underflow + | .revertEmpty => match stack with + | _ :: _ :: _ => .reverted + | _ => .failed .underflow + | .jump destination => + if stack.length + 1 > 1024 then .failed .overflow else .edge destination stack + | .branch destination fallthrough => + if stack.length + 1 > 1024 then .failed .overflow + else match stack with + | condition :: rest => .edge (if condition = 0 then fallthrough else destination) rest + | _ => .failed .underflow + | .branchStop destination => + if stack.length + 1 > 1024 then .failed .overflow + else match stack with + | condition :: rest => if condition = 0 then .success else .edge destination rest + | _ => .failed .underflow + +/-- Execute one block window, preserving the first exception. Stack values are +observable at an outgoing edge; terminal halts discard the remaining stack. -/ +def execute (ctx : Context) : List Op → Terminal → Stack → Execution + | [], terminal, stack => finish terminal stack + | op :: ops, terminal, stack => match stepChecked ctx op stack with + | .error reason => .failed reason + | .ok next => execute ctx ops terminal next + +/-- Used only for solver witness discovery. Exact execution equality is replayed +in the kernel before a counterexample is reported. -/ +def code : Execution → List Word + | .edge destination stack => 0 :: destination :: stack + | .success => [1] + | .reverted => [3] + | .failed .underflow => [4] + | .failed .overflow => [5] + | .failed .invalid => [6] + +@[simp] theorem code_ite (condition : Prop) [Decidable condition] (yes no : Execution) : + code (if condition then yes else no) = if condition then code yes else code no := by + split <;> rfl + +@[simp] theorem code_cond (condition : Bool) (yes no : Execution) : + code (bif condition then yes else no) = bif condition then code yes else code no := by + cases condition <;> rfl + +def describe : Execution → String + | .edge destination stack => + let edge := if destination = 0 then "fallthrough" else s!"bb{destination.toNat}" + s!"{edge}, stack={stack.map BitVec.toNat}" + | .success => "success(empty)" + | .reverted => "revert(empty)" + | .failed .underflow => "exception(stack-underflow)" + | .failed .overflow => "exception(stack-overflow)" + | .failed .invalid => "exception(invalid-instruction)" + +end SolarTV.EVM diff --git a/tv/SolarTV/EVMIR/Precompiles/BLS12381.lean b/tv/SolarTV/EVMIR/Precompiles/BLS12381.lean new file mode 100644 index 00000000..32e25e3a --- /dev/null +++ b/tv/SolarTV/EVMIR/Precompiles/BLS12381.lean @@ -0,0 +1,89 @@ +import SolarTV.EVMIR.Precompiles.Pairing + +/-! Canonical encodings and arithmetic for EIP-2537. ADD checks curve membership +but intentionally does not require the prime-order subgroup; MSM and pairing do. +Fp elements occupy 64 bytes, scalars 32, and Fp2 coefficients are (real,imaginary). +Empty MSM/pairing inputs are invalid. Scalar multiplication accepts all 256 bits. +https://eips.ethereum.org/EIPS/eip-2537 -/ + +namespace SolarTV.Precompiles.BLS12381 +open EVM.State + +def p : Nat := 0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaab +def order : Nat := 0x73eda753299d7d483339d80809a1d80553bda402fffe5bfeffffffff00000001 +def f := fp p +def f2 := fp2 p +def generator1 : Point Nat := affine f + 3685416753713387016781088315183077757961620795782546409894578378688607592378376318836054947676345821548104185464507 + 1339506544944476473020471379941921221584933875938349620426543736416511423956333506472724655353366534992391756441569 +def generator2 : Point F2 := affine f2 + (352701069587466618187139116011060144890029952792775240219908644239793785735715026873347600343865175952761926303160, + 3059144344244213709971259814753781636986470325476647558659373206291635324768958432433509563104347017837885763365758) + (1985150602287291935568054521177171638300868978215655730859378665066344726373823718423869104263333984641494340347905, + 927553665492332455747201965776037880757740193453592970025027978793976877002675564980949289727957565575433344219582) +def decode1 (input : List Byte) (offset : Nat) (subgroup : Bool) : Option (Point Nat) := + let x := readBE input offset 64; let y := readBE input (offset+64) 64 + if x ≥ p || y ≥ p then none + else if x = 0 && y = 0 then some (infinity f) + else let point := affine f x y + if onCurve f 0 4 point && (!subgroup || isInfinity f (multiply f 0 point order)) then some point else none +def decode2 (input : List Byte) (offset : Nat) (subgroup : Bool) : Option (Point F2) := + let xr := readBE input offset 64; let xi := readBE input (offset+64) 64 + let yr := readBE input (offset+128) 64; let yi := readBE input (offset+192) 64 + if xi ≥ p || xr ≥ p || yi ≥ p || yr ≥ p then none + else if xi = 0 && xr = 0 && yi = 0 && yr = 0 then some (infinity f2) + else let point := affine f2 (xr,xi) (yr,yi) + if onCurve f2 f2.zero (4,4) point && + (!subgroup || isInfinity f2 (multiply f2 f2.zero point order)) then some point else none +def encode1 (point : Point Nat) : List Byte := + match normalize f point with + | none => List.replicate 128 0 + | some (x,y) => be 64 x ++ be 64 y +def encode2 (point : Point F2) : List Byte := + match normalize f2 point with + | none => List.replicate 256 0 + | some (x,y) => be 64 x.1 ++ be 64 x.2 ++ be 64 y.1 ++ be 64 y.2 +def addition1 (input : List Byte) : Option (List Byte) := do + if input.length != 256 then none else + let a ← decode1 input 0 false; let b ← decode1 input 128 false + return encode1 (add f 0 a b) +def addition2 (input : List Byte) : Option (List Byte) := do + if input.length != 512 then none else + let a ← decode2 input 0 false; let b ← decode2 input 256 false + return encode2 (add f2 f2.zero a b) +def msm1 (input : List Byte) : Option (List Byte) := do + if input.isEmpty || input.length%160 != 0 then none else + let result ← (List.range (input.length/160)).foldlM (fun acc i => do + let point ← decode1 input (160*i) true + return add f 0 acc (multiply f 0 point (readBE input (160*i+128) 32))) (infinity f) + return encode1 result +def msm2 (input : List Byte) : Option (List Byte) := do + if input.isEmpty || input.length%288 != 0 then none else + let result ← (List.range (input.length/288)).foldlM (fun acc i => do + let point ← decode2 input (288*i) true + return add f2 f2.zero acc (multiply f2 f2.zero point (readBE input (288*i+256) 32))) (infinity f2) + return encode2 result +def pairing (input : List Byte) : Option (List Byte) := do + if input.isEmpty || input.length%384 != 0 then none else + let pairs ← (List.range (input.length/384)).mapM fun i => do + let a ← decode1 input (384*i) true + let b ← decode2 input (384*i+128) true + return (a,b) + return be 32 (if Pairing.check p order true pairs then 1 else 0) + +def sqrt2 (n : F2) : Option F2 := do + if n.2 = 0 then + match sqrt p n.1 with + | some x => return (x,0) + | none => let y ← sqrt p (f.neg n.1); return (0,y) + else + let norm ← sqrt p (f.add (f.square n.1) (f.square n.2)) + let half := (p+1)/2 + let x ← match sqrt p (f.mul (f.add n.1 norm) half) with + | some x => some x + | none => sqrt p (f.mul (f.sub n.1 norm) half) + if x = 0 then none else + let candidate := (x, f.div n.2 (f.mul 2 x)) + if f2.eq (f2.square candidate) n then some candidate else none + +end SolarTV.Precompiles.BLS12381 diff --git a/tv/SolarTV/EVMIR/Precompiles/BN254.lean b/tv/SolarTV/EVMIR/Precompiles/BN254.lean new file mode 100644 index 00000000..c2fdd300 --- /dev/null +++ b/tv/SolarTV/EVMIR/Precompiles/BN254.lean @@ -0,0 +1,51 @@ +import SolarTV.EVMIR.Precompiles.Pairing + +/-! EIP-196/197 BN254 interfaces. ADD/MUL right-pad short inputs and ignore excess +bytes. Pairing requires an exact multiple of 192 bytes and validates G2 subgroup +membership. Wire encoding puts the imaginary Fp2 coefficient first, unlike the +internal (real,imaginary) representation. Infinity is encoded as all-zero bytes. +https://eips.ethereum.org/EIPS/eip-196 +https://eips.ethereum.org/EIPS/eip-197 -/ + +namespace SolarTV.Precompiles.BN254 +open EVM.State + +def p : Nat := 21888242871839275222246405745257275088696311157297823662689037894645226208583 +def order : Nat := 21888242871839275222246405745257275088548364400416034343698204186575808495617 +def f := fp p +def f2 := fp2 p +def decode1 (input : List Byte) (offset : Nat) : Option (Point Nat) := + let x := readBE input offset 32; let y := readBE input (offset+32) 32 + if x ≥ p || y ≥ p then none + else if x = 0 && y = 0 then some (infinity f) + else let point := affine f x y + if onCurve f 0 3 point then some point else none +def decode2 (input : List Byte) (offset : Nat) : Option (Point F2) := + let xi := readBE input offset 32; let xr := readBE input (offset+32) 32 + let yi := readBE input (offset+64) 32; let yr := readBE input (offset+96) 32 + if xi ≥ p || xr ≥ p || yi ≥ p || yr ≥ p then none + else if xi = 0 && xr = 0 && yi = 0 && yr = 0 then some (infinity f2) + else + let point := affine f2 (xr,xi) (yr,yi) + if onCurve f2 f2.zero (f2.div (3,0) (9,1)) point && + isInfinity f2 (multiply f2 f2.zero point order) then some point else none +def encode (point : Point Nat) : List Byte := + match normalize f point with + | none => List.replicate 64 0 + | some (x,y) => be 32 x ++ be 32 y +def addition (input : List Byte) : Option (List Byte) := do + let a ← decode1 input 0 + let b ← decode1 input 64 + return encode (add f 0 a b) +def multiplication (input : List Byte) : Option (List Byte) := do + let a ← decode1 input 0 + return encode (multiply f 0 a (readBE input 64 32)) +def pairing (input : List Byte) : Option (List Byte) := do + if input.length%192 != 0 then none else + let pairs ← (List.range (input.length/192)).mapM fun i => do + let a ← decode1 input (192*i) + let b ← decode2 input (192*i+64) + return (a,b) + return be 32 (if Pairing.check p order false pairs then 1 else 0) + +end SolarTV.Precompiles.BN254 diff --git a/tv/SolarTV/EVMIR/Precompiles/Blake2F.lean b/tv/SolarTV/EVMIR/Precompiles/Blake2F.lean new file mode 100644 index 00000000..6b3f1f7e --- /dev/null +++ b/tv/SolarTV/EVMIR/Precompiles/Blake2F.lean @@ -0,0 +1,51 @@ +import SolarTV.EVMIR.Precompiles.Bytes + +/-! The BLAKE2b compression function F from RFC 7693, section 3.2. This is the +compression precompile, not a padded BLAKE2 hash. Rounds are decoded big-endian; +state, message, counters and output are little-endian 64-bit words. +https://www.rfc-editor.org/rfc/rfc7693#section-3.2 +https://eips.ethereum.org/EIPS/eip-152 -/ + +namespace SolarTV.Precompiles.Blake2F +open EVM.State +abbrev W := BitVec 64 +def iv : List W := [0x6a09e667f3bcc908,0xbb67ae8584caa73b,0x3c6ef372fe94f82b,0xa54ff53a5f1d36f1, + 0x510e527fade682d1,0x9b05688c2b3e6c1f,0x1f83d9abfb41bd6b,0x5be0cd19137e2179] +def sigma : List (List Nat) := [ + [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15], + [14,10,4,8,9,15,13,6,1,12,0,2,11,7,5,3], + [11,8,12,0,5,2,15,13,10,14,3,6,7,1,9,4], + [7,9,3,1,13,12,11,14,2,6,5,10,4,0,15,8], + [9,0,5,7,2,4,10,15,14,1,11,12,6,8,3,13], + [2,12,6,10,0,11,8,3,4,13,7,5,15,14,1,9], + [12,5,1,15,14,13,4,10,0,7,6,3,9,2,8,11], + [13,11,7,14,12,1,3,9,5,0,15,4,8,6,2,10], + [6,15,14,9,11,3,0,8,12,2,13,7,1,4,10,5], + [10,2,8,4,7,6,1,5,15,11,9,14,3,12,13,0]] +def mix (v : List W) (a b c d : Nat) (x y : W) : List W := + let va := v[a]?.getD 0 + v[b]?.getD 0 + x + let vd := (v[d]?.getD 0 ^^^ va).rotateRight 32 + let vc := v[c]?.getD 0 + vd + let vb := (v[b]?.getD 0 ^^^ vc).rotateRight 24 + let va := va + vb + y + let vd := (vd ^^^ va).rotateRight 16 + let vc := vc + vd + let vb := (vb ^^^ vc).rotateRight 63 + (((v.set a va).set b vb).set c vc).set d vd +def compress (input : List Byte) : List Byte := Id.run do + let rounds := readBE input 0 4 + let h := (List.range 8).map (fun i => BitVec.ofNat 64 (readLE input (4+8*i) 8)) + let m := (List.range 16).map (fun i => BitVec.ofNat 64 (readLE input (68+8*i) 8)) + let mut v := h ++ iv + v := v.set 12 (v[12]?.getD 0 ^^^ BitVec.ofNat 64 (readLE input 196 8)) + v := v.set 13 (v[13]?.getD 0 ^^^ BitVec.ofNat 64 (readLE input 204 8)) + if input[212]?.getD 0 == 1 then v := v.set 14 (~~~(v[14]?.getD 0)) + for round in List.range rounds do + let s := sigma[round % 10]?.getD [] + let indices := [(0,4,8,12),(1,5,9,13),(2,6,10,14),(3,7,11,15), + (0,5,10,15),(1,6,11,12),(2,7,8,13),(3,4,9,14)] + for (j,(a,b,c,d)) in indices.zipIdx.map (fun (v,i) => (i,v)) do + v := mix v a b c d (m[s[2*j]?.getD 0]?.getD 0) (m[s[2*j+1]?.getD 0]?.getD 0) + return (List.range 8).flatMap (fun i => le 8 (h[i]?.getD 0 ^^^ v[i]?.getD 0 ^^^ v[i+8]?.getD 0).toNat) + +end SolarTV.Precompiles.Blake2F diff --git a/tv/SolarTV/EVMIR/Precompiles/Bytes.lean b/tv/SolarTV/EVMIR/Precompiles/Bytes.lean new file mode 100644 index 00000000..ec64fae1 --- /dev/null +++ b/tv/SolarTV/EVMIR/Precompiles/Bytes.lean @@ -0,0 +1,31 @@ +import SolarTV.EVMIR.State.Types + +/-! Byte encodings and bounded binary exponentiation shared by the precompiles. +Reads pad on the right, as the EVM precompile interfaces require; outputs have +an exact caller-specified width and preserve leading zero bytes. -/ + +namespace SolarTV.Precompiles +open EVM.State + +def readBE (bytes : List Byte) (offset count : Nat) : Nat := + (readBytes bytes offset count).foldl (fun n b => n * 256 + b.toNat) 0 + +def readLE (bytes : List Byte) (offset count : Nat) : Nat := + (readBytes bytes offset count).reverse.foldl (fun n b => n * 256 + b.toNat) 0 + +def be (width n : Nat) : List Byte := + (List.range width).map (fun i => BitVec.ofNat 8 (n >>> (8 * (width - 1 - i)))) + +def le (width n : Nat) : List Byte := (be width n).reverse + +def powLoop (modulus : Nat) : Nat → Nat → Nat → Nat → Nat + | 0, _, _, acc => acc + | fuel + 1, base, exponent, acc => + if exponent = 0 then acc else + powLoop modulus fuel (base * base % modulus) (exponent / 2) + (if exponent % 2 = 1 then acc * base % modulus else acc) + +def powMod (base exponent modulus : Nat) : Nat := + if modulus = 0 then 0 else powLoop modulus (exponent.log2 + 1) (base % modulus) exponent (1 % modulus) + +end SolarTV.Precompiles diff --git a/tv/SolarTV/EVMIR/Precompiles/Curve.lean b/tv/SolarTV/EVMIR/Precompiles/Curve.lean new file mode 100644 index 00000000..e0d6e304 --- /dev/null +++ b/tv/SolarTV/EVMIR/Precompiles/Curve.lean @@ -0,0 +1,66 @@ +import SolarTV.EVMIR.Precompiles.Field + +/-! Short-Weierstrass arithmetic in homogeneous coordinates (x/z,y/z). Scalar +multiplication uses doubling and addition without intermediate inversions. The +point at infinity has z=0. Interface modules separately enforce canonical field +encodings, curve membership and the required subgroup checks. -/ + +namespace SolarTV.Precompiles + +structure Point (K : Type) where + x : K + y : K + z : K + +def infinity (f : Arithmetic K) : Point K := ⟨f.one,f.one,f.zero⟩ +def affine (f : Arithmetic K) (x y : K) : Point K := ⟨x,y,f.one⟩ +def isInfinity (f : Arithmetic K) (p : Point K) : Bool := f.eq p.z f.zero +def negate (f : Arithmetic K) (p : Point K) : Point K := {p with y := f.neg p.y} +def normalize (f : Arithmetic K) (p : Point K) : Option (K × K) := + if isInfinity f p then none else + let inverse := f.inv p.z + some (f.mul p.x inverse, f.mul p.y inverse) +def onCurve (f : Arithmetic K) (a b : K) (p : Point K) : Bool := + isInfinity f p || f.eq (f.mul (f.square p.y) p.z) + (f.add (f.add (f.mul (f.square p.x) p.x) (f.mul a (f.mul p.x (f.square p.z)))) + (f.mul b (f.mul (f.square p.z) p.z))) + +def double (f : Arithmetic K) (a : K) (p : Point K) : Point K := + if isInfinity f p || f.eq p.y f.zero then infinity f else + let w := f.add (f.mul (f.nat 3) (f.square p.x)) (f.mul a (f.square p.z)) + let s := f.mul p.y p.z + let b := f.mul (f.mul p.x p.y) s + let h := f.sub (f.square w) (f.mul (f.nat 8) b) + ⟨f.mul (f.nat 2) (f.mul h s), + f.sub (f.mul w (f.sub (f.mul (f.nat 4) b) h)) + (f.mul (f.nat 8) (f.mul (f.square p.y) (f.square s))), + f.mul (f.nat 8) (f.mul s (f.square s))⟩ + +def add (f : Arithmetic K) (a : K) (p q : Point K) : Point K := + if isInfinity f p then q else if isInfinity f q then p else + let u1 := f.mul q.y p.z; let u2 := f.mul p.y q.z + let v1 := f.mul q.x p.z; let v2 := f.mul p.x q.z + if f.eq v1 v2 then + if f.eq u1 u2 then double f a p else infinity f + else + let u := f.sub u1 u2; let v := f.sub v1 v2 + let v2v2 := f.mul (f.square v) v2 + let v3 := f.mul (f.square v) v + let z := f.mul p.z q.z + let h := f.sub (f.sub (f.mul (f.square u) z) v3) (f.mul (f.nat 2) v2v2) + ⟨f.mul v h, f.sub (f.mul u (f.sub v2v2 h)) (f.mul v3 u2), f.mul v3 z⟩ + +def multiplyLoop (f : Arithmetic K) (a : K) : Nat → Nat → Point K → Point K → Point K + | 0, _, _, result => result + | fuel + 1, scalar, point, result => + if scalar = 0 then result else + multiplyLoop f a fuel (scalar/2) (double f a point) + (if scalar%2 = 1 then add f a result point else result) +def multiply (f : Arithmetic K) (a : K) (point : Point K) (scalar : Nat) : Point K := + multiplyLoop f a (scalar.log2+1) scalar point (infinity f) + +def sqrt (p n : Nat) : Option Nat := + let root := powMod n ((p+1)/4) p + if root*root%p = n%p then some root else none + +end SolarTV.Precompiles diff --git a/tv/SolarTV/EVMIR/Precompiles/Execute.lean b/tv/SolarTV/EVMIR/Precompiles/Execute.lean new file mode 100644 index 00000000..b8dfe974 --- /dev/null +++ b/tv/SolarTV/EVMIR/Precompiles/Execute.lean @@ -0,0 +1,81 @@ +import SolarTV.EVMIR.Precompiles.SHA256 +import SolarTV.EVMIR.Precompiles.RIPEMD160 +import SolarTV.EVMIR.Precompiles.Blake2F +import SolarTV.EVMIR.Precompiles.Signatures +import SolarTV.EVMIR.Precompiles.BN254 +import SolarTV.EVMIR.Precompiles.Maps +import SolarTV.EVMIR.Precompiles.KZG +import SolarTV.EVMIR.Precompiles.Gas +import SolarTV.EVMIR.State.Decode + +/-! Complete precompile dispatch for the world's admitted Istanbul–Osaka forks. +Activation is shared with the bytecode evaluator; inactive addresses execute +ordinary account code. Invalid encodings/proofs burn the child budget, whereas +invalid ECDSA signatures return successful empty output. Gas is charged before +expensive crypto. Explicit model work limits are errors, never EVM failures. +Every cryptographic result is computed in Lean from executable arithmetic. +https://eips.ethereum.org/EIPS/eip-7823 -/ + +namespace SolarTV.Precompiles +open EVM.State + +def modexp (input : List Byte) : Except String (List Byte) := do + let base := readBE input 0 32 + let exponent := readBE input 32 32 + let modulus := readBE input 64 32 + if base = 0 && modulus = 0 then return [] + if base > 65536 || exponent > 65536 || modulus > 65536 then + .error "ModExp model byte limit of 64 KiB" + else + let value := powMod (readBE input 96 base) (readBE input (96+base) exponent) + (readBE input (96+base+exponent) modulus) + return be modulus value + +def compute (address : Nat) (input : List Byte) : Except String (Option (List Byte)) := + match address with + | 1 => .ok (some (Signatures.recover input)) + | 2 => .ok (some (SHA256.hash input)) + | 3 => .ok (some (List.replicate 12 0 ++ RIPEMD160.hash input)) + | 4 => .ok (some input) + | 5 => some <$> modexp input + | 6 => .ok (BN254.addition input) + | 7 => .ok (BN254.multiplication input) + | 8 => .ok (BN254.pairing input) + | 9 => + if input.length != 213 || input[212]?.getD 0 > 1 then .ok none + else if readBE input 0 4 > 4096 then .error "BLAKE2F model limit of 4096 rounds" + else .ok (some (Blake2F.compress input)) + | 10 => .ok (KZG.evaluate input) + | 11 => .ok (BLS12381.addition1 input) + | 12 => .ok (BLS12381.msm1 input) + | 13 => .ok (BLS12381.addition2 input) + | 14 => .ok (BLS12381.msm2 input) + | 15 => .ok (BLS12381.pairing input) + | 16 => .ok (BLS12381.map1 input) + | 17 => .ok (BLS12381.map2 input) + | 256 => .ok (some (Signatures.verify input)) + | _ => .error "unrecognized active precompile" + +def execute (fork : Fork) (address : Address) (input : List Byte) (gas : Nat) : + Except String (Stop × List Byte × Nat) := do + if fork = .amsterdam then .error "Amsterdam precompile pricing is not modeled" else + if !precompile fork address then .error "inactive precompile must execute account code" else + -- EIP-152 validates the compression input length before reading rounds. + if address = 9 && input.length != 213 then return (.exception,[],0) + -- MSM/pairing validate their repeated-record layout before charging gas. + if (address = 12 && (input.isEmpty || input.length%160 != 0)) || + (address = 14 && (input.isEmpty || input.length%288 != 0)) || + (address = 15 && (input.isEmpty || input.length%384 != 0)) then + return (.exception,[],0) + if address = 5 && fork.atLeast .osaka && gas < 500 then return (.outOfGas,[],0) + let cost := price fork address.toNat input + if address = 5 && fork.atLeast .osaka && + (readBE input 0 32 > 1024 || readBE input 32 32 > 1024 || readBE input 64 32 > 1024) then + return (.exception,[],0) + if gas < cost then return (.outOfGas,[],0) + let output ← compute address.toNat input + match output with + | none => return (.exception,[],0) + | some bytes => return (.success,bytes,gas-cost) + +end SolarTV.Precompiles diff --git a/tv/SolarTV/EVMIR/Precompiles/Field.lean b/tv/SolarTV/EVMIR/Precompiles/Field.lean new file mode 100644 index 00000000..4c06eccf --- /dev/null +++ b/tv/SolarTV/EVMIR/Precompiles/Field.lean @@ -0,0 +1,79 @@ +import SolarTV.EVMIR.Precompiles.Bytes + +/-! Executable finite-field arithmetic for the curve precompiles. Prime fields +use canonical natural residues; quadratic extensions use i² = -1. The degree-12 +extension is a polynomial quotient, with coefficients in ascending order. Its +modulus is x¹² - c*x⁶ + d (BN254: c=18,d=82; BLS12-381: c=2,d=2). +All loops have explicit structural bounds. Inversion at zero is zero; callers +must check the nonzero/curve conditions required by their interface. -/ + +namespace SolarTV.Precompiles + +structure Arithmetic (K : Type) where + zero : K + one : K + nat : Nat → K + add : K → K → K + neg : K → K + mul : K → K → K + inv : K → K + eq : K → K → Bool + +def Arithmetic.sub (f : Arithmetic K) (a b : K) : K := f.add a (f.neg b) +def Arithmetic.square (f : Arithmetic K) (a : K) : K := f.mul a a +def Arithmetic.div (f : Arithmetic K) (a b : K) : K := f.mul a (f.inv b) + +def powerLoop (mul : K → K → K) : Nat → K → Nat → K → K + | 0, _, _, acc => acc + | fuel + 1, base, exponent, acc => + if exponent = 0 then acc else + powerLoop mul fuel (mul base base) (exponent / 2) + (if exponent % 2 = 1 then mul acc base else acc) + +def Arithmetic.pow (f : Arithmetic K) (a : K) (n : Nat) : K := + powerLoop f.mul (n.log2 + 1) a n f.one + +def fp (p : Nat) : Arithmetic Nat := + ⟨0, 1, (· % p), (fun a b => (a+b)%p), (fun a => (p-a%p)%p), + (fun a b => a*b%p), (fun a => powMod a (p-2) p), (· == ·)⟩ + +abbrev F2 := Nat × Nat + +def fp2 (p : Nat) : Arithmetic F2 := + let f := fp p + ⟨(0,0), (1,0), (fun n => (n%p,0)), + (fun a b => (f.add a.1 b.1, f.add a.2 b.2)), + (fun a => (f.neg a.1, f.neg a.2)), + (fun a b => (f.sub (f.mul a.1 b.1) (f.mul a.2 b.2), + f.add (f.mul a.1 b.2) (f.mul a.2 b.1))), + (fun a => let d := f.inv (f.add (f.square a.1) (f.square a.2)) + (f.mul a.1 d, f.neg (f.mul a.2 d))), (· == ·)⟩ + +abbrev F12 := List Nat + +def polynomial (index value : Nat) : F12 := + (List.range 12).map (fun i => if i = index then value else 0) + +def mul12 (p c d : Nat) (a b : F12) : F12 := Id.run do + let mut v := (List.range 23).map (fun k => + ((List.range 12).foldl (fun sum i => + if i ≤ k && k-i < 12 then sum + a[i]?.getD 0 * b[k-i]?.getD 0 else sum) 0) % p) + for j in List.range 11 do + let i := 22-j + let high := v[i]?.getD 0 + v := v.set (i-6) ((v[i-6]?.getD 0 + c*high)%p) + v := v.set (i-12) ((v[i-12]?.getD 0 + p - (d*high)%p)%p) + return v.take 12 + +def fp12 (p c d : Nat) : Arithmetic F12 := + let mul := mul12 p c d + let one := polynomial 0 1 + ⟨polynomial 0 0, one, (fun n => polynomial 0 (n%p)), + (fun a b => (List.range 12).map (fun i => (a[i]?.getD 0 + b[i]?.getD 0)%p)), + (fun a => a.map (fun x => (p-x%p)%p)), mul, + (fun a => powerLoop mul ((p^12-2).log2+1) a (p^12-2) one), (· == ·)⟩ + +def lift2 (p c : Nat) (a : F2) : F12 := + (polynomial 0 ((a.1 + p - (c*a.2)%p)%p)).set 6 a.2 + +end SolarTV.Precompiles diff --git a/tv/SolarTV/EVMIR/Precompiles/Gas.lean b/tv/SolarTV/EVMIR/Precompiles/Gas.lean new file mode 100644 index 00000000..56195414 --- /dev/null +++ b/tv/SolarTV/EVMIR/Precompiles/Gas.lean @@ -0,0 +1,74 @@ +import SolarTV.EVMIR.Precompiles.Bytes + +/-! Precompile gas schedules and MSM discount tables. ModExp follows EIP-198, +Berlin EIP-2565 and Osaka EIP-7883; the Osaka size restriction is checked before +evaluation by the dispatcher. BN254 repricing starts at Istanbul. BLS discounts +are EIP-2537's exact integer tables, saturated at the final entry. +https://eips.ethereum.org/EIPS/eip-198 +https://eips.ethereum.org/EIPS/eip-2565 +https://eips.ethereum.org/EIPS/eip-7883 +https://eips.ethereum.org/EIPS/eip-2537#gas-schedule -/ + +namespace SolarTV.Precompiles +open EVM.State + +def discount1 : List Nat := [ + 1000,949,848,797,764,750,738,728,719,712,705,698,692,687,682,677,673,669,665, + 661,658,654,651,648,645,642,640,637,635,632,630,627,625,623,621,619,617,615, + 613,611,609,608,606,604,603,601,599,598,596,595,593,592,591,589,588,586,585, + 584,582,581,580,579,577,576,575,574,573,572,570,569,568,567,566,565,564,563, + 562,561,560,559,558,557,556,555,554,553,552,551,550,549,548,547,547,546,545, + 544,543,542,541,540,540,539,538,537,536,536,535,534,533,532,532,531,530,529, + 528,528,527,526,525,525,524,523,522,522,521,520,520,519] +def discount2 : List Nat := [ + 1000,1000,923,884,855,832,812,796,782,770,759,749,740,732,724,717,711,704, + 699,693,688,683,679,674,670,666,663,659,655,652,649,646,643,640,637,634,632, + 629,627,624,622,620,618,615,613,611,609,607,606,604,602,600,598,597,595,593, + 592,590,589,587,586,584,583,582,580,579,578,576,575,574,573,571,570,569,568, + 567,566,565,563,562,561,560,559,558,557,556,555,554,553,552,552,551,550,549, + 548,547,546,545,545,544,543,542,541,541,540,539,538,537,537,536,535,535,534, + 533,532,532,531,530,530,529,528,528,527,526,526,525,524,524] + +def modexpPrice (fork : Fork) (input : List Byte) : Nat := + let base := readBE input 0 32 + let exponent := readBE input 32 32 + let modulus := readBE input 64 32 + let head := readBE input (96+base) (min exponent 32) + let length := max base modulus + let iterations := max 1 ((if fork.atLeast .osaka then 16 else 8)*(exponent-32) + head.log2) + if fork.atLeast .osaka then + max 500 ((if length ≤ 32 then 16 else 2*((length+7)/8)^2)*iterations) + else if fork.atLeast .berlin then max 200 (((length+7)/8)^2 * iterations / 3) + else + let complexity := if length ≤ 64 then length^2 + else if length ≤ 1024 then length^2/4 + 96*length - 3072 + else length^2/16 + 480*length - 199680 + complexity * iterations / 20 + +def price (fork : Fork) (address : Nat) (input : List Byte) : Nat := + let words := (input.length+31)/32 + match address with + | 1 => 3000 + | 2 => 60 + 12*words + | 3 => 600 + 120*words + | 4 => 15 + 3*words + | 5 => modexpPrice fork input + | 6 => if fork.atLeast .istanbul then 150 else 500 + | 7 => if fork.atLeast .istanbul then 6000 else 40000 + | 8 => if fork.atLeast .istanbul then 45000 + 34000*(input.length/192) + else 100000 + 80000*(input.length/192) + | 9 => readBE input 0 4 + | 10 => 50000 + | 11 => 375 + | 12 => let k := input.length/160 + 12000*k*(discount1[min (k-1) 127]?.getD 519)/1000 + | 13 => 600 + | 14 => let k := input.length/288 + 22500*k*(discount2[min (k-1) 127]?.getD 524)/1000 + | 15 => 37700 + 32600*(input.length/384) + | 16 => 5500 + | 17 => 23800 + | 256 => 6900 + | _ => 0 + +end SolarTV.Precompiles diff --git a/tv/SolarTV/EVMIR/Precompiles/KZG.lean b/tv/SolarTV/EVMIR/Precompiles/KZG.lean new file mode 100644 index 00000000..70e14b86 --- /dev/null +++ b/tv/SolarTV/EVMIR/Precompiles/KZG.lean @@ -0,0 +1,63 @@ +import SolarTV.EVMIR.Precompiles.BLS12381 +import SolarTV.EVMIR.Precompiles.SHA256 + +/-! EIP-4844 point evaluation against Ethereum's fixed KZG ceremony G2 point. +Compressed points are decoded canonically and checked for subgroup membership; +infinity is permitted. Scalars are canonical Fr values. Verification evaluates +the actual pairing product e(C-yG1,-G2) * e(proof,tauG2-zG2) = 1. +The trusted setup is public protocol data, not a result oracle or pairing axiom. +https://eips.ethereum.org/EIPS/eip-4844#point-evaluation-precompile +https://github.com/ethereum/consensus-specs/blob/dev/specs/deneb/polynomial-commitments.md -/ + +namespace SolarTV.Precompiles.KZG +open EVM.State BLS12381 + +def compressed1 (input : List Byte) : Option (Point Nat) := do + if input.length != 48 then none else + let flags := input[0]?.getD 0 |>.toNat + let x := readBE input 0 48 % 2^381 + if flags/128 != 1 || x ≥ p then none + else if flags/64%2 = 1 then + if x = 0 && flags/32%2 = 0 then some (infinity f) else none + else + let y ← sqrt p (f.add (f.mul (f.square x) x) 4) + let y := if (y > p/2) == (flags/32%2 = 1) then y else f.neg y + let point := affine f x y + if isInfinity f (multiply f 0 point order) then some point else none + +def compressed2 (input : List Byte) : Option (Point F2) := do + if input.length != 96 then none else + let flags := input[0]?.getD 0 |>.toNat + let xi := readBE input 0 48 % 2^381 + let xr := readBE input 48 48 + if flags/128 != 1 || xi ≥ p || xr ≥ p then none + else if flags/64%2 = 1 then + if xi = 0 && xr = 0 && flags/32%2 = 0 then some (infinity f2) else none + else + let x := (xr,xi) + let y ← sqrt2 (f2.add (f2.mul (f2.square x) x) (4,4)) + let sign := y.2 > p/2 || (y.2 = 0 && y.1 > p/2) + let y := if sign == (flags/32%2 = 1) then y else f2.neg y + let point := affine f2 x y + if isInfinity f2 (multiply f2 f2.zero point order) then some point else none + +def tau : Option (Point F2) := compressed2 (be 96 + 0xb5bfd7dd8cdeb128843bc287230af38926187075cbfbefa81009a2ce615ac53d2914e5870cb452d2afaaab24f3499f72185cbfee53492714734429b7b38608e23926c911cceceac9a36851477ba4c60b087041de621000edc98edada20c1def2) + +def evaluate (input : List Byte) : Option (List Byte) := do + if input.length != 192 then none else + let commitment := (input.drop 96).take 48 + let expected := [1] ++ (SHA256.hash commitment).drop 1 + if input.take 32 != expected then none else + let z := readBE input 32 32; let y := readBE input 64 32 + if z ≥ order || y ≥ order then none else + let c ← compressed1 commitment + let proof ← compressed1 (input.drop 144) + let tau ← tau + let left := add f 0 c (negate f (multiply f 0 generator1 y)) + let right := add f2 f2.zero tau (negate f2 (multiply f2 f2.zero generator2 z)) + if Pairing.check p order true [(left,negate f2 generator2),(proof,right)] then + some (be 32 4096 ++ be 32 order) + else none + +end SolarTV.Precompiles.KZG diff --git a/tv/SolarTV/EVMIR/Precompiles/MapConstants.lean b/tv/SolarTV/EVMIR/Precompiles/MapConstants.lean new file mode 100644 index 00000000..41718831 --- /dev/null +++ b/tv/SolarTV/EVMIR/Precompiles/MapConstants.lean @@ -0,0 +1,98 @@ +import SolarTV.EVMIR.Precompiles.Field + +/-! EIP-2537 isogeny constants, in ascending polynomial order. Generated +by tools/gen_bls_tables.py from ark-bls12-381 0.6.0; only mathematical +constants are copied, with negative values reduced to canonical residues. +https://eips.ethereum.org/assets/eip-2537/field_to_curve -/ + +namespace SolarTV.Precompiles.BLS12381.MapConstants + +-- Source SHA-256: 1e8090ef8a4774391d7f20c9599c61cdb9476532051b3d0645cf7743bf1421dd. +def g1XNumerator : List Nat := [ + 2712959285290305970661081772124144179193819192423276218370281158706191519995889425075952244140278856085036081760695, + 3564859427549639835253027846704205725951033235539816243131874237388832081954622352624080767121604606753339903542203, + 2051387046688339481714726479723076305756384619135044672831882917686431912682625619320120082313093891743187631791280, + 3612713941521031012780325893181011392520079402153354595775735142359240110423346445050803899623018402874731133626465, + 2247053637822768981792833880270996398470828564809439728372634811976089874056583714987807553397615562273407692740057, + 3415427104483187489859740871640064348492611444552862448295571438270821994900526625562705192993481400731539293415811, + 2067521456483432583860405634125513059912765526223015704616050604591207046392807563217109432457129564962571408764292, + 3650721292069012982822225637849018828271936405382082649291891245623305084633066170122780668657208923883092359301262, + 1239271775787030039269460763652455868148971086016832054354147730155061349388626624328773377658494412538595239256855, + 3479374185711034293956731583912244564891370843071137483962415222733470401948838363051960066766720884717833231600798, + 2492756312273161536685660027440158956721981129429869601638362407515627529461742974364729223659746272460004902959995, + 1058488477413994682556770863004536636444795456512795473806825292198091015005841418695586811009326456605062948114985] + +def g1XDenominator : List Nat := [ + 1353092447850172218905095041059784486169131709710991428415161466575141675351394082965234118340787683181925558786844, + 2822220997908397120956501031591772354860004534930174057793539372552395729721474912921980407622851861692773516917759, + 1717937747208385987946072944131378949849282930538642983149296304709633281382731764122371874602115081850953846504985, + 501624051089734157816582944025690868317536915684467868346388760435016044027032505306995281054569109955275640941784, + 3025903087998593826923738290305187197829899948335370692927241015584233559365859980023579293766193297662657497834014, + 2224140216975189437834161136818943039444741035168992629437640302964164227138031844090123490881551522278632040105125, + 1146414465848284837484508420047674663876992808692209238763293935905506532411661921697047880549716175045414621825594, + 3179090966864399634396993677377903383656908036827452986467581478509513058347781039562481806409014718357094150199902, + 1549317016540628014674302140786462938410429359529923207442151939696344988707002602944342203885692366490121021806145, + 1442797143427491432630626390066422021593505165588630398337491100088557278058060064930663878153124164818522816175370, + 1] + +def g1YNumerator : List Nat := [ + 1393399195776646641963150658816615410692049723305861307490980409834842911816308830479576739332720113414154429643571, + 2968610969752762946134106091152102846225411740689724909058016729455736597929366401532929068084731548131227395540630, + 122933100683284845219599644396874530871261396084070222155796123161881094323788483360414289333111221370374027338230, + 303251954782077855462083823228569901064301365507057490567314302006681283228886645653148231378803311079384246777035, + 1353972356724735644398279028378555627591260676383150667237975415318226973994509601413730187583692624416197017403099, + 3443977503653895028417260979421240655844034880950251104724609885224259484262346958661845148165419691583810082940400, + 718493410301850496156792713845282235942975872282052335612908458061560958159410402177452633054233549648465863759602, + 1466864076415884313141727877156167508644960317046160398342634861648153052436926062434809922037623519108138661903145, + 1536886493137106337339531461344158973554574987550750910027365237255347020572858445054025958480906372033954157667719, + 2171468288973248519912068884667133903101171670397991979582205855298465414047741472281361964966463442016062407908400, + 3915937073730221072189646057898966011292434045388986394373682715266664498392389619761133407846638689998746172899634, + 3802409194827407598156407709510350851173404795262202653149767739163117554648574333789388883640862266596657730112910, + 1707589313757812493102695021134258021969283151093981498394095062397393499601961942449581422761005023512037430861560, + 349697005987545415860583335313370109325490073856352967581197273584891698473628451945217286148025358795756956811571, + 885704436476567581377743161796735879083481447641210566405057346859953524538988296201011389016649354976986251207243, + 3370924952219000111210625390420697640496067348723987858345031683392215988129398381698161406651860675722373763741188] + +def g1YDenominator : List Nat := [ + 3396434800020507717552209507749485772788165484415495716688989613875369612529138640646200921379825018840894888371137, + 3907278185868397906991868466757978732688957419873771881240086730384895060595583602347317992689443299391009456758845, + 854914566454823955479427412036002165304466268547334760894270240966182605542146252771872707010378658178126128834546, + 3496628876382137961119423566187258795236027183112131017519536056628828830323846696121917502443333849318934945158166, + 1828256966233331991927609917644344011503610008134915752990581590799656305331275863706710232159635159092657073225757, + 1362317127649143894542621413133849052553333099883364300946623208643344298804722863920546222860227051989127113848748, + 3443845896188810583748698342858554856823966611538932245284665132724280883115455093457486044009395063504744802318172, + 3484671274283470572728732863557945897902920439975203610275006103818288159899345245633896492713412187296754791689945, + 3755735109429418587065437067067640634211015783636675372165599470771975919172394156249639331555277748466603540045130, + 3459661102222301807083870307127272890283709299202626530836335779816726101522661683404130556379097384249447658110805, + 742483168411032072323733249644347333168432665415341249073150659015707795549260947228694495111018381111866512337576, + 1662231279858095762833829698537304807741442669992646287950513237989158777254081548205552083108208170765474149568658, + 1668238650112823419388205992952852912407572045257706138925379268508860023191233729074751042562151098884528280913356, + 369162719928976119195087327055926326601627748362769544198813069133429557026740823593067700396825489145575282378487, + 2164195715141237148945939585099633032390257748382945597506236650132835917087090097395995817229686247227784224263055, + 1] + +-- Source SHA-256: 6edfd3d72eea73164ce6ed78dabd4e4772389987e8c084340f628f4981464cc7. +def g2XNumerator : List F2 := [ + (889424345604814976315064405719089812568196182208668418962679585805340366775741747653930584250892369786198727235542, 889424345604814976315064405719089812568196182208668418962679585805340366775741747653930584250892369786198727235542), + (0, 2668273036814444928945193217157269437704588546626005256888038757416021100327225242961791752752677109358596181706522), + (2668273036814444928945193217157269437704588546626005256888038757416021100327225242961791752752677109358596181706526, 1334136518407222464472596608578634718852294273313002628444019378708010550163612621480895876376338554679298090853261), + (3557697382419259905260257622876359250272784728834673675850718343221361467102966990615722337003569479144794908942033, 0)] + +def g2XDenominator : List F2 := [ + (0, 4002409555221667393417789825735904156556882819939007885332058136124031650490837864442687629129015664037894272559715), + (12, 4002409555221667393417789825735904156556882819939007885332058136124031650490837864442687629129015664037894272559775), + (1, 0)] + +def g2YNumerator : List F2 := [ + (3261222600550988246488569487636662646083386001431784202863158481286248011511053074731078808919938689216061999863558, 3261222600550988246488569487636662646083386001431784202863158481286248011511053074731078808919938689216061999863558), + (0, 889424345604814976315064405719089812568196182208668418962679585805340366775741747653930584250892369786198727235518), + (2668273036814444928945193217157269437704588546626005256888038757416021100327225242961791752752677109358596181706524, 1334136518407222464472596608578634718852294273313002628444019378708010550163612621480895876376338554679298090853263), + (2816510427748580758331037284777117739799287910327449993381818688383577828123182200904113516794492504322962636245776, 0)] + +def g2YDenominator : List F2 := [ + (4002409555221667393417789825735904156556882819939007885332058136124031650490837864442687629129015664037894272559355, 4002409555221667393417789825735904156556882819939007885332058136124031650490837864442687629129015664037894272559355), + (0, 4002409555221667393417789825735904156556882819939007885332058136124031650490837864442687629129015664037894272559571), + (18, 4002409555221667393417789825735904156556882819939007885332058136124031650490837864442687629129015664037894272559769), + (1, 0)] + +end SolarTV.Precompiles.BLS12381.MapConstants diff --git a/tv/SolarTV/EVMIR/Precompiles/Maps.lean b/tv/SolarTV/EVMIR/Precompiles/Maps.lean new file mode 100644 index 00000000..9ee1832b --- /dev/null +++ b/tv/SolarTV/EVMIR/Precompiles/Maps.lean @@ -0,0 +1,58 @@ +import SolarTV.EVMIR.Precompiles.BLS12381 +import SolarTV.EVMIR.Precompiles.MapConstants + +/-! EIP-2537's simplified SWU maps, rational isogenies and effective-cofactor +clearing. Exceptional SWU inputs use B/(Z*A); zero isogeny denominators map to +infinity. The output sign follows sgn0 (parity of the first nonzero coefficient), +not the lexicographic sign used by compressed KZG point encodings. +https://eips.ethereum.org/assets/eip-2537/field_to_curve -/ + +namespace SolarTV.Precompiles.BLS12381 +open EVM.State MapConstants + +def polynomialValue (f : Arithmetic K) (coefficients : List K) (x : K) : K := + coefficients.reverse.foldl (fun acc c => f.add (f.mul acc x) c) f.zero + +def swu (f : Arithmetic K) (a b z : K) (root : K → Option K) + (sign : K → Bool) (u : K) : Option (Point K) := do + let zu2 := f.mul z (f.square u) + let inverse := f.inv (f.add (f.square zu2) zu2) + let x1 := if f.eq inverse f.zero then f.div b (f.mul z a) + else f.mul (f.div (f.neg b) a) (f.add f.one inverse) + let equation := fun x => f.add (f.add (f.mul (f.square x) x) (f.mul a x)) b + let (x,y) ← match root (equation x1) with + | some y => some (x1,y) + | none => let x2 := f.mul zu2 x1; (fun y => (x2,y)) <$> root (equation x2) + return affine f x (if sign u == sign y then y else f.neg y) + +def isogeny (f : Arithmetic K) (xn xd yn yd : List K) (point : Point K) : Point K := + match normalize f point with + | none => infinity f + | some (x,y) => + let dx := polynomialValue f xd x; let dy := polynomialValue f yd x + if f.eq dx f.zero || f.eq dy f.zero then infinity f else + affine f (f.div (polynomialValue f xn x) dx) + (f.div (f.mul y (polynomialValue f yn x)) dy) + +def map1 (input : List Byte) : Option (List Byte) := do + if input.length != 64 then none else + let u := readBE input 0 64 + if u ≥ p then none else + let point ← swu f + 0x144698a3b8e9433d693a02c96d4982b0ea985383ee66a8d8e8981aefd881ac98936f8da0e0f97f5cf428082d584c1d + 0x12e2908d11688030018b12e8753eee3b2016c1f0f24f4070a0b9c14fcef35ef55a23215a316ceaa5d1cc48e98e172be0 + 11 (sqrt p) (fun n => n%2 == 1) u + let mapped := isogeny f g1XNumerator g1XDenominator g1YNumerator g1YDenominator point + return encode1 (multiply f 0 mapped 0xd201000000010001) + +def map2 (input : List Byte) : Option (List Byte) := do + if input.length != 128 then none else + let a := readBE input 0 64; let b := readBE input 64 64 + if a ≥ p || b ≥ p then none else + let point ← swu f2 (0,240) (1012,1012) (p-2,p-1) sqrt2 + (fun n => n.1%2 == 1 || (n.1 == 0 && n.2%2 == 1)) (a,b) + let mapped := isogeny f2 g2XNumerator g2XDenominator g2YNumerator g2YDenominator point + let cofactor := 0xbc69f08f2ee75b3584c6a0ea91b352888e2a8e9145ad7689986ff031508ffe1329c2f178731db956d82bf015d1212b02ec0ec69d7477c1ae954cbc06689f6a359894c0adebbf6b4e8020005aaa95551 + return encode2 (multiply f2 f2.zero mapped cofactor) + +end SolarTV.Precompiles.BLS12381 diff --git a/tv/SolarTV/EVMIR/Precompiles/Observe.lean b/tv/SolarTV/EVMIR/Precompiles/Observe.lean new file mode 100644 index 00000000..f64914c7 --- /dev/null +++ b/tv/SolarTV/EVMIR/Precompiles/Observe.lean @@ -0,0 +1,24 @@ +import SolarTV.EVMIR.Precompiles.Execute +import Lean.Data.Json + +/-! Direct precompile observations for boundary tests and independent replay. +These observations do not bypass the kernel proof required for a world-entry +verification. An inactive address is identified separately: its account code, +not a precompile, must be executed by the caller's world evaluator. -/ + +namespace SolarTV.Precompiles +open EVM.State + +def describe (fork : Fork) (address : Address) (input : List Byte) (gas : Nat) : String := + let result := if precompile fork address then execute fork address input gas + else .ok (.success,[],gas) + match result with + | .error reason => (Lean.Json.mkObj [("unsupported",.str reason)]).compress + | .ok (stop,data,remaining) => + let name := if !precompile fork address then "inactive" else match stop with + | .success => "success" | .exception => "exception" + | .outOfGas => "out-of-gas" | .reverted => "revert" + (Lean.Json.arr #[.str name, + .arr (data.map (fun b => Lean.toJson b.toNat)).toArray, Lean.toJson remaining]).compress + +end SolarTV.Precompiles diff --git a/tv/SolarTV/EVMIR/Precompiles/Pairing.lean b/tv/SolarTV/EVMIR/Precompiles/Pairing.lean new file mode 100644 index 00000000..25fc58ec --- /dev/null +++ b/tv/SolarTV/EVMIR/Precompiles/Pairing.lean @@ -0,0 +1,81 @@ +import SolarTV.EVMIR.Precompiles.Curve + +/-! Optimal-Ate pairing products over explicit degree-12 polynomial fields. +Miller lines retain numerator/denominator pairs, avoiding an inversion per line. +Final exponentiation compares their powers, not an unchecked foreign result. +BN254 includes its two Frobenius correction lines. BLS12-381 uses the absolute +loop parameter: inversion of the whole product for the negative parameter does +not change the product-equals-one predicate exposed by either precompile. + +The homogeneous line and group formulas follow EVMYulLean's alt_bn128 reference +and the pairing definitions in EIP-197 and EIP-2537. Infinity pairs contribute +one. Decoders must enforce curve and subgroup membership before calling here. +https://eips.ethereum.org/EIPS/eip-197 +https://eips.ethereum.org/EIPS/eip-2537 -/ + +namespace SolarTV.Precompiles.Pairing + +def line (f : Arithmetic F12) (p q t : Point F12) : F12 × F12 := + let numerator := f.sub (f.mul q.y p.z) (f.mul p.y q.z) + let denominator := f.sub (f.mul q.x p.z) (f.mul p.x q.z) + let dx := f.sub (f.mul t.x p.z) (f.mul p.x t.z) + let dy := f.sub (f.mul t.y p.z) (f.mul p.y t.z) + if !f.eq denominator f.zero then + (f.sub (f.mul numerator dx) (f.mul denominator dy), f.mul denominator (f.mul t.z p.z)) + else if f.eq numerator f.zero then + let numerator := f.mul (f.nat 3) (f.square p.x) + let denominator := f.mul (f.nat 2) (f.mul p.y p.z) + (f.sub (f.mul numerator dx) (f.mul denominator dy), f.mul denominator (f.mul t.z p.z)) + else (dx, f.mul p.z t.z) + +def cast (f : Arithmetic F12) (p : Point Nat) : Point F12 := + ⟨f.nat p.x, f.nat p.y, f.nat p.z⟩ + +def twist (p : Nat) (bls : Bool) (q : Point F2) : Point F12 := + let f := fp12 p (if bls then 2 else 18) (if bls then 2 else 82) + let w := polynomial 1 1 + let x := lift2 p (if bls then 1 else 9) q.x + let y := lift2 p (if bls then 1 else 9) q.y + let z := lift2 p (if bls then 1 else 9) q.z + if bls then ⟨f.mul x w, y, f.mul z (f.pow w 3)⟩ + else ⟨f.mul x (f.pow w 2), f.mul y (f.pow w 3), z⟩ + +def miller (p : Nat) (bls : Bool) (g1 : Point Nat) (g2 : Point F2) : F12 × F12 := Id.run do + let f := fp12 p (if bls then 2 else 18) (if bls then 2 else 82) + if isInfinity (fp p) g1 || isInfinity (fp2 p) g2 then return (f.one,f.one) + let q := twist p bls g2 + let t := cast f g1 + let count := if bls then 0xd201000000010000 else 29793968203157093288 + let mut r := q + let mut numerator := f.one + let mut denominator := f.one + for j in List.range count.log2 do + let bit := count.log2-1-j + let l := line f r r t + numerator := f.mul (f.square numerator) l.1 + denominator := f.mul (f.square denominator) l.2 + r := double f f.zero r + if (count >>> bit)%2 = 1 then + let l := line f r q t + numerator := f.mul numerator l.1 + denominator := f.mul denominator l.2 + r := add f f.zero r q + if !bls then + let q1 := Point.mk (f.pow q.x p) (f.pow q.y p) (f.pow q.z p) + let q2 := Point.mk (f.pow q1.x p) (f.neg (f.pow q1.y p)) (f.pow q1.z p) + let l := line f r q1 t + numerator := f.mul numerator l.1; denominator := f.mul denominator l.2 + r := add f f.zero r q1 + let l := line f r q2 t + numerator := f.mul numerator l.1; denominator := f.mul denominator l.2 + return (numerator,denominator) + +def check (p order : Nat) (bls : Bool) (pairs : List (Point Nat × Point F2)) : Bool := + let f := fp12 p (if bls then 2 else 18) (if bls then 2 else 82) + let product := pairs.foldl (fun acc pair => + let (n,d) := miller p bls pair.1 pair.2 + (f.mul acc.1 n, f.mul acc.2 d)) (f.one,f.one) + !f.eq product.2 f.zero && + (f.eq product.1 product.2 || f.eq (f.pow product.1 ((p^12-1)/order)) (f.pow product.2 ((p^12-1)/order))) + +end SolarTV.Precompiles.Pairing diff --git a/tv/SolarTV/EVMIR/Precompiles/RIPEMD160.lean b/tv/SolarTV/EVMIR/Precompiles/RIPEMD160.lean new file mode 100644 index 00000000..7b31fd98 --- /dev/null +++ b/tv/SolarTV/EVMIR/Precompiles/RIPEMD160.lean @@ -0,0 +1,72 @@ +import SolarTV.EVMIR.Precompiles.Bytes + +/-! RIPEMD-160's two parallel 80-round compression lanes, with little-endian +words, length padding and digest encoding. The precompile adds its twelve zero +output bytes separately. Constants follow the designers' reference specification. +https://homes.esat.kuleuven.be/~bosselae/ripemd160.html -/ + +namespace SolarTV.Precompiles.RIPEMD160 +open EVM.State +abbrev W := BitVec 32 + +def leftIndex : List Nat := [ + 0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15, + 7,4,13,1,10,6,15,3,12,0,9,5,2,14,11,8, + 3,10,14,4,9,15,8,1,2,7,0,6,13,11,5,12, + 1,9,11,10,0,8,12,4,13,3,7,15,14,5,6,2, + 4,0,5,9,7,12,2,10,14,1,3,8,11,6,15,13] +def rightIndex : List Nat := [ + 5,14,7,0,9,2,11,4,13,6,15,8,1,10,3,12, + 6,11,3,7,0,13,5,10,14,15,8,12,4,9,1,2, + 15,5,1,3,7,14,6,9,11,8,12,2,10,0,4,13, + 8,6,4,1,3,11,15,0,5,12,2,13,9,7,10,14, + 12,15,10,4,1,5,8,7,6,2,13,14,0,3,9,11] +def leftShift : List Nat := [ + 11,14,15,12,5,8,7,9,11,13,14,15,6,7,9,8, + 7,6,8,13,11,9,7,15,7,12,15,9,11,7,13,12, + 11,13,6,7,14,9,13,15,14,8,13,6,5,12,7,5, + 11,12,14,15,14,15,9,8,9,14,5,6,8,6,5,12, + 9,15,5,11,6,8,13,12,5,12,13,14,11,8,5,6] +def rightShift : List Nat := [ + 8,9,9,11,13,15,15,5,7,7,8,11,14,14,12,6, + 9,13,15,7,12,8,9,11,7,7,12,7,6,15,13,11, + 9,7,15,11,8,6,6,14,12,13,5,14,13,13,7,5, + 15,5,8,11,14,14,6,14,6,9,12,9,12,5,15,8, + 8,5,12,9,12,5,14,6,8,13,6,5,15,13,11,11] +def constant (right : Bool) (round : Nat) : W := + (if right then [0x50a28be6,0x5c4dd124,0x6d703ef3,0x7a6d76e9,0] + else [0,0x5a827999,0x6ed9eba1,0x8f1bbcdc,0xa953fd4e])[round]?.getD 0 +def boolean (round : Nat) (x y z : W) : W := + match round with + | 0 => x ^^^ y ^^^ z + | 1 => (x &&& y) ||| (~~~x &&& z) + | 2 => (x ||| ~~~y) ^^^ z + | 3 => (x &&& z) ||| (y &&& ~~~z) + | _ => x ^^^ (y ||| ~~~z) +def lane (right : Bool) (words state : List W) : List W := + (List.range 80).foldl (fun s j => + let a := s[0]?.getD 0; let b := s[1]?.getD 0; let c := s[2]?.getD 0 + let d := s[3]?.getD 0; let e := s[4]?.getD 0 + let index := (if right then rightIndex else leftIndex)[j]?.getD 0 + let shift := (if right then rightShift else leftShift)[j]?.getD 0 + let f := boolean (if right then 4-j/16 else j/16) b c d + let t := (a + f + words[index]?.getD 0 + constant right (j/16)).rotateLeft shift + e + [e,t,b,c.rotateLeft 10,d]) state +def initial : List W := [0x67452301,0xefcdab89,0x98badcfe,0x10325476,0xc3d2e1f0] +def compress (s : List W) (block : List Byte) : List W := + let words := (List.range 16).map (fun i => BitVec.ofNat 32 (readLE block (4*i) 4)) + let a := lane false words s + let b := lane true words s + [s[1]?.getD 0 + a[2]?.getD 0 + b[3]?.getD 0, + s[2]?.getD 0 + a[3]?.getD 0 + b[4]?.getD 0, + s[3]?.getD 0 + a[4]?.getD 0 + b[0]?.getD 0, + s[4]?.getD 0 + a[0]?.getD 0 + b[1]?.getD 0, + s[0]?.getD 0 + a[1]?.getD 0 + b[2]?.getD 0] +def hash (input : List Byte) : List Byte := + let pad := (64 - ((input.length + 9) % 64)) % 64 + let padded := input ++ [128] ++ List.replicate pad 0 ++ le 8 (input.length * 8) + let state := (List.range (padded.length / 64)).foldl + (fun s i => compress s ((padded.drop (i*64)).take 64)) initial + state.flatMap (fun w => le 4 w.toNat) + +end SolarTV.Precompiles.RIPEMD160 diff --git a/tv/SolarTV/EVMIR/Precompiles/SHA256.lean b/tv/SolarTV/EVMIR/Precompiles/SHA256.lean new file mode 100644 index 00000000..44793f06 --- /dev/null +++ b/tv/SolarTV/EVMIR/Precompiles/SHA256.lean @@ -0,0 +1,52 @@ +import SolarTV.EVMIR.Precompiles.Bytes + +/-! Executable SHA-256, following FIPS 180-4, sections 5 and 6.2. The compression +state and schedule use 32-bit words; padding and output lengths are byte-exact. +No foreign function or uninterpreted hash is used by the Lean evaluator. +https://doi.org/10.6028/NIST.FIPS.180-4 -/ + +namespace SolarTV.Precompiles.SHA256 +open EVM.State +abbrev W := BitVec 32 + +def constants : List W := [ + 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, + 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, + 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, + 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, + 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, + 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, + 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, + 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2] + +def initial : List W := [0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, + 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19] + +def compress (state : List W) (block : List Byte) : List W := Id.run do + let mut schedule := (List.range 16).map (fun i => BitVec.ofNat 32 (readBE block (4*i) 4)) + for i in List.range 48 do + let x := schedule[i+1]?.getD 0 + let y := schedule[i+14]?.getD 0 + let s0 := x.rotateRight 7 ^^^ x.rotateRight 18 ^^^ (x >>> 3) + let s1 := y.rotateRight 17 ^^^ y.rotateRight 19 ^^^ (y >>> 10) + schedule := schedule ++ [schedule[i]?.getD 0 + s0 + schedule[i+9]?.getD 0 + s1] + let mut s := state + for i in List.range 64 do + let a := s[0]?.getD 0; let b := s[1]?.getD 0; let c := s[2]?.getD 0; let d := s[3]?.getD 0 + let e := s[4]?.getD 0; let f := s[5]?.getD 0; let g := s[6]?.getD 0; let h := s[7]?.getD 0 + let big1 := e.rotateRight 6 ^^^ e.rotateRight 11 ^^^ e.rotateRight 25 + let choose := (e &&& f) ^^^ (~~~e &&& g) + let t1 := h + big1 + choose + constants[i]?.getD 0 + schedule[i]?.getD 0 + let big0 := a.rotateRight 2 ^^^ a.rotateRight 13 ^^^ a.rotateRight 22 + let majority := (a &&& b) ^^^ (a &&& c) ^^^ (b &&& c) + s := [t1 + big0 + majority, a, b, c, d + t1, e, f, g] + return (state.zip s).map (fun (a,b) => a+b) + +def hash (input : List Byte) : List Byte := + let pad := (64 - ((input.length + 9) % 64)) % 64 + let padded := input ++ [128] ++ List.replicate pad 0 ++ be 8 (input.length * 8) + let state := (List.range (padded.length / 64)).foldl + (fun s i => compress s ((padded.drop (i*64)).take 64)) initial + state.flatMap (fun w => be 4 w.toNat) + +end SolarTV.Precompiles.SHA256 diff --git a/tv/SolarTV/EVMIR/Precompiles/Safety.lean b/tv/SolarTV/EVMIR/Precompiles/Safety.lean new file mode 100644 index 00000000..7a503baf --- /dev/null +++ b/tv/SolarTV/EVMIR/Precompiles/Safety.lean @@ -0,0 +1,22 @@ +import SolarTV.EVMIR.Precompiles.Observe + +/-! Kernel-checked digest vectors and failure boundaries. Differential tests +cover every active precompile against the native engine; these checks additionally +pin the pure hashing definitions and distinctions between malformed input, +out-of-gas, and successful empty signature output without foreign computation. -/ + +namespace SolarTV.Precompiles +open EVM.State +set_option maxRecDepth 16384 + +example : SHA256.hash [] = be 32 0xe3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 := by + decide +kernel +example : RIPEMD160.hash [97,98,99] = be 20 0x8eb208f7e05d987a9b044a8e98c6b087f15a0bfc := by + decide +kernel +example : execute .cancun 1 [] 3000 = .ok (.success,[],0) := by rfl +example : execute .osaka 256 [] 6899 = .ok (.outOfGas,[],0) := by rfl +example : execute .prague 12 [] 0 = .ok (.exception,[],0) := by rfl +example : execute .osaka 5 (be 32 1025 ++ be 32 0 ++ be 32 0) 499 = + .ok (.outOfGas,[],0) := by rfl + +end SolarTV.Precompiles diff --git a/tv/SolarTV/EVMIR/Precompiles/Signatures.lean b/tv/SolarTV/EVMIR/Precompiles/Signatures.lean new file mode 100644 index 00000000..eba6c579 --- /dev/null +++ b/tv/SolarTV/EVMIR/Precompiles/Signatures.lean @@ -0,0 +1,56 @@ +import SolarTV.EVMIR.Precompiles.Curve + +/-! ECRECOVER and EIP-7951 P256VERIFY. Both validate their scalar and point +encodings before curve arithmetic. ECRECOVER accepts high s and right-pads its +128-byte input; invalid recovery succeeds with empty output. P256VERIFY requires +exactly 160 bytes and also returns empty output for an invalid signature. +https://eips.ethereum.org/EIPS/eip-7951 -/ + +namespace SolarTV.Precompiles.Signatures +open EVM.State + +def k1p : Nat := 0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f +def k1n : Nat := 0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141 +def k1g : Point Nat := affine (fp k1p) + 0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798 + 0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8 + +def recover (input : List Byte) : List Byte := Id.run do + let hash := readBE input 0 32 + let v := readBE input 32 32 + let r := readBE input 64 32 + let s := readBE input 96 32 + if (v != 27 && v != 28) || r = 0 || r ≥ k1n || s = 0 || s ≥ k1n then return [] + let f := fp k1p + let some y := sqrt k1p (f.add (f.mul (f.square r) r) 7) | return [] + let y := if y%2 = v-27 then y else k1p-y + let point := affine f r y + let combined := add f 0 (multiply f 0 point s) (multiply f 0 k1g (k1n - hash%k1n)) + let some (x,y) := normalize f (multiply f 0 combined (powMod r (k1n-2) k1n)) | return [] + let digest := Keccak.hash (be 32 x ++ be 32 y) + return be 32 ((digest.setWidth 160).toNat) + +def p256p : Nat := 0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff +def p256n : Nat := 0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551 +def p256a : Nat := p256p-3 +def p256b : Nat := 0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b +def p256g : Point Nat := affine (fp p256p) + 0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296 + 0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5 + +def verify (input : List Byte) : List Byte := Id.run do + if input.length != 160 then return [] + let hash := readBE input 0 32 + let r := readBE input 32 32; let s := readBE input 64 32 + let x := readBE input 96 32; let y := readBE input 128 32 + if r = 0 || s = 0 || r ≥ p256n || s ≥ p256n || x ≥ p256p || y ≥ p256p then return [] + let f := fp p256p + let q := affine f x y + if !onCurve f p256a p256b q then return [] + let inverse := powMod s (p256n-2) p256n + let point := add f p256a (multiply f p256a p256g (hash*inverse%p256n)) + (multiply f p256a q (r*inverse%p256n)) + let some (x,_) := normalize f point | return [] + return if x%p256n = r then be 32 1 else [] + +end SolarTV.Precompiles.Signatures diff --git a/tv/SolarTV/EVMIR/Program.lean b/tv/SolarTV/EVMIR/Program.lean new file mode 100644 index 00000000..a9c827bb --- /dev/null +++ b/tv/SolarTV/EVMIR/Program.lean @@ -0,0 +1,196 @@ +import SolarTV.Machine +import SolarTV.EVMIR.Memory + +/-! Scheduled EVM IR programs as a layer. + +A program is a list of blocks of instructions over one stack, run with the checked stack +operations and memory instructions of [Memory.lean](Memory.lean) (`SolarTV.EVM.Memory.Op`) +through `stepOp`, which runs them on `Machine.Mem`; `stepOp_project` shows it is +`SolarTV.EVM.Memory.step` on the projection. Effects pop their operands, top first, and +push their result. Static transfers are fused with their label push: `jump b` and +`jumpi b` (the condition on top) need room for the label. A `jumpi` not taken goes on +with the rest of its block, as EVM IR's `push bbN; jumpi` does in the middle of a block, +and at the end of a block falls through to the next one. Running off the end of a block +enters the next one, and past the last block the program stops, as the EVM does past its +code. Block numbers are EVM IR's `BlockId`s, its layout order, as `-Zemit-lean-stages` +writes them. An internal call pushes the label of the block it returns to as a value +(`pushLabel`), and the callee returns with a dynamic `jump` (`jumpDyn`) to the label on top +of the stack. A conditional jump whose label is not pushed right before it (`jumpiDyn`), as +when blocks that share their tail jump to labels their predecessors pushed, takes the label on +top of the stack and the condition below it. A jump table (`jumpTable`) jumps to the block its +index, on top of the stack, numbers; EVM IR requires the index to be in range, and here an index +past the table halts. The label of a block is its number here, where the bytecode has its offset; no +observable shows a label. A dynamic jump to a word that numbers no block is an exceptional +halt, as a jump to a byte that is no `JUMPDEST`. A stack failure is an exceptional +halt, which observes as `invalid`. Each block costs one unit of fuel. -/ + +namespace SolarTV.EVM.Program + +open EvmRules Machine + +inductive Instr where + | op (op : EVM.Memory.Op) + | effect (effect : Effect) (arity : Nat) + | jump (target : Nat) + | jumpi (target : Nat) + /-- The label of a block as a value. -/ + | pushLabel (target : Nat) + /-- A jump to the label on top of the stack. -/ + | jumpDyn + /-- A jump to the label on top of the stack when the word below it is nonzero. -/ + | jumpiDyn + /-- A jump to the block the index on top of the stack numbers in the table (`indexed_jump`); + an index past the table is an exceptional halt. -/ + | jumpTable (targets : List Nat) + | stop | ret | revert | invalid + +structure Program where + blocks : List (List Instr) + +/-- `SolarTV.EVM.Memory.step` on memory of every byte. -/ +def stepOp (ctx : Context) (op : EVM.Memory.Op) (stack : Stack) (m : Mem) : + Except Failure (Stack × Mem) := + if stack.length > 1024 then .error .overflow + else match op, stack with + | .stack op, stack => (stepChecked ctx op stack).map (fun next => (next, m)) + | .load, offset :: rest => .ok (m.load offset.toNat :: rest, m.expand offset.toNat 32) + | .store, offset :: value :: rest => .ok (rest, m.store offset.toNat value) + | .storeByte, offset :: value :: rest => .ok (rest, m.storeByte offset.toNat value) + | .size, stack => + if stack.length + 1 > 1024 then .error .overflow else .ok (m.msize :: stack, m) + | _, _ => .error .underflow + +/-- A load reads inside the 256-byte projection. `stepOp` does not run copies or hashes +on `Machine.Mem`, so the projection covers neither. -/ +def InBounds : EVM.Memory.Op → Stack → Prop + | .load, offset :: _ => offset.toNat + 32 ≤ 256 + | .copy, _ | .hash, _ => False + | _, _ => True + +theorem stepOp_project (ctx : Context) (op : EVM.Memory.Op) (stack : Stack) (m : Mem) + (bounded : InBounds op stack) : + (stepOp ctx op stack m).map (fun next => (next.1, next.2.project)) = + EVM.Memory.step ctx op stack m.project := by + unfold stepOp EVM.Memory.step + split + · rfl + · cases op with + | stack op => + show Except.map _ (Except.map _ (stepChecked ctx op stack)) = + Except.map _ (stepChecked ctx op stack) + cases stepChecked ctx op stack <;> rfl + | load => + cases stack with + | nil => rfl + | cons offset rest => + simp only [InBounds] at bounded + simp only [Except.map, Mem.project_load m _ bounded, Mem.project_expand] + | store => + match stack with + | [] | [_] => rfl + | offset :: value :: rest => simp only [Except.map, Mem.project_store] + | storeByte => + match stack with + | [] | [_] => rfl + | offset :: value :: rest => simp only [Except.map, Mem.project_storeByte] + | size => + by_cases h : stack.length + 1 > 1024 <;> simp [h, Except.map, Mem.project_msize] + | copy => exact absurd bounded (by cases stack <;> simp [InBounds]) + | hash => exact absurd bounded (by cases stack <;> simp [InBounds]) + +def context (o : Oracle) (call : Call) (s : State) : Context := + ⟨BitVec.ofNat 256 call.calldata.size, o.env "returndatasize" s.world []⟩ + +def output (s : State) (stack : Stack) (reverted : Bool) : Halt × State := + match stack with + | offset :: size :: _ => + let memory := s.memory.expand offset.toNat size.toNat + let data := memory.read offset.toNat size.toNat + ((if reverted then .revert data else .ret data), { s with memory }) + | _ => (.invalid, s) + +/-- A block's instructions from block `b`: its end, or the next block and its stack. -/ +def exec (o : Oracle) (call : Call) (b : Nat) : + List Instr → Stack → State → (Halt × State) ⊕ (Nat × Stack × State) + | [], stack, s => .inr (b + 1, stack, s) + | .op op :: rest, stack, s => + match stepOp (context o call s) op stack s.memory with + | .error _ => .inl (.invalid, s) + | .ok (stack, memory) => exec o call b rest stack { s with memory } + | .effect effect arity :: rest, stack, s => + if stack.length < arity then .inl (.invalid, s) + else match effect.apply o call (stack.take arity) s with + | none => .inl (.invalid, s) + | some (result, s) => + let stack := match result with + | some value => value :: stack.drop arity + | none => stack.drop arity + if stack.length > 1024 then .inl (.invalid, s) else exec o call b rest stack s + | .jump target :: _, stack, s => + if stack.length + 1 > 1024 then .inl (.invalid, s) else .inr (target, stack, s) + | .jumpi target :: rest, stack, s => + if stack.length + 1 > 1024 then .inl (.invalid, s) + else match stack with + | condition :: stack => + if condition = 0 then exec o call b rest stack s else .inr (target, stack, s) + | [] => .inl (.invalid, s) + | .pushLabel target :: rest, stack, s => + if stack.length + 1 > 1024 then .inl (.invalid, s) + else exec o call b rest (BitVec.ofNat 256 target :: stack) s + | .jumpDyn :: _, stack, s => + match stack with + | target :: stack => .inr (target.toNat, stack, s) + | [] => .inl (.invalid, s) + | .jumpiDyn :: rest, stack, s => + match stack with + | target :: condition :: stack => + if condition = 0 then exec o call b rest stack s else .inr (target.toNat, stack, s) + | _ => .inl (.invalid, s) + | .jumpTable targets :: _, stack, s => + match stack with + | index :: stack => + match targets[index.toNat]? with + | some target => .inr (target, stack, s) + | none => .inl (.invalid, s) + | [] => .inl (.invalid, s) + | .stop :: _, _, s => .inl (.stop, s) + | .ret :: _, stack, s => .inl (output s stack false) + | .revert :: _, stack, s => .inl (output s stack true) + | .invalid :: _, _, s => .inl (.invalid, s) + +def block (o : Oracle) (call : Call) (p : Program) : + Nat × Stack × State → Option ((Halt × State) ⊕ (Nat × Stack × State)) + | (b, stack, s) => + match p.blocks[b]? with + -- NOTE: running off the last block reaches the number past it, where the program stops; + -- a dynamic jump to that number stops too, where the bytecode's jump to its end fails. + -- Labels only name blocks, so no exported program jumps there. + | none => some (.inl (if b = p.blocks.length then .stop else .invalid, s)) + | some instrs => some (exec o call b instrs stack s) + +def run (o : Oracle) (p : Program) (call : Call) (fuel : Nat) : Option (Halt × State) := + iterate (block o call p) fuel (0, [], State.initial call) + +def layer : Layer where + Prog := Program + run := run + mono _ _ _ n r := iterate_mono _ n _ r + +/-- The fuel-free semantics of scheduled EVM IR under an oracle. -/ +noncomputable def sem (o : Oracle) : Sem := layer.sem o + +theorem sem_failure (o : Oracle) (p : Program) (call : Call) (obs : Observable) + (ran : (sem o).run p call = some obs) (failed : obs.success = false) : + obs.logs = [] ∧ obs.storage = slotValue call.storage := by + obtain ⟨_, _, logs, storage, _⟩ := layer.sem_failure o p call obs ran failed + exact ⟨logs, storage⟩ + +theorem failureConvention (o : Oracle) : (sem o).FailureConvention := layer.failureConvention o + +/-- A program of one block that halts runs it at fuel one. -/ +theorem run_straight (o : Oracle) (call : Call) (instrs : List Instr) (n : Nat) + (result : Halt × State) (halts : exec o call 0 instrs [] (State.initial call) = .inl result) : + run o ⟨[instrs]⟩ call (n + 1) = some result := by + simp only [run, iterate, block, List.getElem?_cons_zero, halts] + +end SolarTV.EVM.Program diff --git a/tv/SolarTV/EVMIR/StackSafety.lean b/tv/SolarTV/EVMIR/StackSafety.lean new file mode 100644 index 00000000..fb784469 --- /dev/null +++ b/tv/SolarTV/EVMIR/StackSafety.lean @@ -0,0 +1,75 @@ +import SolarTV.EVMIR.Ops + +/-! Exceptional stack behavior of the bounded EVM window machine. +These lemmas use symbolic tails at the full 1024-word boundary, following +EVMYulLean EVM/Semantics.lean:450-471. Terminal halts ignore leftover words; +an earlier underflow or overflow still terminates execution immediately. -/ + +namespace SolarTV.EVM +open EvmRules + +theorem pop_underflows (ctx : Context) : stepChecked ctx .pop [] = .error .underflow := rfl + +theorem dup_underflows (ctx : Context) (value : Word) : + stepChecked ctx (.dup 1) [value] = .error .underflow := rfl + +theorem swap_underflows (ctx : Context) (value : Word) : + stepChecked ctx (.swap 0) [value] = .error .underflow := rfl + +theorem push_at_limit (ctx : Context) (stack : Stack) (value : Word) + (full : stack.length = 1024) : + stepChecked ctx (.push value) stack = .error .overflow := by + simp [stepChecked, step, full] + +theorem dup_at_limit (ctx : Context) (value : Word) (rest : Stack) + (full : rest.length = 1023) : + stepChecked ctx (.dup 0) (value :: rest) = .error .overflow := by + simp [stepChecked, step, full] + +theorem swap_at_limit (ctx : Context) (a b : Word) (rest : Stack) + (full : rest.length = 1022) : + stepChecked ctx (.swap 0) (a :: b :: rest) = .ok (b :: a :: rest) := by + simp [stepChecked, step, full] + +theorem push_pop_cannot_recover (ctx : Context) (stack : Stack) (value : Word) + (full : stack.length = 1024) : + execute ctx [.push value, .pop] .stop stack = .failed .overflow := by + simp [execute, push_at_limit ctx stack value full] + +theorem dropping_full_push_pop_changes_outcome (ctx : Context) (stack : Stack) (value : Word) + (full : stack.length = 1024) : + execute ctx [.push value, .pop] .stop stack ≠ execute ctx [] .stop stack := by + rw [push_pop_cannot_recover ctx stack value full] + simp [execute, finish, full] + +theorem full_stack_can_halt (stack : Stack) (full : stack.length = 1024) : + finish .stop stack = .success := by simp [finish, full] + +theorem label_push_can_overflow (stack : Stack) (full : stack.length = 1024) : + finish (.jump 1) stack = .failed .overflow := by simp [finish, full] + +theorem empty_return_needs_two_words (value : Word) : + finish .returnEmpty [value] = .failed .underflow := rfl + +theorem empty_return_discards_stack (offset : Word) (rest : Stack) + (legal : rest.length ≤ 1022) : + finish .returnEmpty (offset :: 0 :: rest) = .success := by + simp [finish] + omega + +theorem untaken_branch_executes_stop (destination : Word) (rest : Stack) + (legal : rest.length ≤ 1022) : + finish (.branchStop destination) (0 :: rest) = .success := by + have h1 : ¬ (rest.length + 1 > 1024) := by omega + have h2 : ¬ (rest.length + 1 + 1 > 1024) := by omega + simp [finish, h1, h2] + +theorem taken_branch_leaves_the_block (destination condition : Word) (rest : Stack) + (nonzero : condition ≠ 0) (legal : rest.length ≤ 1022) : + finish (.branchStop destination) (condition :: rest) = .edge destination rest := by + have h1 : ¬ (rest.length + 1 > 1024) := by omega + have h2 : ¬ (rest.length + 1 + 1 > 1024) := by omega + simp [finish, h1, h2] + exact nonzero + +end SolarTV.EVM diff --git a/tv/SolarTV/EVMIR/State/Create.lean b/tv/SolarTV/EVMIR/State/Create.lean new file mode 100644 index 00000000..d576d078 --- /dev/null +++ b/tv/SolarTV/EVMIR/State/Create.lean @@ -0,0 +1,42 @@ +import SolarTV.EVMIR.State.Types + +/-! CREATE and CREATE2 address derivation, collision and deployment rules. +RLP is encoded directly for the creator's twenty-byte address and a 64-bit nonce. +Initcode is executed by the same nested evaluator as ordinary calls. A creation +checkpoint is taken after the creator's nonce bump and destination warming, so +constructor rollback does not undo either caller-side effect. +https://eips.ethereum.org/EIPS/eip-684 +https://eips.ethereum.org/EIPS/eip-1014 +https://eips.ethereum.org/EIPS/eip-2681 +https://eips.ethereum.org/EIPS/eip-3860 -/ + +namespace SolarTV.EVM.State +open EvmRules + +def addressBytes (address : Address) : List Byte := (wordBytes (address.setWidth 256)).drop 12 + +def nonceBytes (nonce : Nat) : List Byte := + ((wordBytes (BitVec.ofNat 256 nonce)).dropWhile (fun b => b == 0)) + +def encodedNonce (nonce : Nat) : List Byte := + if nonce = 0 then [0x80] + else if nonce < 128 then [BitVec.ofNat 8 nonce] + else let bytes := nonceBytes nonce + BitVec.ofNat 8 (128 + bytes.length) :: bytes + +def createAddress (creator : Address) (nonce : Nat) : Address := + let payload := [0x94] ++ addressBytes creator ++ encodedNonce nonce + (Keccak.hash (BitVec.ofNat 8 (192 + payload.length) :: payload)).setWidth 160 + +def create2Address (creator : Address) (salt : Word) (initcode : List Byte) : Address := + (Keccak.hash ([0xff] ++ addressBytes creator ++ wordBytes salt ++ wordBytes (Keccak.hash initcode))).setWidth 160 + +def collision (world : Journal) (address : Address) : Bool := + let old := account world address + old.nonce != 0 || !old.code.isEmpty + +def validDeployedCode (fork : Fork) (code : List Byte) : Bool := + (!fork.atLeast .spuriousDragon || code.length ≤ 24576) && + (!fork.atLeast .london || code[0]?.getD 0 != 0xef) + +end SolarTV.EVM.State diff --git a/tv/SolarTV/EVMIR/State/Decode.lean b/tv/SolarTV/EVMIR/State/Decode.lean new file mode 100644 index 00000000..a0cb484f --- /dev/null +++ b/tv/SolarTV/EVMIR/State/Decode.lean @@ -0,0 +1,52 @@ +import SolarTV.EVMIR.State.Create + +/-! Bytecode decoding for explicit-world execution. PUSH payload bytes are not +instructions or jump destinations. Availability and static prices are supplied +from the compiler's reflected opcode schema and bound into the proof input. +Pure instruction values use the separately tested word model. -/ + +namespace SolarTV.EVM.State +open EvmRules + +def pureOp : Nat → Option EVM.Op + | 0x01 => some .add | 0x02 => some .mul | 0x03 => some .sub + | 0x04 => some .div | 0x05 => some .sdiv | 0x06 => some .mod | 0x07 => some .smod + | 0x08 => some .addmod | 0x09 => some .mulmod | 0x0a => some .exp + | 0x0b => some .signextend | 0x10 => some .lt | 0x11 => some .gt + | 0x12 => some .slt | 0x13 => some .sgt | 0x14 => some .eq + | 0x15 => some .iszero | 0x16 => some .and | 0x17 => some .or | 0x18 => some .xor + | 0x19 => some .not | 0x1a => some .byte | 0x1b => some .shl | 0x1c => some .shr + | 0x1d => some .sar | 0x1e => some .clz + | _ => none + +def jumpDestinations (fuel : Nat) (code : List Byte) (pc : Nat := 0) : List Nat := + match fuel with + | 0 => [] + | fuel + 1 => + if pc ≥ code.length then [] else + let byte := code[pc]?.getD 0 |>.toNat + let next := pc + 1 + if 0x60 ≤ byte ∧ byte ≤ 0x7f then byte - 0x5f else 0 + let rest := jumpDestinations fuel code next + if byte = 0x5b then pc :: rest else rest + +def validJump (code : List Byte) (target : Word) : Bool := + (jumpDestinations code.length code).contains target.toNat + +def pushValue (code : List Byte) (pc count : Nat) : Word := + (readBytes code (pc + 1) count).foldl (fun value byte => (value <<< 8) ||| byte.setWidth 256) 0 + +/-- Fork-specific precompile activation, shared by decoding and execution. -/ +def precompile (fork : Fork) (address : Address) : Bool := + let n := address.toNat + (1 ≤ n && n ≤ 4) || + (fork.atLeast .byzantium && 5 ≤ n && n ≤ 8) || + (fork.atLeast .istanbul && n = 9) || + (fork.atLeast .cancun && n = 10) || + (fork.atLeast .prague && 11 ≤ n && n ≤ 17) || + (fork.atLeast .osaka && n = 256) + +def dead (world : Journal) (address : Address) : Bool := + let a := account world address + a.nonce == 0 && a.balance == 0 && a.code.isEmpty + +end SolarTV.EVM.State diff --git a/tv/SolarTV/EVMIR/State/Delegation.lean b/tv/SolarTV/EVMIR/State/Delegation.lean new file mode 100644 index 00000000..9f5602ab --- /dev/null +++ b/tv/SolarTV/EVMIR/State/Delegation.lean @@ -0,0 +1,36 @@ +import SolarTV.EVMIR.State.Decode + +/-! EIP-7702 execution after authorization processing. Exactly 23-byte designators +resolve once from Prague onward. The resolved target access costs 100/2600 gas, +after warming the authority and before the EIP-150 gas split, even if a call is +later rejected for balance/depth. Resolution warmth survives child revert. +Code introspection reads the original account bytes; execution uses the resolved +image. Delegation to a precompile does not invoke it. A second designator is +executed as ordinary (invalid) bytecode, not recursively resolved. +Authorization signatures, transaction intrinsic gas and authorization refunds +precede this entry model; the fixture supplies their resulting account state. +https://eips.ethereum.org/EIPS/eip-7702#delegation-indicator -/ + +namespace SolarTV.EVM.State + +structure ExecutionCode where + address : Address + bytes : List Byte + delegated : Bool + +def delegationTarget (fork : Fork) (code : List Byte) : Option Address := + if fork.atLeast .prague && code.length = 23 && code.take 3 == [0xef,0x01,0x00] then + some ((readWord (List.replicate 12 0 ++ code.drop 3) 0).setWidth 160) + else none + +def executionCode (fork : Fork) (world : Journal) (destination : Address) : + ExecutionCode × Nat × Journal := + let code := (account world destination).code + let world := warmAddress world destination + match delegationTarget fork code with + | none => (⟨destination,code,false⟩,0,world) + | some target => + let price := if world.warmAddresses.contains target then 100 else 2600 + (⟨target,(account world target).code,true⟩,price,warmAddress world target) + +end SolarTV.EVM.State diff --git a/tv/SolarTV/EVMIR/State/Environment.lean b/tv/SolarTV/EVMIR/State/Environment.lean new file mode 100644 index 00000000..a4ea820e --- /dev/null +++ b/tv/SolarTV/EVMIR/State/Environment.lean @@ -0,0 +1,22 @@ +import SolarTV.EVMIR.State.Decode + +/-! Explicit environment reads for complete-entry execution. BLOCKHASH accepts +only the previous 256 blocks, excluding the current block, without word-wrap. +The Paris transition selects randomness instead of difficulty; opcode activation +is checked by the reflected fork table before reading context. Blob indices are +full words, so enormous indices return zero rather than truncating to a host index. +SLOTNUM widens the consensus uint64 value. History and blobs are fixture inputs, +not hash oracles inferred from the IR being validated. +https://eips.ethereum.org/EIPS/eip-4399 +https://eips.ethereum.org/EIPS/eip-4844 +https://eips.ethereum.org/EIPS/eip-7843 -/ + +namespace SolarTV.EVM.State +open EvmRules + +export SolarTV.Execution (blockHash) + +def environmentValue (cfg : Config) (opcode : Nat) (argument : Word) : Word := + SolarTV.Execution.environmentValue cfg.fork cfg.block opcode argument + +end SolarTV.EVM.State diff --git a/tv/SolarTV/EVMIR/State/Interpreter.lean b/tv/SolarTV/EVMIR/State/Interpreter.lean new file mode 100644 index 00000000..1c16a6fb --- /dev/null +++ b/tv/SolarTV/EVMIR/State/Interpreter.lean @@ -0,0 +1,314 @@ +import SolarTV.EVMIR.State.Selfdestruct +import SolarTV.EVMIR.Precompiles.Execute +import SolarTV.EVMIR.State.Environment +import SolarTV.EVMIR.State.Delegation +import SolarTV.EVMIR.State.Messages + +/-! Gas-charged bytecode execution with real nested frames and constructors. +Every frame owns its stack, memory and return-data buffer. Accounts, original +storage and access sets are transaction-wide and journaled at call boundaries. +Unsupported opcodes and finite evaluator limits are model errors; +they never become EVM exceptions and cannot prove a pair correct. + +The explicit-world mode starts after transaction validation, with zero root +value and explicit transaction/block context. The CLI admits Istanbul through +Osaka, plus Amsterdam's environment/scalar/memory fragment. Its two-resource +state/account/call gas remains unsupported. +Calls follow EIP-150/214/2929; creation follows EIP-161/170/684/1014/2681/3541/3860. +https://eips.ethereum.org/EIPS/eip-150 +https://eips.ethereum.org/EIPS/eip-2929 -/ + +namespace SolarTV.EVM.State +open EvmRules + +inductive Step where + | next (world : Journal) (frame : Frame) + | done (result : Result) + | call (message : Calls.Message) (outOffset outSize requested : Nat) + (code : ExecutionCode) (world : Journal) (frame : Frame) + | create (salt : Option Word) (value : Word) (initcode : List Byte) + (world : Journal) (frame : Frame) + +abbrev Action := Except String Step + +def stepFailed (world : Journal) : Action := .ok (.done ⟨.exception, [], world, 0, 0⟩) + +def stepExhausted (world : Journal) : Action := .ok (.done ⟨.outOfGas, [], world, 0, 0⟩) + +def next (world : Journal) (frame : Frame) (stack : List Word) : Action := + .ok (.next world {frame with pc := frame.pc + 1, stack}) + +def available (cfg : Config) (opcode : Nat) : Opcode := + cfg.opcodes[opcode]?.getD ⟨false, 0, 0, 0, 0⟩ + +/-- Charge expansion before allocating host memory. Natural address sums do not wrap. -/ +def withMemory (world : Journal) (frame : Frame) (charge offset count : Nat) + (continuation : Frame → Action) : Action := + let total := charge + memoryCharge frame.memory offset count + if frame.gas < total then stepExhausted world else do + let memory ← expand frame.memory offset count + continuation {frame with memory, gas := frame.gas - total} + +def instruction (cfg : Config) (world : Journal) (frame : Frame) : Action := + if frame.pc ≥ frame.code.length then .ok (.done ⟨.success, [], world, frame.gas, 0⟩) else + let opcode := frame.code[frame.pc]?.getD 0 |>.toNat + let info := available cfg opcode + if !info.available then stepFailed world + -- Amsterdam's environment/memory fragment is admitted independently of the + -- two-resource gas model. Account, storage and call operations remain errors. + else if cfg.fork.atLeast .amsterdam && + ([0x31,0x3b,0x3c,0x3f,0x47,0x54,0x55,0x5c,0x5d,0xf0,0xf1,0xf2,0xf4,0xf5,0xfa,0xff].contains opcode || + (0xa0 ≤ opcode && opcode ≤ 0xa4)) then + .error "Amsterdam state/account/call gas is not modeled" + else if frame.stack.length < info.inputs || frame.stack.length - info.inputs + info.outputs > 1024 then + stepFailed world + else if let some op := pureOp opcode then + let dynamic := if opcode = 0x0a then + info.dynamic * ((256 - (frame.stack[1]?.getD 0).clz.toNat + 7) / 8) else 0 + if frame.gas < info.base + dynamic then stepExhausted world else + match EVM.step ⟨BitVec.ofNat 256 frame.environment.input.length, + BitVec.ofNat 256 frame.returnData.length⟩ op frame.stack with + | none => stepFailed world + | some stack => next world {frame with gas := frame.gas - info.base - dynamic} stack + else if 0x60 ≤ opcode ∧ opcode ≤ 0x7f then + if frame.gas < info.base then stepExhausted world else + .ok (.next world {frame with + pc := frame.pc + 1 + (opcode - 0x5f) + stack := pushValue frame.code frame.pc (opcode - 0x5f) :: frame.stack + gas := frame.gas - info.base}) + else if 0x80 ≤ opcode ∧ opcode ≤ 0x9f then + let op := if opcode < 0x90 then EVM.Op.dup ⟨opcode - 0x80, by omega⟩ + else EVM.Op.swap ⟨opcode - 0x90, by omega⟩ + if frame.gas < info.base then stepExhausted world else + match EVM.step ⟨0, 0⟩ op frame.stack with + | none => stepFailed world + | some stack => next world {frame with gas := frame.gas - info.base} stack + else + let values := frame.stack.take info.inputs + let rest := frame.stack.drop info.inputs + let a := values[0]?.getD 0 + let b := values[1]?.getD 0 + let c := values[2]?.getD 0 + match opcode with + | 0x00 => .ok (.done ⟨.success, [], world, frame.gas, 0⟩) + | 0xfe => stepFailed world + | 0x40 | 0x41 | 0x42 | 0x43 | 0x44 | 0x45 | 0x46 | 0x48 | 0x49 | 0x4a | 0x4b => + if frame.gas < info.base then stepExhausted world + else next world {frame with gas := frame.gas - info.base} + (environmentValue cfg opcode a :: rest) + | 0x20 => withMemory world frame (info.base + info.dynamic * ((b.toNat + 31) / 32)) a.toNat b.toNat fun frame => + next world frame (Keccak.hash (readBytes frame.memory a.toNat b.toNat) :: rest) + | 0x30 | 0x32 | 0x33 | 0x34 | 0x36 | 0x38 | 0x3a | 0x3d | 0x47 | 0x58 | 0x59 | 0x5a | 0x5f => + if frame.gas < info.base then stepExhausted world else + let value := match opcode with + | 0x30 => frame.environment.address.setWidth 256 + | 0x32 => frame.environment.origin.setWidth 256 + | 0x33 => frame.environment.caller.setWidth 256 + | 0x34 => frame.environment.value + | 0x36 => BitVec.ofNat 256 frame.environment.input.length + | 0x38 => BitVec.ofNat 256 frame.code.length + | 0x3a => frame.environment.gasPrice + | 0x3d => BitVec.ofNat 256 frame.returnData.length + | 0x47 => (account world frame.environment.address).balance + | 0x58 => BitVec.ofNat 256 frame.pc + | 0x59 => BitVec.ofNat 256 frame.memory.length + | 0x5a => BitVec.ofNat 256 (frame.gas - info.base) + | _ => 0 + next world {frame with gas := frame.gas - info.base} (value :: rest) + | 0x31 | 0x3b | 0x3f => + let address := a.setWidth 160 + if opcode != 0x31 && cfg.unknownCode == some address then + .error "MIR root runtime code is unknown" else + let charge := if cfg.fork.atLeast .berlin && world.warmAddresses.contains address then 100 else info.base + if frame.gas < charge then stepExhausted world else + let value := if opcode = 0x31 then (account world address).balance + else if opcode = 0x3b then BitVec.ofNat 256 (account world address).code.length + else if world.accounts.any (fun a => a.address == address) then Keccak.hash (account world address).code else 0 + next (warmAddress world address) {frame with gas := frame.gas - charge} (value :: rest) + | 0x35 => + if frame.gas < info.base then stepExhausted world + else next world {frame with gas := frame.gas - info.base} + (readWord frame.environment.input a.toNat :: rest) + | 0x3c => + let owner := a.setWidth 160 + if cfg.unknownCode == some owner then .error "MIR root runtime code is unknown" else + let count := (values[3]?.getD 0).toNat + let base := if cfg.fork.atLeast .berlin && world.warmAddresses.contains owner then 100 else info.base + -- The EXTCODE gas class reflects account access; copying also pays the + -- same per-word price as CALLDATACOPY (Yellow Paper W_copy). + let copyWord := (available cfg 0x37).dynamic + withMemory world frame (base + copyWord * ((count+31)/32)) b.toNat count fun frame => + let bytes := readBytes (account world owner).code c.toNat count + next (warmAddress world owner) {frame with memory := writeBytes frame.memory b.toNat bytes} rest + | 0x37 | 0x39 | 0x3e => + if opcode = 0x3e && b.toNat + c.toNat > frame.returnData.length then stepFailed world + else withMemory world frame (info.base + info.dynamic * ((c.toNat + 31) / 32)) a.toNat c.toNat fun frame => + let source := if opcode = 0x37 then frame.environment.input + else if opcode = 0x39 then frame.code else frame.returnData + let memory := writeBytes frame.memory a.toNat (readBytes source b.toNat c.toNat) + next world {frame with memory} rest + | 0x50 => + if frame.gas < info.base then stepExhausted world + else next world {frame with gas := frame.gas - info.base} rest + | 0x51 | 0x52 | 0x53 => withMemory world frame info.base a.toNat (if opcode = 0x53 then 1 else 32) fun frame => + if opcode = 0x51 then next world frame (readWord frame.memory a.toNat :: rest) + else + let bytes := if opcode = 0x53 then [b.setWidth 8] else wordBytes b + next world {frame with memory := writeBytes frame.memory a.toNat bytes} rest + | 0x54 | 0x55 | 0x5c | 0x5d => + let owner := frame.environment.address + let old := account world owner + let transient := opcode = 0x5c || opcode = 0x5d + let store := opcode = 0x55 || opcode = 0x5d + let current := slotsRead (if transient then old.transient else old.storage) a + let original := slotsRead ((world.original.find? (fun x => x.address == owner)).getD {address := owner}).storage a + let price := if transient then Storage.Price.mk 100 0 + else if store then Storage.writePrice cfg.fork (world.warmSlots.contains (owner, a)) original current b + else Storage.Price.mk (Storage.readPrice cfg.fork (world.warmSlots.contains (owner, a))) 0 + if store && frame.environment.isStatic then stepFailed world + else if opcode = 0x55 && cfg.fork.atLeast .istanbul && frame.gas ≤ 2300 then stepExhausted world + else if frame.gas < price.gas then stepExhausted world else + let world := if transient then world else warmSlot world owner a + let world := if !store then world else + putAccount {world with refund := world.refund + price.refund} + (if transient then {old with transient := slotsWrite old.transient a b} + else {old with storage := slotsWrite old.storage a b}) + next world {frame with gas := frame.gas - price.gas} (if store then rest else current :: rest) + | 0x56 | 0x57 => + if frame.gas < info.base then stepExhausted world + else if opcode = 0x57 && b == 0 then next world {frame with gas := frame.gas - info.base} rest + else if !validJump frame.code a then stepFailed world + else .ok (.next world {frame with stack := rest, pc := a.toNat, gas := frame.gas - info.base}) + | 0x5b => + if frame.gas < info.base then stepExhausted world + else next world {frame with gas := frame.gas - info.base} rest + | 0x5e => + let charge := info.base + info.dynamic * ((c.toNat + 31) / 32) + let sourceGrowth := memoryCost (max (requiredWords frame.memory b.toNat c.toNat) + (requiredWords frame.memory a.toNat c.toNat)) - memoryCost (requiredWords frame.memory a.toNat c.toNat) + withMemory world frame (charge + sourceGrowth) a.toNat c.toNat fun frame => do + let memory ← expand frame.memory b.toNat c.toNat + let bytes := readBytes memory b.toNat c.toNat + next world {frame with memory := writeBytes memory a.toNat bytes} rest + | 0xf3 | 0xfd => withMemory world frame info.base a.toNat b.toNat fun frame => + .ok (.done ⟨if opcode = 0xfd then .reverted else .success, + readBytes frame.memory a.toNat b.toNat, world, frame.gas, 0⟩) + | 0xf1 | 0xf2 | 0xf4 | 0xfa => + let kind := if opcode = 0xf1 then Calls.Kind.call else if opcode = 0xf2 then .callcode + else if opcode = 0xf4 then .delegatecall else .staticcall + let explicitValue := opcode = 0xf1 || opcode = 0xf2 + let value := if explicitValue then c else 0 + let inputOffset := (values[if explicitValue then 3 else 2]?.getD 0).toNat + let inputSize := (values[if explicitValue then 4 else 3]?.getD 0).toNat + let outOffset := (values[if explicitValue then 5 else 4]?.getD 0).toNat + let outSize := (values[if explicitValue then 6 else 5]?.getD 0).toNat + let destination := b.setWidth 160 + let base := if cfg.fork.atLeast .berlin && world.warmAddresses.contains destination then 100 else info.base + let valueCharge := if explicitValue && value != 0 then 9000 else 0 + let newAccount := if kind == .call && dead world destination && + (!cfg.fork.atLeast .spuriousDragon || value != 0) then 25000 else 0 + let (code, resolution, entered) := executionCode cfg.fork world destination + if cfg.unknownCode == some code.address then .error "MIR root runtime code is unknown" else + if frame.environment.isStatic && kind == .call && value != 0 then stepFailed world else + withMemory world frame (base + valueCharge + newAccount + resolution) inputOffset inputSize fun frame => + withMemory world frame 0 outOffset outSize fun frame => + .ok (.call ⟨kind, destination, value, readBytes frame.memory inputOffset inputSize⟩ + outOffset outSize a.toNat code entered {frame with stack := rest, pc := frame.pc + 1}) + | 0xf0 | 0xf5 => + let size := c.toNat + if frame.environment.isStatic then stepFailed world + else if cfg.fork.atLeast .shanghai && size > 49152 then stepExhausted world + else + let perWord := (if cfg.fork.atLeast .shanghai then 2 else 0) + if opcode = 0xf5 then 6 else 0 + withMemory world frame (info.base + perWord * ((size + 31) / 32)) b.toNat size fun frame => + .ok (.create (if opcode = 0xf5 then some (values[3]?.getD 0) else none) a + (readBytes frame.memory b.toNat size) world {frame with stack := rest, pc := frame.pc + 1}) + | 0xff => + let beneficiary := a.setWidth 160 + let charge := destructionPrice cfg.fork world frame.environment.address beneficiary + if frame.environment.isStatic then stepFailed world + else if frame.gas < charge then stepExhausted world + else .ok (.done ⟨.success, [], destroy cfg.fork world frame.environment.address beneficiary, + frame.gas - charge, 0⟩) + | opcode => + if 0xa0 ≤ opcode ∧ opcode ≤ 0xa4 then + if frame.environment.isStatic then stepFailed world else + withMemory world frame (info.base + info.dynamic * b.toNat) a.toNat b.toNat fun frame => + let log := World.Log.mk frame.environment.address (values.drop 2) (readBytes frame.memory a.toNat b.toNat) + next {world with logs := world.logs ++ [log]} frame rest + else .error s!"unmodeled world opcode {opcode}" + +/-- Work fuel bounds the evaluator, not the EVM. Exhaustion is unsupported. -/ +def run (fuel : Nat) (cfg : Config) (world : Journal) (frame : Frame) : Run := + match fuel with + | 0 => .error "world instruction/depth evaluation limit" + | fuel + 1 => do + let result ← match ← instruction cfg world frame with + | .done result => pure result + | .next world frame => run fuel cfg world frame + | .call message outOffset outSize requested code world frame => + let checkpoint := warmAddress world message.destination + if frame.environment.depth ≥ 1024 || + ((message.kind == .call || message.kind == .callcode) && + (account world frame.environment.address).balance.ult message.value) then + -- A rejected value-bearing call returns its unspent stipend too. + run fuel cfg checkpoint {frame with + stack := 0 :: frame.stack + returnData := [] + gas := frame.gas + if Calls.hasValue message then 2300 else 0} + else + match Calls.forwardGas cfg.fork frame.gas requested (Calls.hasValue message) with + | none => exhausted checkpoint + | some budget => + let child ← executeCall (run fuel cfg) cfg checkpoint frame.environment message code budget.supplied + let committed := child.world + let data := child.data + let returned := child.gas + let copied := data.take outSize + let resumed ← run (fuel - child.work) cfg committed {frame with + stack := child.value :: frame.stack + memory := writeBytes frame.memory outOffset copied + returnData := data + gas := frame.gas - budget.charged + returned} + pure {resumed with work := resumed.work + child.work} + | .create salt value initcode world frame => + let creator := account world frame.environment.address + if frame.environment.depth ≥ 1024 || creator.balance.ult value || creator.nonce ≥ 2^64 - 1 then + run fuel cfg world {frame with stack := 0 :: frame.stack, returnData := []} + else + let forwarded := if cfg.fork.atLeast .tangerineWhistle then frame.gas - frame.gas / 64 else frame.gas + let child ← executeCreation (run fuel cfg) cfg world frame.environment salt value initcode forwarded + let resumed ← run (fuel - child.work) cfg child.world {frame with + stack := child.value :: frame.stack + returnData := child.data + gas := frame.gas - forwarded + child.gas} + pure {resumed with work := resumed.work + child.work} + return {result with work := result.work + 1} +termination_by fuel +decreasing_by all_goals omega + +/-- Single-step equations keep symbolic execution from unfolding unknown continuations. -/ +theorem run_next (fuel : Nat) {cfg world frame nextWorld nextFrame} + (h : instruction cfg world frame = .ok (.next nextWorld nextFrame)) : + run (fuel + 1) cfg world frame = (do + let result ← run fuel cfg nextWorld nextFrame + return {result with work := result.work + 1}) := by + simp only [run, h, Except.bind, Bind.bind, Except.pure, Pure.pure] + +theorem run_done (fuel : Nat) {cfg world frame result} + (h : instruction cfg world frame = .ok (.done result)) : + run (fuel + 1) cfg world frame = .ok {result with work := result.work + 1} := by + simp only [run, h, Except.bind, Bind.bind, Except.pure, Pure.pure] + +theorem run_error (fuel : Nat) {cfg world frame reason} + (h : instruction cfg world frame = .error reason) : + run (fuel + 1) cfg world frame = .error reason := by + simp only [run, h, Except.bind, Bind.bind] + +/-- Frame rollback keeps parent-side warming/nonce changes in the checkpoint. -/ +def execute (fuel : Nat) (cfg : Config) (world : Journal) (frame : Frame) : Run := do + let result ← run fuel cfg world frame + return if result.stop = .success then {result with world := finalize result.world} else + {result with world, gas := if result.stop = .exception || result.stop = .outOfGas then 0 else result.gas} + +end SolarTV.EVM.State diff --git a/tv/SolarTV/EVMIR/State/Messages.lean b/tv/SolarTV/EVMIR/State/Messages.lean new file mode 100644 index 00000000..d7720c87 --- /dev/null +++ b/tv/SolarTV/EVMIR/State/Messages.lean @@ -0,0 +1,87 @@ +import SolarTV.EVMIR.State.Selfdestruct +import SolarTV.EVMIR.State.Delegation +import SolarTV.EVMIR.Precompiles.Execute + +/-! Shared execution of prepared call and creation messages. The caller owns +memory access and parent gas pricing/forwarding; this module owns child entry, +state checkpoints and completion. A child is executed by the supplied evaluator, +never an unconstrained result. MIR can use the bytecode evaluator for fixture +accounts without lowering its own program to bytecode. -/ + +namespace SolarTV.EVM.State +open EvmRules + +structure MessageOutcome where + value : Word + data : List Byte + world : Journal + gas : Nat + work : Nat + +abbrev ChildExecutor := Journal → Frame → Run + +def executeCall (execute : ChildExecutor) (cfg : Config) (checkpoint : Journal) + (parent : World.Environment) (message : Calls.Message) (code : ExecutionCode) + (supplied : Nat) : Except String MessageOutcome := do + if cfg.unknownCode == some code.address then .error "MIR root runtime code is unknown" else + if parent.depth ≥ 1024 || + ((message.kind == .call || message.kind == .callcode) && + (account checkpoint parent.address).balance.ult message.value) then + return ⟨0,[],checkpoint,supplied,0⟩ + else + let entered := if message.kind == .call then + (transfer checkpoint parent.address message.destination message.value).getD checkpoint + else checkpoint + let child ← if !code.delegated && precompile cfg.fork message.destination then do + let (stop,data,gas) ← Precompiles.execute cfg.fork message.destination message.input supplied + pure ⟨stop,data,entered,gas,0⟩ + else execute entered { + environment := {Calls.childEnvironment parent message with codeAddress := code.address} + code := code.bytes + gas := supplied} + let failed := child.stop = .exception || child.stop = .outOfGas + return ⟨if child.stop = .success then 1 else 0, + if failed then [] else child.data, + if child.stop = .success then child.world else checkpoint, + if failed then 0 else child.gas,child.work⟩ + +def executeCreation (execute : ChildExecutor) (cfg : Config) (world : Journal) + (parent : World.Environment) (salt : Option Word) (value : Word) + (initcode : List Byte) (supplied : Nat) : Except String MessageOutcome := do + let creator := account world parent.address + if parent.depth ≥ 1024 || creator.balance.ult value || creator.nonce ≥ 2^64 - 1 then + return ⟨0,[],world,supplied,0⟩ + else + let target := match salt with + | none => createAddress creator.address creator.nonce + | some salt => create2Address creator.address salt initcode + let checkpoint := warmAddress (putAccount world {creator with nonce := creator.nonce + 1}) target + if collision checkpoint target then return ⟨0,[],checkpoint,0,0⟩ else + let old := account checkpoint target + let fresh := {old with + nonce := if cfg.fork.atLeast .spuriousDragon then 1 else 0 + code := [] + storage := [] + transient := [] + created := true + destroyed := false} + let entered := putAccount checkpoint fresh + let entered := {entered with original := fresh :: entered.original.filter (fun a => a.address != target)} + let entered := (transfer entered creator.address target value).getD entered + let child ← execute entered { + environment := {parent with + address := target + codeAddress := target + caller := creator.address + value + input := [] + depth := parent.depth + 1} + code := initcode,gas := supplied} + let deposit := 200 * child.data.length + let success := child.stop == .success && validDeployedCode cfg.fork child.data && deposit ≤ child.gas + return ⟨if success then target.setWidth 256 else 0, + if child.stop = .reverted then child.data else [], + if success then putAccount child.world {(account child.world target) with code := child.data} else checkpoint, + if success then child.gas - deposit else if child.stop = .reverted then child.gas else 0,child.work⟩ + +end SolarTV.EVM.State diff --git a/tv/SolarTV/EVMIR/State/Normalize.lean b/tv/SolarTV/EVMIR/State/Normalize.lean new file mode 100644 index 00000000..37ca6a58 --- /dev/null +++ b/tv/SolarTV/EVMIR/State/Normalize.lean @@ -0,0 +1,35 @@ +import SolarTV.EVMIR.State.Interpreter +import Lean + +/-! Proof-producing execution at a known bytecode position. Symbolic data must not +cause the simplifier to unfold every remaining unit of global work fuel. Reduce +one known instruction and use its proved equation, leaving unknown control flow +opaque. This produces kernel-checkable terms, not native evaluation evidence. -/ + +namespace SolarTV.EVM.State +open Lean Meta Simp + +simproc_decl reduceRun (run _ _ _ _) := fun expression => do + let args := expression.getAppArgs + let some fuel ← getNatValue? args[0]! | return .continue + if fuel = 0 then return .done {expr := ← whnf expression} + let frame ← whnf args[3]! + unless frame.isAppOf ``Frame.mk do return .continue + let step ← mkAppM ``instruction #[args[1]!,args[2]!,args[3]!] + let reduction ← simp step + let reduced ← whnf reduction.expr + let proof ← reduction.getProof + let parameters := #[toExpr (fuel - 1),args[1]!,args[2]!,args[3]!] + let equation ← if reduced.isAppOf ``Except.error then + pure (mkAppN (mkConst ``run_error) (parameters ++ #[reduced.appArg!,proof])) + else if reduced.isAppOf ``Except.ok then + let signal ← whnf reduced.appArg! + if signal.isAppOf ``Step.next then + pure (mkAppN (mkConst ``run_next) (parameters ++ signal.getAppArgs ++ #[proof])) + else if signal.isAppOf ``Step.done then + pure (mkAppN (mkConst ``run_done) (parameters ++ #[signal.appArg!,proof])) + else return .continue + else return .continue + return .visit {expr := (← inferType equation).appArg!,proof? := some equation} + +end SolarTV.EVM.State diff --git a/tv/SolarTV/EVMIR/State/Observe.lean b/tv/SolarTV/EVMIR/State/Observe.lean new file mode 100644 index 00000000..4e5e806c --- /dev/null +++ b/tv/SolarTV/EVMIR/State/Observe.lean @@ -0,0 +1,81 @@ +import SolarTV.EVMIR.State.Interpreter +import Lean.Data.Json + +/-! Observable transaction effects for explicit-world entry checks. Private memory, +transient storage and access warmth die with the root frame. Persistent accounts, +nonces, balances, deployed code and logs remain visible. The running root's code +is compared through execution, not as an output byte-string, so ordinary code +rewrites do not count as state changes. CODECOPY/EXTCODEHASH still read the actual +before/after root image during execution. + +Model errors are excluded on both sides of a positive proof. Their textual +observations let the host reject a proposed witness before claiming a compiler +counterexample. Gas/refund observations are optional, but execution always pays +gas from the explicit fixture budget. -/ + +namespace SolarTV.EVM.State +open EvmRules + +structure Observation where + stop : Stop + data : List Byte + gas : Nat + refund : Int + accounts : List Account + logs : List World.Log + deriving DecidableEq + +inductive Policy where + | effects | exact | refine + deriving DecidableEq + +export SolarTV.Execution (orderedInsert ordered normalizedSlots) + +def observe (cfg : Config) (policy : Policy) (result : Result) : Observation := + let accounts := result.world.accounts.map (fun a => {a with + code := if a.address == cfg.root then [] else a.code + storage := normalizedSlots a.storage + transient := [] + created := false + destroyed := false}) + ⟨result.stop, result.data, if policy = .effects then 0 else result.gas, + if policy = .effects then 0 else result.world.refund, + ordered (fun a b => a.address.ule b.address) accounts, result.world.logs⟩ + +def equivalent (cfgBefore cfgAfter : Config) (policy : Policy) (before after : Run) : Prop := + match before, after with + | .ok a, .ok b => + if policy = .refine then + (a.stop = .outOfGas ∨ + (observe cfgBefore .effects a = observe cfgAfter .effects b ∧ + a.world.refund = b.world.refund ∧ a.gas ≤ b.gas)) + else observe cfgBefore policy a = observe cfgAfter policy b + | _, _ => False + +instance (a b : Config) (policy : Policy) (before after : Run) : + Decidable (equivalent a b policy before after) := by + unfold equivalent + split <;> infer_instance + +private def wordJson (value : Word) : Lean.Json := .str (toString value.toNat) +private def byteJson (value : Byte) : Lean.Json := Lean.toJson value.toNat + +def describe (cfg : Config) (policy : Policy) (result : Run) : String := + match result with + | .error reason => "unsupported: " ++ reason + | .ok result => + let result := observe cfg policy result + let accounts := result.accounts.map fun a => Lean.Json.arr #[ + .str (toString a.address.toNat), .str (toString a.nonce), wordJson a.balance, + .arr (a.code.map byteJson).toArray, + .arr (a.storage.map (fun entry => Lean.Json.arr #[wordJson entry.1, wordJson entry.2])).toArray] + let logs := result.logs.map fun log => Lean.Json.arr #[ + .str (toString log.address.toNat), .arr (log.topics.map wordJson).toArray, + .arr (log.data.map byteJson).toArray] + let stop := match result.stop with + | .success => "success" | .reverted => "revert" + | .exception => "exception" | .outOfGas => "out-of-gas" + (Lean.Json.arr #[.str stop, .arr (result.data.map byteJson).toArray, + Lean.toJson result.gas, Lean.toJson result.refund, .arr accounts.toArray, .arr logs.toArray]).compress + +end SolarTV.EVM.State diff --git a/tv/SolarTV/EVMIR/State/Safety.lean b/tv/SolarTV/EVMIR/State/Safety.lean new file mode 100644 index 00000000..469e652b --- /dev/null +++ b/tv/SolarTV/EVMIR/State/Safety.lean @@ -0,0 +1,60 @@ +import SolarTV.EVMIR.State.Observe + +/-! Kernel checks for the entry evaluator's proof boundary and creation rules. +Unsupported execution cannot establish equivalence, and reverted frames restore +their original journal. Address derivation is pinned to EIP-1014's published +vector, independently of the native replay engine. -/ + +namespace SolarTV.EVM.State + +theorem unsupported_not_equivalent (a b : Config) (policy : Policy) + (reason : String) (other : Run) : + ¬ equivalent a b policy (.error reason) other := by + cases other <;> simp [equivalent] + +theorem reverted_entry_restores_world (fuel : Nat) (cfg : Config) + (world changed : Journal) (frame : Frame) (data : List Byte) (gas : Nat) + (work : Nat) + (execution : run fuel cfg world frame = .ok ⟨.reverted, data, changed, gas, work⟩) : + execute fuel cfg world frame = .ok ⟨.reverted, data, world, gas, work⟩ := by + simp only [execute, execution] + rfl + +theorem exception_cannot_refine_to_success (cfg : Config) (world : Journal) : + ¬ equivalent cfg cfg .refine (.ok ⟨.exception, [], world, 0, 0⟩) + (.ok ⟨.success, [], world, 0, 0⟩) := by + simp [equivalent, observe] + +-- EIP-1014, example 0: https://eips.ethereum.org/EIPS/eip-1014#examples +example : create2Address 0 0 [0] = 0x4d1a2e2bb4f88f0250f26ffff098b0b30b26bf38 := by + decide +kernel + +example : validDeployedCode .berlin [0xef] = true := by decide +example : validDeployedCode .london [0xef] = false := by decide +example (code : List Byte) (size : code.length > 24576) : + validDeployedCode .cancun code = false := by + simp [validDeployedCode, Fork.atLeast, Fork.ordinal, show ¬ code.length ≤ 24576 by omega] + +example : validJump [0x60, 0x5b, 0x00] 1 = false := by decide +example : validJump [0x60, 0x01, 0x5b] 2 = true := by decide + +private def destructionFixture (created : Bool) : Journal := + {accounts := [{address := 1, nonce := 1, balance := 100, code := [0], storage := [(0,7)], created}] + original := [] + warmAddresses := [1] + warmSlots := []} + +example : (finalize (destroy .shanghai (destructionFixture false) 1 1)).accounts = [] := by decide +kernel +example : (account (destroy .cancun (destructionFixture false) 1 1) 1).balance = 100 := by decide +kernel +example : (finalize (destroy .cancun (destructionFixture true) 1 1)).accounts = [] := by decide +kernel +example : (account (destroy .shanghai (destructionFixture false) 1 1) 1).code = [0] := by decide +kernel +example : (destroy .berlin (destroy .berlin (destructionFixture false) 1 1) 1 1).refund = 24000 := by decide +kernel + +example : blockHash {number := 300, hashes := [(43,1),(44,2),(299,3),(300,4)]} 43 = 0 := by decide +kernel +example : blockHash {number := 300, hashes := [(44,2)]} 44 = 2 := by decide +kernel +example : blockHash {number := 300, hashes := [(300,4)]} 300 = 0 := by decide +kernel +example : delegationTarget .cancun ([0xef,0x01,0x00] ++ List.replicate 20 0) = none := by decide +kernel +example : delegationTarget .prague ([0xef,0x01,0x00] ++ List.replicate 19 0 ++ [42]) = some 42 := by decide +kernel +example : delegationTarget .prague ([0xef,0x01,0x00] ++ List.replicate 21 0) = none := by decide +kernel + +end SolarTV.EVM.State diff --git a/tv/SolarTV/EVMIR/State/Selfdestruct.lean b/tv/SolarTV/EVMIR/State/Selfdestruct.lean new file mode 100644 index 00000000..e980d8fe --- /dev/null +++ b/tv/SolarTV/EVMIR/State/Selfdestruct.lean @@ -0,0 +1,35 @@ +import SolarTV.EVMIR.State.Decode + +/-! SELFDESTRUCT's immediate balance effects and deferred account deletion. +Code and storage survive until transaction finalization, allowing another call +to the same account before the root returns. Cancun preserves existing accounts +under EIP-6780; accounts created in this transaction retain the legacy deletion +and self-beneficiary balance-burning rules. The flags are journaled with accounts, +so reverting any parent also reverts deletion, creation and refund eligibility. +https://eips.ethereum.org/EIPS/eip-6780 +https://eips.ethereum.org/EIPS/eip-3529 +https://eips.ethereum.org/EIPS/eip-2929 -/ + +namespace SolarTV.EVM.State + +def destructionPrice (fork : Fork) (world : Journal) (owner beneficiary : Address) : Nat := + 5000 + (if fork.atLeast .berlin && !world.warmAddresses.contains beneficiary then 2600 else 0) + + if (account world owner).balance != 0 && dead world beneficiary then 25000 else 0 + +def destroy (fork : Fork) (world : Journal) (owner beneficiary : Address) : Journal := + let old := account world owner + let deletes := !fork.atLeast .cancun || old.created + let world := warmAddress world beneficiary + let world := if owner = beneficiary then world else + (transfer world owner beneficiary old.balance).getD world + let current := account world owner + let refund := if !fork.atLeast .london && !old.destroyed then 24000 else 0 + putAccount {world with refund := world.refund + refund} + {current with + balance := if deletes then 0 else current.balance + destroyed := old.destroyed || deletes} + +def finalize (world : Journal) : Journal := + {world with accounts := world.accounts.filter (fun a => !a.destroyed)} + +end SolarTV.EVM.State diff --git a/tv/SolarTV/EVMIR/State/Types.lean b/tv/SolarTV/EVMIR/State/Types.lean new file mode 100644 index 00000000..d3afa6ef --- /dev/null +++ b/tv/SolarTV/EVMIR/State/Types.lean @@ -0,0 +1,70 @@ +import SolarTV.State.Calls +import SolarTV.State.ByteMemory +import SolarTV.State.Context +import SolarTV.Keccak +import SolarTV.EVMIR.Ops + +/-! Executable, journaled account state for explicit-world validation. Lists are +finite representations of total maps with an absent/zero default. Updates replace +keys rather than appending histories, and observations sort/erase zero slots. +The world fixture is an explicit assumption, never an arbitrary-account proof. +The evaluator reports unsupported behavior and work/memory limits separately +from EVM exceptional halts; neither may certify equivalence. -/ + +namespace SolarTV.EVM.State +open EvmRules +export SolarTV.Execution (Byte Address Slots Account Journal Block slotsRead slotsWrite account putAccount + warmAddress warmSlot transfer memoryWords requiredWords expand readBytes writeBytes wordBytes readWord) + +structure Frame where + environment : World.Environment + code : List Byte + pc : Nat := 0 + stack : List Word := [] + memory : List Byte := [] + returnData : List Byte := [] + gas : Nat + +inductive Stop where + | success | reverted | exception | outOfGas + deriving DecidableEq + +structure Result where + stop : Stop + data : List Byte + world : Journal + gas : Nat + work : Nat := 0 + deriving DecidableEq + +/-- Model errors are not execution outcomes and cannot be equated by the prover. -/ +abbrev Run := Except String Result + +def memoryCost (words : Nat) : Nat := 3 * words + words * words / 512 + +def memoryCharge (memory : List Byte) (offset count : Nat) : Nat := + memoryCost (requiredWords memory offset count) - memoryCost (memoryWords memory) + +def failed (world : Journal) : Run := .ok ⟨.exception, [], world, 0, 0⟩ + +def exhausted (world : Journal) : Run := .ok ⟨.outOfGas, [], world, 0, 0⟩ + +def finished (world : Journal) (frame : Frame) (reverted : Bool) (data : List Byte := []) : Run := + .ok ⟨if reverted then .reverted else .success, data, world, frame.gas, 0⟩ + +structure Opcode where + available : Bool + base : Nat + dynamic : Nat + inputs : Nat + outputs : Nat + deriving DecidableEq + +structure Config where + fork : Fork + opcodes : List Opcode + root : Address + block : Block := {} + unknownCode : Option Address := none + +end SolarTV.EVM.State diff --git a/tv/SolarTV/EVMIR/Transforms/EqIszeroJumpi.lean b/tv/SolarTV/EVMIR/Transforms/EqIszeroJumpi.lean new file mode 100644 index 00000000..8b06cbef --- /dev/null +++ b/tv/SolarTV/EVMIR/Transforms/EqIszeroJumpi.lean @@ -0,0 +1,21 @@ +import SolarTV.EVMIR.Ops + +/-! EVM IR peephole: replace EQ followed by ISZERO with SUB before a conditional jump. -/ + +namespace SolarTV.EVM +open EvmRules + +/-- After EQ (or SUB), the window has room for its single PUSH on any legal +entry stack. No memory, storage or return data is touched by these opcodes. -/ +theorem eq_iszero_jumpi (ctx : Context) (stack : Stack) (dst fallthrough : Word) + (legal : stack.length ≤ 1024) : + execute ctx [.eq, .iszero] (.branch dst fallthrough) stack = + execute ctx [.sub] (.branch dst fallthrough) stack := by + rcases stack with _ | ⟨a, _ | ⟨b, rest⟩⟩ <;> try rfl + have h : ¬ 1024 < rest.length + 1 + 1 := by simpa using legal + have h' : ¬ 1024 < rest.length + 1 := by omega + have zero (x y : Word) : Evm.sub x y = 0#256 ↔ x = y := by + simp [Evm.sub, BitVec.sub_eq_iff_eq_add] + by_cases same : a = b <;> simp [execute, stepChecked, step, finish, Evm.eq, Evm.iszero, zero, same, h, h'] + +end SolarTV.EVM diff --git a/tv/SolarTV/EVMIR/Transforms/GasSwapAdd.lean b/tv/SolarTV/EVMIR/Transforms/GasSwapAdd.lean new file mode 100644 index 00000000..52cc7ec6 --- /dev/null +++ b/tv/SolarTV/EVMIR/Transforms/GasSwapAdd.lean @@ -0,0 +1,25 @@ +import SolarTV.EVMIR.Gas + +/-! Resource refinement for the real commutative-swap peephole. +Dropping SWAP1 before ADD preserves the outgoing stack and memory while saving +three gas. For every budget at which the original completes, the candidate +completes with the same observation and at least as much remaining gas. Original +out-of-gas is unconstrained by this policy; exact gas equality would reject it. -/ + +namespace SolarTV.EVM.Gas +open EvmRules + +theorem swap_add_refines (ctx : Context) (a b destination : Word) + (memory : SolarTV.Memory.State) (gas : Nat) : + refines + (execute ctx [.instruction (.stack (.swap 0)), .instruction (.stack .add)] + (.control (.jump destination)) [a, b] memory gas) + (execute ctx [.instruction (.stack .add)] + (.control (.jump destination)) [a, b] memory gas) := by + simp [refines, execute, finish, cost, baseCost, pureCost, touched, expansionCost, + halted, exhausted, Memory.step, Memory.finish, EVM.stepChecked, EVM.step, + EVM.finish, Except.map, Evm.add, BitVec.add_comm] + repeat' (first | omega | (split <;> simp_all)) + all_goals omega + +end SolarTV.EVM.Gas diff --git a/tv/SolarTV/EVMIR/Transforms/StackPeephole.lean b/tv/SolarTV/EVMIR/Transforms/StackPeephole.lean new file mode 100644 index 00000000..6783e411 --- /dev/null +++ b/tv/SolarTV/EVMIR/Transforms/StackPeephole.lean @@ -0,0 +1,19 @@ +import SolarTV.EVMIR.Ops + +/-! The commutative-swap peephole removes SWAP1 before ADD. +Both versions use the same live-in stack. At a valid entry height the swap +preserves the height, ADD removes one word, and the outgoing label push fits. +The proof observes the entire resulting stack at the outgoing edge. -/ + +namespace SolarTV.EVM +open EvmRules + +theorem swap_add (ctx : Context) (a b destination : Word) (rest : Stack) + (legal : rest.length ≤ 1022) : + execute ctx [.swap 0, .add] (.jump destination) (a :: b :: rest) = + execute ctx [.add] (.jump destination) (a :: b :: rest) := by + have h : ¬ 1024 < rest.length + 1 + 1 := by omega + have h' : ¬ 1024 < rest.length + 1 := by omega + simp [execute, stepChecked, step, finish, h, h', Evm.add, BitVec.add_comm] + +end SolarTV.EVM diff --git a/tv/SolarTV/Keccak.lean b/tv/SolarTV/Keccak.lean new file mode 100644 index 00000000..15ac1e94 --- /dev/null +++ b/tv/SolarTV/Keccak.lean @@ -0,0 +1,70 @@ +import EvmRules.Word + +/-! Keccak-256 with the EVM's original Keccak padding (0x01, not SHA3's 0x06). +The state is 25 little-endian 64-bit lanes, indexed x + 5*y. Each of the 24 +Keccak-f rounds performs theta, rho/pi, chi and iota; the rate is 136 bytes. +There is no hash oracle or collision-freedom axiom. Symbolic hashes may exceed +the prover's limits, which must remain inconclusive rather than uninterpreted. +Reference: https://keccak.team/files/Keccak-reference-3.0.pdf, Algorithms 1-6. -/ + +namespace SolarTV.Keccak + +abbrev Byte := BitVec 8 +abbrev Lane := BitVec 64 +abbrev State := List Lane + +def constants : List Lane := [ + 0x0000000000000001, 0x0000000000008082, 0x800000000000808A, 0x8000000080008000, + 0x000000000000808B, 0x0000000080000001, 0x8000000080008081, 0x8000000000008009, + 0x000000000000008A, 0x0000000000000088, 0x0000000080008009, 0x000000008000000A, + 0x000000008000808B, 0x800000000000008B, 0x8000000000008089, 0x8000000000008003, + 0x8000000000008002, 0x8000000000000080, 0x000000000000800A, 0x800000008000000A, + 0x8000000080008081, 0x8000000000008080, 0x0000000080000001, 0x8000000080008008] + +def rotations : List Nat := [ + 0, 1, 62, 28, 27, 36, 44, 6, 55, 20, 3, 10, 43, 25, 39, + 41, 45, 15, 21, 8, 18, 2, 61, 56, 14] + +def lane (state : State) (x y : Nat) : Lane := state[x % 5 + 5 * (y % 5)]?.getD 0 + +def rotate (value : Lane) (amount : Nat) : Lane := + (value <<< (amount % 64)) ||| (value >>> ((64 - amount % 64) % 64)) + +def round (state : State) (constant : Lane) : State := + let parity := (List.range 5).map (fun x => + (List.range 5).foldl (fun acc y => acc ^^^ lane state x y) 0) + let theta := (List.range 25).map (fun i => + state[i]?.getD 0 ^^^ parity[(i % 5 + 4) % 5]?.getD 0 ^^^ + rotate (parity[(i % 5 + 1) % 5]?.getD 0) 1) + let rhoPi := (List.range 25).foldl (fun result i => + let x := i % 5 + let y := i / 5 + result.set (y + 5 * ((2 * x + 3 * y) % 5)) + (rotate (theta[i]?.getD 0) (rotations[i]?.getD 0))) (List.replicate 25 0) + let chi := (List.range 25).map (fun i => + lane rhoPi (i % 5) (i / 5) ^^^ + ((~~~lane rhoPi (i % 5 + 1) (i / 5)) &&& lane rhoPi (i % 5 + 2) (i / 5))) + chi.set 0 (chi[0]?.getD 0 ^^^ constant) + +def permutation (state : State) : State := constants.foldl round state + +def pad (data : List Byte) : List Byte := + if data.length % 136 = 135 then data ++ [0x81] + else data ++ [1] ++ List.replicate (134 - data.length % 136) 0 ++ [0x80] + +def littleWord (data : List Byte) (offset : Nat) : Lane := + (List.range 8).foldl (fun acc i => + acc ||| ((data[offset + i]?.getD 0).setWidth 64 <<< (8 * i))) 0 + +def absorb (state : State) (block : List Byte) : State := + permutation ((List.range 25).map (fun i => + state[i]?.getD 0 ^^^ if i < 17 then littleWord block (8 * i) else 0)) + +def hash (data : List Byte) : EvmRules.Word := + let padded := pad data + let state := (List.range (padded.length / 136)).foldl (fun state i => + absorb state ((padded.drop (136 * i)).take 136)) (List.replicate 25 0) + (List.range 32).foldl (fun acc i => (acc <<< 8) ||| + (((state[i / 8]?.getD 0) >>> (8 * (i % 8))).setWidth 8).setWidth 256) 0 + +end SolarTV.Keccak diff --git a/tv/SolarTV/KeccakSafety.lean b/tv/SolarTV/KeccakSafety.lean new file mode 100644 index 00000000..a028a594 --- /dev/null +++ b/tv/SolarTV/KeccakSafety.lean @@ -0,0 +1,33 @@ +import SolarTV.Keccak + +/-! Kernel-evaluated Keccak vectors cover empty input, byte/lane ordering, +the one-byte pad boundary and multi-block absorption. Positive checks never +use native_decide, an external hash function or a cryptographic axiom. -/ + +set_option maxRecDepth 8192 +set_option maxHeartbeats 2000000 + +namespace SolarTV.Keccak + +@[simp] theorem empty : hash [] = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 := by + decide +kernel + +example : hash [97, 98, 99] = + 0x4e03657aea45a94fc7d47ba826c8d667c0d1e6e33a64a036ec44f58fa12d6c45 := by + decide +kernel + +example : (pad (List.replicate 135 0)).length = 136 := by decide +example : (pad (List.replicate 136 0)).length = 272 := by decide + +-- These boundary values are also checked by the Rust interpreter tests. +example : hash (List.replicate 135 0) = + 18946676226192871058387231643792898752776336720096239710285640021474136472638 := by + decide +kernel +example : hash (List.replicate 136 0) = + 26391523361189685675012273911989963211388955111946558690139574972697269708281 := by + decide +kernel +example : hash (List.replicate 137 0) = + 86349320094517957708823086655008166321692264600573236910167712870522516913448 := by + decide +kernel + +end SolarTV.Keccak diff --git a/tv/SolarTV/MIR/Ops.lean b/tv/SolarTV/MIR/Ops.lean new file mode 100644 index 00000000..5d345842 --- /dev/null +++ b/tv/SolarTV/MIR/Ops.lean @@ -0,0 +1,149 @@ +import EvmRules.Word +import SolarTV.Outcome +import SolarTV.Word + +/-! Pure typed MIR operations and ordered switch dispatch. +A case stores an SSA value ID. Reading from an arbitrary total environment models +defined MIR operands, including nonconstant cases. The interpreter tests them in +source order and enters the first matching successor from the current block. -/ + +namespace SolarTV.MIR + +open EvmRules + +inductive Op where + | add | sub | mul | div | sdiv | mod | smod | exp | and | or | xor + | shl | shr | sar + +/-- Semantic arithmetic wraps at the operand width, as in lower-integers. Division and +remainder by zero give zero, as the EVM opcodes do. Shifts take the amount first, in EVM +pop order, and shift out every bit once it reaches the width; an arithmetic shift then +fills with the sign bit. The signed operations read the sign bit at the operand width. -/ +def eval {width : Nat} : Op → BitVec width → BitVec width → BitVec width + | .add => fun a b => a + b + | .sub => fun a b => a - b + | .mul => fun a b => a * b + | .div => Word.binary .div + | .sdiv => Word.binary .sdiv + | .mod => Word.binary .mod + | .smod => Word.binary .smod + | .exp => Word.binary .exp + | .and => fun a b => a &&& b + | .or => fun a b => a ||| b + | .xor => fun a b => a ^^^ b + | .shl => fun shift value => value <<< shift.toNat + | .shr => fun shift value => value >>> shift.toNat + | .sar => fun shift value => value.sshiftRight shift.toNat + +/-- Bitwise complement at the operand width. -/ +def not {width : Nat} (a : BitVec width) : BitVec width := ~~~a + +abbrev unary := @Word.unary +abbrev shift := @Word.shift + +/-- MIR `select` takes a normalized i1: the first arm when it is 1. -/ +def select {width : Nat} (condition : BitVec 1) (yes no : BitVec width) : BitVec width := + if condition = 0 then no else yes + +inductive WordBinary where + | byte | signextend + +def wordBinary : WordBinary → EvmRules.Word → EvmRules.Word → EvmRules.Word + | .byte => Evm.byte + | .signextend => Evm.signextend + +inductive Ternary where + | addmod | mulmod + +def ternary : Ternary → EvmRules.Word → EvmRules.Word → EvmRules.Word → EvmRules.Word + | .addmod => Evm.addmod + | .mulmod => Evm.mulmod + +/-- Ordered switch selection, also used when compiling a pair obligation. -/ +abbrev choose {width : Nat} (key test : BitVec width) (yes no : α) := if test = key then yes else no + +abbrev Case := Nat × Nat -- (SSA value ID, destination block) + +def dispatch (read : Nat → EvmRules.Word) (key : EvmRules.Word) (fallback : Nat) : + List Case → Nat + | [] => fallback + | (id, dst) :: rest => choose key (read id) dst (dispatch read key fallback rest) + +/-- Phi operands are read in the incoming environment and selected by predecessor. +An absent predecessor is undefined; the importer requires exactly one match. -/ +def phi {width : Nat} (predecessor : Nat) : List (Nat × BitVec width) → Option (BitVec width) + | [] => none + | (block, value) :: rest => + if predecessor = block then some value else phi predecessor rest + +inductive Cast where + | trunc | zext | sext + +/-- Cast widths are checked by the compiler verifier before import. +Truncation keeps the low bits, including for i1. Extension preserves either the +unsigned value or the source width's sign bit. Neither cast tests for nonzero. -/ +def cast {sourceWidth : Nat} (kind : Cast) (to : Nat) (value : BitVec sourceWidth) : BitVec to := + match kind with + | .trunc | .zext => value.setWidth to + | .sext => value.signExtend to + +inductive Comparison where + | eq | ne | lt | gt | slt | sgt + +/-- Comparisons produce exactly 0 or 1. Signed comparisons use the operand +width's sign bit, matching the sign extensions materialized by lower-integers. -/ +def compare {width : Nat} (kind : Comparison) (a b : BitVec width) : BitVec 1 := + let condition := match kind with + | .eq => a == b + | .ne => a != b + | .lt => a.ult b + | .gt => b.ult a + | .slt => a.slt b + | .sgt => b.slt a + if condition then 1 else 0 + +/-- jumpi takes a normalized i1, so its only possible inputs are 0 and 1. -/ +abbrev branch (condition : BitVec 1) (yes no : α) := if condition = 1 then yes else no + +inductive CheckedOp where + | add | sub | mul | div | wrappingDiv | rem + +/-- Lean's overflow predicates check the unbounded result against the declared +unsigned or two's-complement range. A failure is the Panic(0x11) emitted by +lower-arithmetic; successful results retain the declared width. -/ +def checked {width : Nat} (op : CheckedOp) (signed : Bool) + (a b : BitVec width) : Outcome (BitVec width) := + match op with + | .add => if (if signed then a.saddOverflow b else a.uaddOverflow b) then + .reverted (.panic 0x11) else .returned (a + b) + | .sub => if (if signed then a.ssubOverflow b else a.usubOverflow b) then + .reverted (.panic 0x11) else .returned (a - b) + | .mul => if (if signed then a.smulOverflow b else a.umulOverflow b) then + .reverted (.panic 0x11) else .returned (a * b) + | .div => + if b == 0 then .reverted (.panic 0x12) + else if signed && a == BitVec.intMin width && b == -1 then .reverted (.panic 0x11) + else .returned (if signed then a.sdiv b else a / b) + | .wrappingDiv => + if b == 0 then .reverted (.panic 0x12) + else .returned (if signed then a.sdiv b else a / b) + | .rem => + if b == 0 then .reverted (.panic 0x12) + else .returned (if signed then Word.binary .smod a b else Word.binary .mod a b) + +def checkedPower {width : Nat} (signed : Bool) (base : BitVec width) + (exponent : Nat) : Outcome (BitVec width) := + if _h : exponent = 0 then .returned 1 + else if exponent = 1 then .returned base + else + Outcome.bind (checked .mul signed base base) fun square => + Outcome.bind (checkedPower signed square (exponent / 2)) fun half => + if exponent % 2 = 0 then .returned half else checked .mul signed half base +termination_by exponent +decreasing_by exact Nat.div_lt_self (Nat.pos_of_ne_zero _h) (by decide) + +/-- Semantic checks fail synchronously before any later instruction runs. -/ +def guard (fails : Bool) (failure : RevertData) (next : Outcome α) : Outcome α := + if fails then .reverted failure else next + +end SolarTV.MIR diff --git a/tv/SolarTV/MIR/Program.lean b/tv/SolarTV/MIR/Program.lean new file mode 100644 index 00000000..de885403 --- /dev/null +++ b/tv/SolarTV/MIR/Program.lean @@ -0,0 +1,434 @@ +import SolarTV.Machine +import SolarTV.EVMIR.Ops + +/-! Lowered MIR functions and modules as layers. + +This is MIR at the `lowered` phase, the input of `-Zvalidate-passes`: word SSA values, +phis, branches, switches, the pure EVM operations, `ne`, effects, facts (`assume`), tail +calls and the halts of a contract entry. `lower-abi` and `lower-dispatch` run before it, so the semantic-phase +pipeline that builds the dispatcher is outside this semantics. A function runs block by +block with one unit of fuel per block, from block 0 with every value zero. A phi reads the +incoming environment and selects by predecessor. Pure operations are the word semantics of +`EVM.step`, the same `EvmRules.Evm` definitions the agreement theorems relate to the +encoder, and `ne` is `Evm.ne`. A switch enters the first case whose operand equals its key, +else its default. Malformed code (an unknown block, a phi without the predecessor, an +effect of the wrong arity) has no end, so it has no observable result, and neither has a +run that reaches a fact that does not hold. Casts and `select` have the semantics the +operation schema declares (`crates/mir/src/semantics.rs`): a zero extension or a pointer cast +leaves the word as it is, since every `iN` value keeps the bits above N zero, a truncation +keeps the low bits (`lowBits`), and a select picks by a nonzero condition. + +Two words of memory layout are the backend's, which MIR does not show and the MIR interpreter +reads from the backend memory records: the free memory pointer a runtime entry stores in the +pointer's slot `0x40` when it starts (`Function.entryHeap`, stored on entering the function, +`Function.start`), and the heap floor every `heap_floor` of a function reads, the initial +pointer of the entries that run it (`Inst.heapFloor`). `-Zemit-lean-stages` writes the words +codegen placed, so a stage holds for that placement. So are the allocations (`alloc`) codegen +placed: at a fixed address, or by bumping the free memory pointer by a size, which loads the +pointer and stores it raised as codegen's `mload 0x40; dup1; push size; add; push 0x40; mstore` +does. + +A module is the functions of a contract and the one its runtime code enters +(`Module.run`). A `tail_call` enters the callee's block 0 with a fresh environment that +binds its parameters to the arguments, and keeps the machine state; control never comes +back. An internal call (`icall`) does the same but first pushes a `Return`: the rest of its +block and the caller's values. The callee's `ret` (`leave` here) pops it, binds the call's +result to the returned value and runs the rest of the caller's block, for one more unit of +fuel. A `leave` with no caller, or whose values do not match the call's result, has no end. +A function that returns several words leaves all of them, as stack scheduling returns them on +the stack, and the call binds each to the value that reads it (`bindResults`), where MIR reads +the further ones from the multi-return buffer; those reads are not in the exported block. When +codegen also publishes them to the buffer, the call stores them there (`publishResults`). Block, value and function numbers are the compiler's indices (`BlockId`, `ValueId`, +`FunctionId`), as `-Zemit-lean-stages` writes them. The single-function layer (`layer`) +has no calls: a tail call, an internal call or a `leave` has no end there. -/ + +namespace SolarTV.MIR.Lowered + +open EvmRules Machine + +inductive Operand where + | value (id : Nat) + | const (word : Word) + +/-- Where codegen placed an allocation. -/ +inductive Placement where + /-- At a fixed address, below the heap. -/ + | static (address : Word) + /-- At the free memory pointer, which it raises by `size`. -/ + | dynamic (size : Word) + +inductive Inst where + | pure (dst : Nat) (op : EVM.Op) (args : List Operand) + | effect (dst : Option Nat) (effect : Effect) (args : List Operand) + /-- One when the operands differ, zero otherwise. -/ + | ne (dst : Nat) (a b : Operand) + /-- A fact a pass relied on (`assume`): `op` leaves a nonzero word on the operands, or zero + when `negated`. Where it fails the run has no end, so the fact is checked, never trusted. -/ + | assume (negated : Bool) (op : EVM.Op) (args : List Operand) + /-- The operand's word, unchanged: `zext`, `inttoptr` and `ptrtoint` to 256 bits, whose + operands already keep every bit above their width zero. -/ + | word (dst : Nat) (arg : Operand) + /-- An internal call of a function of the module, binding its result, if any. A callee that + returns several words leaves them all, as stack scheduling does: the call binds the first to + `dst` and each further one to its value in `extras`, if any, and when `publish` names + the callee's return buffer, stores them there too (`publishResults`). -/ + | call (dst : Option Nat) (callee : Nat) (args : List Operand) + (extras : List (Option Nat) := []) (publish : Option Word := none) + /-- The operand's low `bits` bits, zero above them: `trunc` and a narrower `ptrtoint`. -/ + | low (dst : Nat) (bits : Nat) (arg : Operand) + /-- The second operand when the first is nonzero, else the third: `select`. -/ + | select (dst : Nat) (condition yes no : Operand) + /-- The heap floor codegen placed for the function (`heap_floor`). -/ + | heapFloor (dst : Nat) (floor : Word) + /-- An allocation where codegen placed it (`alloc`), binding its address. -/ + | alloc (dst : Nat) (placement : Placement) + +inductive Terminator where + | jump (target : Nat) + | branch (condition : Operand) (yes no : Nat) + | ret (offset size : Operand) + | revert (offset size : Operand) + | stop + | invalid + /-- The first case whose operand equals the key, else the default. -/ + | switch (key : Operand) (default : Nat) (cases : List (Operand × Nat)) + /-- Control moves to the callee's entry for good, binding its parameters to the arguments. -/ + | tailCall (callee : Nat) (args : List Operand) + /-- An internal function's return with its values, to the instruction after the call. -/ + | leave (values : List Operand) + +structure Block where + phis : List (Nat × List (Nat × Operand)) + insts : List Inst + term : Terminator + +structure Function where + blocks : List Block + /-- The value numbers a call binds to its arguments, in order. -/ + params : List Nat := [] + /-- The free memory pointer codegen stores at `0x40` when the function starts as a runtime + entry, if any. -/ + entryHeap : Option Word := none + +/-- The state a function starts in: its entry heap stored in the free memory pointer's slot. -/ +def Function.start (f : Function) (s : State) : State := + match f.entryHeap with + | none => s + | some heap => { s with memory := s.memory.store 64 heap } + +abbrev Env := Nat → Word + +def Env.set (env : Env) (id : Nat) (value : Word) : Env := fun j => if j = id then value else env j + +def Operand.eval (env : Env) : Operand → Word + | .value id => env id + | .const word => word + +/-- The low `bits` bits of a word, zero above them, as the mask a narrow integer keeps. -/ +def lowBits (bits : Nat) (w : Word) : Word := Evm.and w (BitVec.ofNat 256 (2 ^ bits - 1)) + +/-- The second word when the first is nonzero, else the third. -/ +def selectWord (condition yes no : Word) : Word := if condition = 0 then no else yes + +/-- A pure operation on its operands in pop order: the single word `EVM.step` leaves. -/ +def evalPure (op : EVM.Op) (args : List Word) : Option Word := + match EVM.step ⟨0, 0⟩ op args with + | some [value] => some value + | _ => none + +def execInsts (o : Oracle) (call : Call) : List Inst → Env → State → Option (Env × State) + | [], env, s => some (env, s) + | .pure dst op args :: rest, env, s => + match evalPure op (args.map (Operand.eval env)) with + | some value => execInsts o call rest (env.set dst value) s + | none => none + | .effect dst effect args :: rest, env, s => + match effect.apply o call (args.map (Operand.eval env)) s with + | some (result, s) => + let env := match dst, result with + | some dst, some value => env.set dst value + | _, _ => env + execInsts o call rest env s + | none => none + | .ne dst a b :: rest, env, s => execInsts o call rest (env.set dst (Evm.ne (a.eval env) (b.eval env))) s + | .assume negated op args :: rest, env, s => + match evalPure op (args.map (Operand.eval env)) with + | some value => + if value = 0 then (if negated then execInsts o call rest env s else none) + else (if negated then none else execInsts o call rest env s) + | none => none + | .word dst a :: rest, env, s => execInsts o call rest (env.set dst (a.eval env)) s + | .low dst bits a :: rest, env, s => execInsts o call rest (env.set dst (lowBits bits (a.eval env))) s + | .select dst c yes no :: rest, env, s => + execInsts o call rest (env.set dst (selectWord (c.eval env) (yes.eval env) (no.eval env))) s + | .heapFloor dst floor :: rest, env, s => execInsts o call rest (env.set dst floor) s + | .alloc dst (.static address) :: rest, env, s => execInsts o call rest (env.set dst address) s + | .alloc dst (.dynamic size) :: rest, env, s => + let pointer := s.memory.load 64 + let memory := (s.memory.expand 64 32).store 64 (Evm.add size pointer) + execInsts o call rest (env.set dst pointer) { s with memory } + | .call .. :: _, _, _ => none + +/-- Result `k` of a call, from `k`, stored at `buffer + 32 * k`. -/ +def publishWords (memory : Mem) (buffer : Nat) : + Nat → List Word → Mem + | _, [] => memory + | k, value :: rest => publishWords (memory.store (buffer + 32 * k) value) buffer (k + 1) rest + +/-- The further results of a call returning several words, published where codegen publishes +them: result `k` at `buffer + 32 * k` for `k ≥ 1`, then `buffer` at the multi-return buffer +pointer's slot `0x20`, as its `swap1; push buffer+32k; mstore` and +`push buffer; push 0x20; mstore` do. -/ +def publishResults (s : State) : Option Word → List Word → State + | none, _ => s + | some _, [] => s + | some buffer, _ :: rest => + { s with memory := (publishWords s.memory buffer.toNat 1 rest).store 32 buffer } + +/-- The target of a switch on `key`: the first case whose operand equals it, else `default`. -/ +def switchTarget (env : Env) (key : Word) (default : Nat) : List (Operand × Nat) → Nat + | [] => default + | (case, target) :: rest => if case.eval env = key then target else switchTarget env key default rest + +/-- Every phi reads the incoming environment, then all are bound. -/ +def bindPhis (incoming : Env) (predecessor : Nat) : + List (Nat × List (Nat × Operand)) → Env → Option Env + | [], env => some env + | (dst, arms) :: rest, env => + match arms.find? (fun arm => arm.1 == predecessor) with + | some (_, operand) => bindPhis incoming predecessor rest (env.set dst (operand.eval incoming)) + | none => none + +def halt (s : State) (offset size : Word) (reverted : Bool) : Halt × State := + let memory := s.memory.expand offset.toNat size.toNat + let data := memory.read offset.toNat size.toNat + ((if reverted then .revert data else .ret data), { s with memory }) + +/-- One block from a predecessor: its end, or the next block with the state there. -/ +def block (o : Oracle) (call : Call) (f : Function) : + Nat × Nat × Env × State → Option ((Halt × State) ⊕ (Nat × Nat × Env × State)) + | (predecessor, b, env, s) => + match f.blocks[b]? with + | none => none + | some blk => + match bindPhis env predecessor blk.phis env with + | none => none + | some env => + match execInsts o call blk.insts env s with + | none => none + | some (env, s) => + match blk.term with + | .jump target => some (.inr (b, target, env, s)) + | .branch condition yes no => + some (.inr (b, if condition.eval env = 0 then no else yes, env, s)) + | .ret offset size => some (.inl (halt s (offset.eval env) (size.eval env) false)) + | .revert offset size => some (.inl (halt s (offset.eval env) (size.eval env) true)) + | .stop => some (.inl (.stop, s)) + | .invalid => some (.inl (.invalid, s)) + | .switch key default cases => + some (.inr (b, switchTarget env (key.eval env) default cases, env, s)) + | .tailCall _ _ => none + | .leave _ => none + +def run (o : Oracle) (f : Function) (call : Call) (fuel : Nat) : Option (Halt × State) := + iterate (block o call f) fuel (0, 0, fun _ => 0, f.start (State.initial call)) + +def layer : Layer where + Prog := Function + run := run + mono _ _ _ n r := iterate_mono _ n _ r + +/-- The fuel-free semantics of lowered MIR under an oracle. -/ +noncomputable def sem (o : Oracle) : Sem := layer.sem o + +theorem sem_failure (o : Oracle) (f : Function) (call : Call) (obs : Observable) + (ran : (sem o).run f call = some obs) (failed : obs.success = false) : + obs.logs = [] ∧ obs.storage = slotValue call.storage := by + obtain ⟨_, _, logs, storage, _⟩ := layer.sem_failure o f call obs ran failed + exact ⟨logs, storage⟩ + +theorem failureConvention (o : Oracle) : (sem o).FailureConvention := layer.failureConvention o + +/-- A function of one block without phis runs it at fuel one. -/ +theorem run_straight (o : Oracle) (call : Call) (insts : List Inst) (term : Terminator) + (n : Nat) : + run o ⟨[⟨[], insts, term⟩], [], none⟩ call (n + 1) = + match execInsts o call insts (fun _ => 0) (State.initial call) with + | none => none + | some (env, s) => + match term with + | .jump target => iterate (block o call ⟨[⟨[], insts, term⟩], [], none⟩) n (0, target, env, s) + | .branch condition yes no => + iterate (block o call ⟨[⟨[], insts, term⟩], [], none⟩) n + (0, if condition.eval env = 0 then no else yes, env, s) + | .ret offset size => some (halt s (offset.eval env) (size.eval env) false) + | .revert offset size => some (halt s (offset.eval env) (size.eval env) true) + | .stop => some (.stop, s) + | .invalid => some (.invalid, s) + | .switch key default cases => + iterate (block o call ⟨[⟨[], insts, term⟩], [], none⟩) n + (0, switchTarget env (key.eval env) default cases, env, s) + | .tailCall _ _ => none + | .leave _ => none := by + simp only [run, iterate, block, List.getElem?_cons_zero, bindPhis, Function.start] + cases execInsts o call insts (fun _ => 0) (State.initial call) with + | none => rfl + | some r => cases term <;> rfl + +/-! Modules. -/ + +structure Module where + functions : List Function + /-- The function the runtime code enters. -/ + entry : Nat + +/-- The environment a call enters with: each parameter bound to its argument, every other +value zero; `none` when their numbers differ. -/ +def bindParams : List Nat → List Word → Env → Option Env + | [], [], env => some env + | param :: params, arg :: args, env => bindParams params args (env.set param arg) + | _, _, _ => none + +/-- Where an internal call returns: the caller's function and block, the value its result +binds, the instructions after the call, the block's terminator and the caller's values. -/ +structure Return where + fn : Nat + block : Nat + dst : Option Nat + rest : List Inst + term : Terminator + env : Env + /-- The values the further results bind, for a callee that returns several words. -/ + extras : List (Option Nat) := [] + /-- The return buffer the further results are published to, if any. -/ + publish : Option Word := none + +/-- Where a module goes on: into a block of a function from a predecessor, or on with the +rest of a block after an internal call returned. -/ +inductive Pos where + | enter (fn predecessor block : Nat) + | resume (fn block : Nat) (insts : List Inst) (term : Terminator) + +/-- A configuration of a module: the returns of the calls in progress, innermost first, where +it goes on, its values and the machine state. -/ +abbrev Frame := List Return × Pos × Env × State + +/-- The instructions before the first internal call, and that call with the instructions +after it. -/ +def splitCall : List Inst → + List Inst × Option (Option Nat × Nat × List Operand × List (Option Nat) × Option Word × List Inst) + | [] => ([], none) + | .call dst callee args extras publish :: rest => ([], some (dst, callee, args, extras, publish, rest)) + | inst :: rest => + match splitCall rest with + | (before, next) => (inst :: before, next) + +/-- The caller's values after a return: the call's result bound to the returned value. -/ +def bindResult (env : Env) : Option Nat → List Word → Option Env + | none, [] => some env + | some dst, [value] => some (env.set dst value) + | _, _ => none + +/-- The values the further results of a call bind, in order: none for a result no value reads. -/ +def bindExtras (env : Env) : List (Option Nat) → List Word → Option Env + | [], [] => some env + | none :: extras, _ :: values => bindExtras env extras values + | some dst :: extras, value :: values => bindExtras (env.set dst value) extras values + | _, _ => none + +/-- The caller's values after a return: the call's result bound to the first returned value, +and the further ones to the values that read them when the callee returns several words. -/ +def bindResults (env : Env) (dst : Option Nat) : List (Option Nat) → List Word → Option Env + | [], values => bindResult env dst values + | extras, value :: values => + bindExtras (match dst with | some dst => env.set dst value | none => env) extras values + | _ :: _, [] => none + +/-- The rest of a block from its instructions: its end, or the next frame. -/ +def segment (o : Oracle) (call : Call) (m : Module) (stack : List Return) (fn b : Nat) + (insts : List Inst) (term : Terminator) (env : Env) (s : State) : + Option ((Halt × State) ⊕ Frame) := + match splitCall insts with + | (before, some (dst, callee, args, extras, publish, rest)) => + match execInsts o call before env s with + | none => none + | some (env, s) => + match m.functions[callee]? with + | none => none + | some g => + match bindParams g.params (args.map (Operand.eval env)) (fun _ => 0) with + | none => none + | some inner => + some (.inr (⟨fn, b, dst, rest, term, env, extras, publish⟩ :: stack, .enter callee 0 0, + inner, g.start s)) + | (before, none) => + match execInsts o call before env s with + | none => none + | some (env, s) => + match term with + | .jump target => some (.inr (stack, .enter fn b target, env, s)) + | .branch condition yes no => + some (.inr (stack, .enter fn b (if condition.eval env = 0 then no else yes), env, s)) + | .switch key default cases => + some (.inr (stack, .enter fn b (switchTarget env (key.eval env) default cases), env, s)) + | .tailCall callee args => + match m.functions[callee]? with + | none => none + | some g => + match bindParams g.params (args.map (Operand.eval env)) (fun _ => 0) with + | none => none + | some env => some (.inr (stack, .enter callee 0 0, env, g.start s)) + | .leave values => + match stack with + | [] => none + | ret :: stack => + let values := values.map (Operand.eval env) + match bindResults ret.env ret.dst ret.extras values with + | none => none + | some env => + some (.inr (stack, .resume ret.fn ret.block ret.rest ret.term, env, + publishResults s ret.publish values)) + | .ret offset size => some (.inl (halt s (offset.eval env) (size.eval env) false)) + | .revert offset size => some (.inl (halt s (offset.eval env) (size.eval env) true)) + | .stop => some (.inl (.stop, s)) + | .invalid => some (.inl (.invalid, s)) + +/-- One step of a module: a block entered, or the rest of a block after a return; its end, or +the next frame. -/ +def moduleBlock (o : Oracle) (call : Call) (m : Module) : Frame → Option ((Halt × State) ⊕ Frame) + | (stack, .enter fn predecessor b, env, s) => + match m.functions[fn]? with + | none => none + | some f => + match f.blocks[b]? with + | none => none + | some blk => + match bindPhis env predecessor blk.phis env with + | none => none + | some env => segment o call m stack fn b blk.insts blk.term env s + | (stack, .resume fn b insts term, env, s) => segment o call m stack fn b insts term env s + +/-- The state the module's entry function starts in. -/ +def Module.startState (m : Module) (s : State) : State := + match m.functions[m.entry]? with + | some f => f.start s + | none => s + +/-- A module run from its entry function's block 0, with every value zero and no call in +progress. -/ +def Module.run (o : Oracle) (m : Module) (call : Call) (fuel : Nat) : Option (Halt × State) := + iterate (moduleBlock o call m) fuel + ([], .enter m.entry 0 0, fun _ => 0, m.startState (State.initial call)) + +def moduleLayer : Layer where + Prog := Module + run := Module.run + mono _ _ _ n r := iterate_mono _ n _ r + +/-- The fuel-free semantics of lowered MIR modules under an oracle. -/ +noncomputable def moduleSem (o : Oracle) : Sem := moduleLayer.sem o + +theorem moduleFailureConvention (o : Oracle) : (moduleSem o).FailureConvention := + moduleLayer.failureConvention o + +end SolarTV.MIR.Lowered diff --git a/tv/SolarTV/MIR/State/Aggregates.lean b/tv/SolarTV/MIR/State/Aggregates.lean new file mode 100644 index 00000000..3597c765 --- /dev/null +++ b/tv/SolarTV/MIR/State/Aggregates.lean @@ -0,0 +1,54 @@ +import SolarTV.MIR.State.IR + +/-! Functional product updates and projections. Construction has no memory effect. +An undefined product provides undefined components, rather than zero-filled words; +a projection reads only its selected component. Location-tagged slices use the +same product algebra, with exactly a pointer and a word length. -/ + +namespace SolarTV.MIR.State + +def insertField (ty : ValueType) (aggregate : Value) (index : Nat) (value : Value) : Except String Value := do + let types ← required ty.fields "MIR insertion needs a product" + let _ ← required types[index]? "MIR aggregate index" + let fields ← match aggregate with + | .undefined => pure (List.replicate types.length Value.undefined) + | .aggregate fields => pure fields + | _ => .error "MIR insertion needs a product" + if fields.length != types.length then .error "MIR aggregate arity mismatch" else + return .aggregate (fields.set index value) + +def extractField (ty : ValueType) (aggregate : Value) (index : Nat) : Except String Value := do + let types ← required ty.fields "MIR projection needs a product" + let _ ← required types[index]? "MIR aggregate index" + match aggregate with + | .undefined => pure Value.undefined + | .aggregate fields => required fields[index]? "MIR aggregate index" + | _ => .error "MIR projection needs a product" + +@[simp↓] theorem insertField_ite (ty : ValueType) (index : Nat) (value : Value) + (p : Prop) [Decidable p] (a b : Value) : + insertField ty (if p then a else b) index value = + (if p then insertField ty a index value else insertField ty b index value) := by + split <;> rfl + +@[simp↓] theorem extractField_ite (ty : ValueType) (index : Nat) + (p : Prop) [Decidable p] (a b : Value) : + extractField ty (if p then a else b) index = + (if p then extractField ty a index else extractField ty b index) := by + split <;> rfl + +/-- Reading an initialized field does not consult the still-undefined neighbor. -/ +theorem project_inserted_field (word : EvmRules.Word) : + (do let value ← insertField (.product [.word 256,.word 1]) .undefined 0 + (.scalar (Scalar.ofWord 256 word)) + extractField (.product [.word 256,.word 1]) value 0) = + .ok (.scalar (Scalar.ofWord 256 word)) := by rfl + +/-- The uninitialized neighbor has not acquired an arbitrary value. -/ +theorem uninitialized_neighbor : + (do let value ← insertField (.product [.word 256,.word 1]) .undefined 0 + (.scalar (Scalar.ofWord 256 7)) + let field ← extractField (.product [.word 256,.word 1]) value 1 + field.word) = .error "undefined MIR scalar operand" := by rfl + +end SolarTV.MIR.State diff --git a/tv/SolarTV/MIR/State/Allocation.lean b/tv/SolarTV/MIR/State/Allocation.lean new file mode 100644 index 00000000..b708efff --- /dev/null +++ b/tv/SolarTV/MIR/State/Allocation.lean @@ -0,0 +1,34 @@ +import SolarTV.MIR.State.IR +import SolarTV.State.MemoryLaws + +/-! Direct allocation semantics, with the FMP supplied in explicit byte memory. +Reservation reads word 0x40 and writes the new end without touching the reserved +range. Zero initialization follows the FMP write and touches exactly that range. +The caller includes any alignment/padding in the requested size. Checked bumps +panic with 0x41 on wrapping or exceeding uint64; an invalid infallible bump is +outside its producer's validity contract and remains unsupported. No placement, +heap floor, synthetic pointer or implicit entry initialization is inferred. -/ + +namespace SolarTV.MIR.State +open EvmRules SolarTV.Execution + +def freePointer (frame : Frame) : Step := do + let memory ← expand frame.memory 64 32 + return .returned (some (readWord memory 64),{frame with memory}) + +def allocate (frame : Frame) (size : Word) (zeroed checked : Bool) : Step := do + let memory ← expand frame.memory 64 32 + let pointer := readWord memory 64 + let next := pointer + size + if next.toNat < pointer.toNat || next.toNat > 2^64 - 1 then + if checked then return .reverted (.panic 0x41) + else .error "infallible allocation validity precondition" + else + let memory := writeBytes memory 64 (wordBytes next) + let memory ← if zeroed then do + let memory ← expand memory pointer.toNat size.toNat + pure (writeBytes memory pointer.toNat (List.replicate size.toNat 0)) + else pure memory + return .returned (some pointer,{frame with memory}) + +end SolarTV.MIR.State diff --git a/tv/SolarTV/MIR/State/IR.lean b/tv/SolarTV/MIR/State/IR.lean new file mode 100644 index 00000000..db831011 --- /dev/null +++ b/tv/SolarTV/MIR/State/IR.lean @@ -0,0 +1,192 @@ +import SolarTV.MIR.State.Values +import SolarTV.EVMIR.State.Types +import Init.Data.List.Monadic +import SolarTV.State.ByteMemory +import SolarTV.State.Context + +/-! Structured typed SSA for direct MIR execution, including immutable products. The compiler's parser and +operation schema supply IDs, types and operation identities; the importer does +not lower MIR or synthesize backend addresses. Phis remain edge-selected and +simultaneous, and blocks retain their CFG, including cycles. -/ + +namespace SolarTV.MIR.State +open EvmRules SolarTV.Execution + +inductive Atom where + | constant (value : Scalar) + | argument (index : Nat) + | local (id : Nat) + | undefined + +structure Operand where + atom : Atom + ty : ValueType + +inductive MemoryOp where + | load | store | storeByte | copy | hash | size | zero + | calldataLoad | calldataSize | calldataCopy | returnDataSize | returnDataCopy + +/-- The predicate of a fact a pass relied on (`assume`), on the operands' words: `ult` and `ule` +compare them unsigned. -/ +inductive Fact where + | eq | ne | ult | ule + +def Fact.holds : Fact → Word → Word → Bool + | .eq, a, b => a == b + | .ne, a, b => a != b + | .ult, a, b => a.ult b + | .ule, a, b => a.ule b + +inductive Operation where + | binary (op : MIR.Op) (width : Nat) + | comparison (op : MIR.Comparison) (width : Nat) + | unary (op : Word.Unary) (width : Nat) + | shift (op : Word.Shift) (width : Nat) + | wordBinary (op : MIR.WordBinary) + | ternary (op : MIR.Ternary) + | word | pointerAdd | lowBits (width : Nat) | signExtend (source target : Nat) + | notEqual | select + | checked (op : MIR.CheckedOp) (width : Nat) (signed : Bool) + | checkedPower (width : Nat) (signed : Bool) + | check (zero : Bool) (panic : Option Word) + | memory (op : MemoryOp) + | storage (transient write : Bool) + | environment (opcode : Nat) + | log (topics : Nat) + | call (callee : Nat) + | freePointer + | allocate (zeroed checked : Bool) + | external (opcode : Nat) + | insertValue (ty : ValueType) (index : Nat) + | extractValue (ty : ValueType) (index : Nat) + | makeSlice (location : Nat) + /-- A fact a pass relied on. Where it fails the program is undefined, as for LLVM's `assume`: + a source run that reaches it has no outcome a target must keep, and a target run that + reaches it where the source is defined does not refine the source. -/ + | assume (fact : Fact) + +structure Instruction where + result : Option Nat + ty : ValueType + opcode : Option Nat + operation : Operation + operands : List Operand + +structure Phi where + result : Nat + ty : ValueType + incoming : List (Nat × Operand) + +inductive Terminator where + | jump (target : Nat) + | branch (condition : Operand) (yes no : Nat) + | switch (value : Operand) (fallback : Nat) (cases : List (Operand × Nat)) + | returned (values : List Operand) + | returndata (offset size : Operand) + | reverted (offset size : Operand) + | tailCall (callee : Nat) (args : List Operand) + | stop | invalid + +structure Block where + phis : List Phi + instructions : List Instruction + terminator : Terminator + +/-- Typed bodies retain their own SSA namespaces; calls share only execution state. -/ +structure Function where + params : List ValueType + returns : List ValueType + blocks : List Block + +abbrev Functions := List (Nat × Function) + +/-- An explicit control position, independent of physical EVM stack or frame placement. -/ +structure Cursor where + function : Nat + block : Nat := 0 + next : Nat := 0 + entered : Bool := false + predecessor : Option Nat := none + +structure Config where + fork : Fork + environment : World.Environment + context : Execution.Block + available : List Nat + entry : Bool + callDepth : Nat := 128 + externalConfig : Option EVM.State.Config := none + creationGas : List Nat := [] + +structure Frame where + world : Journal + memory : List Byte + arguments : List Value + locals : List (Nat × Value) := [] + returnData : List Byte := [] + creationIndex : Nat := 0 + +/-- A caller continuation owns its SSA snapshot, not a private copy of execution memory. -/ +structure Continuation where + cursor : Cursor + frame : Frame + result : Option Nat + ty : ValueType + +inductive Completion where + | returned (values : List Word) + | success (data : List Byte) + | reverted (data : List Byte) + | invalid + /-- A failed `assume`: undefined behaviour, not a program outcome. -/ + | undefined + deriving DecidableEq + +structure Result where + completion : Completion + world : Journal + memory : List Byte + returnData : List Byte := [] + creationIndex : Nat := 0 + +abbrev Run := Except String Result +abbrev Step := Except String (Outcome (Option Word × Frame)) + +def narrow (width : Nat) (value : Word) : Word := + if width = 256 then value else (value.setWidth width).setWidth 256 + +@[simp] theorem narrow_full (value : Word) : narrow 256 value = value := by + simp [narrow] + +def required (value : Option α) (reason : String) : Except String α := + match value with | some value => .ok value | none => .error reason + +def readValue (frame : Frame) (operand : Operand) : Except String Value := do + let value ← match operand.atom with + | .constant value => .ok (.scalar value) + | .argument index => required frame.arguments[index]? "missing MIR argument" + | .local id => required ((frame.locals.find? (·.1 == id)).map Prod.snd) "undefined MIR local" + | .undefined => .ok .undefined + if !value.fits 34 operand.ty then .error "MIR operand type mismatch" else return value + +def read (frame : Frame) (operand : Operand) : Except String Word := do + (← readValue frame operand).word + +def put (locals : List (Nat × α)) (id : Nat) (value : α) : List (Nat × α) := + (id,value) :: locals.filter (·.1 != id) + +def enter (predecessor : Option Nat) (phis : List Phi) (frame : Frame) : Except String Frame := do + -- Read every incoming value from the old environment before assigning any phi. + let values ← phis.mapM fun phi => do + let some predecessor := predecessor | .error "phi at MIR entry" + let incoming := phi.incoming.filter (·.1 == predecessor) + let [(_,operand)] := incoming | .error "ambiguous or missing MIR phi edge" + let value ← readValue frame operand + if !(phi.ty.same operand.ty) then .error "MIR phi type mismatch" else return (phi.result,value) + return {frame with locals := values.foldl (fun locals (id,value) => put locals id value) frame.locals} + +def failureData : RevertData → List Byte + | .empty => [] + | .panic code => [0x4e,0x48,0x7b,0x71] ++ wordBytes code + +end SolarTV.MIR.State diff --git a/tv/SolarTV/MIR/State/Interpreter.lean b/tv/SolarTV/MIR/State/Interpreter.lean new file mode 100644 index 00000000..e412660d --- /dev/null +++ b/tv/SolarTV/MIR/State/Interpreter.lean @@ -0,0 +1,199 @@ +import SolarTV.MIR.State.Messages + +/-! A direct SSA abstract machine with explicit caller continuations. Each body +has its own arguments/locals; internal calls share byte memory and the journal. +Returning restores only the caller's SSA context, while STOP, raw RETURN, revert +and exception terminate the whole frame. Tail calls replace the activation. +Phis read their incoming values simultaneously. One global work budget covers +all calls and CFG edges; call depth has a separate model bound. Exhaustion is +unsupported, never program failure or a reason to accept equal executions. +No stack scheduling, backend return protocol or frame initialization is used. -/ + +namespace SolarTV.MIR.State +open EvmRules SolarTV.Execution + +def finish (completion : Completion) (frame : Frame) : Result := + ⟨completion,frame.world,frame.memory,frame.returnData,frame.creationIndex⟩ + +def function (functions : Functions) (id : Nat) : Except String Function := + required ((functions.find? (·.1 == id)).map Prod.snd) "unknown MIR function" + +def typedWords (types : List ValueType) (values : List Value) : Except String Unit := + if types.length != values.length then .error "MIR call arity mismatch" + else if (types.zip values).all (fun (ty,value) => value.fits 34 ty) then .ok () + else .error "unmodeled or mismatched MIR call type" + +def choose (frame : Frame) (key : Word) (fallback : Nat) : List (Operand × Nat) → Except String Nat + | [] => .ok fallback + | (operand,target) :: rest => do + let test ← read frame operand + if test = key then return target else choose frame key fallback rest + +def branch (cursor : Cursor) (target : Nat) : Cursor := + {function := cursor.function,block := target,predecessor := some cursor.block} + +def advance (cursor : Cursor) : Cursor := {cursor with next := cursor.next + 1} + +def start (functions : Functions) (callee : Nat) (args : List Value) (frame : Frame) : Except String Frame := do + let body ← function functions callee + typedWords body.params args + return {frame with arguments := args,locals := []} + +def callSignature (callee : Function) (result : Option Nat) (ty : ValueType) : Except String Unit := + if callee.returns.length > 1 then .error "physical multi-return protocol is not modeled" + else if result.isNone || sameTypes callee.returns [ty] then .ok () + else .error "MIR call result signature mismatch" + + +structure Machine where + cursor : Cursor + stack : List Continuation + frame : Frame + +inductive Transition where + | next (extraWork : Nat) (machine : Machine) + | finished (result : Result) + +def next (cursor : Cursor) (stack : List Continuation) (frame : Frame) : Except String Transition := + .ok (.next 0 ⟨cursor,stack,frame⟩) + +def stop (completion : Completion) (frame : Frame) : Except String Transition := + .ok (.finished (finish completion frame)) + +/-- One MIR transition. Internal calls use continuations; external children spend the shared fuel. -/ +def transition (fuel : Nat) (cfg : Config) (functions : Functions) (machine : Machine) : Except String Transition := do + let ⟨cursor,stack,frame⟩ := machine + let body ← function functions cursor.function + let block ← required body.blocks[cursor.block]? "unknown MIR block" + if !cursor.entered then + let frame ← enter cursor.predecessor block.phis frame + return .next block.phis.length ⟨{cursor with entered := true},stack,frame⟩ + else if cursor.next < block.instructions.length then + let inst ← required block.instructions[cursor.next]? "unknown MIR instruction" + match inst.operation with + | .external opcode => + if inst.opcode.any (fun opcode => !cfg.available.contains opcode) then stop .invalid frame else + let args ← inst.operands.mapM (read frame) + let (effect,work) ← external fuel cfg frame opcode args + match effect with + | .returned (value,parent) => + match ← assign parent inst.result inst.ty value with + | .returned (_,parent) => return .next work ⟨advance cursor,stack,parent⟩ + | _ => .error "MIR message result assignment failed" + | .reverted data => stop (.reverted (failureData data)) frame + | .invalid => stop .invalid frame + | .assume fact => + let [lhs,rhs] := inst.operands | .error "MIR assume operand count" + let lhs ← read frame lhs + let rhs ← read frame rhs + if fact.holds lhs rhs then next (advance cursor) stack frame else stop .undefined frame + | .call callee => + let args ← inst.operands.mapM (readValue frame) + let target ← function functions callee + callSignature target inst.result inst.ty + if stack.length + 1 ≥ cfg.callDepth then .error "MIR internal call depth limit" else + let child ← start functions callee args frame + let caller := ⟨advance cursor,frame,inst.result,inst.ty⟩ + next {function := callee} (caller :: stack) child + | _ => + match ← instruction cfg frame inst with + | .returned (_,frame) => next (advance cursor) stack frame + | .reverted data => stop (.reverted (failureData data)) frame + | .invalid => stop .invalid frame + else + match block.terminator with + | .jump target => next (branch cursor target) stack frame + | .branch condition yes no => + let condition ← read frame condition + if condition = 1 then next (branch cursor yes) stack frame + else next (branch cursor no) stack frame + | .switch value fallback cases => + let key ← read frame value + let target ← choose frame key fallback cases + next (branch cursor target) stack frame + | .tailCall callee operands => + let args ← operands.mapM (readValue frame) + let target ← function functions callee + if !(sameTypes target.returns body.returns) then .error "MIR tail call result mismatch" else + let child ← start functions callee args frame + next {function := callee} stack child + | .returned operands => + let values ← operands.mapM (readValue frame) + typedWords body.returns values + match stack with + | [] => + let words ← (body.returns.zip values).mapM (fun (ty,value) => value.flatten 34 ty) + stop (.returned words.flatten) frame + | caller :: rest => + let parent := {caller.frame with + world := frame.world + memory := frame.memory + returnData := frame.returnData + creationIndex := frame.creationIndex} + if caller.result.isNone then next caller.cursor rest parent else + let [value] := values | .error "physical multi-return protocol is not modeled" + match ← assignValue parent caller.result caller.ty value with + | .returned (_,parent) => next caller.cursor rest parent + | _ => .error "MIR call return assignment failed" + | .stop => stop (.success []) frame + | .invalid => stop .invalid frame + | .returndata offset size | .reverted offset size => + let offset ← read frame offset + let size ← read frame size + let memory ← expand frame.memory offset.toNat size.toNat + let data := readBytes memory offset.toNat size.toNat + let reverted := match block.terminator with | .reverted .. => true | _ => false + stop (if reverted then .reverted data else .success data) {frame with memory} + +def run (fuel : Nat) (cfg : Config) (functions : Functions) (machine : Machine) : Run := do + match fuel with + | 0 => .error "MIR evaluation work limit" + | fuel + 1 => + match ← transition fuel cfg functions machine with + | .finished result => return result + | .next extra machine => + if extra > fuel then .error "MIR evaluation work limit" + else run (fuel - extra) cfg functions machine +termination_by fuel +decreasing_by all_goals omega + +theorem run_one (fuel : Nat) (cfg : Config) (functions : Functions) (machine : Machine) : + run (fuel + 1) cfg functions machine = (do + match ← transition fuel cfg functions machine with + | .finished result => return result + | .next extra nextMachine => + if extra > fuel then .error "MIR evaluation work limit" + else run (fuel - extra) cfg functions nextMachine) := by + rw [run] + +theorem run_next (fuel : Nat) {cfg functions machine extra nextMachine} + (h : transition fuel cfg functions machine = .ok (.next extra nextMachine)) : + run (fuel + 1) cfg functions machine = + if extra > fuel then .error "MIR evaluation work limit" + else run (fuel - extra) cfg functions nextMachine := by + simp only [run, h, Except.bind, Bind.bind] + +theorem run_finished (fuel : Nat) {cfg functions machine result} + (h : transition fuel cfg functions machine = .ok (.finished result)) : + run (fuel + 1) cfg functions machine = .ok result := by + simp only [run, h, Except.bind, Bind.bind, Pure.pure, Except.pure] + +theorem run_error (fuel : Nat) {cfg functions machine reason} + (h : transition fuel cfg functions machine = .error reason) : + run (fuel + 1) cfg functions machine = .error reason := by + simp only [run, h, Except.bind, Bind.bind] + +def execute (fuel : Nat) (cfg : Config) (functions : Functions) (entry : Nat) (frame : Frame) : Run := do + if cfg.callDepth = 0 then .error "MIR internal call depth limit" else + let initial ← start functions entry frame.arguments frame + let result ← run fuel cfg functions ⟨{function := entry},[],initial⟩ + match result.completion with + | .reverted _ | .invalid | .undefined => return {result with world := frame.world} + | .returned values => + if cfg.entry then + if values.isEmpty then return {result with completion := .success [],world := EVM.State.finalize result.world} + else .error "MIR entry returned word values" + else return result + | .success _ => return {result with world := EVM.State.finalize result.world} + +end SolarTV.MIR.State diff --git a/tv/SolarTV/MIR/State/Messages.lean b/tv/SolarTV/MIR/State/Messages.lean new file mode 100644 index 00000000..5c7955d5 --- /dev/null +++ b/tv/SolarTV/MIR/State/Messages.lean @@ -0,0 +1,64 @@ +import SolarTV.MIR.State.Ops +import SolarTV.EVMIR.State.Interpreter + +/-! Direct MIR message boundaries. Explicit CALL gas is forwarded without a +caller-side cap under the sufficient-caller-gas assumption. CREATE's child gas +is an explicit boundary input; it is not invented from an unpriced MIR body. +Children execute real fixture bytecode with fork-specific gas, precompiles and +journaling. The current MIR runtime's code is unknown, so inspecting or executing +it from a child remains unsupported instead of compiling it through the backend. +Missing creation budgets make a scenario unsupported; an unused suffix is allowed. -/ + +namespace SolarTV.MIR.State +open EvmRules SolarTV.Execution + +abbrev MessageStep := Except String (Outcome (Option Word × Frame) × Nat) + +def external (fuel : Nat) (cfg : Config) (frame : Frame) (opcode : Nat) + (args : List Word) : MessageStep := do + let externalConfig ← required cfg.externalConfig "missing MIR external execution configuration" + if cfg.fork.atLeast .amsterdam then .error "Amsterdam MIR message gas is not modeled" else + match opcode,args with + | 0xf1,_ | 0xf2,_ | 0xf4,_ | 0xfa,_ => + let explicitValue := opcode = 0xf1 || opcode = 0xf2 + if args.length != (if explicitValue then 7 else 6) then + .error "MIR call operand count" else + let gas := args[0]?.getD 0 + let destination := args[1]?.getD 0 + let start := if explicitValue then 3 else 2 + let inputOffset := args[start]?.getD 0 + let inputSize := args[start + 1]?.getD 0 + let outputOffset := args[start + 2]?.getD 0 + let outputSize := args[start + 3]?.getD 0 + let amount := if opcode = 0xf1 || opcode = 0xf2 then args[2]?.getD 0 else 0 + let kind := if opcode = 0xf1 then Calls.Kind.call else if opcode = 0xf2 then .callcode + else if opcode = 0xf4 then .delegatecall else .staticcall + if cfg.environment.isStatic && kind == .call && amount != 0 then return (.invalid,0) else + if gas.toNat > 30000000 then .error "MIR requested child gas exceeds 30000000" else + let memory ← expand frame.memory inputOffset.toNat inputSize.toNat + let memory ← expand memory outputOffset.toNat outputSize.toNat + let (code,_,world) := EVM.State.executionCode cfg.fork frame.world (destination.setWidth 160) + let message := ⟨kind,destination.setWidth 160,amount,readBytes memory inputOffset.toNat inputSize.toNat⟩ + let child ← EVM.State.executeCall (EVM.State.run fuel externalConfig) externalConfig world + cfg.environment message code (gas.toNat + if Calls.hasValue message then 2300 else 0) + let next := {frame with + world := child.world + memory := writeBytes memory outputOffset.toNat (child.data.take outputSize.toNat) + returnData := child.data} + return (.returned (some child.value,next),child.work) + | 0xf0,[amount,offset,size] | 0xf5,[amount,offset,size,_] => + if cfg.environment.isStatic then return (.invalid,0) else + if cfg.fork.atLeast .shanghai && size.toNat > 49152 then return (.invalid,0) else + let supplied ← required cfg.creationGas[frame.creationIndex]? "missing MIR creation gas budget" + let memory ← expand frame.memory offset.toNat size.toNat + let salt := if opcode = 0xf5 then args[3]? else none + let child ← EVM.State.executeCreation (EVM.State.run fuel externalConfig) externalConfig frame.world + cfg.environment salt amount (readBytes memory offset.toNat size.toNat) supplied + return (.returned (some child.value,{frame with + world := child.world + memory + returnData := child.data + creationIndex := frame.creationIndex + 1}),child.work) + | _,_ => .error "unmodeled MIR external message or operand count" + +end SolarTV.MIR.State diff --git a/tv/SolarTV/MIR/State/Normalize.lean b/tv/SolarTV/MIR/State/Normalize.lean new file mode 100644 index 00000000..41c93167 --- /dev/null +++ b/tv/SolarTV/MIR/State/Normalize.lean @@ -0,0 +1,42 @@ +import SolarTV.MIR.State.Interpreter +import Lean + +/-! Proof-producing execution of one known MIR control position at a time. +The simplifier must not unfold recursive execution under an unknown continuation: +that expands the work budget rather than the program's actual path. Each rewrite +uses a proved transition equation and kernel-checkable reduction of that finite +step. Symbolic branches expose one layer; unknown control positions stay opaque. +No VM/native evaluation, rewrite-name recognition or accepted-result axiom is used. -/ + +namespace SolarTV.MIR.State +open Lean Meta Simp + +simproc_decl reduceRun (run _ _ _ _) := fun expression => do + let args := expression.getAppArgs + let some fuel ← getNatValue? args[0]! | return .continue + if fuel = 0 then return .done {expr := ← whnf expression} + let machine ← whnf args[3]! + unless machine.isAppOf ``Machine.mk do return .continue + let cursor ← whnf machine.getAppArgs[0]! + unless cursor.isAppOf ``Cursor.mk do return .continue + for index in [0,1,2] do + unless (← getNatValue? (← withTransparency .default (whnf cursor.getAppArgs[index]!))).isSome do return .continue + let step ← mkAppM ``transition #[toExpr (fuel - 1),args[1]!,args[2]!,args[3]!] + let reduction ← simp step + let reduced ← whnf reduction.expr + let proof ← reduction.getProof + let parameters := #[toExpr (fuel - 1),args[1]!,args[2]!,args[3]!] + let equation ← if reduced.isAppOf ``Except.error then + pure (mkAppN (mkConst ``run_error) (parameters ++ #[reduced.appArg!,proof])) + else if reduced.isAppOf ``Except.ok then + let signal ← whnf reduced.appArg! + if signal.isAppOf ``Transition.next then + pure (mkAppN (mkConst ``run_next) (parameters ++ signal.getAppArgs ++ #[proof])) + else if signal.isAppOf ``Transition.finished then + pure (mkAppN (mkConst ``run_finished) (parameters ++ #[signal.appArg!,proof])) + else mkAppM ``run_one parameters + else mkAppM ``run_one parameters + let rhs := (← inferType equation).appArg! + return .visit {expr := rhs,proof? := some equation} + +end SolarTV.MIR.State diff --git a/tv/SolarTV/MIR/State/Observe.lean b/tv/SolarTV/MIR/State/Observe.lean new file mode 100644 index 00000000..8a1fdcff --- /dev/null +++ b/tv/SolarTV/MIR/State/Observe.lean @@ -0,0 +1,80 @@ +import SolarTV.MIR.State.Interpreter +import Lean.Data.Json + +/-! Observable direct MIR effects at the selected boundary. A normal internal +return exposes all live memory and transient storage to its caller. STOP/raw +RETURN end the transaction, so private memory and transient storage disappear. +Revert/exception roll back state and expose no memory. No gas placeholders or +backend image hashes are part of this observation. Model errors on either side +exclude a proof, including identical nontermination or resource exhaustion. A source +run that fails an `assume` is undefined and constrains no completed target run. -/ + +namespace SolarTV.MIR.State +open EvmRules SolarTV.Execution + +structure Observation where + status : String + values : List Word + data : List Byte + memory : Option (List Byte) + accounts : List Account + logs : List World.Log + returnData : List Byte + warmAddresses : List Address + warmSlots : List (Address × Word) + deriving DecidableEq + +def observe (result : Result) : Observation := + let (status,values,data,memory,keepTransient) := match result.completion with + | .returned values => ("return",values,[],some result.memory,true) + | .success data => ("success",[],data,none,false) + | .reverted data => ("revert",[],data,none,false) + | .invalid => ("exception",[],[],none,false) + | .undefined => ("undefined",[],[],none,false) + let accounts := result.world.accounts.map fun a => {a with + storage := normalizedSlots a.storage + transient := if keepTransient then normalizedSlots a.transient else [] + created := keepTransient && a.created + destroyed := keepTransient && a.destroyed} + ⟨status,values,data,memory,ordered (fun a b => a.address.ule b.address) accounts,result.world.logs, + if keepTransient then result.returnData else [], + if keepTransient then ordered (fun a b => a.ule b) result.world.warmAddresses.eraseDups else [], + if keepTransient then ordered (fun a b => if a.1 == b.1 then a.2.ule b.2 else a.1.ule b.1) result.world.warmSlots.eraseDups else []⟩ + +/-- The target refines the source: equal observations, unless the source run is undefined (a +failed `assume`), which any target run that completes refines. An undefined target run observes +as `undefined`, which no defined source run observes, so it never refines one. -/ +def equivalent (before after : Run) : Prop := + match before,after with + | .ok a,.ok b => a.completion = .undefined ∨ observe a = observe b + | _,_ => False + +instance (a b : Run) : Decidable (equivalent a b) := by + unfold equivalent + split <;> infer_instance + +private def wordJson (v : Word) : Lean.Json := .str (toString v.toNat) +private def bytesJson (bytes : List Byte) : Lean.Json := + .arr (bytes.map (fun b => Lean.toJson b.toNat)).toArray +private def slotsJson (slots : Slots) : Lean.Json := + .arr (slots.map (fun (k,v) => Lean.Json.arr #[wordJson k,wordJson v])).toArray + +def describe (result : Run) : String := + match result with + | .error reason => "unsupported: " ++ reason + | .ok result => + let o := observe result + (Lean.Json.mkObj [ + ("returndata",bytesJson o.returnData), + ("warm_addresses",.arr (o.warmAddresses.map (fun a => .str (toString a.toNat))).toArray), + ("warm_slots",.arr (o.warmSlots.map (fun (a,k) => Lean.Json.arr #[.str (toString a.toNat),wordJson k])).toArray), + ("outcome",.str o.status), ("values",.arr (o.values.map wordJson).toArray), + ("data",bytesJson o.data), ("memory",o.memory.map bytesJson |>.getD .null), + ("accounts",.arr (o.accounts.map (fun a => Lean.Json.arr #[ + .str (toString a.address.toNat),.str (toString a.nonce),wordJson a.balance, + bytesJson a.code,slotsJson a.storage,slotsJson a.transient,Lean.toJson a.created,Lean.toJson a.destroyed])).toArray), + ("logs",.arr (o.logs.map (fun l => Lean.Json.arr #[ + .str (toString l.address.toNat),.arr (l.topics.map wordJson).toArray,bytesJson l.data])).toArray) + ]).compress + +end SolarTV.MIR.State diff --git a/tv/SolarTV/MIR/State/Ops.lean b/tv/SolarTV/MIR/State/Ops.lean new file mode 100644 index 00000000..2db95d91 --- /dev/null +++ b/tv/SolarTV/MIR/State/Ops.lean @@ -0,0 +1,162 @@ +import SolarTV.MIR.State.Allocation +import SolarTV.MIR.State.Aggregates +import SolarTV.Keccak + +/-! Direct MIR scalar and state-operation semantics. Typed arithmetic reuses MIR's +width-polymorphic definitions. Memory is byte-addressed and storage is qualified +by its owner in the shared journal. Static violations are exceptional halts. +This layer assigns no physical stack, frame placement, implicit FMP setup or EVM +gas cost. Memory/work bounds are model errors, not program outcomes. -/ + +namespace SolarTV.MIR.State +open EvmRules SolarTV.Execution + +def value (frame : Frame) (word : Word) : Step := .ok (.returned (some word,frame)) +def effect (frame : Frame) : Step := .ok (.returned (none,frame)) + +private def checkedResult (frame : Frame) (result : Outcome (BitVec width)) : Step := + .ok (match result with + | .returned v => .returned (some (v.setWidth 256),frame) + | .reverted data => .reverted data + | .invalid => .invalid) + +def memoryOperation (cfg : Config) (frame : Frame) (op : MemoryOp) (args : List Word) : Step := do + match op,args with + | .size,[] => value frame (BitVec.ofNat 256 frame.memory.length) + | .returnDataSize,[] => value frame (BitVec.ofNat 256 frame.returnData.length) + | .returnDataCopy,[destination,source,count] => + if source.toNat + count.toNat > frame.returnData.length then return .invalid + else + let memory ← expand frame.memory destination.toNat count.toNat + effect {frame with memory := writeBytes memory destination.toNat (readBytes frame.returnData source.toNat count.toNat)} + | .calldataSize,[] => value frame (BitVec.ofNat 256 cfg.environment.input.length) + | .calldataLoad,[offset] => value frame (readWord cfg.environment.input offset.toNat) + | .load,[offset] => + let memory ← expand frame.memory offset.toNat 32 + value {frame with memory} (readWord memory offset.toNat) + | .store,[offset,word] | .storeByte,[offset,word] => + let bytes := match op with | .storeByte => [word.setWidth 8] | _ => wordBytes word + let memory ← expand frame.memory offset.toNat bytes.length + effect {frame with memory := writeBytes memory offset.toNat bytes} + | .copy,[destination,source,size] | .calldataCopy,[destination,source,size] => + let memory ← expand frame.memory destination.toNat size.toNat + let memory ← match op with | .copy => expand memory source.toNat size.toNat | _ => pure memory + let sourceBytes := match op with | .copy => memory | _ => cfg.environment.input + effect {frame with memory := writeBytes memory destination.toNat (readBytes sourceBytes source.toNat size.toNat)} + | .zero,[offset,size] => + let memory ← expand frame.memory offset.toNat size.toNat + effect {frame with memory := writeBytes memory offset.toNat (List.replicate size.toNat 0)} + | .hash,[offset,size] => + let memory ← expand frame.memory offset.toNat size.toNat + value {frame with memory} (Keccak.hash (readBytes memory offset.toNat size.toNat)) + | _,_ => .error "MIR memory operand count" + +def storageOperation (cfg : Config) (frame : Frame) (transient write : Bool) (args : List Word) : Step := do + let owner := cfg.environment.address + let old := account frame.world owner + let slots := if transient then old.transient else old.storage + match write,args with + | false,[key] => value (if transient then frame else + {frame with world := warmSlot frame.world owner key}) (slotsRead slots key) + | true,[key,word] => + if cfg.environment.isStatic then return .invalid + let updated := slotsWrite slots key word + let world := putAccount (if transient then frame.world else warmSlot frame.world owner key) + (if transient then {old with transient := updated} else {old with storage := updated}) + effect {frame with world} + | _,_ => .error "MIR storage operand count" + +def contextOperation (cfg : Config) (frame : Frame) (opcode : Nat) (args : List Word) : Step := + match opcode,args with + | 0x30,[] => value frame (cfg.environment.address.setWidth 256) + | 0x32,[] => value frame (cfg.environment.origin.setWidth 256) + | 0x33,[] => value frame (cfg.environment.caller.setWidth 256) + | 0x34,[] => value frame cfg.environment.value + | 0x3a,[] => value frame cfg.environment.gasPrice + | 0x47,[] => value frame (account frame.world cfg.environment.address).balance + | 0x40,[argument] | 0x49,[argument] => value frame (Execution.environmentValue cfg.fork cfg.context opcode argument) + | 0x41,[] | 0x42,[] | 0x43,[] | 0x44,[] | 0x45,[] | 0x46,[] | 0x48,[] | 0x4a,[] | 0x4b,[] => + value frame (Execution.environmentValue cfg.fork cfg.context opcode 0) + | _,_ => .error "unmodeled MIR context read" + +def operation (cfg : Config) (frame : Frame) (op : Operation) (args : List Word) : Step := do + match op,args with + | .binary op width,[a,b] => value frame (widenBits (MIR.eval op (wordBits width a) (wordBits width b))) + | .comparison op width,[a,b] => value frame (widenBits (MIR.compare op (wordBits width a) (wordBits width b))) + | .unary op width,[a] => value frame (widenBits (MIR.unary op (wordBits width a))) + | .shift op width,[amount,v] => value frame (widenBits (MIR.shift op (wordBits width v) (wordBits width amount))) + | .wordBinary op,[a,b] => value frame (MIR.wordBinary op a b) + | .ternary op,[a,b,c] => value frame (MIR.ternary op a b c) + | .word,[a] => value frame a + | .freePointer,[] => freePointer frame + | .allocate zeroed checked,[size] => allocate frame size zeroed checked + | .insertValue ..,_ | .extractValue ..,_ | .makeSlice ..,_ => .error "aggregate operation needs typed operands" + | .external _,_ => .error "external instruction requires MIR machine context" + | .call _,_ => .error "internal call requires MIR machine context" + | .pointerAdd,[pointer,offset] => value frame (pointer + offset) + | .lowBits width,[a] => value frame (narrow width a) + | .signExtend source target,[a] => value frame (((a.setWidth source).signExtend target).setWidth 256) + | .notEqual,[a,b] => value frame (if a = b then 0 else 1) + | .select,[c,a,b] => value frame (if c = 0 then b else a) + | .checked op width signed,[a,b] => checkedResult frame (MIR.checked op signed (wordBits width a) (wordBits width b)) + | .checkedPower width signed,[a,b] => checkedResult frame (MIR.checkedPower signed (wordBits width a) b.toNat) + | .check zero panic,[condition] => + if (condition == 0) == zero then + return .reverted (match panic with | none => .empty | some code => .panic code) + else effect frame + | .memory op,args => memoryOperation cfg frame op args + | .storage transient write,args => storageOperation cfg frame transient write args + | .environment opcode,args => contextOperation cfg frame opcode args + | .log count,offset :: size :: topics => + if count != topics.length then .error "MIR log topic count" else + if cfg.environment.isStatic then return .invalid else + let memory ← expand frame.memory offset.toNat size.toNat + effect {frame with memory, world := {frame.world with logs := frame.world.logs ++ + [⟨cfg.environment.address,topics,readBytes memory offset.toNat size.toNat⟩]}} + | _,_ => .error "MIR operation operand count" + +def assignValue (next : Frame) (result : Option Nat) (ty : ValueType) (value : Value) : Step := do + let some id := result | .error "MIR result arity mismatch" + if !value.fits 34 ty then .error "MIR result type mismatch" else + effect {next with locals := put next.locals id value} + +def assign (next : Frame) (result : Option Nat) (ty : ValueType) (word : Option Word) : Step := do + match result,word with + | none,none => effect next + | some _,some word => + if ty.width = 0 || ty.width > 256 then .error "unmodeled MIR result type" else + assignValue next result ty (.scalar (Scalar.ofWord ty.width word)) + | _,_ => .error "MIR result arity mismatch" + +def instruction (cfg : Config) (frame : Frame) (inst : Instruction) : Step := do + if inst.opcode.any (fun opcode => !cfg.available.contains opcode) then return .invalid + match inst.operation,inst.operands with + | .insertValue ty index,[aggregate,field] => + let aggregate ← readValue frame aggregate + let value ← readValue frame field + let updated ← insertField ty aggregate index value + assignValue frame inst.result inst.ty updated + | .extractValue ty index,[aggregate] => + let aggregate ← readValue frame aggregate + let value ← extractField ty aggregate index + assignValue frame inst.result inst.ty value + | .makeSlice location,[pointer,length] => + let pointer ← read frame pointer + let length ← read frame length + if !(inst.ty.same (.slice location)) then .error "MIR slice location mismatch" else + assignValue frame inst.result inst.ty (.aggregate [ + .scalar (Scalar.ofWord 256 pointer),.scalar (Scalar.ofWord 256 length)]) + | .select,[condition,yes,no] => + let condition ← read frame condition + let yes ← readValue frame yes + let no ← readValue frame no + assignValue frame inst.result inst.ty (if condition = 0 then no else yes) + | _,_ => + let args ← inst.operands.mapM (read frame) + let result ← operation cfg frame inst.operation args + match result with + | .returned (word,next) => assign next inst.result inst.ty word + | .reverted data => return .reverted data + | .invalid => return .invalid + +end SolarTV.MIR.State diff --git a/tv/SolarTV/MIR/State/Safety.lean b/tv/SolarTV/MIR/State/Safety.lean new file mode 100644 index 00000000..ae38af84 --- /dev/null +++ b/tv/SolarTV/MIR/State/Safety.lean @@ -0,0 +1,59 @@ +import SolarTV.MIR.State.Observe + +/-! Executable semantic invariants for the direct MIR interpreter. Phi operands +are simultaneous even on cyclic edges; work limits cannot establish equivalence. +Normal returns expose memory and transient cells, unlike transaction termination. +A failed `assume` is undefined: it admits any completed target but is never one. +These checks do not invoke the backend or its physical frame conventions. -/ + +namespace SolarTV.MIR.State +open EvmRules SolarTV.Execution + +theorem work_limit_is_not_equivalence (reason : String) (other : Run) : + ¬ equivalent (.error reason) other := by + simp [equivalent] + +theorem simultaneous_phis : + ((enter (some 1) + [⟨0,.word 256,[(1,⟨.local 1,.word 256⟩)]⟩,⟨1,.word 256,[(1,⟨.local 0,.word 256⟩)]⟩] + ⟨⟨[],[],[],[],[],0⟩,[],[],[(0,.scalar ⟨256,7⟩),(1,.scalar ⟨256,9⟩)],[],0⟩).map (·.locals)) = + .ok [(1,.scalar ⟨256,7⟩),(0,.scalar ⟨256,9⟩)] := by with_unfolding_all rfl + +theorem live_memory_is_observable : + ¬ equivalent + (.ok ⟨.returned [],⟨[],[],[],[],[],0⟩,[],[],0⟩) + (.ok ⟨.returned [],⟨[],[],[],[],[],0⟩,[1],[],0⟩) := by decide +kernel + +theorem live_transient_is_observable : + ¬ equivalent + (.ok ⟨.returned [],⟨[{address:=1}],[],[],[],[],0⟩,[],[],0⟩) + (.ok ⟨.returned [],⟨[{address:=1,transient:=[(0,7)]}],[],[],[],[],0⟩,[],[],0⟩) := by decide +kernel + +theorem live_return_data_is_observable : + ¬ equivalent + (.ok ⟨.returned [],⟨[],[],[],[],[],0⟩,[],[1],0⟩) + (.ok ⟨.returned [],⟨[],[],[],[],[],0⟩,[],[2],0⟩) := by decide +kernel + +theorem undefined_target_is_not_equivalence : + ¬ equivalent + (.ok ⟨.returned [],⟨[],[],[],[],[],0⟩,[],[],0⟩) + (.ok ⟨.undefined,⟨[],[],[],[],[],0⟩,[],[],0⟩) := by decide +kernel + +theorem undefined_source_admits_any_completion : + equivalent + (.ok ⟨.undefined,⟨[],[],[],[],[],0⟩,[],[],0⟩) + (.ok ⟨.returned [7],⟨[],[],[],[],[],0⟩,[],[],0⟩) := by decide +kernel + +theorem undefined_source_does_not_admit_model_errors (reason : String) : + ¬ equivalent (.ok ⟨.undefined,⟨[],[],[],[],[],0⟩,[],[],0⟩) (.error reason) := by + simp [equivalent] + +theorem failed_assume_is_undefined (cfg : Config) : + (transition 1 cfg + [(0,⟨[],[],[⟨[],[⟨none,.word 256,none,.assume .eq, + [⟨.constant (.ofWord 256 1),.word 256⟩,⟨.constant (.ofWord 256 2),.word 256⟩]⟩],.stop⟩]⟩)] + ⟨{function := 0,entered := true},[],⟨⟨[],[],[],[],[],0⟩,[],[],[],[],0⟩⟩).map + (fun | .finished r => some r.completion | .next .. => none) = .ok (some .undefined) := by + with_unfolding_all rfl + +end SolarTV.MIR.State diff --git a/tv/SolarTV/MIR/State/Values.lean b/tv/SolarTV/MIR/State/Values.lean new file mode 100644 index 00000000..b9037308 --- /dev/null +++ b/tv/SolarTV/MIR/State/Values.lean @@ -0,0 +1,121 @@ +import SolarTV.MIR.Ops + +/-! Logical typed SSA values. Products and slices are immutable trees, not memory +objects or backend word layouts. Undefined fields stay undefined until replaced; +projecting another field does not read them. An undefined scalar cannot determine +control flow, an effect or a returned observable. At the selected function boundary +only, products are flattened in declaration order to compare type-lowering passes. +Type depth/node limits are importer resource limits, never execution assumptions. -/ + +namespace SolarTV.MIR.State +open EvmRules + +structure Scalar where + width : Nat + bits : BitVec width + +def wordBits (width : Nat) (value : Word) : BitVec width := + if h : width = 256 then value.cast h.symm else value.setWidth width + +def widenBits {width : Nat} (value : BitVec width) : Word := + if h : width = 256 then value.cast h else value.setWidth 256 + +def Scalar.word (value : Scalar) : Word := widenBits value.bits + +def Scalar.ofWord (width : Nat) (value : Word) : Scalar := ⟨width,wordBits width value⟩ + +/-- Full-width boxing is identity, including before dependent casts are unfolded. -/ +@[simp↓] theorem scalar_word_full (word : Word) : + (Scalar.mk 256 word).word = word := by rfl + +@[simp↓] theorem wordBits_full (word : Word) : wordBits 256 word = word := by rfl + +@[simp↓] theorem widenBits_full (word : Word) : widenBits word = word := by rfl + +inductive ValueType where + | word (width : Nat) + | pointer (location : Nat) + | product (fields : List ValueType) + | slice (location : Nat) + +mutual + def ValueType.same (a b : ValueType) : Bool := + match a,b with + | .word a,.word b | .pointer a,.pointer b | .slice a,.slice b => a == b + | .product a,.product b => sameTypes a b + | _,_ => false + termination_by sizeOf a + + def sameTypes (a b : List ValueType) : Bool := + match a,b with + | [],[] => true + | a :: rest,b :: tail => a.same b && sameTypes rest tail + | _,_ => false + termination_by sizeOf a +end + + +def ValueType.width : ValueType → Nat + | .word width => width + | .pointer _ => 256 + | _ => 0 + +def ValueType.fields : ValueType → Option (List ValueType) + | .product fields => some fields + | .slice location => some [.pointer location,.word 256] + | _ => none + +inductive Value where + | scalar (value : Scalar) + | aggregate (fields : List Value) + | undefined + +/-- Undefined components may be copied, but never silently materialized as zero. -/ +def Value.fits : Nat → ValueType → Value → Bool + | 0,_,_ => false + | _ + 1,_,.undefined => true + | _ + 1,ty,.scalar value => ty.width > 0 && ty.width ≤ 256 && ty.width == value.width + | fuel + 1,ty,.aggregate values => + match ty.fields with + | none => false + | some types => types.length == values.length && + (types.zip values).all (fun (ty,value) => value.fits fuel ty) + +/-- Scalars alone may feed word operations. Pointer bits carry no validity proof. -/ +def Value.word : Value → Except String Word + | .scalar value => .ok value.word + | .undefined => .error "undefined MIR scalar operand" + | _ => .error "aggregate MIR operand used as a scalar" + +/-- Only complete, defined logical leaves are exposed at the function boundary. -/ +def Value.flatten : Nat → ValueType → Value → Except String (List Word) + | 0,_,_ => .error "MIR aggregate type depth limit" + | fuel + 1,ty,value => do + match ty.fields with + | none => return [← value.word] + | some types => + let values ← match value with + | .undefined => pure (List.replicate types.length Value.undefined) + | .aggregate values => pure values + | _ => .error "MIR aggregate return shape mismatch" + if types.length != values.length then .error "MIR aggregate return arity" else + return (← (types.zip values).mapM (fun (ty,value) => value.flatten fuel ty)).flatten + +/-- Normalize value conditionals without distributing the whole execution state. -/ +@[simp↓] theorem fits_ite (fuel : Nat) (ty : ValueType) (p : Prop) [Decidable p] (a b : Value) : + (if p then a else b).fits fuel ty = (if p then a.fits fuel ty else b.fits fuel ty) := by + split <;> rfl + +@[simp↓] theorem word_ite (p : Prop) [Decidable p] (a b : Value) : + (if p then a else b).word = (if p then a.word else b.word) := by + split <;> rfl + +@[simp↓] theorem flatten_ite (fuel : Nat) (ty : ValueType) (p : Prop) [Decidable p] (a b : Value) : + (if p then a else b).flatten fuel ty = (if p then a.flatten fuel ty else b.flatten fuel ty) := by + split <;> rfl + +@[simp↓] theorem except_ok_ite (p : Prop) [Decidable p] (a b : α) : + (if p then Except.ok a else Except.ok b : Except ε α) = .ok (if p then a else b) := by + split <;> rfl + +end SolarTV.MIR.State diff --git a/tv/SolarTV/MIR/Transforms/Casts.lean b/tv/SolarTV/MIR/Transforms/Casts.lean new file mode 100644 index 00000000..c94c45b0 --- /dev/null +++ b/tv/SolarTV/MIR/Transforms/Casts.lean @@ -0,0 +1,42 @@ +import SolarTV.MIR.Ops +import SolarTV.MIR.Program + +/-! Integer cleanup can remove a truncation after a lossless zero extension. +The concrete i160/i256 theorem also checks the native bit-vector width model. +The i1 examples pin the difference between truncation and boolean normalization, +and between sign and zero extension. The last two relate the lowered MIR semantics' casts +to these. -/ + +namespace SolarTV.MIR + +theorem truncate_extended_address (value : BitVec 160) : + cast .trunc 160 (cast .zext 256 value) = value := by + simp [cast] + +theorem truncate_even_word : cast .trunc 1 (2#256) = 0#1 := by decide + +theorem extend_true_sign : cast .sext 256 (1#1) = -1#256 := by decide + +theorem extend_true_zero : cast .zext 256 (1#1) = 1#256 := by decide + +/-- The lowered semantics' truncation, `low`, is the typed one extended back to a word. -/ +theorem lowBits_eq_trunc (bits : Nat) (le : bits ≤ 256) (w : BitVec 256) : + Lowered.lowBits bits w = cast .zext 256 (cast .trunc bits w) := by + apply BitVec.eq_of_toNat_eq + have hp : 2 ^ bits ≤ 2 ^ 256 := Nat.pow_le_pow_right (by decide) le + have hpos : 0 < 2 ^ bits := Nat.two_pow_pos _ + simp only [Lowered.lowBits, EvmRules.Evm.and, cast, BitVec.toNat_and, BitVec.toNat_setWidth, + BitVec.toNat_ofNat] + rw [Nat.mod_eq_of_lt (show 2 ^ bits - 1 < 2 ^ 256 by omega), Nat.and_two_pow_sub_one_eq_mod] + rw [Nat.mod_eq_of_lt (show w.toNat % 2 ^ bits < 2 ^ 256 by + exact Nat.lt_of_lt_of_le (Nat.mod_lt _ hpos) hp)] + +/-- The lowered semantics leaves a zero extension's word as it is (`word`), which is the typed +extension on every word whose bits above the source width are zero, as every MIR value's are. -/ +theorem word_eq_zext (bits : Nat) (w : BitVec 256) (clean : w.toNat < 2 ^ bits) : + w = cast .zext 256 (cast .trunc bits w) := by + apply BitVec.eq_of_toNat_eq + simp only [cast, BitVec.toNat_setWidth] + rw [Nat.mod_eq_of_lt clean, Nat.mod_eq_of_lt w.isLt] + +end SolarTV.MIR diff --git a/tv/SolarTV/MIR/Transforms/CheckElim.lean b/tv/SolarTV/MIR/Transforms/CheckElim.lean new file mode 100644 index 00000000..94021788 --- /dev/null +++ b/tv/SolarTV/MIR/Transforms/CheckElim.lean @@ -0,0 +1,19 @@ +import SolarTV.MIR.Ops + +/-! A dominating bound makes the unsigned increment's overflow check redundant. +The operation otherwise retains its defined Panic(0x11) outcome; it is never +modeled as undefined behavior merely because a check fails. -/ + +namespace SolarTV.MIR + +theorem increment_below_bound (value : BitVec 256) (bound : value.ult 100 = true) : + checked .add false value 1 = Outcome.returned (value + 1) := by + have h : value.toNat < 100 := by simpa [BitVec.ult_iff_toNat_lt] using bound + simp [checked, BitVec.uaddOverflow] <;> omega + +/-- Replacing a defined failure by success fails refinement in either direction. -/ +theorem cannot_drop_overflow : + ¬ refines (checked .add false (-1#256) 1) (Outcome.returned (0#256)) := by + simp [checked, BitVec.uaddOverflow] + +end SolarTV.MIR diff --git a/tv/SolarTV/MIR/Transforms/DCE.lean b/tv/SolarTV/MIR/Transforms/DCE.lean new file mode 100644 index 00000000..f293f98f --- /dev/null +++ b/tv/SolarTV/MIR/Transforms/DCE.lean @@ -0,0 +1,18 @@ +import SolarTV.MIR.Ops + +/-! MIR dead-code elimination: removing an unused pure SSA definition. -/ + +namespace SolarTV.MIR + +abbrev Env := Nat → EvmRules.Word + +/-- Removing a pure SSA definition preserves any continuation whose live-ins +exclude the defined ID. Both operands already have defined word values. -/ +theorem erase_unused (op : Op) (dst lhs rhs : Nat) (env : Env) (k : Env → α) + (unused : ∀ x y : Env, (∀ i, i ≠ dst → x i = y i) → k x = k y) : + k (fun i => if i = dst then eval op (env lhs) (env rhs) else env i) = k env := by + apply unused + intro i h + simp [h] + +end SolarTV.MIR diff --git a/tv/SolarTV/MIR/Transforms/DeadStore.lean b/tv/SolarTV/MIR/Transforms/DeadStore.lean new file mode 100644 index 00000000..b45dff41 --- /dev/null +++ b/tv/SolarTV/MIR/Transforms/DeadStore.lean @@ -0,0 +1,18 @@ +import SolarTV.Memory + +/-! MIR memory-dse removes a word store overwritten before any read. +The final store has the same range, so it also subsumes the first expansion. +Both the live return and all projected memory bytes remain observable. The +theorem is independent of the incoming bytes, active size and stored values. -/ + +namespace SolarTV.MIR +open EvmRules + +theorem dead_store (memory : Memory.State) (offset : Nat) (a b : Word) + (result : BitVec width) : + refines (Outcome.returned (⟨result, Memory.store (Memory.store memory offset a) offset b⟩ : + Memory.Returned width)) + (Outcome.returned ⟨result, Memory.store memory offset b⟩) := by + simp [refines_iff_eq, Memory.store, Memory.expand] + +end SolarTV.MIR diff --git a/tv/SolarTV/MIR/Transforms/RenamePhiPredecessors.lean b/tv/SolarTV/MIR/Transforms/RenamePhiPredecessors.lean new file mode 100644 index 00000000..1867cf61 --- /dev/null +++ b/tv/SolarTV/MIR/Transforms/RenamePhiPredecessors.lean @@ -0,0 +1,22 @@ +import SolarTV.MIR.Ops + +/-! Phi selection is preserved when CFG labels are renamed injectively. +Actual cfg-simplify pairs can also remove forwarders; the pair checker expands +those paths and checks the resulting phi values against the original graph. -/ + +namespace SolarTV.MIR + +theorem rename_phi_predecessors (rename : Nat → Nat) (injective : Function.Injective rename) + (predecessor : Nat) (incoming : List (Nat × EvmRules.Word)) : + phi (rename predecessor) (incoming.map (fun (block, value) => (rename block, value))) = + phi predecessor incoming := by + induction incoming with + | nil => rfl + | cons entry rest ih => + obtain ⟨block, value⟩ := entry + have same : rename predecessor = rename block ↔ predecessor = block := + ⟨fun h => injective h, congrArg rename⟩ + simp only [List.map_cons, phi, same] + split <;> simp_all + +end SolarTV.MIR diff --git a/tv/SolarTV/MIR/Transforms/TrimSwitchDefaults.lean b/tv/SolarTV/MIR/Transforms/TrimSwitchDefaults.lean new file mode 100644 index 00000000..c54f6108 --- /dev/null +++ b/tv/SolarTV/MIR/Transforms/TrimSwitchDefaults.lean @@ -0,0 +1,47 @@ +import SolarTV.MIR.Ops + +/-! MIR cfg-simplify: trim trailing switch cases that jump to the default target. -/ + +namespace SolarTV.MIR + +/-- One past the last non-default destination, or zero if there is none. +This is the prefix length computed by Rust's `rposition(...).map_or(0, |i| i + 1)`. -/ +def keepLength (fallback : Nat) : List Case → Nat + | [] => 0 + | (_, dst) :: rest => + match keepLength fallback rest with + | 0 => if dst = fallback then 0 else 1 + | n + 1 => n + 2 + +theorem trim_preserves_dispatch (read : Nat → EvmRules.Word) (key : EvmRules.Word) + (fallback : Nat) (cases : List Case) : + dispatch read key fallback (cases.take (keepLength fallback cases)) = + dispatch read key fallback cases := by + induction cases with + | nil => rfl + | cons c rest ih => + obtain ⟨id, dst⟩ := c + cases h : keepLength fallback rest with + | zero => + simp [h, dispatch] at ih + by_cases hd : dst = fallback <;> simp [keepLength, h, hd, dispatch, choose, ← ih] + | succ n => + simp only [keepLength, h, List.take_succ_cons, dispatch] + rw [h] at ih + rw [ih] + +/-- At prefix length zero the pass emits a jump. Both forms carry the same predecessor +and register environment into the successor (in particular for phi selection). -/ +theorem simplify_switch (enter : Nat → Nat → (Nat → EvmRules.Word) → α) + (pred fallback : Nat) (read : Nat → EvmRules.Word) (key : EvmRules.Word) (cases : List Case) : + enter pred (if keepLength fallback cases = 0 then fallback + else dispatch read key fallback (cases.take (keepLength fallback cases))) read = + enter pred (dispatch read key fallback cases) read := by + have h := trim_preserves_dispatch read key fallback cases + split + · next hz => + simp [hz, dispatch] at h + exact congrArg (fun dst => enter pred dst read) h + · rw [h] + +end SolarTV.MIR diff --git a/tv/SolarTV/MIR/Validation/AddZero.lean b/tv/SolarTV/MIR/Validation/AddZero.lean new file mode 100644 index 00000000..bf4b040f --- /dev/null +++ b/tv/SolarTV/MIR/Validation/AddZero.lean @@ -0,0 +1,107 @@ +import SolarTV.Composition +import SolarTV.Agreement.Encoder + +/-! Lifting one pass validation query to a stage. + +`tests/ui/codegen/mir/validate-passes/lift_egraph.mir` runs `egraph` on a dispatcher that +reads a calldata word, adds zero to it, shifts one left by it and stores the result: +`egraph` drops the addition. `Query` is the query `-Zvalidate-passes` writes for that +rewrite, stated as the certifier translates it (`crates/smt/src/certify/lean.rs`), and +`query_unsat` proves it. `certified_of_query` then proves, using the query only as a +hypothesis, that the function after the pass is certified against the one before: it runs +both, rewrites their words with the agreement theorems `step_add` and `step_shl` into the +query's terms, and instantiates the query's uninterpreted calldata read, memory, storage +and transient storage with the call's calldata and the initial state. `stage` is the +resulting stage of the lowered MIR semantics. This is one instance, not a general +theorem that every `unsat` query gives a certificate. -/ + +namespace SolarTV.MIR.Validation.AddZero + +open EvmRules Machine MIR.Lowered + +/-- `bb0: v0 = calldataload 0; v1 = add v0, 0; v2 = shl 1, v1; sstore 0, v2; stop`, with +operands in pop order. -/ +def before : Function where + blocks := [⟨[], [.effect (some 0) .calldataload [.const 0], .pure 1 .add [.value 0, .const 0], + .pure 2 .shl [.value 1, .const 1], .effect none .sstore [.const 0, .value 2]], .stop⟩] + +/-- `bb0: v0 = calldataload 0; v2 = shl 1, v0; sstore 0, v2; stop`. -/ +def after : Function where + blocks := [⟨[], [.effect (some 0) .calldataload [.const 0], + .pure 2 .shl [.value 0, .const 1], .effect none .sstore [.const 0, .value 2]], .stop⟩] + +/-- An SMT-LIB array store, as the certifier defines it. -/ +def store {a b : Nat} (m : BitVec a → BitVec b) (i : BitVec a) (v : BitVec b) : + BitVec a → BitVec b := + fun j => if j = i then v else m j + +-- The certifier also turns off the unused-variable linter. +set_option linter.unusedVariables false in +/-- The `egraph` query for `@entry`, as the certifier states it: its assertions are +contradictory. -/ +def Query : Prop := + ∀ («$input_calldataload_1» : BitVec 256 → BitVec 256) («$mem0» : (BitVec 256 → BitVec 8)) + («$sto0» : (BitVec 256 → BitVec 256)) («$tra0» : (BitVec 256 → BitVec 256)) + («$t0» : BitVec 256) («$t1» : BitVec 256) («$t2» : BitVec 256) + («$s3» : (BitVec 256 → BitVec 256)) («$t4» : BitVec 256) («$s5» : (BitVec 256 → BitVec 256)) + (h0 : («$t0» = («$input_calldataload_1» (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h1 : («$t1» = ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + «$t0»))) + (h2 : («$t2» = (if («$t1» ≥ (0x0000000000000000000000000000000000000000000000000000000000000100#256)) then (0x0000000000000000000000000000000000000000000000000000000000000000#256) else ((0x0000000000000000000000000000000000000000000000000000000000000001#256) <<< «$t1»)))) + (h3 : («$s3» = (store «$sto0» (0x0000000000000000000000000000000000000000000000000000000000000000#256) «$t2»))) + (h4 : («$t4» = (if («$t0» ≥ (0x0000000000000000000000000000000000000000000000000000000000000100#256)) then (0x0000000000000000000000000000000000000000000000000000000000000000#256) else ((0x0000000000000000000000000000000000000000000000000000000000000001#256) <<< «$t0»)))) + (h5 : («$s5» = (store «$sto0» (0x0000000000000000000000000000000000000000000000000000000000000000#256) «$t4»))) + (h6 : (¬(«$s3» = «$s5»))), + False + +/-- The certifier's `bv_decide` proof does not reach a top-level array disequality, so the +query is proved by hand: adding zero changes nothing. -/ +theorem query_unsat : Query := by + intro _ _ sto0 _ t0 t1 t2 s3 t4 s5 _ h1 h2 h3 h4 h5 h6 + apply h6 + rw [h3, h5, h2, h4, h1, BitVec.zero_add] + +/-- The state the function ends in, writing `value` to slot zero. -/ +def ended (call : Call) (value : Word) : Halt × State := + (.stop, { State.initial call with storage := update (State.initial call).storage 0 value }) + +theorem run_before (o : Oracle) (call : Call) (n : Nat) : + run o before call (n + 1) = some (ended call + (if calldataWord call 0 + 0 ≥ 256#256 then 0#256 else 1#256 <<< (calldataWord call 0 + 0))) := by + rw [before, run_straight] + simp only [execInsts, Operand.eval, List.map, Effect.apply, evalPure, Agreement.step_add, + Agreement.step_shl, Env.set, ↓reduceIte] + rfl + +theorem run_after (o : Oracle) (call : Call) (n : Nat) : + run o after call (n + 1) = some (ended call + (if calldataWord call 0 ≥ 256#256 then 0#256 else 1#256 <<< calldataWord call 0)) := by + rw [after, run_straight] + simp only [execInsts, Operand.eval, List.map, Effect.apply, evalPure, Agreement.step_shl, + Env.set, ↓reduceIte] + rfl + +theorem certified_of_query (query : Query) (o : Oracle) (scope : Call → Prop) : + Certified layer layer o before after scope := by + apply Certified.of_fuel + intro call _ n r ran + cases n with + | zero => simp [layer, run, iterate] at ran + | succ n => + simp only [layer, run_before] at ran + cases ran + refine ⟨1, _, run_after o call 0, ?_⟩ + simp only [ended, Agree, true_and, and_true] + -- The query's array disequality, at the call's calldata and initial storage. + refine Classical.byContradiction fun differ => query (calldataWord call) (fun _ => 0) + (State.initial call).storage (State.initial call).transient (calldataWord call 0) + (0 + calldataWord call 0) _ _ _ _ rfl rfl rfl rfl rfl rfl ?_ + intro same + apply differ + simp only [BitVec.add_comm (calldataWord call 0) 0] + exact same + +theorem stage (o : Oracle) (scope : Call → Prop) : + Stage (sem o) (sem o) before after scope := + stage_of_certified (certified_of_query query_unsat o scope) + +end SolarTV.MIR.Validation.AddZero diff --git a/tv/SolarTV/Machine.lean b/tv/SolarTV/Machine.lean new file mode 100644 index 00000000..f1e03110 --- /dev/null +++ b/tv/SolarTV/Machine.lean @@ -0,0 +1,672 @@ +import SolarTV.Sem +import SolarTV.Memory + +/-! The machine state MIR and EVM IR programs share, and the semantics of a layer. + +Memory is the model of [Memory.lean](Memory.lean) on every byte: its active-word count, +expansion through `Memory.grow` with natural-number offsets, its `MSIZE` formula and +`Memory.byte` order. `Mem.project` is its 256-byte `Memory.State`, and the `project_` +lemmas show that every operation agrees with it there. Storage and transient storage +are total maps. The world is the history of the logs and calls the frame made, and of its +`GAS` reads. `CALLDATACOPY` and `MCOPY` write memory as `Mem.write`, after the expansion +of every range they touch, with calldata zero past its end. + +What the frame cannot see is an `Oracle`: environment reads, and the result and the state +after a call, are functions of the world, as the pass validation encoder takes them to be +uninterpreted functions of its world. An external call (`CALL`, `CALLCODE`, `DELEGATECALL`, +`STATICCALL`) records what its callee sees: the gas, address and value words and the input +bytes, with the storage and transient storage it may reenter. Its success flag (0 or 1), the +size and bytes of the return data, and for every call but `STATICCALL` the storage and +transient storage after it are the oracle's, as functions of the world with the call; the +callee cannot touch the caller's memory, so memory only takes the return data at the output +range, at most as many bytes as the return data has, after the expansion of both ranges. +`RETURNDATACOPY` reads the same return data, and copying past its end is an exceptional halt. `KECCAK256` is the oracle's `keccak`, a function of the +hashed bytes alone that every layer shares, so the same bytes hash to the same word. A layer +runs a program on a call with fuel; its `Sem` is fuel-free, the end some fuel reaches. One +frame, no gas: `GAS` is an environment read, but one the world records, so that each read is +a function of a history no other read has and two reads need not agree. A stage then holds for +every gas the frame may have left at each read, as passes may change the gas the code uses; +it needs both programs to read gas in the same order among their logs and calls. An immutable +is a value fixed at deployment: the oracle's environment read `immutable` of its number in the +empty world, the same wherever and whenever the frame reads it. The deployment code writes it +over each of its placeholders, a `PUSH` of zeros in the runtime code, which then pushes the +low `N` bytes of that word (`immutableWord`); a load decodes them as the compiler does +(`ImmutableRead`). The frame's code is such a read too, byte by byte (`code`), which `CODECOPY` +copies like calldata, zero past its end; it holds the program data, +such as the creation code of a contract the frame creates, at the offsets the stages take from +the assembled code. `CREATE` and `CREATE2` record their value, salt, code and state in the world +as a call does, and the new address and the storage after them are the oracle's. -/ + +namespace SolarTV.Machine + +open EvmRules + +/-- Memory on every byte, with the active-word count of `Memory.State`. -/ +structure Mem where + bytes : Nat → Memory.Byte + words : BitVec 251 + +namespace Mem + +def initial : Mem := ⟨fun _ => 0, 0⟩ + +/-- The first 256 bytes and the active size, as the importers model memory. -/ +def project (m : Mem) : Memory.State := ⟨(List.range 256).map m.bytes, m.words⟩ + +def expand (m : Mem) (offset size : Nat) : Mem := + if size = 0 then m + else { m with words := Memory.grow m.words (BitVec.ofNat 251 ((offset + size + 31) / 32)) } + +def msize (m : Mem) : Word := m.words.setWidth 256 <<< 5 + +def read (m : Mem) (offset size : Nat) : List Memory.Byte := + (List.range size).map (fun i => m.bytes (offset + i)) + +def load (m : Mem) (offset : Nat) : Word := + (m.read offset 32).foldl (fun acc b => (acc <<< 8) ||| b.setWidth 256) 0 + +def store (m : Mem) (offset : Nat) (value : Word) : Mem := + expand { m with bytes := fun i => + if offset ≤ i ∧ i < offset + 32 then Memory.byte value (i - offset) else m.bytes i } offset 32 + +def storeByte (m : Mem) (offset : Nat) (value : Word) : Mem := + expand { m with bytes := fun i => if i = offset then value.setWidth 8 else m.bytes i } offset 1 + +/-- `size` bytes of `source` written from `offset`, as a copy writes them. -/ +def write (m : Mem) (offset size : Nat) (source : Nat → Memory.Byte) : Mem := + expand { m with bytes := fun i => + if offset ≤ i ∧ i < offset + size then source (i - offset) else m.bytes i } offset size + +/-- A load reads bytes, which expansion leaves as they are. -/ +theorem load_expand (m : Mem) (offset size address : Nat) : + (m.expand offset size).load address = m.load address := by + unfold expand + split <;> rfl + +/-- Expanding memory again over the same range changes nothing. -/ +theorem expand_expand (m : Mem) (offset size : Nat) : + (m.expand offset size).expand offset size = m.expand offset size := by + unfold expand + split <;> simp only [Memory.grow_idempotent] + +/-- A store already expanded memory over its word, as a load of that word would. -/ +theorem expand_store (m : Mem) (offset : Nat) (value : Word) : + (m.store offset value).expand offset 32 = m.store offset value := by + unfold store + exact expand_expand _ _ _ + +/-- A load reads none of the bytes a write outside its word writes. -/ +theorem load_write_of_disjoint (m : Mem) (offset size address : Nat) (source : Nat → Memory.Byte) + (disjoint : address + 32 ≤ offset ∨ offset + size ≤ address) : + (m.write offset size source).load address = m.load address := by + unfold write + rw [load_expand] + unfold load read + congr 1 + apply List.map_congr_left + intro i mem + simp only [List.mem_range] at mem + have : ¬(offset ≤ address + i ∧ address + i < offset + size) := by omega + simp only [this, if_false] + +/-- A store is a write of the value's bytes. -/ +theorem store_eq_write (m : Mem) (offset : Nat) (value : Word) : + m.store offset value = m.write offset 32 (Memory.byte value) := rfl + +/-- A load reads none of the bytes a store outside its word writes. -/ +theorem load_store_of_disjoint (m : Mem) (offset address : Nat) (value : Word) + (disjoint : address + 32 ≤ offset ∨ offset + 32 ≤ address) : + (m.store offset value).load address = m.load address := by + rw [store_eq_write] + exact load_write_of_disjoint m offset 32 address _ disjoint + +/-- Memory a call starts with reads as zero everywhere. -/ +theorem load_initial (address : Nat) : initial.load address = 0 := by + unfold load read initial + generalize List.range 32 = l + suffices h : ∀ acc : Word, acc = 0 → + (l.map (fun _ => (0 : Memory.Byte))).foldl + (fun (acc : Word) (b : Memory.Byte) => (acc <<< 8) ||| b.setWidth 256) acc = 0 from + h 0 rfl + induction l with + | nil => intro acc h; exact h + | cons _ l ih => + intro acc h + subst h + exact ih _ (by simp) + +/-- One more byte of a word, from the top: the word shifted right by one byte less. -/ +private theorem step_bytes (v : BitVec 256) (n : Nat) (h : n < 32) : + ((v >>> (8 * (32 - n))) <<< 8) ||| (SolarTV.Memory.byte v n).setWidth 256 = + v >>> (8 * (32 - (n + 1))) := by + apply BitVec.eq_of_getLsbD_eq + intro j hj + simp only [SolarTV.Memory.byte, BitVec.getLsbD_or, BitVec.getLsbD_shiftLeft, + BitVec.getLsbD_ushiftRight, BitVec.getLsbD_setWidth] + by_cases hj8 : j < 8 + · simp only [hj8, decide_true, Bool.true_and, Bool.not_true, Bool.false_and, Bool.false_or, hj] + have : 8 * (31 - n) + j = 8 * (32 - (n + 1)) + j := by omega + rw [this] + · have h1 : ¬ (j < 8) := hj8 + simp only [h1, decide_false, Bool.false_and, Bool.not_false] + simp only [hj, decide_true, Bool.true_and, Bool.or_false] + have : 8 * (32 - n) + (j - 8) = 8 * (32 - (n + 1)) + j := by omega + rw [this] + +/-- A word's first `n` bytes, big-endian, as a load folds them: its top `n` bytes. -/ +private theorem fold_bytes (v : BitVec 256) (n : Nat) (h : n ≤ 32) : + ((List.range n).map (SolarTV.Memory.byte v)).foldl + (fun (acc : BitVec 256) (b : SolarTV.Memory.Byte) => (acc <<< 8) ||| b.setWidth 256) + (0 : BitVec 256) = v >>> (8 * (32 - n)) := by + induction n with + | zero => + simp only [List.range_zero, List.map_nil, List.foldl_nil] + apply BitVec.eq_of_getLsbD_eq + intro j hj + simp only [BitVec.getLsbD_ushiftRight, BitVec.getLsbD_zero] + rw [BitVec.getLsbD_of_ge v _ (by omega)] + simp + | succ n ih => + rw [List.range_succ, List.map_append, List.foldl_append, ih (by omega)] + simp only [List.map_cons, List.map_nil, List.foldl_cons, List.foldl_nil] + exact step_bytes v n (by omega) + +/-- A load of the word a store wrote reads it back. -/ +theorem load_store_same (m : Mem) (offset : Nat) (value : Word) : + (m.store offset value).load offset = value := by + unfold store + rw [load_expand] + unfold load read + have : (List.range 32).map (fun i => + (if offset ≤ offset + i ∧ offset + i < offset + 32 then + SolarTV.Memory.byte value (offset + i - offset) else m.bytes (offset + i))) = + (List.range 32).map (SolarTV.Memory.byte value) := by + apply List.map_congr_left + intro i mem + simp only [List.mem_range] at mem + have c : offset ≤ offset + i ∧ offset + i < offset + 32 := by omega + simp only [c, and_self, ite_true, Nat.add_sub_cancel_left] + simp only [this] + rw [fold_bytes value 32 (by omega)] + simp + +theorem project_initial : initial.project = Memory.initial [] 0 := by + unfold project initial Memory.initial + congr 1 + +theorem project_expand (m : Mem) (offset size : Nat) : + (m.expand offset size).project = Memory.expand m.project offset size := by + unfold expand Memory.expand project + split <;> rfl + +theorem project_msize (m : Mem) : m.msize = Memory.msize m.project := rfl + +theorem project_read (m : Mem) (offset size : Nat) (bounded : offset + size ≤ 256) : + m.read offset size = Memory.read m.project offset size := by + unfold read Memory.read project + apply List.map_congr_left + intro i mem + have : offset + i < 256 := by simp at mem; omega + simp [this] + +theorem project_load (m : Mem) (offset : Nat) (bounded : offset + 32 ≤ 256) : + m.load offset = Memory.load m.project offset := by + unfold load Memory.load + rw [project_read m offset 32 bounded] + +theorem project_store (m : Mem) (offset : Nat) (value : Word) : + (m.store offset value).project = Memory.store m.project offset value := by + unfold store Memory.store + rw [project_expand] + apply congrArg (Memory.expand · offset 32) + simp only [project, Memory.writeWord] + rw [Memory.State.mk.injEq] + refine ⟨?_, rfl⟩ + apply List.ext_getElem (by simp only [List.length_map, List.length_mapIdx]) + intro i h _ + simp only [List.getElem_map, List.getElem_range, List.getElem_mapIdx] + +theorem project_storeByte (m : Mem) (offset : Nat) (value : Word) : + (m.storeByte offset value).project = Memory.storeByte m.project offset value := by + unfold storeByte Memory.storeByte + rw [project_expand] + apply congrArg (Memory.expand · offset 1) + simp only [project] + rw [Memory.State.mk.injEq] + refine ⟨?_, rfl⟩ + apply List.ext_getElem (by simp only [List.length_map, List.length_set]) + intro i h _ + simp only [List.getElem_map, List.getElem_range, List.getElem_set] + by_cases e : i = offset + · subst e; simp + · have e' : ¬offset = i := fun h => e h.symm + simp only [e, e', ↓reduceIte] + +end Mem + +/-- The external calls. -/ +inductive CallKind where + | call | callcode | delegatecall | staticcall + deriving DecidableEq + +/-- An event of the frame: a log, a call with its operands and the state it sees, or a read +of a word that changes as the frame runs, such as `GAS`. -/ +inductive Event where + | log (topics : List Word) (data : List Memory.Byte) + | call (kind : CallKind) (operands : List Word) (input : List Memory.Byte) + (storage transient : Word → Word) + | read (name : String) + /-- A contract creation: its value (and `CREATE2`'s salt), the creation code and the state the + new contract may reenter. -/ + | create (operands : List Word) (code : List Memory.Byte) (storage transient : Word → Word) + +structure State where + memory : Mem + storage : Word → Word + transient : Word → Word + world : List Event + +/-- The state a call starts in: zeroed memory, the call's storage, no events. -/ +def State.initial (call : Call) : State := + ⟨Mem.initial, fun slot => BitVec.ofNat 256 (slotValue call.storage slot.toNat), fun _ => 0, []⟩ + +theorem State.initial_memory (call : Call) : (State.initial call).memory = Mem.initial := rfl + +/-- What the frame cannot see, as functions of the world (`Encoder`'s `env_`, `result` +and the state after a call event). The size of the return data is the environment read +`returndatasize` and its byte `i` the low byte of the read `returndata` of `i`. -/ +structure Oracle where + env : String → List Event → List Word → Word + result : List Event → Word + storageAfter : List Event → Word → Word + transientAfter : List Event → Word → Word + /-- The hash of a byte string. Uninterpreted, but a function, so hashing is deterministic. -/ + keccak : List Memory.Byte → Word + /-- The address that made the call (`CALLER`): any address, so that what holds for every + oracle holds for every caller. -/ + caller : BitVec 160 + +/-- The big-endian word of calldata at an offset, zero past its end. -/ +def calldataWord (call : Call) (offset : Word) : Word := + (List.range 32).foldl + (fun acc i => (acc <<< 8) ||| BitVec.ofNat 256 (call.calldata.data.getD (offset.toNat + i) 0).toNat) 0 + +/-- The calldata byte at an offset, zero past its end. -/ +def calldataByte (call : Call) (offset : Nat) : Memory.Byte := + BitVec.ofNat 8 (call.calldata.data.getD offset 0).toNat + +/-- `store m k v` as the certifier translates an SMT-LIB array store. -/ +def update (m : Word → Word) (key value : Word) : Word → Word := + fun j => if j = key then value else m j + +/-- How a load of an immutable decodes the word its placeholder pushes, as the code after the +push does: as it is (a full word, or a value zero-extended from the placeholder's bytes), +sign-extended from byte `byte` (`SIGNEXTEND`, a signed integer), or shifted left by `bits` +(`SHL`, fixed bytes the placeholder holds right-aligned). -/ +inductive ImmutableRead where + | word + | signExtend (byte : Word) + | shiftLeft (bits : Word) + +def ImmutableRead.apply : ImmutableRead → Word → Word + | .word, x => x + | .signExtend byte, x => Evm.signextend byte x + | .shiftLeft bits, x => Evm.shl bits x + +/-- The value fixed at deployment for immutable `id`. -/ +def immutableValue (o : Oracle) (id : Nat) : Word := o.env "immutable" [] [BitVec.ofNat 256 id] + +/-- The word a `PUSH` placeholder of immutable `id` pushes: the low `bytes` bytes of the +value, which the deployment code writes there. -/ +def immutableWord (o : Oracle) (id bytes : Nat) : Word := + if bytes < 32 then BitVec.ofNat 256 ((immutableValue o id).toNat % 2 ^ (8 * bytes)) + else immutableValue o id + +/-- The word a placeholder of width `bytes` pushes in the stages is the value a deployment +links there: the immutable's value modulo `256 ^ bytes`. -/ +theorem immutableWord_toNat (o : Oracle) (id bytes : Nat) (b1 : 1 ≤ bytes) (b32 : bytes ≤ 32) : + (immutableWord o id bytes).toNat = (immutableValue o id).toNat % 256 ^ bytes := by + have pow : 2 ^ (8 * bytes) = 256 ^ bytes := by + rw [Nat.pow_mul] + unfold immutableWord + split + · rw [BitVec.toNat_ofNat, pow] + apply Nat.mod_eq_of_lt + have : 256 ^ bytes ≤ 2 ^ 256 := by + rw [← pow]; exact Nat.pow_le_pow_right (by decide) (by omega) + have := Nat.mod_lt (immutableValue o id).toNat (Nat.pow_pos (n := bytes) (by decide : 0 < 256)) + omega + · have : bytes = 32 := by omega + subst this + rw [Nat.mod_eq_of_lt] + exact (immutableValue o id).isLt + +inductive Effect where + | mload | mstore | mstore8 | msize | sload | sstore | tload | tstore + | calldataload | calldatasize | callvalue | caller | address | returndatasize + | log (topics : Nat) + | keccak256 + | env (name : String) + | call (kind : CallKind) + | calldatacopy | mcopy | returndatacopy + | gas + /-- Immutable `id` from its `PUSH` placeholder, decoded by `read` (`loadimmutable`; + the placeholder push itself reads `.word`). -/ + | immutable (id bytes : Nat) (read : ImmutableRead) + | codecopy | create | create2 + +/-- The size of the return data the world's last call left. -/ +abbrev returndataSize (o : Oracle) (world : List Event) : Word := o.env "returndatasize" world [] + +/-- Byte `i` of the return data the world's last call left. -/ +def returndataByte (o : Oracle) (world : List Event) (i : Nat) : Memory.Byte := + (o.env "returndata" world [BitVec.ofNat 256 i]).setWidth 8 + +/-- A call's operands in pop order: the words its callee sees (gas, address and, for `CALL` +and `CALLCODE`, value), and its input and output offsets and sizes. -/ +def CallKind.shape : CallKind → List Word → Option (List Word × Word × Word × Word × Word) + | .call, [gas, address, value, inOffset, inSize, outOffset, outSize] + | .callcode, [gas, address, value, inOffset, inSize, outOffset, outSize] => + some ([gas, address, value], inOffset, inSize, outOffset, outSize) + | .delegatecall, [gas, address, inOffset, inSize, outOffset, outSize] + | .staticcall, [gas, address, inOffset, inSize, outOffset, outSize] => + some ([gas, address], inOffset, inSize, outOffset, outSize) + | _, _ => none + +/-- The state after an external call whose world, with the call, is `world`. -/ +def called (o : Oracle) (kind : CallKind) (s : State) (memory : Mem) (outOffset outSize : Word) + (world : List Event) : State := + let copied := min outSize.toNat (returndataSize o world).toNat + let memory := memory.write outOffset.toNat copied (returndataByte o world) + match kind with + | .staticcall => { s with memory, world } + | _ => ⟨memory, o.storageAfter world, o.transientAfter world, world⟩ + +/-- Byte `i` of the frame's code, the oracle's environment read `code` of `i` in the empty world. -/ +def codeByte (o : Oracle) (i : Nat) : Memory.Byte := + (o.env "code" [] [BitVec.ofNat 256 i]).setWidth 8 + +/-- A contract creation with the operands its new contract sees (value, and `CREATE2`'s salt) +and its creation code at `offset`: the new address (the low 160 bits of the oracle's result, +zero for a failed creation), and the storage after it, as after a call; memory only expands. -/ +def created (o : Oracle) (s : State) (seen : List Word) (offset size : Word) : + Option Word × State := + let memory := s.memory.expand offset.toNat size.toNat + let world := s.world ++ [.create seen (memory.read offset.toNat size.toNat) s.storage s.transient] + (some (BitVec.ofNat 256 ((o.result world).toNat % 2 ^ 160)), + ⟨memory, o.storageAfter world, o.transientAfter world, world⟩) + +/-- A call's success flag. -/ +def callFlag (o : Oracle) (world : List Event) : Word := if o.result world = 0 then 0 else 1 + +/-- An effect on its operands, in pop order: its result, if any, and the state after it; +`none` for operands of the wrong arity. -/ +def Effect.apply (o : Oracle) (call : Call) : Effect → List Word → State → Option (Option Word × State) + | .mload, [offset], s => + some (some (s.memory.load offset.toNat), { s with memory := s.memory.expand offset.toNat 32 }) + | .mstore, [offset, value], s => some (none, { s with memory := s.memory.store offset.toNat value }) + | .mstore8, [offset, value], s => + some (none, { s with memory := s.memory.storeByte offset.toNat value }) + | .msize, [], s => some (some s.memory.msize, s) + | .sload, [key], s => some (some (s.storage key), s) + | .sstore, [key, value], s => some (none, { s with storage := update s.storage key value }) + | .tload, [key], s => some (some (s.transient key), s) + | .tstore, [key, value], s => some (none, { s with transient := update s.transient key value }) + | .calldataload, [offset], s => some (some (calldataWord call offset), s) + | .calldatasize, [], s => some (some (BitVec.ofNat 256 call.calldata.size), s) + | .callvalue, [], s => some (some (BitVec.ofNat 256 call.callvalue), s) + | .caller, [], s => some (some (o.caller.setWidth 256), s) + | .address, [], s => some (some (BitVec.ofNat 256 environment.callee), s) + | .returndatasize, [], s => some (some (o.env "returndatasize" s.world []), s) + | .log n, offset :: size :: topics, s => + if topics.length = n then + let memory := s.memory.expand offset.toNat size.toNat + some (none, { s with + memory, world := s.world ++ [.log topics (memory.read offset.toNat size.toNat)] }) + else none + | .keccak256, [offset, size], s => + let memory := s.memory.expand offset.toNat size.toNat + some (some (o.keccak (memory.read offset.toNat size.toNat)), { s with memory }) + | .env name, operands, s => some (some (o.env name s.world operands), s) + | .calldatacopy, [dest, offset, size], s => + let memory := s.memory.write dest.toNat size.toNat (fun i => calldataByte call (offset.toNat + i)) + some (none, { s with memory }) + | .mcopy, [dest, source, size], s => + let read := s.memory.expand source.toNat size.toNat + let memory := read.write dest.toNat size.toNat (fun i => read.bytes (source.toNat + i)) + some (none, { s with memory }) + | .immutable id bytes read, [], s => some (some (read.apply (immutableWord o id bytes)), s) + | .codecopy, [dest, offset, size], s => + let memory := s.memory.write dest.toNat size.toNat (fun i => codeByte o (offset.toNat + i)) + some (none, { s with memory }) + | .create, [value, offset, size], s => some (created o s [value] offset size) + | .create2, [value, offset, size, salt], s => some (created o s [value, salt] offset size) + | .gas, [], s => + let world := s.world ++ [.read "gas"] + some (some (o.env "gas" world []), { s with world }) + | .returndatacopy, [dest, offset, size], s => + if (returndataSize o s.world).toNat < offset.toNat + size.toNat then none + else + let memory := s.memory.write dest.toNat size.toNat + (fun i => returndataByte o s.world (offset.toNat + i)) + some (none, { s with memory }) + | .call kind, operands, s => + match kind.shape operands with + | none => none + | some (seen, inOffset, inSize, outOffset, outSize) => + let memory := (s.memory.expand inOffset.toNat inSize.toNat).expand outOffset.toNat + outSize.toNat + let world := s.world ++ + [.call kind seen (memory.read inOffset.toNat inSize.toNat) s.storage s.transient] + some (some (callFlag o world), called o kind s memory outOffset outSize world) + | _, _, _ => none + +/-- How a frame ends. `invalid` also stands for every exceptional halt. -/ +inductive Halt where + | stop + | ret (data : List Memory.Byte) + | revert (data : List Memory.Byte) + | invalid + +def logs (s : State) : List (List Nat × List Nat) := + s.world.filterMap fun + | .log topics data => some (topics.map BitVec.toNat, data.map BitVec.toNat) + | .call .. | .read _ | .create .. => none + +def storageOf (s : State) : Nat → Nat := fun slot => (s.storage (BitVec.ofNat 256 slot)).toNat + +def revertData : Halt → List Nat + | .revert data => data.map BitVec.toNat + | _ => [] + +/-- A successful end commits its storage and logs; a failed one rolls them back. -/ +def observe (call : Call) (s : State) : Halt → Observable + | .stop => ⟨true, [], logs s, storageOf s⟩ + | .ret data => ⟨true, data.map BitVec.toNat, logs s, storageOf s⟩ + | .revert data => ⟨false, data.map BitVec.toNat, [], slotValue call.storage⟩ + | .invalid => ⟨false, [], [], slotValue call.storage⟩ + +theorem observe_failure (call : Call) (s : State) (halt : Halt) + (failed : (observe call s halt).success = false) : + (observe call s halt).logs = [] ∧ (observe call s halt).storage = slotValue call.storage ∧ + (observe call s halt).output = revertData halt := by + cases halt <;> simp_all [observe, revertData] + +/-- Two ends no observer tells apart, as `Encoder::differ` compares them: the kind, the +returned bytes (`stop` returns none), and on success storage, transient storage and the +world; a revert compares its data alone. -/ +def Agree : Halt × State → Halt × State → Prop + | (.revert d, _), (.revert e, _) => d = e + | (.invalid, _), (.invalid, _) => True + | (a, s), (b, t) => + (match a, b with + | .stop, .stop => True + | .stop, .ret e => e = [] + | .ret d, .stop => d = [] + | .ret d, .ret e => d = e + | _, _ => False) ∧ + s.storage = t.storage ∧ s.transient = t.transient ∧ s.world = t.world + +theorem Agree.refl (r : Halt × State) : Agree r r := by + obtain ⟨h, s⟩ := r + cases h <;> simp [Agree] + +theorem Agree.trans {a b c : Halt × State} (ab : Agree a b) (bc : Agree b c) : Agree a c := by + obtain ⟨ha, sa⟩ := a + obtain ⟨hb, sb⟩ := b + obtain ⟨hc, sc⟩ := c + cases ha <;> cases hb <;> cases hc <;> simp_all [Agree] + +theorem storageOf_congr {s t : State} (h : s.storage = t.storage) : storageOf s = storageOf t := by + unfold storageOf + rw [h] + +theorem logs_congr {s t : State} (h : s.world = t.world) : logs s = logs t := by + unfold logs + rw [h] + +theorem observe_of_agree (call : Call) {a b : Halt × State} (agree : Agree a b) : + observe call a.2 a.1 = observe call b.2 b.1 := by + obtain ⟨ha, sa⟩ := a + obtain ⟨hb, sb⟩ := b + cases ha <;> cases hb <;> simp only [Agree] at agree <;> simp only [observe] + all_goals first + | exact agree.1.elim + | (obtain ⟨kind, storage, _, world⟩ := agree + rw [storageOf_congr storage, logs_congr world] + try first | rfl | (subst kind; rfl) | (rw [kind]; rfl)) + | (subst agree; rfl) + | rfl + | exact agree.elim + +/-- An iteration that either ends or continues from a new configuration, with fuel. -/ +def iterate {σ : Type} (step : σ → Option ((Halt × State) ⊕ σ)) : Nat → σ → Option (Halt × State) + | 0, _ => none + | n + 1, x => + match step x with + | some (.inl result) => some result + | some (.inr next) => iterate step n next + | none => none + +theorem iterate_mono {σ : Type} (step : σ → Option ((Halt × State) ⊕ σ)) (n : Nat) (x : σ) + (result : Halt × State) (ran : iterate step n x = some result) : + iterate step (n + 1) x = some result := by + induction n generalizing x with + | zero => simp [iterate] at ran + | succ n ih => + unfold iterate at ran ⊢ + cases hs : step x with + | none => simp [hs] at ran + | some v => + cases v with + | inl r => simp_all + | inr y => + simp only [hs] at ran ⊢ + exact ih y ran + +/-- A language whose programs run on a call with fuel, deterministically: more fuel never +changes an end. -/ +structure Layer where + Prog : Type + run : Oracle → Prog → Call → Nat → Option (Halt × State) + mono : ∀ o p call n result, run o p call n = some result → run o p call (n + 1) = some result + +namespace Layer + +variable (L : Layer) + +/-- Some fuel reaches this end. -/ +def Ends (o : Oracle) (p : L.Prog) (call : Call) (result : Halt × State) : Prop := + ∃ n, L.run o p call n = some result + +theorem mono_le {o : Oracle} {p : L.Prog} {call : Call} {result : Halt × State} {n m : Nat} + (le : n ≤ m) (ran : L.run o p call n = some result) : L.run o p call m = some result := by + induction le with + | refl => exact ran + | step _ ih => exact L.mono _ _ _ _ _ ih + +theorem ends_unique {o : Oracle} {p : L.Prog} {call : Call} {a b : Halt × State} + (ea : L.Ends o p call a) (eb : L.Ends o p call b) : a = b := by + obtain ⟨n, hn⟩ := ea + obtain ⟨m, hm⟩ := eb + have := L.mono_le (Nat.le_max_left n m) hn + rw [L.mono_le (Nat.le_max_right n m) hm] at this + exact (Option.some.inj this).symm + +open Classical in +/-- The end of a call, which some fuel reaches, or `none` when no fuel does. -/ +noncomputable def result (o : Oracle) (p : L.Prog) (call : Call) : Option (Halt × State) := + if h : ∃ r, L.Ends o p call r then some h.choose else none + +theorem result_of_ends {o : Oracle} {p : L.Prog} {call : Call} {r : Halt × State} + (ends : L.Ends o p call r) : L.result o p call = some r := by + have h : ∃ r, L.Ends o p call r := ⟨r, ends⟩ + simp only [result, h, dite_true] + exact congrArg some (L.ends_unique h.choose_spec ends) + +theorem ends_of_result {o : Oracle} {p : L.Prog} {call : Call} {r : Halt × State} + (res : L.result o p call = some r) : L.Ends o p call r := by + unfold result at res + split at res + · rename_i h + cases res + exact h.choose_spec + · cases res + +/-- The fuel-free semantics of a layer under an oracle. -/ +noncomputable def sem (o : Oracle) : Sem := + ⟨L.Prog, fun p call => (L.result o p call).map fun r => observe call r.2 r.1⟩ + +theorem sem_failure (o : Oracle) (p : L.Prog) (call : Call) (obs : Observable) + (ran : (L.sem o).run p call = some obs) (failed : obs.success = false) : + ∃ r, L.Ends o p call r ∧ obs.logs = [] ∧ obs.storage = slotValue call.storage ∧ + obs.output = revertData r.1 := by + simp only [sem, Option.map_eq_some_iff] at ran + obtain ⟨r, res, rfl⟩ := ran + exact ⟨r, L.ends_of_result res, observe_failure call r.2 r.1 failed⟩ + +theorem failureConvention (o : Oracle) : (L.sem o).FailureConvention := by + intro p call obs ran failed + obtain ⟨_, _, logs, storage, _⟩ := L.sem_failure o p call obs ran failed + exact ⟨logs, storage⟩ + +end Layer + +/-- Every end `p` reaches on a call in scope, `q` reaches an end that agrees with. This is +what an `unsat` pass validation query states, and it gives a stage. -/ +def Certified (A B : Layer) (o : Oracle) (p : A.Prog) (q : B.Prog) (scope : Call → Prop) : Prop := + ∀ call, scope call → ∀ r, A.Ends o p call r → ∃ r', B.Ends o q call r' ∧ Agree r r' + +theorem stage_of_certified {A B : Layer} {o : Oracle} {p : A.Prog} {q : B.Prog} + {scope : Call → Prop} (certified : Certified A B o p q scope) : + Stage (A.sem o) (B.sem o) p q scope := by + intro call inScope obs ran + simp only [Layer.sem, Option.map_eq_some_iff] at ran ⊢ + obtain ⟨r, res, rfl⟩ := ran + obtain ⟨r', ends, agree⟩ := certified call inScope r (A.ends_of_result res) + exact ⟨r', B.result_of_ends ends, (observe_of_agree call agree).symm⟩ + +theorem Certified.refl (A : Layer) (o : Oracle) (p : A.Prog) (scope : Call → Prop) : + Certified A A o p p scope := + fun _ _ r ends => ⟨r, ends, Agree.refl r⟩ + +theorem Certified.trans {A B C : Layer} {o : Oracle} {p : A.Prog} {q : B.Prog} {r : C.Prog} + {scope : Call → Prop} (first : Certified A B o p q scope) + (second : Certified B C o q r scope) : Certified A C o p r scope := by + intro call inScope x ends + obtain ⟨y, ey, xy⟩ := first call inScope x ends + obtain ⟨z, ez, yz⟩ := second call inScope y ey + exact ⟨z, ez, xy.trans yz⟩ + +/-- A certificate from runs at given fuel: for every fuel at which `p` ends, `q` ends at +some fuel in an agreeing end. -/ +theorem Certified.of_fuel {A B : Layer} {o : Oracle} {p : A.Prog} {q : B.Prog} + {scope : Call → Prop} + (runs : ∀ call, scope call → ∀ n r, A.run o p call n = some r → + ∃ m r', B.run o q call m = some r' ∧ Agree r r') : + Certified A B o p q scope := by + intro call inScope r ⟨n, hn⟩ + obtain ⟨m, r', hm, agree⟩ := runs call inScope n r hn + exact ⟨r', ⟨m, hm⟩, agree⟩ + +end SolarTV.Machine diff --git a/tv/SolarTV/Memory.lean b/tv/SolarTV/Memory.lean new file mode 100644 index 00000000..cd1bff71 --- /dev/null +++ b/tv/SolarTV/Memory.lean @@ -0,0 +1,116 @@ +import SolarTV.Outcome +import EvmRules.Word +import SolarTV.Keccak + +/-! Byte-addressed memory shared by the MIR and EVM IR importers. +The current projection retains the first 256 bytes and the complete active-word +count. Importers admit only constant accesses inside that prefix. Incoming bytes +are arbitrary in active words and zero outside them; bytes beyond the projection +are unchanged by every admitted operation. This is a projected-state model, not +a bounded-address assumption on a symbolic pointer. + +Expansion follows EVMYulLean 047f630, MachineStateOps.lean:24-33: zero-length +accesses do not expand, and offset + length is natural arithmetic, not wrapping +word arithmetic. Byte order and the low byte of MSTORE8 follow lines 35-68. +Gas remains outside this fragment. -/ + +namespace SolarTV.Memory +open EvmRules + +abbrev Byte := BitVec 8 + +structure State where + bytes : List Byte + words : BitVec 251 + deriving DecidableEq + +/-- Big-endian byte i of a word. -/ +def byte (value : Word) (i : Nat) : Byte := + (value >>> (8 * (31 - i))).setWidth 8 + +/-- The count covers all representable, word-aligned MSIZE values. +The importer limits accesses to eight words, so expansion cannot overflow it. -/ +def initial (values : List Word) (words : BitVec 251) : State := + ⟨(List.range 256).map (fun i => + if (BitVec.ofNat 251 (i / 32)).ult words then byte (values[i / 32]?.getD 0) (i % 32) + else 0), words⟩ + +def grow (words required : BitVec 251) : BitVec 251 := + if words.ult required then required else words + +@[simp] theorem grow_idempotent (words required : BitVec 251) : + grow (grow words required) required = grow words required := by + unfold grow + split <;> simp_all [BitVec.ult_iff_toNat_lt] + +def expand (memory : State) (offset size : Nat) : State := + if size = 0 then memory + else + let required := BitVec.ofNat 251 ((offset + size + 31) / 32) + { memory with words := grow memory.words required } + +def msize (memory : State) : Word := memory.words.setWidth 256 <<< 5 + +def read (memory : State) (offset size : Nat) : List Byte := + (List.range size).map (fun i => memory.bytes[offset + i]?.getD 0) + +def load (memory : State) (offset : Nat) : Word := + (read memory offset 32).foldl (fun acc b => (acc <<< 8) ||| b.setWidth 256) 0 + +def writeWord (bytes : List Byte) (offset : Nat) (value : Word) : List Byte := + bytes.mapIdx (fun i old => if offset ≤ i ∧ i < offset + 32 then byte value (i - offset) else old) + +@[simp] theorem writeWord_overwrite (bytes : List Byte) (offset : Nat) (a b : Word) : + writeWord (writeWord bytes offset a) offset b = writeWord bytes offset b := by + simp only [writeWord, List.mapIdx_mapIdx] + congr 1 + funext i old + split <;> simp_all + +def store (memory : State) (offset : Nat) (value : Word) : State := + let bytes := writeWord memory.bytes offset value + expand { memory with bytes } offset 32 + +def storeByte (memory : State) (offset : Nat) (value : Word) : State := + expand { memory with bytes := memory.bytes.set offset (value.setWidth 8) } offset 1 + +/-- Snapshot the source before writing, including overlapping MCOPY ranges. -/ +def copy (memory : State) (destination source count : Nat) : State := + if count = 0 then memory else + let bytes := memory.bytes.mapIdx (fun i old => + if destination ≤ i ∧ i < destination + count then + memory.bytes[source + i - destination]?.getD 0 else old) + expand (expand {memory with bytes} source count) destination count + +def hash (memory : State) (offset count : Nat) : Word := + Keccak.hash (read memory offset count) + +/-- Only witness discovery uses this projection. Concrete witnesses are replayed +against equality of the actual modeled executions in Lean's kernel. -/ +def snapshot (memory : State) : List Word := + msize memory :: memory.bytes.map (fun b => b.setWidth 256) + +def describe (memory : State) : String := + let values := (List.range 8).map (fun i => (load memory (i * 32)).toNat) + s!"msize={msize memory |>.toNat}, memory={values}" + +structure Returned (width : Nat) where + value : BitVec width + memory : State + deriving DecidableEq + +def code (result : Outcome (Returned width)) : List Word := + match result with + | .returned result => 0 :: result.value.setWidth 256 :: snapshot result.memory + | .reverted .empty => [1] + | .reverted (.panic value) => [2, value] + | .invalid => [3] + +def describeReturn (result : Outcome (Returned width)) : String := + match result with + | .returned result => s!"return={result.value.toNat}, {describe result.memory}" + | .reverted .empty => "revert(empty)" + | .reverted (.panic value) => s!"revert Panic({value.toNat})" + | .invalid => "invalid" + +end SolarTV.Memory diff --git a/tv/SolarTV/MemorySafety.lean b/tv/SolarTV/MemorySafety.lean new file mode 100644 index 00000000..42672776 --- /dev/null +++ b/tv/SolarTV/MemorySafety.lean @@ -0,0 +1,19 @@ +import SolarTV.Memory + +/-! Executable checks of byte order, overlapping writes and exact expansion. +Gas is deliberately not priced yet. These kernel proofs pin the memory rules +used by both IR models, including zero-sized accesses at maximal offsets. -/ + +namespace SolarTV.Memory + +set_option maxRecDepth 4096 + +example : (expand (initial [] 0) (2^256 - 1) 0).words = 0 := by decide +example : msize (expand (initial [] 0) 1 32) = 64 := by decide +example : load (initial [0xffff] 0) 0 = 0 := by decide +example : load (initial [0x1234] 1) 0 = 0x1234 := by decide +example : load (store (initial [] 0) 1 0x1234) 1 = 0x1234 := by decide +example : load (storeByte (store (initial [] 0) 0 0x1234) 31 0x1ff) 0 = 0x12ff := by decide +example : load (storeByte (initial [] 0) 0 0xff) 0 = (0xff : EvmRules.Word) <<< 248 := by decide + +end SolarTV.Memory diff --git a/tv/SolarTV/MemorySymbolic.lean b/tv/SolarTV/MemorySymbolic.lean new file mode 100644 index 00000000..87e7af02 --- /dev/null +++ b/tv/SolarTV/MemorySymbolic.lean @@ -0,0 +1,264 @@ +import SolarTV.Machine + +/-! Read-over-write laws of `Machine.Mem` at symbolic addresses. + +`Mem` is a total byte map with an active-word count, so a computed offset is just a +natural number: nothing here bounds an address or assumes two pointers are distinct. +Every law that moves a read past a write takes the disjointness, containment or exact +match of the two ranges as a hypothesis over natural numbers, for `omega` (or a caller's +`omega`-based discharger over word `toNat`s) to prove from the path's cases. When it +cannot, the law does not fire and the read stays over the write: overlapping or unproved +ranges fail closed. `read_store` and `bytes_store` give the byte-exact fallback for an +overlap. Expansion stays exact: `words_store` and `words_write` are the active-word +count the semantics defines, with no rounding or bound. -/ + +namespace SolarTV.Machine.Mem +open EvmRules + +/-- The 32 big-endian bytes `store` writes. -/ +def wordBytes (value : Word) : List Memory.Byte := (List.range 32).map (Memory.byte value) + +@[simp] theorem wordBytes_length (value : Word) : (wordBytes value).length = 32 := by + simp [wordBytes] + +@[simp] theorem read_length (m : Mem) (offset size : Nat) : (m.read offset size).length = size := by + simp [read] + +@[simp] theorem read_zero (m : Mem) (offset : Nat) : m.read offset 0 = [] := rfl + +/-! Bytes and active size after each operation. -/ + +@[simp] theorem bytes_expand (m : Mem) (offset size : Nat) : (m.expand offset size).bytes = m.bytes := by + unfold expand; split <;> rfl + +theorem words_expand (m : Mem) (offset size : Nat) : (m.expand offset size).words = + if size = 0 then m.words else Memory.grow m.words (BitVec.ofNat 251 ((offset + size + 31) / 32)) := by + unfold expand; split <;> rfl + +theorem bytes_store (m : Mem) (offset : Nat) (value : Word) (i : Nat) : + (m.store offset value).bytes i = + if offset ≤ i ∧ i < offset + 32 then Memory.byte value (i - offset) else m.bytes i := by + simp [store] + +theorem words_store (m : Mem) (offset : Nat) (value : Word) : + (m.store offset value).words = Memory.grow m.words (BitVec.ofNat 251 ((offset + 32 + 31) / 32)) := by + simp [store, words_expand] + +theorem bytes_storeByte (m : Mem) (offset : Nat) (value : Word) (i : Nat) : + (m.storeByte offset value).bytes i = if i = offset then value.setWidth 8 else m.bytes i := by + simp [storeByte] + +theorem words_storeByte (m : Mem) (offset : Nat) (value : Word) : + (m.storeByte offset value).words = Memory.grow m.words (BitVec.ofNat 251 ((offset + 1 + 31) / 32)) := by + simp [storeByte, words_expand] + +theorem bytes_write (m : Mem) (offset size : Nat) (source : Nat → Memory.Byte) (i : Nat) : + (m.write offset size source).bytes i = + if offset ≤ i ∧ i < offset + size then source (i - offset) else m.bytes i := by + simp [write] + +theorem words_write (m : Mem) (offset size : Nat) (source : Nat → Memory.Byte) : + (m.write offset size source).words = (m.expand offset size).words := by + simp [write, words_expand] + +/-- Growth to a size memory already has changes nothing. -/ +theorem grow_of_le (words required : BitVec 251) (h : required.toNat ≤ words.toNat) : + Memory.grow words required = words := by + unfold Memory.grow + simp only [BitVec.ult_iff_toNat_lt] + split <;> first | rfl | omega + +/-- Growth past the active size is exactly the required size. -/ +theorem grow_of_lt (words required : BitVec 251) (h : words.toNat < required.toNat) : + Memory.grow words required = required := by + unfold Memory.grow + simp only [BitVec.ult_iff_toNat_lt] + split <;> first | rfl | omega + +/-! Reads. -/ + +@[simp] theorem read_expand (m : Mem) (offset size address count : Nat) : + (m.expand offset size).read address count = m.read address count := by + simp [read] + +/-- Reading two adjacent ranges is reading their union. -/ +theorem read_append (m : Mem) (address k l : Nat) : + m.read address (k + l) = m.read address k ++ m.read (address + k) l := by + unfold read + rw [List.range_add, List.map_append, List.map_map] + congr 1 + apply List.map_congr_left + intro i _ + simp [Function.comp, Nat.add_assoc] + +/-- A range longer than a word as its first word and the rest, for word-by-word reads of +`abi.encode` output. The lower bound keeps the rewrite from unfolding a word into itself; the +upper bound (32 words) keeps it to the short encodings a hash reads, so a long or symbolic +range is never unfolded byte-word by byte-word. -/ +theorem read_split (m : Mem) (address count : Nat) (h : 32 < count) (bounded : count ≤ 1024) : + m.read address count = m.read address 32 ++ m.read (address + 32) (count - 32) := by + have := read_append m address 32 (count - 32) + rwa [Nat.add_sub_cancel' (by omega)] at this + +/-- A read is unchanged by a store outside it. -/ +theorem read_store_disjoint (m : Mem) (offset : Nat) (value : Word) (address count : Nat) + (h : address + count ≤ offset ∨ offset + 32 ≤ address) : + (m.store offset value).read address count = m.read address count := by + unfold read + apply List.map_congr_left + intro i hi + simp only [List.mem_range] at hi + rw [bytes_store] + have : ¬(offset ≤ address + i ∧ address + i < offset + 32) := by omega + simp only [this, ite_false] + +/-- A load is unchanged by a store whose word it does not overlap. -/ +theorem load_store_disjoint (m : Mem) (offset : Nat) (value : Word) (address : Nat) + (h : address + 32 ≤ offset ∨ offset + 32 ≤ address) : + (m.store offset value).load address = m.load address := by + unfold load + rw [read_store_disjoint m offset value address 32 h] + +/-- A read is unchanged by a byte store outside it. -/ +theorem read_storeByte_disjoint (m : Mem) (offset : Nat) (value : Word) (address count : Nat) + (h : address + count ≤ offset ∨ offset < address) : + (m.storeByte offset value).read address count = m.read address count := by + unfold read + apply List.map_congr_left + intro i hi + simp only [List.mem_range] at hi + rw [bytes_storeByte] + have : ¬(address + i = offset) := by omega + simp only [this, ite_false] + +theorem load_storeByte_disjoint (m : Mem) (offset : Nat) (value : Word) (address : Nat) + (h : address + 32 ≤ offset ∨ offset < address) : + (m.storeByte offset value).load address = m.load address := by + unfold load + rw [read_storeByte_disjoint m offset value address 32 h] + +/-- A read is unchanged by a copy, calldata or return data write outside it. -/ +theorem read_write_disjoint (m : Mem) (offset size : Nat) (source : Nat → Memory.Byte) + (address count : Nat) (h : address + count ≤ offset ∨ offset + size ≤ address) : + (m.write offset size source).read address count = m.read address count := by + unfold read + apply List.map_congr_left + intro i hi + simp only [List.mem_range] at hi + rw [bytes_write] + have : ¬(offset ≤ address + i ∧ address + i < offset + size) := by omega + simp only [this, ite_false] + +/-- The word a store wrote, read back as bytes, as `KECCAK256` over it reads them. -/ +theorem read_store_same (m : Mem) (offset : Nat) (value : Word) : + (m.store offset value).read offset 32 = wordBytes value := by + unfold read wordBytes + apply List.map_congr_left + intro i hi + simp only [List.mem_range] at hi + rw [bytes_store] + have : offset ≤ offset + i ∧ offset + i < offset + 32 := by omega + simp only [this, and_self, ite_true, Nat.add_sub_cancel_left] + +/-- A word stored at an offset equal to the read's, as `omega` proves it (such as +`(p + 32).toNat` and `p.toNat + 32` when the sum does not wrap). -/ +theorem read_store_at (m : Mem) (offset : Nat) (value : Word) (address count : Nat) + (h : address = offset) (hc : count = 32) : + (m.store offset value).read address count = wordBytes value := by + subst h hc; exact read_store_same m address value + +theorem load_store_at (m : Mem) (offset : Nat) (value : Word) (address : Nat) (h : address = offset) : + (m.store offset value).load address = value := by + subst h; exact load_store_same m address value + +/-- A read inside the range a write wrote reads the source at the same distance. -/ +theorem read_write_inside (m : Mem) (offset size : Nat) (source : Nat → Memory.Byte) + (address count : Nat) (lo : offset ≤ address) (hi : address + count ≤ offset + size) : + (m.write offset size source).read address count = + (List.range count).map (fun i => source (address - offset + i)) := by + unfold read + apply List.map_congr_left + intro i hi' + simp only [List.mem_range] at hi' + rw [bytes_write] + have c : offset ≤ address + i ∧ address + i < offset + size := by omega + have e : address + i - offset = address - offset + i := by omega + simp only [c, and_self, ite_true, e] + +/-- The whole range a write wrote reads its source, at any symbolic length. -/ +theorem read_write_same (m : Mem) (offset size : Nat) (source : Nat → Memory.Byte) : + (m.write offset size source).read offset size = (List.range size).map source := by + rw [read_write_inside m offset size source offset size (Nat.le_refl _) (Nat.le_refl _)] + simp + +/-- An `MCOPY` read back inside its destination: the source memory's bytes, at the source +offset moved by the same distance. `from` is the memory the copy read, which `apply_mcopy` +expands first; `read_expand` then removes that expansion. -/ +theorem read_copy_inside (m src : Mem) (offset size source address count : Nat) + (lo : offset ≤ address) (hi : address + count ≤ offset + size) : + (m.write offset size (fun i => src.bytes (source + i))).read address count = + src.read (source + (address - offset)) count := by + rw [read_write_inside m offset size _ address count lo hi] + unfold read + apply List.map_congr_left + intro i _ + simp [Nat.add_assoc] + +/-- A store's word followed by bytes it does not touch. -/ +theorem read_store_head (m : Mem) (offset : Nat) (value : Word) (count : Nat) : + (m.store offset value).read offset (32 + count) = wordBytes value ++ m.read (offset + 32) count := by + rw [read_append, read_store_same, + read_store_disjoint m offset value (offset + 32) count (Or.inr (Nat.le_refl _))] + +/-- Byte-exact reading over any store, overlapping or not: the fallback when neither +disjointness nor containment holds. -/ +theorem read_store (m : Mem) (offset : Nat) (value : Word) (address count : Nat) : + (m.store offset value).read address count = (List.range count).map (fun i => + if offset ≤ address + i ∧ address + i < offset + 32 then + Memory.byte value (address + i - offset) else m.bytes (address + i)) := by + unfold read + apply List.map_congr_left + intro i _ + rw [bytes_store] + +/-- A range of length zero, as `omega` proves it. -/ +theorem read_of_eq_zero (m : Mem) (address count : Nat) (h : count = 0) : m.read address count = [] := by + subst h; rfl + +/-- The whole range a write wrote, at offsets and lengths `omega` proves equal. -/ +theorem read_write_at (m : Mem) (offset size : Nat) (source : Nat → Memory.Byte) (address count : Nat) + (h : address = offset) (hc : count = size) : + (m.write offset size source).read address count = (List.range size).map source := by + subst h hc; exact read_write_same m address count source + +/-- A range that contains a stored word: the bytes before it, the word, the bytes after it. +This is how a hash over a region built word by word at computed offsets meets its words. -/ +theorem read_store_within (m : Mem) (offset : Nat) (value : Word) (address count : Nat) + (lo : address ≤ offset) (hi : offset + 32 ≤ address + count) : + (m.store offset value).read address count = + m.read address (offset - address) ++ wordBytes value ++ + m.read (offset + 32) (address + count - (offset + 32)) := by + have hk : count = (offset - address) + (32 + (address + count - (offset + 32))) := by omega + have ho : address + (offset - address) = offset := by omega + conv => lhs; rw [hk, read_append, read_append, ho] + rw [read_store_disjoint m offset value address (offset - address) (Or.inl (by omega)), + read_store_same, + read_store_disjoint m offset value (offset + 32) _ (Or.inr (Nat.le_refl _)), + List.append_assoc] + +/-- A range that contains a copy's destination: the bytes before it, the copied bytes at any +symbolic length, the bytes after it, as a hash over a header and a copied array reads them. -/ +theorem read_write_within (m : Mem) (offset size : Nat) (source : Nat → Memory.Byte) + (address count : Nat) (lo : address ≤ offset) (hi : offset + size ≤ address + count) : + (m.write offset size source).read address count = + m.read address (offset - address) ++ (List.range size).map source ++ + m.read (offset + size) (address + count - (offset + size)) := by + have hk : count = (offset - address) + (size + (address + count - (offset + size))) := by omega + have ho : address + (offset - address) = offset := by omega + conv => lhs; rw [hk, read_append, read_append, ho] + rw [read_write_disjoint m offset size source address (offset - address) (Or.inl (by omega)), + read_write_same, + read_write_disjoint m offset size source (offset + size) _ (Or.inr (Nat.le_refl _)), + List.append_assoc] + +end SolarTV.Machine.Mem diff --git a/tv/SolarTV/MemorySymbolicSafety.lean b/tv/SolarTV/MemorySymbolicSafety.lean new file mode 100644 index 00000000..1aabb6ce --- /dev/null +++ b/tv/SolarTV/MemorySymbolicSafety.lean @@ -0,0 +1,183 @@ +import SolarTV.MemorySymbolic + +/-! Kernel-checked uses and negatives of the symbolic memory laws, in the shapes ABI +encoding and order hashing take: words stored at a computed free pointer and hashed as one +range, a calldata copy of variable length hashed in place, the free pointer advanced past +it, and an `MCOPY` read back. The negatives show that a wrong offset, a wrong length or an +overlapping write changes the bytes, and that `mem_simp` refuses to move a read past a write +it cannot prove disjoint. -/ + +namespace SolarTV.Machine.Mem +open EvmRules + +/-- Read-over-write by the laws, each side condition by `omega`. -/ +macro "mem_simp" : tactic => `(tactic| repeat (first + | simp (disch := omega) only [read_expand, read_store_at, read_store_disjoint, load_store_at, + load_store_disjoint, read_storeByte_disjoint, load_storeByte_disjoint, read_write_disjoint, + load_write_of_disjoint, read_write_same, read_write_inside, read_copy_inside, load_expand, + read_store_within, read_write_within, read_of_eq_zero, read_write_at, List.append_nil, List.nil_append, + List.append_assoc] + | simp only [read_split, Nat.reduceLT, Nat.reduceLeDiff, Nat.reduceSub, Nat.reduceAdd])) + +/-- `abi.encode(typehash, a, b)` at a free pointer `p` above the scratch and pointer words, +hashed over its 96 bytes: the hash input is the three words, and the pointer word is intact. -/ +theorem encode3_read (m : Mem) (p : Nat) (h : 0x60 ≤ p) (t a b : Word) : + (((m.store p t).store (p + 32) a).store (p + 64) b).read p 96 = + wordBytes t ++ wordBytes a ++ wordBytes b ∧ + (((m.store p t).store (p + 32) a).store (p + 64) b).load 0x40 = m.load 0x40 := by + constructor <;> mem_simp + +/-- A calldata copy of symbolic length `n` at `p`, the next word stored at `p + n` (the +pointer advanced by the copy), then the copy hashed: the hash reads exactly the copied bytes. -/ +theorem copy_then_store_read (m : Mem) (p n : Nat) (src : Nat → Memory.Byte) (w : Word) : + ((m.write p n src).store (p + n) w).read p n = (List.range n).map src := by + mem_simp + +/-- An order hash over `p .. p+n` followed by an encoding at the advanced pointer: the +encoding's word reads back, the copy is untouched. -/ +theorem copy_encode (m : Mem) (p n : Nat) (src : Nat → Memory.Byte) (t w : Word) : + (((m.write p n src).store (p + n) t).store (p + n + 32) w).read (p + n) 64 = + wordBytes t ++ wordBytes w ∧ + (((m.write p n src).store (p + n) t).store (p + n + 32) w).read p n = (List.range n).map src := by + constructor <;> mem_simp + +/-- `MCOPY` of `n` bytes from `s` to `d`, read back at a computed offset inside. -/ +theorem mcopy_read (m : Mem) (d s n k : Nat) (hk : k + 32 ≤ n) : + let src := m.expand s n + (src.write d n (fun i => src.bytes (s + i))).read (d + k) 32 = m.read (s + k) 32 := by + intro src + rw [read_copy_inside _ _ _ _ _ _ _ (by omega) (by omega)] + simp [src, Nat.add_sub_cancel_left] + +/-! Negatives: concrete memories where the wrong claim is false, checked by the kernel. -/ + +set_option maxRecDepth 8192 in +/-- Wrong offset: the encoding read one byte late is not the encoded words. -/ +theorem wrong_offset : ¬ ∀ (m : Mem) (p : Nat) (t a : Word), + ((m.store p t).store (p + 32) a).read (p + 1) 64 = wordBytes t ++ wordBytes a := by + intro h + have := congrArg (·[31]?) (h initial 0 1 0) + revert this + decide + +/-- Wrong length: 64 bytes are not three words. -/ +theorem wrong_length : ¬ ∀ (m : Mem) (p : Nat) (t a b : Word), + (((m.store p t).store (p + 32) a).store (p + 64) b).read p 64 = + wordBytes t ++ wordBytes a ++ wordBytes b := by + intro h + have := congrArg List.length (h initial 0 0 0 0) + simp at this + +set_option maxRecDepth 8192 in +/-- Overlapping write: a store sixteen bytes into a word replaces its low half. -/ +theorem overlapping_write : ¬ ∀ (m : Mem) (p : Nat) (a b : Word), + ((m.store p a).store (p + 16) b).read p 32 = wordBytes a := by + intro h + have := congrArg (·[31]?) (h initial 0 1 0) + revert this + decide + +/-- The procedure fails closed on the overlap: it cannot move the read past the second store. -/ +example (m : Mem) (p : Nat) (a b : Word) : True := by + fail_if_success + have : ((m.store p a).store (p + 16) b).read p 32 = wordBytes a := by mem_simp + trivial + +/-- ... and on a store it cannot place: an unrelated pointer `q` may alias `p`. -/ +example (m : Mem) (p q : Nat) (a b : Word) : True := by + fail_if_success + have : ((m.store p a).store q b).read p 32 = wordBytes a := by mem_simp + trivial + +/-- With the path's bound on `q`, the same read moves. -/ +example (m : Mem) (p q : Nat) (a b : Word) (h : p + 32 ≤ q) : + ((m.store p a).store q b).read p 32 = wordBytes a := by mem_simp + +/-! Exact expansion at symbolic offsets. -/ + +example (m : Mem) (p : Nat) (v : Word) (h : (BitVec.ofNat 251 ((p + 63) / 32)).toNat ≤ m.words.toNat) : + (m.store p v).words = m.words := by + rw [words_store]; exact grow_of_le _ _ (by simpa using h) + +/-! Containment: a hash range that holds stores and copies at computed offsets. -/ + +/-- An order-hash shape: a type hash at `p`, a copied array of symbolic length `n` after it, +hashed as one range of `32 + n` bytes. -/ +theorem typehash_array_read (m : Mem) (p n : Nat) (t : Word) (src : Nat → Memory.Byte) : + ((m.store p t).write (p + 32) n src).read p (32 + n) = wordBytes t ++ (List.range n).map src := by + mem_simp + +/-- A word stored at a computed offset `q` inside a hashed range of symbolic length. -/ +theorem store_within_read (m : Mem) (p q k : Nat) (v : Word) (lo : p ≤ q) (hi : q + 32 ≤ p + k) : + (m.store q v).read p k = m.read p (q - p) ++ wordBytes v ++ m.read (q + 32) (p + k - (q + 32)) := by + mem_simp + +/-- Wrong split: a word that starts inside the range but ends past it is not inside it. -/ +theorem straddling_store : ¬ ∀ (m : Mem) (p : Nat) (v : Word), + (m.store (p + 16) v).read p 32 = m.read p 16 ++ wordBytes v ++ m.read (p + 48) 0 := by + intro h + have := congrArg List.length (h initial 0 0) + simp at this + +/-- The procedure refuses the straddling store. -/ +example (m : Mem) (p : Nat) (v : Word) : True := by + fail_if_success + have : (m.store (p + 16) v).read p 32 = m.read p 16 ++ wordBytes v := by mem_simp + trivial + +end SolarTV.Machine.Mem + +/-- info: 'SolarTV.Machine.Mem.encode3_read' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in #print axioms SolarTV.Machine.Mem.encode3_read +/-- info: 'SolarTV.Machine.Mem.copy_then_store_read' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in #print axioms SolarTV.Machine.Mem.copy_then_store_read +/-- info: 'SolarTV.Machine.Mem.copy_encode' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in #print axioms SolarTV.Machine.Mem.copy_encode +/-- info: 'SolarTV.Machine.Mem.mcopy_read' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in #print axioms SolarTV.Machine.Mem.mcopy_read +/-- info: 'SolarTV.Machine.Mem.wrong_offset' depends on axioms: [propext] -/ +#guard_msgs in #print axioms SolarTV.Machine.Mem.wrong_offset +/-- info: 'SolarTV.Machine.Mem.wrong_length' depends on axioms: [propext] -/ +#guard_msgs in #print axioms SolarTV.Machine.Mem.wrong_length +/-- info: 'SolarTV.Machine.Mem.overlapping_write' depends on axioms: [propext] -/ +#guard_msgs in #print axioms SolarTV.Machine.Mem.overlapping_write +/-- info: 'SolarTV.Machine.Mem.read_store_disjoint' depends on axioms: [propext, Quot.sound] -/ +#guard_msgs in #print axioms SolarTV.Machine.Mem.read_store_disjoint +/-- info: 'SolarTV.Machine.Mem.load_store_disjoint' depends on axioms: [propext, Quot.sound] -/ +#guard_msgs in #print axioms SolarTV.Machine.Mem.load_store_disjoint +/-- info: 'SolarTV.Machine.Mem.read_storeByte_disjoint' depends on axioms: [propext, Quot.sound] -/ +#guard_msgs in #print axioms SolarTV.Machine.Mem.read_storeByte_disjoint +/-- info: 'SolarTV.Machine.Mem.read_write_disjoint' depends on axioms: [propext, Quot.sound] -/ +#guard_msgs in #print axioms SolarTV.Machine.Mem.read_write_disjoint +/-- info: 'SolarTV.Machine.Mem.read_store_same' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in #print axioms SolarTV.Machine.Mem.read_store_same +/-- info: 'SolarTV.Machine.Mem.read_write_inside' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in #print axioms SolarTV.Machine.Mem.read_write_inside +/-- info: 'SolarTV.Machine.Mem.read_write_same' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in #print axioms SolarTV.Machine.Mem.read_write_same +/-- info: 'SolarTV.Machine.Mem.read_copy_inside' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in #print axioms SolarTV.Machine.Mem.read_copy_inside +/-- info: 'SolarTV.Machine.Mem.read_store_head' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in #print axioms SolarTV.Machine.Mem.read_store_head +/-- info: 'SolarTV.Machine.Mem.read_split' depends on axioms: [propext, Quot.sound] -/ +#guard_msgs in #print axioms SolarTV.Machine.Mem.read_split +/-- info: 'SolarTV.Machine.Mem.read_append' depends on axioms: [propext, Quot.sound] -/ +#guard_msgs in #print axioms SolarTV.Machine.Mem.read_append +/-- info: 'SolarTV.Machine.Mem.grow_of_le' depends on axioms: [propext, Quot.sound] -/ +#guard_msgs in #print axioms SolarTV.Machine.Mem.grow_of_le +/-- info: 'SolarTV.Machine.Mem.grow_of_lt' depends on axioms: [propext] -/ +#guard_msgs in #print axioms SolarTV.Machine.Mem.grow_of_lt +/-- info: 'SolarTV.Machine.Mem.words_store' depends on axioms: [propext] -/ +#guard_msgs in #print axioms SolarTV.Machine.Mem.words_store +/-- info: 'SolarTV.Machine.Mem.read_store' depends on axioms: [propext, Quot.sound] -/ +#guard_msgs in #print axioms SolarTV.Machine.Mem.read_store +/-- info: 'SolarTV.Machine.Mem.typehash_array_read' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in #print axioms SolarTV.Machine.Mem.typehash_array_read +/-- info: 'SolarTV.Machine.Mem.store_within_read' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in #print axioms SolarTV.Machine.Mem.store_within_read +/-- info: 'SolarTV.Machine.Mem.straddling_store' depends on axioms: [propext] -/ +#guard_msgs in #print axioms SolarTV.Machine.Mem.straddling_store +/-- info: 'SolarTV.Machine.Mem.read_store_within' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in #print axioms SolarTV.Machine.Mem.read_store_within +/-- info: 'SolarTV.Machine.Mem.read_write_within' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in #print axioms SolarTV.Machine.Mem.read_write_within diff --git a/tv/SolarTV/Outcome.lean b/tv/SolarTV/Outcome.lean new file mode 100644 index 00000000..f84eecba --- /dev/null +++ b/tv/SolarTV/Outcome.lean @@ -0,0 +1,116 @@ +/-! Observable termination and refinement for the supported, gas-independent fragment. +A semantic Panic(uint256) has a fixed four-byte selector and one ABI word, so its +code identifies the complete payload and cannot alias the empty revert payload. +`invalid` is an exceptional halt, distinct from both forms of revert. Unsupported +IR and checker limits are host-side failures, never execution outcomes. +-/ + +namespace SolarTV + +inductive RevertData where + | empty + | panic (code : BitVec 256) + deriving DecidableEq + +inductive Outcome (α : Type) where + | returned (value : α) + | reverted (data : RevertData) + | invalid + deriving DecidableEq + +/-- Continue only after successful execution. Later failures cannot overwrite the first one. -/ +def Outcome.bind (result : Outcome α) (next : α → Outcome β) : Outcome β := + match result with + | .returned value => next value + | .reverted data => .reverted data + | .invalid => .invalid + +@[simp] theorem Outcome.bind_return (result : Outcome α) : + result.bind Outcome.returned = result := by + cases result <;> rfl + +@[simp] theorem Outcome.bind_returned (value : α) (next : α → Outcome β) : + (Outcome.returned value).bind next = next value := rfl + +@[simp] theorem Outcome.bind_reverted (data : RevertData) (next : α → Outcome β) : + (Outcome.reverted data).bind next = Outcome.reverted data := rfl + +@[simp] theorem Outcome.bind_invalid (next : α → Outcome β) : + Outcome.invalid.bind next = Outcome.invalid := rfl + +@[simp] theorem Outcome.bind_ite (condition : Prop) [Decidable condition] + (yes no : Outcome α) (next : α → Outcome β) : + (if condition then yes else no).bind next = + if condition then yes.bind next else no.bind next := by + split <;> rfl + +/-- A behavior records the outcomes a program permits at a fixed input. +This allows future nondeterministic semantics without equating failure with undefinedness. -/ +abbrev Behavior (α : Type) := Outcome α → Prop + +def Behavior.exact (result : Outcome α) : Behavior α := fun observed => observed = result + +/-- A candidate may produce only outcomes permitted by the original program. -/ +def Behavior.refines (original candidate : Behavior α) : Prop := + ∀ observed, candidate observed → original observed + +/-- The current importer emits deterministic, defined executions. -/ +def refines (original candidate : Outcome α) : Prop := + Behavior.refines (Behavior.exact original) (Behavior.exact candidate) + +@[simp] theorem refines_iff_eq (original candidate : Outcome α) : + refines original candidate ↔ original = candidate := by + constructor + · intro h + exact (h candidate rfl).symm + · intro h + subst candidate + exact fun _ observed => observed + +theorem refinement_transitive (a b c : Behavior α) + (ab : Behavior.refines a b) (bc : Behavior.refines b c) : Behavior.refines a c := + fun result hc => ab result (bc result hc) + +/-- A bit-vector projection used only to ask the solver for candidate witnesses. +The importer bounds return widths by 256. Every proposed input is then checked +against the actual refinement proposition, independently of this projection. -/ +def Outcome.code (result : Outcome (BitVec width)) : BitVec 258 := + match result with + | .returned value => value.setWidth 258 + | .reverted .empty => 1#258 <<< 256 + | .reverted (.panic code) => (2#258 <<< 256) ||| code.setWidth 258 + | .invalid => 3#258 <<< 256 + +@[simp] theorem Outcome.code_returned (value : BitVec width) : + Outcome.code (.returned value) = value.setWidth 258 := rfl + +@[simp] theorem Outcome.code_empty : + Outcome.code (Outcome.reverted .empty : Outcome (BitVec width)) = 1#258 <<< 256 := rfl + +@[simp] theorem Outcome.code_panic (code : BitVec 256) : + Outcome.code (Outcome.reverted (.panic code) : Outcome (BitVec width)) = + (2#258 <<< 256) ||| code.setWidth 258 := rfl + +@[simp] theorem Outcome.code_invalid : + Outcome.code (Outcome.invalid : Outcome (BitVec width)) = 3#258 <<< 256 := rfl + +@[simp] theorem Outcome.code_cond (condition : Bool) (yes no : Outcome (BitVec width)) : + Outcome.code (bif condition then yes else no) = + bif condition then Outcome.code yes else Outcome.code no := by + cases condition <;> rfl + +@[simp] theorem Outcome.code_ite (condition : Prop) [Decidable condition] + (yes no : Outcome (BitVec width)) : + Outcome.code (if condition then yes else no) = + if condition then Outcome.code yes else Outcome.code no := by + split <;> rfl + +/-- Render a concrete observation without erasing the reason execution failed. -/ +def Outcome.describe (result : Outcome (BitVec width)) : String := + match result with + | .returned value => toString value.toNat + | .reverted .empty => "revert(empty)" + | .reverted (.panic code) => s!"revert Panic({code.toNat})" + | .invalid => "invalid" + +end SolarTV diff --git a/tv/SolarTV/Sem.lean b/tv/SolarTV/Sem.lean new file mode 100644 index 00000000..f3b81e42 --- /dev/null +++ b/tv/SolarTV/Sem.lean @@ -0,0 +1,64 @@ +/-! Contract-level semantics: what a call observes, and stages between languages. + +The definitions up to the marker below restate the interface of solidity-lean verbatim, so +that a stage proved here composes with its stages from Solidity to bytecode. A `Sem` runs a +program on a call and gives its observable result, or `none` when it has none (it diverges, +or the call is outside what the semantics defines). `Stage A B p q scope` says that every +result `p` gives for a call in `scope`, `q` gives too. -/ + +namespace SolarTV + +structure Call where + calldata : ByteArray + callvalue : Nat + storage : List (Nat × Nat) + +structure Observable where + success : Bool + output : List Nat + logs : List (List Nat × List Nat) + storage : Nat → Nat + +def slotValue (storage : List (Nat × Nat)) (slot : Nat) : Nat := + storage.foldl (fun acc kv => if kv.1 % 2^256 = slot % 2^256 then kv.2 % 2^256 else acc) 0 + +structure Sem where + Prog : Type + run : Prog → Call → Option Observable + +def Stage (A B : Sem) (p : A.Prog) (q : B.Prog) (scope : Call → Prop) : Prop := + ∀ call, scope call → ∀ obs, A.run p call = some obs → B.run q call = some obs + +theorem Stage.trans {A B C : Sem} {p : A.Prog} {q : B.Prog} {r : C.Prog} {scope : Call → Prop} + (first : Stage A B p q scope) (second : Stage B C q r scope) : Stage A C p r scope := + fun call inScope obs ran => second call inScope obs (first call inScope obs ran) + +/-! Everything below this marker is ours, not solidity-lean's interface. -/ + +theorem Stage.refl (A : Sem) (p : A.Prog) (scope : Call → Prop) : Stage A A p p scope := + fun _ _ _ ran => ran + +/-- A stage holds on any narrower scope. -/ +theorem Stage.mono {A B : Sem} {p : A.Prog} {q : B.Prog} {scope narrower : Call → Prop} + (stage : Stage A B p q scope) (within : ∀ call, narrower call → scope call) : + Stage A B p q narrower := + fun call inScope => stage call (within call inScope) + +/-- The frame a call runs in, which the interface leaves implicit. -/ +structure Environment where + caller : Nat + callee : Nat + frames : Nat + +/-- One frame, called by 0x2000 at 0x1000, as solidity-lean's test environment. The machine +runs at its callee but takes the caller from the oracle, so a stage proved for every oracle holds +for every caller, this one among them. -/ +def environment : Environment := ⟨0x2000, 0x1000, 1⟩ + +/-- A failed call rolls back: it logs nothing and leaves the storage it started with. Its +output is then its revert data, which each semantics defines (`Machine.revertData` here). -/ +def Sem.FailureConvention (S : Sem) : Prop := + ∀ p call obs, S.run p call = some obs → obs.success = false → + obs.logs = [] ∧ obs.storage = slotValue call.storage + +end SolarTV diff --git a/tv/SolarTV/Stages/Assembly.lean b/tv/SolarTV/Stages/Assembly.lean new file mode 100644 index 00000000..a26e3e76 --- /dev/null +++ b/tv/SolarTV/Stages/Assembly.lean @@ -0,0 +1,248 @@ +import SolarTV.Sem + +/-! The stage from assembly to bytecode, which `-Zvalidate-assembly` checks. + +The assembler solves a program of opcodes, pushes of constants and of label offsets, and label +definitions to a layout and emits bytes. `-Zvalidate-assembly` (`validate_assembly.rs`) decodes the +bytes in lockstep with the program: `Walk` is that walk, with the checker's conditions as its +constructors. Each item decodes, at the offset the walk reached, to the instruction it is at the +layout (`Item.expected`): an opcode to its byte, a constant push to a PUSH of the constant, so its +width suffices, a label push to a PUSH of the label's offset, and a label to a `JUMPDEST` at the +label's offset; and the walk ends exactly at the end of the code. Jump tables +(`indexed_jump.rs`) add two items: a packed table, a PUSH of a word of one-byte label offsets +that `BYTE` picks from, each offset below 256 so that its byte is the offset, and the entry +stubs of a stride table, each a `JUMPDEST` at the table's offset plus its index times the +stride (`Item.placed`). + +From the walk, `walk_decodes` proves that linear decoding of the bytes from offset 0 is exactly the +program's instructions at their offsets, `jump_targets` that every pushed label is the offset of a +`JUMPDEST` that decoding reaches as an instruction, and `stage` that assembly to bytecode is a +stage for any bytecode semantics that runs the code's linear decoding, against the assembly program +run at the layout the walk found. No axioms. + +An immutable's placeholder is an item of its own, a push of zeros of its width, which the +deployment code links with the immutable's value: `SolarTV.Stages.Link` shows that linear +decoding of the linked code is the walk's instructions with each placeholder pushing its value. + +Outside this model, as in the checker's limits: program data and library placeholders, which the checker checks byte for byte against the artifact's records, +and the data flow of the deployment code's copy of the runtime code. The bytecode semantics +running the linear decoding is a hypothesis: legacy EVM code runs instruction by instruction from +offset 0 and jumps only to a `JUMPDEST` that starts an instruction, which is what the decoding +lists. -/ + +namespace SolarTV.Assembly + +/-- An instruction as bytecode decodes it: an opcode, or a push of its immediate's value. -/ +inductive Instr where + | op (byte : Nat) + | push (value : Nat) + deriving DecidableEq, Repr + +def PUSH0 : Nat := 0x5f +def PUSH1 : Nat := 0x60 +def PUSH32 : Nat := 0x7f +def JUMPDEST : Nat := 0x5b + +/-- The big-endian value of `bytes`. -/ +def bigEndian (bytes : List Nat) : Nat := + bytes.foldl (fun value byte => value * 256 + byte) 0 + +/-- The instruction at `pc` of `code` and the offset after it, or `none` past the end of the +code or for a push whose immediate runs past it, as the checker reads it. -/ +def decode (code : List Nat) (pc : Nat) : Option (Instr × Nat) := + match code[pc]? with + | none => none + | some byte => + if byte = PUSH0 then some (.push 0, pc + 1) + else if PUSH1 ≤ byte ∧ byte ≤ PUSH32 then + if pc + 1 + (byte - PUSH1 + 1) ≤ code.length then + some (.push (bigEndian ((code.drop (pc + 1)).take (byte - PUSH1 + 1))), + pc + 1 + (byte - PUSH1 + 1)) + else none + else some (.op byte, pc + 1) + +/-- Linear decoding of `code` from `pc`, each instruction at its offset, for at most `fuel` +instructions. -/ +def decodeFrom (code : List Nat) : Nat → Nat → List (Nat × Instr) + | 0, _ => [] + | fuel + 1, pc => + match decode code pc with + | some (instr, next) => (pc, instr) :: decodeFrom code fuel next + | none => [] + +/-- An instruction of the assembly program: an opcode, a push of a constant or of a label's +offset, a label's definition, or the `PUSH` placeholder of immutable `id`, zeros until a +deployment links it. -/ +inductive Item where + | op (byte : Nat) + | push (value : Nat) + | pushLabel (label : Nat) + | label (label : Nat) + | immutable (id bytes : Nat) + /-- A push of a word of one-byte label offsets, the first label's in the word's highest byte + of the push: a packed jump table, which `BYTE` picks an entry of. -/ + | pushTable (labels : List Nat) + /-- Entry `index` of a stride table whose first entry is label `table`: a `JUMPDEST` + `index` strides past the table's offset. -/ + | entry (table index stride : Nat) + deriving DecidableEq, Repr + +/-- The instruction an item is at a layout that puts each label at `offset`. -/ +def Item.expected (offset : Nat → Nat) : Item → Instr + | .op byte => .op byte + | .push value => .push value + | .pushLabel l => .push (offset l) + | .label _ => .op JUMPDEST + | .immutable _ _ => .push 0 + | .pushTable labels => .push (bigEndian (labels.map offset)) + | .entry _ _ _ => .op JUMPDEST + +/-- Whether an item is placed where the layout says at `pc`: a label at its offset, a packed +table's every offset in one byte, so that the word's bytes are the offsets, and a stride table's +entry its index of strides past the table's offset. -/ +def Item.placed (offset : Nat → Nat) (pc : Nat) : Item → Bool + | .label l => offset l == pc + | .pushTable labels => labels.all (offset · < 256) + | .entry table index stride => offset table + index * stride == pc + | _ => true + +/-- The checker's walk: decoding `code` from `pc` in lockstep with `items` gives each item's +instruction at the layout `offset`, with each item placed as the layout says (`Item.placed`), +and ends at the end of the code. `stream` is the program's instructions at the offsets the walk reached. -/ +inductive Walk (code : List Nat) (offset : Nat → Nat) : + Nat → List Item → List (Nat × Instr) → Prop + | nil : Walk code offset code.length [] [] + | cons {pc next : Nat} {item : Item} {items : List Item} {stream : List (Nat × Instr)} : + decode code pc = some (item.expected offset, next) → + item.placed offset pc = true → + Walk code offset next items stream → + Walk code offset pc (item :: items) ((pc, item.expected offset) :: stream) + +theorem decode_advances {code : List Nat} {pc next : Nat} {instr : Instr} + (h : decode code pc = some (instr, next)) : pc < next := by + unfold decode at h + split at h + · simp at h + · split at h + · rcases h with ⟨_, rfl⟩ + omega + · split at h + · split at h + · rcases h with ⟨_, rfl⟩ + omega + · simp at h + · rcases h with ⟨_, rfl⟩ + omega + +/-- Each item takes at least a byte. -/ +theorem walk_length {code : List Nat} {offset : Nat → Nat} {pc : Nat} {items : List Item} + {stream : List (Nat × Instr)} (w : Walk code offset pc items stream) : + pc + items.length ≤ code.length := by + induction w with + | nil => simp + | cons decoded _ _ ih => + have := decode_advances decoded + simp only [List.length_cons] + omega + +/-- Linear decoding is the program's instructions at their offsets. -/ +theorem walk_decodes {code : List Nat} {offset : Nat → Nat} {pc : Nat} {items : List Item} + {stream : List (Nat × Instr)} (w : Walk code offset pc items stream) : + ∀ fuel, items.length < fuel → decodeFrom code fuel pc = stream := by + induction w with + | nil => + intro fuel h + cases fuel with + | zero => simp at h + | succ fuel => + simp [decodeFrom, decode] + | cons decoded _ _ ih => + intro fuel h + cases fuel with + | zero => simp at h + | succ fuel => + simp only [List.length_cons] at h + simp only [decodeFrom, decoded] + rw [ih fuel (by omega)] + +/-- The decoded instructions are the program's items at the layout. -/ +theorem walk_instructions {code : List Nat} {offset : Nat → Nat} {pc : Nat} {items : List Item} + {stream : List (Nat × Instr)} (w : Walk code offset pc items stream) : + stream.map Prod.snd = items.map (Item.expected offset) := by + induction w with + | nil => rfl + | cons _ _ _ ih => simp [ih] + +/-- A defined label's offset holds a `JUMPDEST` that starts an instruction. -/ +theorem walk_label {code : List Nat} {offset : Nat → Nat} {pc : Nat} {items : List Item} + {stream : List (Nat × Instr)} (w : Walk code offset pc items stream) {label : Nat} + (defined : Item.label label ∈ items) : (offset label, Instr.op JUMPDEST) ∈ stream := by + induction w with + | nil => simp at defined + | @cons pc next item items stream _ labels _ ih => + rcases List.mem_cons.1 defined with here | later + · subst here + simp only [Item.placed, beq_iff_eq] at labels + rw [labels] + simp [Item.expected] + · exact List.mem_cons_of_mem _ (ih later) + +/-- A stride table's entry, its index of strides past the table's offset, holds a `JUMPDEST` +that starts an instruction. -/ +theorem walk_entry {code : List Nat} {offset : Nat → Nat} {pc : Nat} {items : List Item} + {stream : List (Nat × Instr)} (w : Walk code offset pc items stream) {table index stride : Nat} + (defined : Item.entry table index stride ∈ items) : + (offset table + index * stride, Instr.op JUMPDEST) ∈ stream := by + induction w with + | nil => simp at defined + | @cons pc next item items stream _ placed _ ih => + rcases List.mem_cons.1 defined with here | later + · subst here + simp only [Item.placed, beq_iff_eq] at placed + rw [placed] + simp [Item.expected] + · exact List.mem_cons_of_mem _ (ih later) + +/-- Every label the program pushes and defines is the offset of a `JUMPDEST` that the code's +linear decoding reaches as an instruction. -/ +theorem jump_targets {code : List Nat} {offset : Nat → Nat} {items : List Item} + {stream : List (Nat × Instr)} (w : Walk code offset 0 items stream) {label : Nat} + (defined : Item.label label ∈ items) : + (offset label, Instr.op JUMPDEST) ∈ decodeFrom code (code.length + 1) 0 := by + have := walk_length w + rw [walk_decodes w _ (by omega)] + exact walk_label w defined + +/-- Assembly to bytecode is a stage: the program `p`, run at the layout the walk found, and the +code, run by a bytecode semantics that runs its linear decoding, give the same result. -/ +theorem stage {A B : Sem} {p : A.Prog} {code : B.Prog} {scope : Call → Prop} + (bytes : List Nat) (items : List Item) (offset : Nat → Nat) (stream : List (Nat × Instr)) + (run : List (Nat × Instr) → Call → Option Observable) + (assembly : ∀ call, A.run p call = run stream call) + (bytecode : ∀ call, B.run code call = run (decodeFrom bytes (bytes.length + 1) 0) call) + (checked : Walk bytes offset 0 items stream) : Stage A B p code scope := by + intro call _ obs ran + have := walk_length checked + rw [bytecode, walk_decodes checked _ (by omega), ← assembly] + exact ran + +/-! A jump over a label push: `PUSH1 3; JUMP; JUMPDEST; STOP`, with label 0 at offset 3. -/ + +def example_items : List Item := [.pushLabel 0, .op 0x56, .label 0, .op 0x00] + +def example_code : List Nat := [0x60, 3, 0x56, 0x5b, 0x00] + +theorem example_walk : + Walk example_code (fun _ => 3) 0 example_items + [(0, .push 3), (2, .op 0x56), (3, .op 0x5b), (4, .op 0x00)] := + .cons (by rfl) rfl (.cons (by rfl) rfl (.cons (by rfl) rfl (.cons (by rfl) rfl .nil))) + +/-- Off by one, the label push misses the label: no walk exists, as the checker reports. -/ +theorem example_fault (stream : List (Nat × Instr)) : + ¬ Walk [0x60, 4, 0x56, 0x5b, 0x00] (fun _ => 3) 0 example_items stream := by + intro w + cases w with + | cons decoded _ _ => + simp [decode, bigEndian, Item.expected, PUSH0, PUSH1, PUSH32] at decoded + +end SolarTV.Assembly diff --git a/tv/SolarTV/Stages/AssemblyCheck.lean b/tv/SolarTV/Stages/AssemblyCheck.lean new file mode 100644 index 00000000..b1b435ef --- /dev/null +++ b/tv/SolarTV/Stages/AssemblyCheck.lean @@ -0,0 +1,74 @@ +import SolarTV.Stages.Assembly + +/-! The checker's walk as a function, which the kernel evaluates. + +`walk` runs `-Zvalidate-assembly`'s lockstep decoding (`Walk`) on concrete bytes and +items: it gives the stream of instructions the walk reaches, or `none` where an item does not +decode to its instruction at the layout, an item is not placed as the layout says, or the walk +does not end exactly at the end of the code. `walk_sound` and `walk_complete` show it is +`Walk`, so a kernel-checked `walk … = some stream` proves the walk, and `walk … = none` +refutes every walk (`no_walk`), as the checker rejects the code. -/ + +namespace SolarTV.Assembly + +/-- The checker's walk from `pc`: the stream of instructions it reaches, or `none`. -/ +def walk (code : List Nat) (offset : Nat → Nat) : Nat → List Item → Option (List (Nat × Instr)) + | pc, [] => if pc = code.length then some [] else none + | pc, item :: items => + match decode code pc with + | none => none + | some (instr, next) => + if instr = item.expected offset ∧ item.placed offset pc = true then + match walk code offset next items with + | some rest => some ((pc, instr) :: rest) + | none => none + else none + +theorem walk_sound {code : List Nat} {offset : Nat → Nat} : + ∀ {pc : Nat} {items : List Item} {stream : List (Nat × Instr)}, + walk code offset pc items = some stream → Walk code offset pc items stream + | pc, [], stream, h => by + simp only [walk] at h + by_cases e : pc = code.length + · simp only [e, ite_true] at h + cases h + rw [e] + exact .nil + · simp only [e, ite_false] at h + cases h + | pc, item :: items, stream, h => by + simp only [walk] at h + cases hd : decode code pc with + | none => rw [hd] at h; cases h + | some r => + obtain ⟨instr, next⟩ := r + rw [hd] at h + simp only at h + by_cases ok : instr = item.expected offset ∧ item.placed offset pc = true + · simp only [ok, and_self, ite_true] at h + cases hw : walk code offset next items with + | none => rw [hw] at h; cases h + | some rest => + rw [hw] at h + cases h + rw [ok.1] at hd + exact .cons hd ok.2 (walk_sound hw) + · simp only [ok, ite_false] at h + cases h + +theorem walk_complete {code : List Nat} {offset : Nat → Nat} {pc : Nat} {items : List Item} + {stream : List (Nat × Instr)} (w : Walk code offset pc items stream) : + walk code offset pc items = some stream := by + induction w with + | nil => simp [walk] + | cons decoded labels _ ih => + simp [walk, decoded, labels, ih] + +/-- A walk the function refutes does not exist. -/ +theorem no_walk {code : List Nat} {offset : Nat → Nat} {pc : Nat} {items : List Item} + (h : walk code offset pc items = none) (stream : List (Nat × Instr)) : + ¬ Walk code offset pc items stream := fun w => by + rw [walk_complete w] at h + cases h + +end SolarTV.Assembly diff --git a/tv/SolarTV/Stages/Entries.lean b/tv/SolarTV/Stages/Entries.lean new file mode 100644 index 00000000..57fd2bea --- /dev/null +++ b/tv/SolarTV/Stages/Entries.lean @@ -0,0 +1,93 @@ +import SolarTV.Sem + +/-! The stages of `lower-abi` and `lower-dispatch`, which `-Zvalidate-passes` checks query by +query (`validate_passes/entries.rs`). + +Before them, a contract's code is its external entries, and the ABI routes each call: to an entry +by its selector, to `receive` or `fallback`, or to an outcome of its own, such as a rejected value +or an empty revert on a miss. `Routing` is that routing and `routed` the semantics of a contract +whose entries run `body`. `lower-abi` replaces each entry's body with a wrapper that decodes its +arguments from calldata, runs the body and encodes its results; `lower-dispatch` replaces the +routing with a dispatcher, a program of whatever semantics runs the lowered MIR. + +Each query's `unsat` verdict is an obligation here: `AbiObligation` for the query of one wrapper, +that on every call the routing sends to its entry the wrapper ends as the reference over the body +does, and `DispatchObligation` for the dispatcher's query, that the dispatcher ends as the routing +over the wrappers does. They are discharged per query by the solver, or by a certificate as the +pass queries are, not proved here: each states what its query's reference encodes, over the +semantics the encoder gives MIR, and relating that to a Lean semantics of MIR is the work of the +pass validation stages, outside this file. From them `abi_stage` proves the stage of `lower-abi` over all entries, and +`entries_stage` the stage from the routed contract to its dispatcher, which `to_bytecode` +composes with the stages after it. -/ + +namespace SolarTV.Entries + +/-- How the ABI routes a call over a contract's entries `E`: to an entry, or to an outcome of the +routing itself. -/ +structure Routing (E : Type) where + route : Call → Option E + miss : Call → Option Observable + +/-- A routed contract whose entries run `body`. -/ +def Routing.run {E : Type} (r : Routing E) (body : E → Call → Option Observable) (call : Call) : + Option Observable := + match r.route call with + | some entry => body entry call + | none => r.miss call + +/-- The semantics of a contract routed by `r`: a program is the body of each entry. -/ +def routed {E : Type} (r : Routing E) : Sem := ⟨E → Call → Option Observable, r.run⟩ + +/-- What the `lower-abi` query of `entry` proves: on every call in scope that the routing sends to +the entry, its wrapper ends as its body does under the ABI's decoding and encoding, which +`body` includes. -/ +def AbiObligation {E : Type} (r : Routing E) (scope : Call → Prop) + (body wrapper : E → Call → Option Observable) (entry : E) : Prop := + ∀ call, scope call → r.route call = some entry → + ∀ obs, body entry call = some obs → wrapper entry call = some obs + +/-- What the `lower-dispatch` query proves: the dispatcher `q` ends as the routing over the +wrappers does. -/ +def DispatchObligation {E : Type} (D : Sem) (r : Routing E) (scope : Call → Prop) + (wrapper : E → Call → Option Observable) (q : D.Prog) : Prop := + ∀ call, scope call → ∀ obs, r.run wrapper call = some obs → D.run q call = some obs + +/-- The queries of every wrapper give the stage of `lower-abi`. -/ +theorem abi_stage {E : Type} {r : Routing E} {scope : Call → Prop} + {body wrapper : E → Call → Option Observable} + (each : ∀ entry, AbiObligation r scope body wrapper entry) : + Stage (routed r) (routed r) body wrapper scope := by + intro call inScope obs ran + change r.run body call = some obs at ran + change r.run wrapper call = some obs + unfold Routing.run at ran ⊢ + cases h : r.route call with + | none => rw [h] at ran; exact ran + | some entry => rw [h] at ran; exact each entry call inScope h obs ran + +theorem dispatch_stage {E : Type} {D : Sem} {r : Routing E} {scope : Call → Prop} + {wrapper : E → Call → Option Observable} {q : D.Prog} + (query : DispatchObligation D r scope wrapper q) : Stage (routed r) D wrapper q scope := + query + +/-- The stage from the routed contract to its dispatcher: `lower-abi` then `lower-dispatch`. -/ +theorem entries_stage {E : Type} {D : Sem} {r : Routing E} {scope : Call → Prop} + {body wrapper : E → Call → Option Observable} {q : D.Prog} + (abi : ∀ entry, AbiObligation r scope body wrapper entry) + (dispatch : DispatchObligation D r scope wrapper q) : Stage (routed r) D body q scope := + (abi_stage abi).trans (dispatch_stage dispatch) + +/-- From a source semantics to bytecode: a stage into the routed contract, such as the one from +SolidCore to semantic MIR, the entry lowering, a stage from the dispatcher to assembly, such as +the composed MIR, scheduling and EVM IR stages, and the assembly stage. -/ +theorem to_bytecode {E : Type} {S D A B : Sem} {r : Routing E} {scope : Call → Prop} + {src : S.Prog} {body wrapper : E → Call → Option Observable} {q : D.Prog} {p : A.Prog} + {code : B.Prog} + (front : Stage S (routed r) src body scope) + (abi : ∀ entry, AbiObligation r scope body wrapper entry) + (dispatch : DispatchObligation D r scope wrapper q) + (backend : Stage D A q p scope) (assembly : Stage A B p code scope) : + Stage S B src code scope := + ((front.trans (entries_stage abi dispatch)).trans backend).trans assembly + +end SolarTV.Entries diff --git a/tv/SolarTV/Stages/Link.lean b/tv/SolarTV/Stages/Link.lean new file mode 100644 index 00000000..46966911 --- /dev/null +++ b/tv/SolarTV/Stages/Link.lean @@ -0,0 +1,351 @@ +import SolarTV.Stages.Assembly +import SolarTV.Machine + +/-! Linking immutables into the runtime bytecode. + +An immutable is fixed at deployment: the deployment code writes its value over each of its +placeholders, the zero bytes of a `PUSH` in the runtime code, as the big-endian encoding +of its low `bytes` bytes (`link`). The bytecode a stage is checked against is the code before +that, as the compiler emits it, with each placeholder an `Item.immutable` that walks as a push of +zeros. `placeholdersOf` reads the placeholders off a walk: each at the byte after its push. + +`walk_link` shows that for every value of the immutables, the linear decoding of the linked code +is the walk's stream with each placeholder pushing its value modulo `256 ^ bytes` +(`linkedStream`), and `linked_instructions` that those are the program's items with each +placeholder linked. `placed`, which the kernel evaluates, checks what that takes of the walk: +each placeholder is a `PUSH` of its width. So a proof that the walk accepts the unlinked +bytecode binds every bytecode a deployment runs: its hash is that of `link` of the code with the +placeholders the manifest lists. `Machine.immutableWord_toNat` connects the pushed value with +the word the stages read. No axioms beyond the standard three. -/ + +namespace SolarTV.Assembly + +/-- An immutable placeholder: the immutable, the offset of its bytes and their count. -/ +structure Placeholder where + id : Nat + start : Nat + bytes : Nat + deriving DecidableEq, Repr + +/-- Whether byte `i` of the code is one of the placeholder's. -/ +def Placeholder.covers (p : Placeholder) (i : Nat) : Bool := + decide (p.start ≤ i) && decide (i < p.start + p.bytes) + +/-- Byte `j` of the `n`-byte big-endian encoding of `value`. -/ +def beByte (value n j : Nat) : Nat := value / 256 ^ (n - 1 - j) % 256 + +/-- Byte `i` of the linked code, `b` before linking. -/ +def linkByte (ps : List Placeholder) (values : Nat → Nat) (i b : Nat) : Nat := + match ps.find? (·.covers i) with + | some p => beByte (values p.id) p.bytes (i - p.start) + | none => b + +/-- `code` as a deployment runs it: the bytes of each placeholder the big-endian encoding of its +immutable's value. -/ +def link (code : List Nat) (ps : List Placeholder) (values : Nat → Nat) : List Nat := + code.mapIdx (linkByte ps values) + +/-- The placeholders of a walk's immutable items, each at the byte after its push. -/ +def placeholdersOf : List (Nat × Instr) → List Item → List Placeholder + | (pc, _) :: stream, item :: items => + match item with + | .immutable id bytes => ⟨id, pc + 1, bytes⟩ :: placeholdersOf stream items + | _ => placeholdersOf stream items + | _, _ => [] + +/-- Whether each immutable item of a walk is a `PUSH` of its width, `1 ≤ bytes ≤ 32`. -/ +def placed (code : List Nat) : List (Nat × Instr) → List Item → Bool + | (pc, _) :: stream, item :: items => + match item with + | .immutable _ bytes => + decide (1 ≤ bytes) && decide (bytes ≤ 32) && code[pc]? == some (PUSH1 + bytes - 1) && + placed code stream items + | _ => placed code stream items + | _, _ => true + +/-- A walk's stream with each placeholder pushing its immutable's value. -/ +def linkedStream (values : Nat → Nat) : List (Nat × Instr) → List Item → List (Nat × Instr) + | (pc, instr) :: stream, item :: items => + match item with + | .immutable id bytes => (pc, .push (values id % 256 ^ bytes)) :: linkedStream values stream items + | _ => (pc, instr) :: linkedStream values stream items + | _, _ => [] + +/-- The instruction an item is once a deployment links it. -/ +def Item.linked (offset : Nat → Nat) (values : Nat → Nat) : Item → Instr + | .immutable id bytes => .push (values id % 256 ^ bytes) + | item => item.expected offset + +theorem bigEndian_append (xs : List Nat) (b : Nat) : + bigEndian (xs ++ [b]) = bigEndian xs * 256 + b := by + simp [bigEndian, List.foldl_append] + +/-- The big-endian bytes of a value are the value modulo the bytes' range. -/ +theorem bigEndian_beBytes (n value : Nat) : + bigEndian ((List.range n).map (beByte value n)) = value % 256 ^ n := by + induction n generalizing value with + | zero => simp [bigEndian, Nat.mod_one] + | succ n ih => + rw [List.range_succ, List.map_append, List.map_singleton, bigEndian_append] + have hpre : (List.range n).map (beByte value (n + 1)) = + (List.range n).map (beByte (value / 256) n) := by + apply List.map_congr_left + intro j hj + have hj := List.mem_range.1 hj + unfold beByte + have e : n + 1 - 1 - j = (n - 1 - j) + 1 := by omega + rw [e, Nat.pow_succ, Nat.mul_comm, ← Nat.div_div_eq_div_mul] + rw [hpre, ih] + unfold beByte + simp only [Nat.add_sub_cancel, Nat.sub_self, Nat.pow_zero, Nat.div_one] + rw [Nat.pow_succ, Nat.mul_comm (256 ^ n) 256, Nat.mod_mul] + omega + +theorem link_length (code : List Nat) (ps : List Placeholder) (values : Nat → Nat) : + (link code ps values).length = code.length := by + simp [link] + +theorem link_getElem? (code : List Nat) (ps : List Placeholder) (values : Nat → Nat) (i : Nat) : + (link code ps values)[i]? = code[i]?.map (linkByte ps values i) := by + simp [link, List.getElem?_mapIdx] + +/-- A byte no placeholder covers is the code's. -/ +theorem link_getElem?_of_uncovered {code : List Nat} {ps : List Placeholder} {values : Nat → Nat} + {i : Nat} (h : ∀ p ∈ ps, p.covers i = false) : (link code ps values)[i]? = code[i]? := by + rw [link_getElem?] + have : ps.find? (·.covers i) = none := List.find?_eq_none.2 (fun p hp => by simp [h p hp]) + cases code[i]? <;> simp [linkByte, this] + +/-- The placeholder that covers a byte, when every one that does is the same. -/ +theorem find?_covers {ps : List Placeholder} {p : Placeholder} {i : Nat} (mem : p ∈ ps) + (covers : p.covers i = true) (unique : ∀ q ∈ ps, q.covers i = true → q = p) : + ps.find? (·.covers i) = some p := by + induction ps with + | nil => simp at mem + | cons q qs ih => + by_cases hq : q.covers i = true + · have := unique q (List.mem_cons_self) hq + subst this + simp [hq] + · have hq' : q.covers i = false := by simpa using hq + simp only [List.find?_cons, hq'] + rcases List.mem_cons.1 mem with rfl | later + · exact absurd covers hq + · exact ih later (fun r hr => unique r (List.mem_cons_of_mem _ hr)) + +/-- Decoding reads only the bytes of the instruction and the code's length. -/ +theorem decode_congr {code code' : List Nat} {pc next : Nat} {instr : Instr} + (len : code'.length = code.length) + (same : ∀ i, pc ≤ i → i < next → code'[i]? = code[i]?) + (h : decode code pc = some (instr, next)) : decode code' pc = some (instr, next) := by + have adv := decode_advances h + have hpc := same pc (Nat.le_refl _) adv + unfold decode at h ⊢ + rw [hpc] + cases hc : code[pc]? with + | none => rw [hc] at h; simp at h + | some byte => + rw [hc] at h + simp only at h ⊢ + by_cases h0 : byte = PUSH0 + · simp only [h0, ↓reduceIte] at h ⊢; exact h + · simp only [h0, ↓reduceIte] at h ⊢ + by_cases hr : PUSH1 ≤ byte ∧ byte ≤ PUSH32 + · simp only [hr, and_self, ↓reduceIte] at h ⊢ + by_cases fits : pc + 1 + (byte - PUSH1 + 1) ≤ code.length + · simp only [fits, ↓reduceIte] at h + simp only [Option.some.injEq, Prod.mk.injEq] at h + obtain ⟨rfl, rfl⟩ := h + have take : (code'.drop (pc + 1)).take (byte - PUSH1 + 1) = + (code.drop (pc + 1)).take (byte - PUSH1 + 1) := by + apply List.ext_getElem? + intro j + simp only [List.getElem?_take, List.getElem?_drop] + split + · exact same _ (by omega) (by omega) + · rfl + simp only [len, fits, take, ↓reduceIte] + · simp [fits] at h + · simp only [hr, ↓reduceIte] at h ⊢; exact h + +/-- The offsets a walk reaches are at least where it starts. -/ +theorem walk_ge {code : List Nat} {offset : Nat → Nat} {pc : Nat} {items : List Item} + {stream : List (Nat × Instr)} (w : Walk code offset pc items stream) : + ∀ e ∈ stream, pc ≤ e.1 := by + induction w with + | nil => simp + | cons decoded _ _ ih => + have := decode_advances decoded + intro e he + rcases List.mem_cons.1 he with rfl | later + · exact Nat.le_refl _ + · have := ih e later + omega + +/-- The placeholders of a walk start after where it starts. -/ +theorem placeholdersOf_gt {code : List Nat} {offset : Nat → Nat} {pc : Nat} {items : List Item} + {stream : List (Nat × Instr)} (w : Walk code offset pc items stream) : + ∀ p ∈ placeholdersOf stream items, pc < p.start := by + induction w with + | nil => simp [placeholdersOf] + | @cons pc next item items stream decoded _ rest ih => + have adv := decode_advances decoded + intro p hp + cases item <;> simp only [placeholdersOf] at hp + case immutable id bytes => + rcases List.mem_cons.1 hp with rfl | later + · simp + · have := ih p later + omega + all_goals + have := ih p hp + omega + +/-- A placeholder's push decodes to its width. -/ +theorem decode_placeholder {code : List Nat} {pc next bytes : Nat} + (h : decode code pc = some (.push 0, next)) (b1 : 1 ≤ bytes) (b32 : bytes ≤ 32) + (op : code[pc]? = some (PUSH1 + bytes - 1)) : + next = pc + 1 + bytes ∧ pc + 1 + bytes ≤ code.length := by + unfold decode at h + rw [op] at h + simp only [PUSH0, PUSH1, PUSH32] at h + have n0 : ¬ (96 + bytes - 1 = 95) := by omega + have r : 96 ≤ 96 + bytes - 1 ∧ 96 + bytes - 1 ≤ 127 := by omega + have e : 96 + bytes - 1 - 96 + 1 = bytes := by omega + simp only [n0, ite_false, r, and_self, ite_true, e] at h + split at h + · rename_i fits + simp only [Option.some.injEq, Prod.mk.injEq] at h + exact ⟨h.2.symm, fits⟩ + · simp at h + +/-- Linear decoding of the linked code from `pc` is the walk's stream with each placeholder +pushing its value, when each placeholder is a push of its width, every placeholder of the walk is +linked, and every placeholder linked is before `pc` or one of the walk's. -/ +theorem walk_link {code : List Nat} {offset : Nat → Nat} {pc : Nat} {items : List Item} + {stream : List (Nat × Instr)} (w : Walk code offset pc items stream) (ps : List Placeholder) + (values : Nat → Nat) : + placed code stream items = true → + (∀ p ∈ placeholdersOf stream items, p ∈ ps) → + (∀ p ∈ ps, p.start + p.bytes ≤ pc ∨ p ∈ placeholdersOf stream items) → + ∀ fuel, items.length < fuel → + decodeFrom (link code ps values) fuel pc = linkedStream values stream items := by + induction w with + | nil => + intro _ _ _ fuel h + cases fuel with + | zero => simp at h + | succ fuel => + have : (link code ps values)[code.length]? = none := by + rw [link_getElem?]; simp + simp [decodeFrom, decode, this, linkedStream] + | @cons pc next item items stream decoded labels rest ih => + intro hplaced hmem hps fuel h + cases fuel with + | zero => simp at h + | succ fuel => + simp only [List.length_cons] at h + have adv := decode_advances decoded + have later := placeholdersOf_gt rest + cases item + case immutable id bytes => + simp only [placed, Bool.and_eq_true, decide_eq_true_eq, beq_iff_eq] at hplaced + obtain ⟨⟨⟨b1, b32⟩, op⟩, hplaced⟩ := hplaced + obtain ⟨hnext, fits⟩ := decode_placeholder decoded b1 b32 op + subst hnext + simp only [placeholdersOf] at hmem hps + have here : ∀ p ∈ ps, p.covers pc = false := by + intro p hp + rcases hps p hp with before | mine + · (simp [Placeholder.covers]; try omega) + · rcases List.mem_cons.1 mine with rfl | tail + · (simp [Placeholder.covers]; try omega) + · have := later p tail + (simp [Placeholder.covers]; try omega) + have opByte : (link code ps values)[pc]? = some (PUSH1 + bytes - 1) := by + rw [link_getElem?_of_uncovered here, op] + have imm : ((link code ps values).drop (pc + 1)).take bytes = + (List.range bytes).map (beByte (values id) bytes) := by + apply List.ext_getElem? + intro j + simp only [List.getElem?_take, List.getElem?_drop, List.getElem?_map] + split + · rename_i hj + rw [link_getElem?] + have lt : pc + 1 + j < code.length := by omega + rw [List.getElem?_eq_getElem lt] + simp only [Option.map_some] + have cov : (⟨id, pc + 1, bytes⟩ : Placeholder).covers (pc + 1 + j) = true := by + (simp [Placeholder.covers]; try omega) + have find := find?_covers (ps := ps) (i := pc + 1 + j) (p := ⟨id, pc + 1, bytes⟩) + (hmem _ List.mem_cons_self) cov (by + intro q hq c + rcases hps q hq with before | mine + · simp [Placeholder.covers] at c; omega + · rcases List.mem_cons.1 mine with e | tail + · exact e + · have := later q tail + simp [Placeholder.covers] at c; omega) + simp [linkByte, find, hj] + · rename_i hj + simp [hj] + have d : decode (link code ps values) pc = + some (.push (values id % 256 ^ bytes), pc + 1 + bytes) := by + unfold decode + rw [opByte] + simp only [PUSH0, PUSH1, PUSH32] + have n0 : ¬ (96 + bytes - 1 = 95) := by omega + have r : 96 ≤ 96 + bytes - 1 ∧ 96 + bytes - 1 ≤ 127 := by omega + have e : 96 + bytes - 1 - 96 + 1 = bytes := by omega + have fits' : pc + 1 + bytes ≤ (link code ps values).length := by + rw [link_length]; exact fits + simp only [n0, ite_false, r, and_self, ite_true, e, fits'] + rw [imm, bigEndian_beBytes] + simp only [decodeFrom, d, linkedStream] + rw [ih hplaced (fun p hp => hmem p (List.mem_cons_of_mem _ hp)) (by + intro p hp + rcases hps p hp with before | mine + · left; omega + · rcases List.mem_cons.1 mine with rfl | tail + · left; simp + · right; exact tail) fuel (by omega)] + all_goals + simp only [placed] at hplaced + simp only [placeholdersOf] at hmem hps + have uncovered : ∀ i, pc ≤ i → i < next → (link code ps values)[i]? = code[i]? := by + intro i h1 h2 + apply link_getElem?_of_uncovered + intro p hp + rcases hps p hp with before | mine + · (simp [Placeholder.covers]; try omega) + · have := later p mine + (simp [Placeholder.covers]; try omega) + have d := decode_congr (link_length code ps values) uncovered decoded + simp only [decodeFrom, d, linkedStream] + rw [ih hplaced hmem (by + intro p hp + rcases hps p hp with before | mine + · left; omega + · right; exact mine) fuel (by omega)] + +/-- Linear decoding of the code linked at the walk's placeholders is the walk's stream with each +placeholder pushing its value. -/ +theorem decodes_linked {code : List Nat} {offset : Nat → Nat} {items : List Item} + {stream : List (Nat × Instr)} (w : Walk code offset 0 items stream) + (hplaced : placed code stream items = true) (values : Nat → Nat) : + decodeFrom (link code (placeholdersOf stream items) values) (code.length + 1) 0 = + linkedStream values stream items := + walk_link w _ values hplaced (fun _ hp => hp) (fun _ hp => .inr hp) _ + (by have := walk_length w; omega) + +/-- The linked stream's instructions are the program's items, each placeholder linked. -/ +theorem linked_instructions {code : List Nat} {offset : Nat → Nat} {pc : Nat} {items : List Item} + {stream : List (Nat × Instr)} (w : Walk code offset pc items stream) (values : Nat → Nat) : + (linkedStream values stream items).map Prod.snd = items.map (Item.linked offset values) := by + induction w with + | nil => simp [linkedStream] + | @cons pc next item items stream decoded labels rest ih => + clear decoded labels rest + cases item <;> simp [linkedStream, Item.linked, ih] + +end SolarTV.Assembly diff --git a/tv/SolarTV/State/ByteMemory.lean b/tv/SolarTV/State/ByteMemory.lean new file mode 100644 index 00000000..4faa46ed --- /dev/null +++ b/tv/SolarTV/State/ByteMemory.lean @@ -0,0 +1,34 @@ +import SolarTV.State.Journal + +/-! Shared byte-addressed memory with zero extension, aligned active size and +overlap-safe copies. The 64 KiB bound is a prover work limit, never an EVM trap +or an assumption that permits ignoring a live byte. Gas is modeled separately. -/ + +namespace SolarTV.Execution +open EvmRules + +def memoryWords (memory : List Byte) : Nat := memory.length / 32 + +def requiredWords (memory : List Byte) (offset count : Nat) : Nat := + if count = 0 then memoryWords memory else max (memoryWords memory) ((offset + count + 31) / 32) + +def expand (memory : List Byte) (offset count : Nat) : Except String (List Byte) := + let size := 32 * requiredWords memory offset count + if size > 65536 then .error "world memory limit of 64 KiB" + else .ok (memory ++ List.replicate (size - memory.length) 0) + +def readBytes (bytes : List Byte) (offset count : Nat) : List Byte := + (List.range count).map (fun i => bytes[offset + i]?.getD 0) + +def writeBytes (memory : List Byte) (offset : Nat) (bytes : List Byte) : List Byte := + memory.mapIdx (fun i old => if offset ≤ i ∧ i < offset + bytes.length then + bytes[i - offset]?.getD 0 else old) + +def wordBytes (word : Word) : List Byte := + (List.range 32).map (fun i => (word >>> (8 * (31 - i))).setWidth 8) + +def readWord (bytes : List Byte) (offset : Nat) : Word := + (BitVec.flattenListFast (readBytes bytes offset 32)).setWidth 256 + + +end SolarTV.Execution diff --git a/tv/SolarTV/State/Calls.lean b/tv/SolarTV/State/Calls.lean new file mode 100644 index 00000000..8503c23f --- /dev/null +++ b/tv/SolarTV/State/Calls.lean @@ -0,0 +1,142 @@ +import SolarTV.State.World + +/-! Message-call entry and journal commit/rollback, shared by MIR and EVM IR. +CALL changes the storage owner and transfers value; CALLCODE changes only code; +DELEGATECALL preserves the original caller/value and storage owner; STATICCALL +forces static permission and zero value. All four keep transaction origin. + +Child execution is separate from its boundary. A successful arbitrary child is +not a semantics for CALL; EVMIR/State/Interpreter executes the real child in the +CLI's explicit-world mode. The gas forwarding helper starts after base/memory/value +charges; it does not stand in for the full CALL price or precompile pricing. + +Reference: EVMYulLean 047f630, EVM/Semantics.lean:138-218, 364-418 and 719-815. +https://eips.ethereum.org/EIPS/eip-150 -/ + +namespace SolarTV.Calls +open EvmRules + +inductive Kind where + | call | callcode | delegatecall | staticcall + deriving DecidableEq + +structure Message where + kind : Kind + destination : World.Address + value : Word + input : List World.Byte + deriving DecidableEq + +/-- Whether this opcode explicitly supplies a value operand, not CALLVALUE as +observed by the child. DELEGATECALL can inherit nonzero value in static mode. -/ +def hasValue (message : Message) : Bool := + (message.kind == .call || message.kind == .callcode) && message.value != 0 + +def childEnvironment (parent : World.Environment) (message : Message) : World.Environment := + {parent with + address := if message.kind == .call || message.kind == .staticcall then + message.destination else parent.address + codeAddress := message.destination + caller := if message.kind == .delegatecall then parent.caller else parent.address + value := if message.kind == .delegatecall then parent.value + else if message.kind == .staticcall then 0 else message.value + input := message.input + isStatic := parent.isStatic || message.kind == .staticcall + depth := parent.depth + 1} + +structure Entry where + /-- Snapshot after warming the destination, before any value transfer. -/ + checkpoint : World.State + world : World.State + environment : World.Environment + +inductive Preparation where + | enter (entry : Entry) + | rejected (world : World.State) + | exception (reason : Storage.Error) + +def prepare (world : World.State) (parent : World.Environment) (message : Message) + (fork : Fork := .cancun) : Preparation := + if message.kind == .staticcall && !fork.atLeast .byzantium then .exception .unavailable + else if parent.isStatic && message.kind == .call && message.value != 0 then .exception .staticViolation + else + let checkpoint := World.warmAccount world message.destination + if parent.depth ≥ 1024 then .rejected checkpoint + else if hasValue message && (world.accounts parent.address).balance.ult message.value then + .rejected checkpoint + else + let entered := if message.kind == .call then + World.transfer checkpoint parent.address message.destination message.value + else some checkpoint + match entered with + | none => .rejected checkpoint + | some world => + let world := if message.kind == .call && !fork.atLeast .spuriousDragon then + World.setAccount world message.destination + {(world.accounts message.destination) with present := true} + else world + .enter ⟨checkpoint, world, childEnvironment parent message⟩ + +inductive ChildResult where + | success (world : World.State) (data : List World.Byte) (remaining : Nat) + | reverted (data : List World.Byte) (remaining : Nat) + | exception + +structure Result where + world : World.State + success : Bool + returnData : List World.Byte + remaining : Nat + +/-- Revert keeps return data and unused gas but restores the journal. An +exception has empty return data and burns the complete supplied child budget. -/ +def complete (checkpoint : World.State) : ChildResult → Result + | .success world data remaining => ⟨world, true, data, remaining⟩ + | .reverted data remaining => ⟨checkpoint, false, data, remaining⟩ + | .exception => ⟨checkpoint, false, [], 0⟩ + +structure Budget where + charged : Nat + supplied : Nat + deriving DecidableEq + +def forwardGas (fork : Fork) (available requested : Nat) (value : Bool) : Option Budget := + let cap := if fork.atLeast .tangerineWhistle then available - available / 64 else available + if !fork.atLeast .tangerineWhistle && requested > available then none + else + let forwarded := min requested cap + some ⟨forwarded, forwarded + if value then 2300 else 0⟩ + +@[simp] theorem reverted_restores_journal (checkpoint : World.State) + (data : List World.Byte) (gas : Nat) : + (complete checkpoint (.reverted data gas)).world = checkpoint := rfl + +@[simp] theorem exceptional_call_burns_gas (checkpoint : World.State) : + (complete checkpoint .exception).remaining = 0 := rfl + +@[simp] theorem delegate_keeps_owner (parent : World.Environment) (to : World.Address) + (value : Word) (input : List World.Byte) : + (childEnvironment parent ⟨.delegatecall, to, value, input⟩).address = parent.address := by + simp [childEnvironment] + +@[simp] theorem delegate_keeps_caller (parent : World.Environment) (to : World.Address) + (value : Word) (input : List World.Byte) : + (childEnvironment parent ⟨.delegatecall, to, value, input⟩).caller = parent.caller := by + simp [childEnvironment] + +@[simp] theorem delegate_keeps_value (parent : World.Environment) (to : World.Address) + (value : Word) (input : List World.Byte) : + (childEnvironment parent ⟨.delegatecall, to, value, input⟩).value = parent.value := by + simp [childEnvironment] + +/-- A delegate call in a static frame keeps static permission even if its +inherited CALLVALUE is nonzero. The value is not a new transfer. -/ +theorem static_is_inherited (parent : World.Environment) (message : Message) + (permission : parent.isStatic = true) : + (childEnvironment parent message).isStatic = true := by simp [childEnvironment, permission] + +example : forwardGas .homestead 6400 6401 false = none := by decide +example : forwardGas .tangerineWhistle 6400 6401 false = some ⟨6300, 6300⟩ := by decide +example : forwardGas .cancun 6400 6401 true = some ⟨6300, 8600⟩ := by decide + +end SolarTV.Calls diff --git a/tv/SolarTV/State/Context.lean b/tv/SolarTV/State/Context.lean new file mode 100644 index 00000000..446025f5 --- /dev/null +++ b/tv/SolarTV/State/Context.lean @@ -0,0 +1,46 @@ +import SolarTV.State.Journal + +/-! Explicit transaction and block inputs, shared by direct MIR and EVM execution. +These are immutable inputs, independent of physical instruction selection. -/ + +namespace SolarTV.Execution +open EvmRules + +/-- Explicit block/transaction context, fixed throughout all nested frames. +Missing history entries and out-of-range blob indices denote zero. -/ +structure Block where + number : Word := 0 + beneficiary : Address := 0 + timestamp : Word := 1 + gasLimit : Word := 2^64 - 1 + difficulty : Word := 0 + randomness : Word := 0 + chainId : Word := 1 + baseFee : Word := 0 + blobBaseFee : Word := 1 + slot : BitVec 64 := 0 + hashes : Slots := [] + blobs : List Word := [] + + +def blockHash (context : Block) (number : Word) : Word := + if number.toNat < context.number.toNat && context.number.toNat - number.toNat ≤ 256 then + slotsRead context.hashes number + else 0 + +def environmentValue (fork : Fork) (context : Block) (opcode : Nat) (argument : Word) : Word := + match opcode with + | 0x40 => blockHash context argument + | 0x41 => context.beneficiary.setWidth 256 + | 0x42 => context.timestamp + | 0x43 => context.number + | 0x44 => if fork.atLeast .paris then context.randomness else context.difficulty + | 0x45 => context.gasLimit + | 0x46 => context.chainId + | 0x48 => context.baseFee + | 0x49 => context.blobs[argument.toNat]?.getD 0 + | 0x4a => context.blobBaseFee + | 0x4b => context.slot.setWidth 256 + | _ => 0 + +end SolarTV.Execution diff --git a/tv/SolarTV/State/Fork.lean b/tv/SolarTV/State/Fork.lean new file mode 100644 index 00000000..ec3450e8 --- /dev/null +++ b/tv/SolarTV/State/Fork.lean @@ -0,0 +1,22 @@ +/-! Fork ordering shared by state and gas semantics. The constructors match the +compiler's EvmVersion schema. Feature availability and gas are separate: an +unavailable opcode is exceptional, not an expensive version of a legal one. -/ + +namespace SolarTV + +inductive Fork where + | homestead | tangerineWhistle | spuriousDragon | byzantium + | constantinople | petersburg | istanbul | berlin | london | paris + | shanghai | cancun | prague | osaka | amsterdam + deriving DecidableEq, Repr + +def Fork.ordinal : Fork → Nat + | .homestead => 0 | .tangerineWhistle => 1 | .spuriousDragon => 2 + | .byzantium => 3 | .constantinople => 4 | .petersburg => 5 + | .istanbul => 6 | .berlin => 7 | .london => 8 | .paris => 9 + | .shanghai => 10 | .cancun => 11 | .prague => 12 | .osaka => 13 + | .amsterdam => 14 + +def Fork.atLeast (fork since : Fork) : Bool := since.ordinal ≤ fork.ordinal + +end SolarTV diff --git a/tv/SolarTV/State/Journal.lean b/tv/SolarTV/State/Journal.lean new file mode 100644 index 00000000..bb9c5526 --- /dev/null +++ b/tv/SolarTV/State/Journal.lean @@ -0,0 +1,88 @@ +import SolarTV.State.World + +/-! Shared finite journals for explicit-world MIR and EVM execution. Account and +slot updates preserve unrelated state; both evaluators use the same address-qualified +store. No instruction, backend layout, gas policy or stack convention lives here. -/ + +namespace SolarTV.Execution +open EvmRules + +abbrev Byte := BitVec 8 +abbrev Address := BitVec 160 +abbrev Slots := List (Word × Word) + +structure Account where + address : Address + nonce : Nat := 0 + balance : Word := 0 + code : List Byte := [] + storage : Slots := [] + transient : Slots := [] + created : Bool := false + destroyed : Bool := false + deriving DecidableEq + +structure Journal where + accounts : List Account + original : List Account + warmAddresses : List Address + warmSlots : List (Address × Word) + logs : List World.Log := [] + refund : Int := 0 + deriving DecidableEq + +def slotsRead (slots : Slots) (key : Word) : Word := + (slots.find? (fun entry => entry.1 == key)).map Prod.snd |>.getD 0 + +def slotsWrite (slots : Slots) (key value : Word) : Slots := + (key, value) :: slots.filter (fun entry => entry.1 != key) + +def account (world : Journal) (address : Address) : Account := + (world.accounts.find? (fun a => a.address == address)).getD {address} + +def putAccount (world : Journal) (account : Account) : Journal := + {world with accounts := account :: world.accounts.filter (fun a => a.address != account.address)} + +def warmAddress (world : Journal) (address : Address) : Journal := + {world with warmAddresses := if world.warmAddresses.contains address then world.warmAddresses + else address :: world.warmAddresses} + +def warmSlot (world : Journal) (address : Address) (key : Word) : Journal := + {world with warmSlots := if world.warmSlots.contains (address, key) then world.warmSlots + else (address, key) :: world.warmSlots} + +def transfer (world : Journal) (source destination : Address) (value : Word) : Option Journal := + let sender := account world source + if sender.balance.ult value then none + else if source = destination || value == 0 then some world + else + let world := putAccount world {sender with balance := sender.balance - value} + let to := account world destination + some (putAccount world {to with balance := to.balance + value}) + + +/-- Structural sorting keeps concrete observation proofs reducible in the kernel. +The finite fixture/evaluator bounds keep these comparison-only lists small. -/ +def orderedInsert (le : α → α → Bool) (value : α) : List α → List α + | [] => [value] + | head :: rest => if le value head then value :: head :: rest + else head :: orderedInsert le value rest + +def ordered (le : α → α → Bool) : List α → List α + | [] => [] + | head :: rest => orderedInsert le head (ordered le rest) + +def normalizedSlots (slots : Slots) : Slots := + ordered (fun a b => a.1.ule b.1) (slots.filter (fun entry => entry.2 != 0)) + +/-- Same-key overwrite is the state identity used by storage-DSE, without alias assumptions. -/ +@[simp] theorem slotsWrite_overwrite (slots : Slots) (key old value : Word) : + slotsWrite (slotsWrite slots key old) key value = slotsWrite slots key value := by + simp [slotsWrite, List.filter_filter] + +/-- Reading the cell just written returns its value independently of the initial journal. -/ +@[simp] theorem slotsRead_write (slots : Slots) (key value : Word) : + slotsRead (slotsWrite slots key value) key = value := by + simp [slotsRead, slotsWrite] + +end SolarTV.Execution diff --git a/tv/SolarTV/State/MemoryLaws.lean b/tv/SolarTV/State/MemoryLaws.lean new file mode 100644 index 00000000..162d15ef --- /dev/null +++ b/tv/SolarTV/State/MemoryLaws.lean @@ -0,0 +1,76 @@ +import SolarTV.State.ByteMemory + +/-! Kernel-proved byte-memory normalization, independent of any compiler pass. +Read-over-write rules require actual overlap/active-range proofs; they never +assume that two pointers are distinct. Pre-simplification avoids expanding an +entire symbolic heap merely to read an untouched allocation-cursor word. -/ + +namespace SolarTV.Execution +open EvmRules + +@[simp] theorem wordBytes_length (value : Word) : (wordBytes value).length = 32 := by + simp [wordBytes] + +@[simp] theorem writeBytes_length (memory bytes : List Byte) (offset : Nat) : + (writeBytes memory offset bytes).length = memory.length := by + simp [writeBytes] + +theorem readBytes_writeBytes_disjoint (memory bytes : List Byte) (destination source count : Nat) + (h : destination + bytes.length ≤ source ∨ source + count ≤ destination) : + readBytes (writeBytes memory destination bytes) source count = readBytes memory source count := by + unfold readBytes + apply List.map_congr_left + intro i hi + have hi' : i < count := List.mem_range.mp hi + have outside : ¬ (destination ≤ source + i ∧ source + i < destination + bytes.length) := by omega + simp [writeBytes, List.getElem?_mapIdx, outside] + +theorem readBytes_writeBytes_same (memory bytes : List Byte) (offset : Nat) + (h : offset + bytes.length ≤ memory.length) : + readBytes (writeBytes memory offset bytes) offset bytes.length = bytes := by + apply List.ext_getElem + · simp [readBytes] + · intro i hi hj + have hm : offset + i < memory.length := by omega + simp [readBytes, writeBytes, List.getElem?_mapIdx, List.getElem?_eq_getElem hm, + Nat.add_sub_cancel_left, List.getElem?_eq_getElem hj] <;> omega + +theorem flatten_wordBytes (word : Word) : (BitVec.flattenList (wordBytes word)).setWidth 256 = word := by + have hl : (wordBytes word).length = 32 := by simp [wordBytes] + apply BitVec.eq_of_getLsbD_eq + intro i hi + have hj : 31 - i / 8 < 32 := by omega + have hm : i % 8 < 8 := Nat.mod_lt i (by decide) + have hp : 8 * (31 - (31 - i / 8)) + i % 8 = i := by omega + have hr : (List.range 32)[31 - i / 8]? = some (31 - i / 8) := by + rw [List.getElem?_eq_getElem (by simpa using hj)] + simp + simp only [BitVec.getLsbD_setWidth, BitVec.getLsbD_flattenList, hl, hi, decide_true, Bool.true_and] + simp only [wordBytes, List.getElem?_map, hr, Option.map_some, Option.getD_some] + simp only [BitVec.getLsbD_setWidth, hm, decide_true, Bool.true_and, BitVec.getLsbD_ushiftRight, hp] + +@[simp↓] theorem readWord_writeWord (memory : List Byte) (offset : Nat) (word : Word) + (h : offset + 32 ≤ memory.length) : + readWord (writeBytes memory offset (wordBytes word)) offset = word := by + change (BitVec.flattenListFast (readBytes (writeBytes memory offset (wordBytes word)) offset (wordBytes word).length)).setWidth 256 = word + rw [readBytes_writeBytes_same memory (wordBytes word) offset (by simpa using h)] + rw [← BitVec.flattenList_eq_flattenListFast] + exact flatten_wordBytes word + +@[simp↓] theorem readWord_writeBytes_disjoint (memory bytes : List Byte) (destination source : Nat) + (h : destination + bytes.length ≤ source ∨ source + 32 ≤ destination) : + readWord (writeBytes memory destination bytes) source = readWord memory source := by + unfold readWord + rw [readBytes_writeBytes_disjoint memory bytes destination source 32 h] + +@[simp↓] theorem readWord_append_prefix (memory bytes : List Byte) (offset : Nat) + (h : offset + 32 ≤ memory.length) : readWord (memory ++ bytes) offset = readWord memory offset := by + unfold readWord + congr 2 + unfold readBytes + apply List.map_congr_left + intro i hi + have hm : offset + i < memory.length := by have := List.mem_range.mp hi; omega + simp [List.getElem?_append_left hm] + +end SolarTV.Execution diff --git a/tv/SolarTV/State/Storage.lean b/tv/SolarTV/State/Storage.lean new file mode 100644 index 00000000..b61bdf96 --- /dev/null +++ b/tv/SolarTV/State/Storage.lean @@ -0,0 +1,123 @@ +import SolarTV.State.Fork +import EvmRules.Word + +/-! Persistent and transient storage with transaction-original values, per-address +access warmth and signed refunds. Stores are total functions, so proofs quantify +over all slots rather than assuming an initially empty or finitely sized store. + +Pricing follows EIP-2200 (including its <=2300 gas sentry), EIP-2929's cold +surcharge and reset price, and EIP-3529's clear refund. Constantinople uses +EIP-1283 without the sentry; Petersburg restores the legacy rules. Refunds +are signed because an individual frame may remove a refund earned by its caller. +A failed store leaves all state to its enclosing frame's rollback rule. +https://eips.ethereum.org/EIPS/eip-2200#specification +https://eips.ethereum.org/EIPS/eip-2929#sstore-changes +https://eips.ethereum.org/EIPS/eip-3529#specification -/ + +namespace SolarTV.Storage +open EvmRules + +abbrev Address := BitVec 160 +abbrev Store := Address → Word → Word +abbrev WarmSlots := Address → Word → Bool + +def update (store : Store) (address : Address) (slot value : Word) : Store := + fun a k => if a = address ∧ k = slot then value else store a k + +def warm (slots : WarmSlots) (address : Address) (slot : Word) : WarmSlots := + fun a k => (a == address && k == slot) || slots a k + +structure State where + persistent : Store + original : Store + transient : Store + accessed : WarmSlots + refund : Int + +inductive Error where + | outOfGas | staticViolation | unavailable + deriving DecidableEq + +structure Price where + gas : Nat + refund : Int + deriving DecidableEq + +def readPrice (fork : Fork) (warm : Bool) : Nat := + if fork.atLeast .berlin then if warm then 100 else 2100 + else if fork.atLeast .istanbul then 800 + else if fork.atLeast .tangerineWhistle then 200 else 50 + +def netMetered (fork : Fork) : Bool := + fork == .constantinople || fork.atLeast .istanbul + +/-- Pricing alone does not enforce the sentry or static permission. -/ +def writePrice (fork : Fork) (warm : Bool) (original current value : Word) : Price := + let cold := if fork.atLeast .berlin && !warm then 2100 else 0 + let read := readPrice fork true + let reset := if fork.atLeast .berlin then 2900 else 5000 + let clear : Int := if fork.atLeast .london then 4800 else 15000 + if !netMetered fork then + ⟨if current == 0 && value != 0 then 20000 else 5000, + if current != 0 && value == 0 then clear else 0⟩ + else if current == value then ⟨cold + read, 0⟩ + else if original == current then + if original == 0 then ⟨cold + 20000, 0⟩ + else ⟨cold + reset, if value == 0 then clear else 0⟩ + else + let remove := if original != 0 && current == 0 then -clear else 0 + let add := if original != 0 && value == 0 then clear else 0 + let restored := if original == value then + (if original == 0 then (20000 : Int) else (reset : Int)) - (read : Int) else 0 + ⟨cold + read, remove + add + restored⟩ + +def load (fork : Fork) (state : State) (address : Address) (slot : Word) (gas : Nat) : + Except Error (Word × State × Nat) := + let charge := readPrice fork (state.accessed address slot) + if gas < charge then .error .outOfGas else + .ok (state.persistent address slot, + {state with accessed := warm state.accessed address slot}, gas - charge) + +def store (fork : Fork) (state : State) (address : Address) (slot value : Word) + (gas : Nat) (isStatic : Bool) : Except Error (State × Nat) := + if isStatic then .error .staticViolation + else if fork.atLeast .istanbul && gas ≤ 2300 then .error .outOfGas + else + let price := writePrice fork (state.accessed address slot) + (state.original address slot) (state.persistent address slot) value + if gas < price.gas then .error .outOfGas else + .ok ({state with + persistent := update state.persistent address slot value + accessed := warm state.accessed address slot + refund := state.refund + price.refund}, + gas - price.gas) + +def tload (fork : Fork) (state : State) (address : Address) (slot : Word) (gas : Nat) : + Except Error (Word × Nat) := + if !fork.atLeast .cancun then .error .unavailable + else if gas < 100 then .error .outOfGas + else .ok (state.transient address slot, gas - 100) + +/-- Transient stores have no EIP-2200 sentry and no refund. -/ +def tstore (fork : Fork) (state : State) (address : Address) (slot value : Word) + (gas : Nat) (isStatic : Bool) : Except Error (State × Nat) := + if !fork.atLeast .cancun then .error .unavailable + else if isStatic then .error .staticViolation + else if gas < 100 then .error .outOfGas + else .ok ({state with transient := update state.transient address slot value}, gas - 100) + +@[simp] theorem update_same (state : Store) (a : Address) (k value : Word) : + update state a k value a k = value := by simp [update] + +@[simp] theorem update_other (state : Store) (a b : Address) (k j value : Word) + (different : b ≠ a ∨ j ≠ k) : update state a k value b j = state b j := by + simp only [update] + rcases different with h | h <;> simp_all + +theorem overwrite (state : Store) (a : Address) (k first last : Word) : + update (update state a k first) a k last = update state a k last := by + funext b j + simp only [update] + split <;> simp_all + +end SolarTV.Storage diff --git a/tv/SolarTV/State/StorageSafety.lean b/tv/SolarTV/State/StorageSafety.lean new file mode 100644 index 00000000..11246145 --- /dev/null +++ b/tv/SolarTV/State/StorageSafety.lean @@ -0,0 +1,32 @@ +import SolarTV.State.Storage + +/-! Storage boundary proofs independent of any importer projection. The examples +pin zero/no-op stores, cold/warm pricing, dirty-slot refunds, the stipend sentry +and the distinct transient-store rule. All proofs are checked in the kernel. -/ + +namespace SolarTV.Storage + +example : writePrice .homestead false 0 0 0 = ⟨5000, 0⟩ := by decide +example : writePrice .constantinople false 0 0 0 = ⟨200, 0⟩ := by decide +example : writePrice .petersburg false 0 0 0 = ⟨5000, 0⟩ := by decide +example : writePrice .istanbul false 0 0 0 = ⟨800, 0⟩ := by decide +example : writePrice .berlin false 0 0 0 = ⟨2200, 0⟩ := by decide +example : writePrice .london false 7 7 0 = ⟨5000, 4800⟩ := by decide +example : writePrice .london true 7 0 7 = ⟨100, -2000⟩ := by decide +example : writePrice .london true 0 1 0 = ⟨100, 19900⟩ := by decide + +/-- Equal storage contents do not suffice for gas equivalence: access warmth matters. -/ +theorem cold_read_costs_more : readPrice .cancun false > readPrice .cancun true := by decide + +/-- No-op stores still fail the gas sentry, even though their price is only 100. -/ +theorem sentry_rejects (state : State) (a : Address) (k value : EvmRules.Word) : + store .cancun state a k value 2300 false = .error .outOfGas := by + simp [store, Fork.atLeast, Fork.ordinal] + +/-- A transient store at the same budget succeeds and leaves persistent storage alone. -/ +theorem transient_ignores_sentry (state : State) (a : Address) (k value : EvmRules.Word) : + tstore .cancun state a k value 100 false = + .ok ({state with transient := update state.transient a k value}, 0) := by + simp [tstore, Fork.atLeast, Fork.ordinal] + +end SolarTV.Storage diff --git a/tv/SolarTV/State/World.lean b/tv/SolarTV/State/World.lean new file mode 100644 index 00000000..642e7afe --- /dev/null +++ b/tv/SolarTV/State/World.lean @@ -0,0 +1,87 @@ +import SolarTV.State.Storage + +/-! Account state and journaled transaction effects. Storage includes the address +of its owner, so CALL and DELEGATECALL cannot accidentally share a global slot +map. Snapshots include transient storage, logs, refund and access sets; restoring +only persistent storage would be incorrect after a child reverts. + +These definitions describe state and message boundaries, not an oracle for +executing unknown code. A child result must eventually come from the instruction +semantics; it is not admitted as an unconstrained successful call by the CLI. -/ + +namespace SolarTV.World +open EvmRules + +abbrev Address := Storage.Address +abbrev Byte := BitVec 8 + +structure Account where + present : Bool + nonce : Nat + balance : Word + code : List Byte + deriving DecidableEq + +structure Log where + address : Address + topics : List Word + data : List Byte + deriving DecidableEq + +structure State where + accounts : Address → Account + storage : Storage.State + logs : List Log + accessedAccounts : Address → Bool + created : Address → Bool + destructed : Address → Bool + +structure Environment where + address : Address + codeAddress : Address + caller : Address + origin : Address + value : Word + gasPrice : Word + input : List Byte + isStatic : Bool + depth : Nat + deriving DecidableEq + +def setAccount (state : State) (address : Address) (account : Account) : State := + {state with accounts := fun a => if a = address then account else state.accounts a} + +def warmAccount (state : State) (address : Address) : State := + {state with accessedAccounts := fun a => a == address || state.accessedAccounts a} + +/-- The caller checks sufficient funds. Self-transfers do not mint or destroy funds. -/ +def transfer (state : State) (source destination : Address) (value : Word) : Option State := + if (state.accounts source).balance.ult value then none + else if source = destination then some state + else + let debited := setAccount state source + {(state.accounts source) with balance := (state.accounts source).balance - value} + let credited := {(debited.accounts destination) with + present := (debited.accounts destination).present || value != 0 + balance := (debited.accounts destination).balance + value} + some (setAccount debited destination credited) + +/-- A log is forbidden in static mode, including LOG0 with zero bytes. -/ +def emitLog (state : State) (environment : Environment) (topics : List Word) (data : List Byte) : + Except Storage.Error State := + if environment.isStatic then .error .staticViolation + else .ok {state with logs := state.logs ++ [⟨environment.address, topics, data⟩]} + +@[simp] theorem setAccount_same (state : State) (address : Address) (account : Account) : + (setAccount state address account).accounts address = account := by simp [setAccount] + +@[simp] theorem setAccount_other (state : State) (address other : Address) (account : Account) + (different : other ≠ address) : + (setAccount state address account).accounts other = state.accounts other := by + simp [setAccount, different] + +theorem transfer_to_self (state : State) (address : Address) (value : Word) + (funds : (state.accounts address).balance.ult value = false) : + transfer state address address value = some state := by simp [transfer, funds] + +end SolarTV.World diff --git a/tv/SolarTV/Word.lean b/tv/SolarTV/Word.lean new file mode 100644 index 00000000..e8945339 --- /dev/null +++ b/tv/SolarTV/Word.lean @@ -0,0 +1,56 @@ +import EvmRules.Word + +/-! Width-polymorphic scalar semantics shared by typed MIR and scheduled EVM IR. +Division by zero follows the EVM, shifts saturate instead of reducing modulo the +width, and exponentiation uses squaring so a word-sized exponent needs logarithmic +work. This file has no environment, heap or gas assumptions. -/ + +namespace SolarTV.Word + +def power {width : Nat} (base : BitVec width) (exponent : Nat) : BitVec width := + if _h : exponent = 0 then 1 + else + let half := power (base * base) (exponent / 2) + if exponent % 2 = 0 then half else base * half +termination_by exponent +decreasing_by exact Nat.div_lt_self (Nat.pos_of_ne_zero _h) (by decide) + +@[simp] theorem power_zero (base : BitVec width) : power base 0 = 1 := by simp [power] +@[simp] theorem power_one (base : BitVec width) : power base 1 = base := by simp [power] + +inductive Binary where + | add | sub | mul | div | sdiv | mod | smod | exp | and | or | xor + +def binary {width : Nat} : Binary → BitVec width → BitVec width → BitVec width + | .add => fun a b => a + b + | .sub => fun a b => a - b + | .mul => fun a b => a * b + | .div => fun a b => a / b + | .sdiv => fun a b => a.sdiv b + | .mod => fun a b => if b = 0 then 0 else a % b + | .smod => fun a b => if b = 0 then 0 else a.srem b + | .exp => fun a b => power a b.toNat + | .and => fun a b => a &&& b + | .or => fun a b => a ||| b + | .xor => fun a b => a ^^^ b + +inductive Unary where + | not | clz + +def unary {width : Nat} : Unary → BitVec width → BitVec width + | .not => fun a => ~~~a + | .clz => fun a => a.clz + +inductive Shift where + | shl | shr | sar + +/-- Arguments use MIR textual order: value, then shift. -/ +def shift {width : Nat} (op : Shift) (value amount : BitVec width) : BitVec width := + if amount.toNat ≥ width then + match op with | .shl | .shr => 0 | .sar => if value.msb then -1 else 0 + else match op with + | .shl => value <<< amount.toNat + | .shr => value >>> amount.toNat + | .sar => value.sshiftRight amount.toNat + +end SolarTV.Word diff --git a/tv/SolarTV/WordSafety.lean b/tv/SolarTV/WordSafety.lean new file mode 100644 index 00000000..139e6aef --- /dev/null +++ b/tv/SolarTV/WordSafety.lean @@ -0,0 +1,37 @@ +import SolarTV.Word + +/-! Correspondence of logarithmic exponentiation with the ordinary bit-vector +power. This establishes all exponents, including the full 256-bit range, without +unfolding an exponent-sized number of multiplication steps in the checker. -/ + +namespace SolarTV.Word + +private theorem square_power (base : BitVec width) (n : Nat) : + (base * base) ^ n = base ^ (n + n) := by + induction n with + | zero => simp + | succ n ih => + rw [BitVec.pow_succ, ih] + have h : n + 1 + (n + 1) = (n + n + 1) + 1 := by omega + rw [h, BitVec.pow_succ, BitVec.pow_succ] + simp [BitVec.mul_assoc] + +theorem power_eq_pow (base : BitVec width) (n : Nat) : power base n = base ^ n := by + induction n using Nat.strongRecOn generalizing base with + | ind n ih => + rw [power] + split + · rename_i h + simp [h] + · rename_i h + rw [ih (n / 2) (Nat.div_lt_self (Nat.pos_of_ne_zero h) (by decide)), square_power] + split + · rename_i even + change base ^ (n / 2 + n / 2) = base ^ n + exact congrArg (fun exponent => base ^ exponent) (by omega) + · rename_i odd + change base * base ^ (n / 2 + n / 2) = base ^ n + rw [BitVec.mul_comm, ← BitVec.pow_succ] + exact congrArg (fun exponent => base ^ exponent) (by omega) + +end SolarTV.Word diff --git a/tv/W1Proofs.lean b/tv/W1Proofs.lean new file mode 100644 index 00000000..09adfcec --- /dev/null +++ b/tv/W1Proofs.lean @@ -0,0 +1,3 @@ +-- Generated by solar-tv/milestone/certify.py; do not edit. +import W1Proofs.Stages +import W1Proofs.Assembly diff --git a/tv/W1Proofs/Assembly.lean b/tv/W1Proofs/Assembly.lean new file mode 100644 index 00000000..d5158a87 --- /dev/null +++ b/tv/W1Proofs/Assembly.lean @@ -0,0 +1,42 @@ +-- Generated by solar-tv/milestone/certify.py; do not edit. +import W1Proofs.Items +import gen.Main.Evm4 +import gen.Main.Bytecode + +/-! The final EVM IR of `Main` against its bytecode, by the assembly checker's walk: the bytecode decodes, linearly from offset 0, to exactly the program's instructions, each jumped-to block at its `JUMPDEST`. -/ + +namespace SolarTV.Milestone.W1 + +open SolarTV.Assembly SolarTV.Export.Main SolarTV.Milestone.W1 + +set_option maxRecDepth 100000 + +/-- The items of the final EVM IR. -/ +def items : List Item := (itemsOf evm4).getD [] + +theorem items_eq : itemsOf evm4 = some items := by decide + +/-- The layout: each jumped-to block at the bytecode's next `JUMPDEST`. The walk checks it. -/ +def offset (label : Nat) : Nat := if label = 1 then 0x2e else if label = 2 then 0x32 else 0 + +/-- The instructions the walk reaches, each at its offset. -/ +def stream : List (Nat × Instr) := (walk bytecode offset 0 items).getD [] + +/-- The checker's walk accepts the exported bytecode against the final EVM IR. -/ +theorem walk_eq : walk bytecode offset 0 items = some stream := by decide +kernel + +theorem checked : Walk bytecode offset 0 items stream := walk_sound walk_eq + +/-- The bytecode's linear decoding is the final EVM IR's instructions at the layout. -/ +theorem decodes : decodeFrom bytecode (bytecode.length + 1) 0 = stream := + walk_decodes checked _ (by have := walk_length checked; omega) + +/-- info: 'SolarTV.Milestone.W1.walk_eq' depends on axioms: [propext, Quot.sound] -/ +#guard_msgs in +#print axioms walk_eq + +/-- info: 'SolarTV.Milestone.W1.decodes' depends on axioms: [propext, Quot.sound] -/ +#guard_msgs in +#print axioms decodes + +end SolarTV.Milestone.W1 diff --git a/tv/W1Proofs/Axioms.lean b/tv/W1Proofs/Axioms.lean new file mode 100644 index 00000000..a056c3aa --- /dev/null +++ b/tv/W1Proofs/Axioms.lean @@ -0,0 +1,25 @@ +import Lean + +/-! A fail-closed axiom check for generated proofs. + +`#axioms_within thm` fails unless every axiom `thm` depends on is `propext`, +`Classical.choice` or `Quot.sound`, and otherwise reports that it is within them, so that +`#guard_msgs` can pin the check where a generated proof's exact axiom set is not known in +advance (some runs need `Classical.choice`, some do not). `sorryAx`, `Lean.ofReduceBool` +(`native_decide`) and any declared axiom fail it. -/ + +namespace SolarTV.Milestone.W1 + +open Lean Elab Command in +/-- Fail unless the constant's axioms are among `propext`, `Classical.choice` and +`Quot.sound`. -/ +elab "#axioms_within " id:ident : command => do + let name ← liftCoreM <| realizeGlobalConstNoOverloadWithInfo id + let axioms ← liftCoreM <| collectAxioms name + let allowed := [``propext, ``Classical.choice, ``Quot.sound] + let bad := axioms.toList.filter (!allowed.contains ·) + unless bad.isEmpty do + throwError "'{name}' depends on axioms outside [propext, Classical.choice, Quot.sound]: {bad}" + logInfo m!"'{name}' depends on axioms within [propext, Classical.choice, Quot.sound]" + +end SolarTV.Milestone.W1 diff --git a/tv/W1Proofs/Items.lean b/tv/W1Proofs/Items.lean new file mode 100644 index 00000000..ac56f999 --- /dev/null +++ b/tv/W1Proofs/Items.lean @@ -0,0 +1,268 @@ +import SolarTV.Stages.AssemblyCheck +import SolarTV.EVMIR.Program + +/-! EVM IR programs as the assembly items the assembler solves. + +`itemsOf` spells an EVM IR program as the assembly the assembler solves: each instruction as +its opcode, a push as a push of its constant, a static jump as a push of its target's label +and the jump, a pushed label as its push, a dynamic jump as `JUMP`, and a `JUMPDEST` label +at the start of each block some pushed label targets. A +block's transfer to the block after it is spelled as `lower_terminator` in +`crates/codegen/src/backend/assembler/assembly/lower.rs` spells it: a final `jump` to the next +block is no instruction, and of a final `jumpi then; jump else` that falls through, only the +`JUMPI` to the other block stays, after an `ISZERO` when `then` is the one that follows. The +EVM IR semantics enters the next block past the end of a block, so the spelling runs the same +blocks. The last block's final `stop` is no instruction either, as `lower_terminator` leaves +it out of runtime code that nothing follows: the code ends there, which halts as STOP does. It +is partial: an effect outside the EVM's opcodes (an oracle's environment read or +call) or with another arity than its opcode's has no item, so a program outside that scope +fails the check. Every contract's `Assembly` module (w1's and the ones +`milestone/certify.py` writes) evaluates `SolarTV.Assembly.walk` over its bytecode against +these items. + +A jump table (`jumpTable`) is spelled as `indexed_jump.rs` lowers it, in the encoding the +bytecode shows (`Spelling`), which `itemsWith` takes for each table in layout order: packed, +a word of one-byte offsets, the first target's in its high byte, that `BYTE` picks the entry the +index numbers from, after adding the zero bytes above it (`PUSH 32-n; ADD; PUSHn table; SWAP1; +BYTE; JUMP`); or a stride table, `PUSH stride; MUL; PUSH entry0; ADD; JUMP` into entry stubs +`JUMPDEST; PUSH target; JUMP` laid out after the last block, `stride` bytes apart, each named by +a label past every block's. The walk checks that each packed offset fits its byte and that each +stub sits its index of strides past the first, so that the pick lands on the entry's target. With +stubs after it, the last block's final `stop` is a `STOP` again. The other encodings, relative +to a base or packed wider than a byte (`-Zpack-wide-jump-tables`, the size objective), have no +spelling, so the check refuses them, as it does a table with no spelling given. EVM IR requires a +table's index to be in range, as every lowering of a switch checks before the jump; out of range +the EVM IR semantics halts, while the bytecode jumps wherever the pick lands. -/ + +namespace SolarTV.Milestone.W1 + +open SolarTV.Assembly + +/-- The opcode of a stack operation, or `none` for one with no single-byte opcode: `dup` and +`swap` past the sixteenth word and `exchange` take an immediate, and the exporter writes none +of them. -/ +def stackItem : EVM.Op → Option Item + | .add => some (.op 0x01) | .mul => some (.op 0x02) | .sub => some (.op 0x03) + | .div => some (.op 0x04) | .sdiv => some (.op 0x05) | .mod => some (.op 0x06) + | .smod => some (.op 0x07) | .addmod => some (.op 0x08) | .mulmod => some (.op 0x09) + | .exp => some (.op 0x0a) | .signextend => some (.op 0x0b) + | .lt => some (.op 0x10) | .gt => some (.op 0x11) | .slt => some (.op 0x12) + | .sgt => some (.op 0x13) | .eq => some (.op 0x14) | .iszero => some (.op 0x15) + | .and => some (.op 0x16) | .or => some (.op 0x17) | .xor => some (.op 0x18) + | .not => some (.op 0x19) | .byte => some (.op 0x1a) | .shl => some (.op 0x1b) + | .shr => some (.op 0x1c) | .sar => some (.op 0x1d) | .clz => some (.op 0x1e) + | .calldatasize => some (.op 0x36) | .returndatasize => some (.op 0x3d) + | .pop => some (.op 0x50) + | .push value => some (.push value.toNat) + -- NOTE: DUP1..16 and SWAP1..16 only; deeper positions and EXCHANGE take an immediate, + -- outside these items. + | .dup index => if index.val < 16 then some (.op (0x80 + index.val)) else none + | .swap index => if index.val < 16 then some (.op (0x90 + index.val)) else none + | .exchange _ _ => none + +/-- The opcode of a memory instruction, or `none` for a copy or hash, which the program runs +as effects. -/ +def memoryItem : EVM.Memory.Op → Option Item + | .stack op => stackItem op + | .load => some (.op 0x51) + | .store => some (.op 0x52) + | .storeByte => some (.op 0x53) + | .size => some (.op 0x59) + | .copy | .hash => none + +/-- The opcode of an effect with its arity, or `none` for one that is no opcode. -/ +def effectItem : Machine.Effect → Nat → Option Item + | .address, 0 => some (.op 0x30) + | .caller, 0 => some (.op 0x33) + | .callvalue, 0 => some (.op 0x34) + | .calldataload, 1 => some (.op 0x35) + | .calldatasize, 0 => some (.op 0x36) + | .returndatasize, 0 => some (.op 0x3d) + | .mload, 1 => some (.op 0x51) + | .mstore, 2 => some (.op 0x52) + | .mstore8, 2 => some (.op 0x53) + | .sload, 1 => some (.op 0x54) + | .sstore, 2 => some (.op 0x55) + | .msize, 0 => some (.op 0x59) + | .tload, 1 => some (.op 0x5c) + | .tstore, 2 => some (.op 0x5d) + | .keccak256, 2 => some (.op 0x20) + | .calldatacopy, 3 => some (.op 0x37) + | .returndatacopy, 3 => some (.op 0x3e) + | .gas, 0 => some (.op 0x5a) + | .mcopy, 3 => some (.op 0x5e) + | .call .call, 7 => some (.op 0xf1) + | .call .callcode, 7 => some (.op 0xf2) + | .call .delegatecall, 6 => some (.op 0xf4) + | .call .staticcall, 6 => some (.op 0xfa) + -- NOTE: the runtime code's placeholder, a PUSH of zeros that the manifest lists, which + -- the deployment code links with the immutable (`SolarTV.Assembly.link`). + | .immutable id bytes .word, 0 => some (.immutable id bytes) + | .codecopy, 3 => some (.op 0x39) + | .create, 3 => some (.op 0xf0) + | .create2, 4 => some (.op 0xf5) + | .log n, arity => if n ≤ 4 ∧ arity = n + 2 then some (.op (0xa0 + n)) else none + | _, _ => none + +/-- The items of an instruction. -/ +def instrItems : EVM.Program.Instr → Option (List Item) + | .op op => (memoryItem op).map ([·]) + | .effect effect arity => (effectItem effect arity).map ([·]) + | .jump target => some [.pushLabel target, .op 0x56] + | .jumpi target => some [.pushLabel target, .op 0x57] + | .pushLabel target => some [.pushLabel target] + | .jumpDyn => some [.op 0x56] + | .jumpiDyn => some [.op 0x57] + -- NOTE: a jump table's items depend on its encoding, which `tableItems` spells. + | .jumpTable _ => none + | .stop => some [.op 0x00] + | .ret => some [.op 0xf3] + | .revert => some [.op 0xfd] + | .invalid => some [.op 0xfe] + +/-- How the assembler encoded a jump table, as the bytecode shows: `packed`, one-byte offsets +in a word that `BYTE` picks from, or `stride`, entry stubs whose target pushes are `width` +bytes wide. -/ +inductive Spelling where + | packed + | stride (width : Nat) + deriving DecidableEq, Repr + +def Spelling.isStride : Spelling → Bool + | .stride _ => true + | .packed => false + +/-- The jump tables' spellings not yet used, the label of the next stride table's first entry, +and the entry stubs of the stride tables so far, in layout order. -/ +structure Tables where + spellings : List Spelling + fresh : Nat + stubs : List Item + +/-- The entry stubs of a stride table from entry `index`: `JUMPDEST; PUSH target; JUMP`. -/ +def entries (table stride : Nat) : Nat → List Nat → List Item + | _, [] => [] + | index, target :: rest => + [.entry table index stride, .pushLabel target, .op 0x56] ++ entries table stride (index + 1) rest + +/-- The items of a jump table in the next spelling, as `indexed_jump::lower` writes it. -/ +def tableItems (targets : List Nat) (t : Tables) : Option (List Item × Tables) := + match t.spellings with + | [] => none + | .packed :: rest => + if 2 ≤ targets.length ∧ targets.length ≤ 32 then + -- PUSH 32-n; ADD (when n < 32); PUSHn table; SWAP1; BYTE; JUMP + some ((if targets.length < 32 then [.push (32 - targets.length), .op 0x01] else []) + ++ [.pushTable targets, .op 0x90, .op 0x1a, .op 0x56], { t with spellings := rest }) + else none + | .stride width :: rest => + if 1 ≤ width ∧ width ≤ 32 ∧ targets ≠ [] then + -- PUSH stride; MUL; PUSH entry0; ADD; JUMP + some ([.push (width + 3), .op 0x02, .pushLabel t.fresh, .op 0x01, .op 0x56], + { spellings := rest, fresh := t.fresh + 1, + stubs := t.stubs ++ entries t.fresh (width + 3) 0 targets }) + else none + +/-- The items of an instruction, a jump table in the next spelling. -/ +def instrTableItems (t : Tables) : EVM.Program.Instr → Option (List Item × Tables) + | .jumpTable targets => tableItems targets t + | instr => (instrItems instr).map (·, t) + +/-- The items of a list of instructions. -/ +def instrsItems : List EVM.Program.Instr → Option (List Item) + | [] => some [] + | instr :: rest => do + let head ← instrItems instr + let tail ← instrsItems rest + pure (head ++ tail) + +/-- The items of a block, given the block that follows it in the layout (none for the last +block) and whether the code ends after it: a final transfer to `next` falls through instead of +jumping, and a final stop where the code ends is the end of the code. -/ +def blockItems (next : Option Nat) (ends : Bool) (t : Tables) : + List EVM.Program.Instr → Option (List Item × Tables) + | [] => some ([], t) + | [.stop] => + -- the last block's stop: the code ends + if ends then some ([], t) + -- STOP + else some ([.op 0x00], t) + | [.jump target] => + -- jump next + if next = some target then some ([], t) + -- push target; JUMP + else some ([.pushLabel target, .op 0x56], t) + | [.jumpi yes, .jump no] => + -- push yes; JUMPI + if next = some no then some ([.pushLabel yes, .op 0x57], t) + -- ISZERO; push no; JUMPI + else if next = some yes then some ([.op 0x15, .pushLabel no, .op 0x57], t) + -- push yes; JUMPI; push no; JUMP + else some ([.pushLabel yes, .op 0x57, .pushLabel no, .op 0x56], t) + | instr :: rest => do + let (head, t) ← instrTableItems t instr + let (tail, t) ← blockItems next ends t rest + pure (head ++ tail, t) + +/-- The blocks' items in layout order from block `index`, each with the block after it; the code +ends after the last block when `ends`. -/ +def bodiesOf (ends : Bool) : Nat → Tables → List (List EVM.Program.Instr) → + Option (List (List Item) × Tables) + | _, t, [] => some ([], t) + | index, t, block :: rest => do + let (body, t) ← + blockItems (if rest.isEmpty then none else some (index + 1)) (ends && rest.isEmpty) t block + let (tail, t) ← bodiesOf ends (index + 1) t rest + pure (body :: tail, t) + +/-- The labels some item pushes, a packed table's each. -/ +def pushedLabels (bodies : List (List Item)) : List Nat := + bodies.flatMap fun body => body.flatMap fun + | .pushLabel label => [label] + | .pushTable labels => labels + | _ => [] + +/-- Each body from block `index` on, opening with its label when some item pushes it. -/ +def labelBodies (pushed : List Nat) : Nat → List (List Item) → List Item + | _, [] => [] + | index, body :: rest => + (if index ∈ pushed then [.label index] else []) ++ body ++ labelBodies pushed (index + 1) rest + +/-- The program as assembly items in layout order, each block some item jumps to opening with +its label, its jump tables in `spellings`, one each in layout order, and the stride tables' +entry stubs after the last block. -/ +def itemsWith (spellings : List Spelling) (p : EVM.Program.Program) : Option (List Item) := do + let (bodies, t) ← + bodiesOf (!spellings.any Spelling.isStride) 0 ⟨spellings, p.blocks.length, []⟩ p.blocks + if t.spellings.isEmpty then + pure (labelBodies (pushedLabels (bodies ++ [t.stubs])) 0 bodies ++ t.stubs) + else none + +/-- The program as assembly items, without jump tables. -/ +def itemsOf (p : EVM.Program.Program) : Option (List Item) := itemsWith [] p + +/-! Refusals: a jump table without its encoding has no items, and a packed table whose offsets do +not fit their bytes is placed nowhere, so no walk accepts code for it (`SolarTV.Assembly.no_walk`). -/ + +theorem table_unspelled : itemsOf ⟨[[.jumpTable [1, 1]], [.stop]]⟩ = none := by decide + +/-- A packed table: the bytes above its two entries added to the index, then the BYTE pick. -/ +theorem table_spelled : + itemsWith [.packed] ⟨[[.jumpTable [1, 1]], [.stop]]⟩ = + some [.push 30, .op 0x01, .pushTable [1, 1], .op 0x90, .op 0x1a, .op 0x56, .label 1] := by + decide + +/-- A stride table: its entry stubs after the last block, whose final stop is a STOP again. -/ +theorem table_stride : + itemsWith [.stride 2] ⟨[[.jumpTable [1, 1]], [.stop]]⟩ = + some [.push 5, .op 0x02, .pushLabel 2, .op 0x01, .op 0x56, .label 1, .op 0x00, + .entry 2 0 5, .pushLabel 1, .op 0x56, .entry 2 1 5, .pushLabel 1, .op 0x56] := by + decide + +/-- A table of one entry is never packed. -/ +theorem table_too_few : itemsWith [.packed] ⟨[[.jumpTable [1]], [.stop]]⟩ = none := by decide + +/-- An offset of 256 does not fit its byte. -/ +theorem table_wide (pc : Nat) : (Item.pushTable [1]).placed (fun _ => 256) pc = false := rfl + +end SolarTV.Milestone.W1 diff --git a/tv/W1Proofs/Runs/Evm1.lean b/tv/W1Proofs/Runs/Evm1.lean new file mode 100644 index 00000000..9b64ad6d --- /dev/null +++ b/tv/W1Proofs/Runs/Evm1.lean @@ -0,0 +1,22 @@ +-- Generated by solar-tv/milestone/certify.py; do not edit. +import W1Proofs.Tactic +import W1Proofs.Axioms +import gen.Main.Evm1 +import gen.Main.Sched + +/-! `cfg-simplify-early`: its input and output end in the same result on every call. -/ + +namespace SolarTV.Milestone.W1 + +open Machine SolarTV.Export.Main + +set_option maxHeartbeats 2000000 in +theorem evm1_run (o : Oracle) (call : Call) : + EVM.Program.run o sched call 9 = EVM.Program.run o evm1 call 5 := by + sym_exec + +/-- info: 'SolarTV.Milestone.W1.evm1_run' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms evm1_run + +end SolarTV.Milestone.W1 diff --git a/tv/W1Proofs/Runs/Evm2.lean b/tv/W1Proofs/Runs/Evm2.lean new file mode 100644 index 00000000..d14ef954 --- /dev/null +++ b/tv/W1Proofs/Runs/Evm2.lean @@ -0,0 +1,22 @@ +-- Generated by solar-tv/milestone/certify.py; do not edit. +import W1Proofs.Tactic +import W1Proofs.Axioms +import gen.Main.Evm2 +import gen.Main.Evm1 + +/-! `share-reverts`: its input and output end in the same result on every call. -/ + +namespace SolarTV.Milestone.W1 + +open Machine SolarTV.Export.Main + +set_option maxHeartbeats 2000000 in +theorem evm2_run (o : Oracle) (call : Call) : + EVM.Program.run o evm1 call 5 = EVM.Program.run o evm2 call 5 := by + sym_exec + +/-- info: 'SolarTV.Milestone.W1.evm2_run' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms evm2_run + +end SolarTV.Milestone.W1 diff --git a/tv/W1Proofs/Runs/Evm3.lean b/tv/W1Proofs/Runs/Evm3.lean new file mode 100644 index 00000000..d29e1b9f --- /dev/null +++ b/tv/W1Proofs/Runs/Evm3.lean @@ -0,0 +1,22 @@ +-- Generated by solar-tv/milestone/certify.py; do not edit. +import W1Proofs.Tactic +import W1Proofs.Axioms +import gen.Main.Evm3 +import gen.Main.Evm2 + +/-! `terminal-dedup`: its input and output end in the same result on every call. -/ + +namespace SolarTV.Milestone.W1 + +open Machine SolarTV.Export.Main + +set_option maxHeartbeats 2000000 in +theorem evm3_run (o : Oracle) (call : Call) : + EVM.Program.run o evm2 call 5 = EVM.Program.run o evm3 call 5 := by + sym_exec + +/-- info: 'SolarTV.Milestone.W1.evm3_run' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms evm3_run + +end SolarTV.Milestone.W1 diff --git a/tv/W1Proofs/Runs/Evm4.lean b/tv/W1Proofs/Runs/Evm4.lean new file mode 100644 index 00000000..dd6107c5 --- /dev/null +++ b/tv/W1Proofs/Runs/Evm4.lean @@ -0,0 +1,22 @@ +-- Generated by solar-tv/milestone/certify.py; do not edit. +import W1Proofs.Tactic +import W1Proofs.Axioms +import gen.Main.Evm4 +import gen.Main.Evm3 + +/-! `cfg-simplify-early`: its input and output end in the same result on every call. -/ + +namespace SolarTV.Milestone.W1 + +open Machine SolarTV.Export.Main + +set_option maxHeartbeats 2000000 in +theorem evm4_run (o : Oracle) (call : Call) : + EVM.Program.run o evm3 call 5 = EVM.Program.run o evm4 call 3 := by + sym_exec + +/-- info: 'SolarTV.Milestone.W1.evm4_run' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms evm4_run + +end SolarTV.Milestone.W1 diff --git a/tv/W1Proofs/Runs/Sched.lean b/tv/W1Proofs/Runs/Sched.lean new file mode 100644 index 00000000..329a2efd --- /dev/null +++ b/tv/W1Proofs/Runs/Sched.lean @@ -0,0 +1,22 @@ +-- Generated by solar-tv/milestone/certify.py; do not edit. +import W1Proofs.Tactic +import W1Proofs.Axioms +import gen.Main.Sched +import gen.Main.Stage0 + +/-! Stack scheduling: the last lowered MIR and the scheduled EVM IR end in the same result on every call. -/ + +namespace SolarTV.Milestone.W1 + +open Machine SolarTV.Export.Main + +set_option maxHeartbeats 2000000 in +theorem sched_run (o : Oracle) (call : Call) : + MIR.Lowered.Module.run o stage0 call 9 = EVM.Program.run o sched call 9 := by + sym_exec + +/-- info: 'SolarTV.Milestone.W1.sched_run' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms sched_run + +end SolarTV.Milestone.W1 diff --git a/tv/W1Proofs/Runs/Stage0.lean b/tv/W1Proofs/Runs/Stage0.lean new file mode 100644 index 00000000..4addfd75 --- /dev/null +++ b/tv/W1Proofs/Runs/Stage0.lean @@ -0,0 +1,21 @@ +-- Generated by solar-tv/milestone/certify.py; do not edit. +import W1Proofs.Tactic +import W1Proofs.Axioms +import gen.Main.Stage0 + +/-! The first lowered MIR ends on every call within 9 blocks, the number of its blocks. -/ + +namespace SolarTV.Milestone.W1 + +open Machine SolarTV.Export.Main + +set_option maxHeartbeats 2000000 in +theorem stage0_ends (o : Oracle) (call : Call) : + (MIR.Lowered.Module.run o stage0 call 9).isSome = true := by + sym_exec + +/-- info: 'SolarTV.Milestone.W1.stage0_ends' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms stage0_ends + +end SolarTV.Milestone.W1 diff --git a/tv/W1Proofs/Segment.lean b/tv/W1Proofs/Segment.lean new file mode 100644 index 00000000..4b9c0238 --- /dev/null +++ b/tv/W1Proofs/Segment.lean @@ -0,0 +1,154 @@ +import W1Proofs.Tactic +import SolarTV.CutPoint + +/-! Symbolic execution of loop-free segments between cut points. + +`sym_exec` runs two programs from their first configurations to their ends. A program that +loops has no such end within a fuel its blocks bound, so its stages are proved through cut +points instead (`SolarTV.CutPoint`): from every pair of configurations the exporter relates, +the two segments (`seg`) end alike. `sym_seg` proves one such obligation for configurations +whose words and state are variables: it evaluates both segments with the same definitional +steps as `sym_exec`, splits on the branch conditions they leave, and closes each leaf: + +- two ends, by the agreement of equal results (`agree_of_eq`) and `sym_exec`'s leaf procedures; +- two stuck segments, trivially; +- two cut points, by the relation lemma (`mk`) of a related pair: its source configuration + unifies with the leaf's, which fixes the related words, and the target configuration must + then equal the leaf's, by evaluation and the same leaf procedures. + +A segment that runs out of fuel, or ends differently from the other, leaves `False` or a +goal the procedures cannot close: the proof fails by mismatch. Nothing here proves an +invariant: the relations are the exporter's, and Lean only checks that they are preserved. -/ + +namespace SolarTV.Milestone.W1 + +open SolarTV.CutPoint Machine + +theorem agree_of_eq {a b : Halt × State} (h : a = b) : Agree a b := h ▸ Agree.refl a + +/-- One step of a segment from a configuration the code has built. Matching only a pair keeps +`dsimp` from unfolding the steps after one it cannot compute yet, as `iterate_mk` does for runs. -/ +@[defeq] theorem seg_mk {α β R : Type} (step : α × β → Option (R ⊕ (α × β))) (cut : α × β → Bool) + (k : Nat) (a : α) (b : β) : + seg step cut (k + 1) (a, b) = + match step (a, b) with + | none => .stuck + | some (.inl r) => .done r + | some (.inr y) => if cut y then .cut y else seg step cut k y := by + rw [seg] + cases step (a, b) with + | none => rfl + | some v => cases v <;> rfl + +@[defeq] theorem seg_zero {σ R : Type} (step : σ → Option (R ⊕ σ)) (cut : σ → Bool) (x : σ) : + seg step cut 0 x = .fuel := by + rw [seg] + +/-- A related pair from one relation of a list. -/ +theorem rel_mem {α β : Type} {rels : List (α → β → Prop)} {Q : α → β → Prop} {y : α} {y' : β} + (mem : Q ∈ rels) (h : Q y y') : ∃ Q ∈ rels, Q y y' := ⟨Q, mem, h⟩ + +open Lean Meta Simp in +/-- A stack position, a numeral of `Fin n`, as the number it is: a segment starts from a stack of +variables, so a `dup` or `swap` reads it at that number. -/ +dsimproc_decl finValLit (Fin.val _) := fun e => do + let_expr Fin.val n a := e | return .continue + let some n ← Nat.fromExpr? n | return .continue + let_expr OfNat.ofNat _ lit _ := a | return .continue + let some k := lit.rawNatLit? | return .continue + if n == 0 then return .continue + return .done (toExpr (k % n)) + +open Lean Meta Simp in +/-- `||` and `&&` of a literal, as a cut test of a known block leaves them. -/ +dsimproc_decl boolLit (_ || _) := fun e => do + let_expr or a b := e | return .continue + match a.constName?, b.constName? with + | some ``true, _ | _, some ``true => return .done (mkConst ``true) + | some ``false, _ => return .done b + | _, some ``false => return .done a + | _, _ => return .continue + +open Lean Meta Simp in +/-- `&&` of a literal. -/ +dsimproc_decl boolAndLit (_ && _) := fun e => do + let_expr and a b := e | return .continue + match a.constName?, b.constName? with + | some ``false, _ | _, some ``false => return .done (mkConst ``false) + | some ``true, _ => return .done b + | _, some ``true => return .done a + | _, _ => return .continue + +open Lean Meta Simp in +/-- A conditional on two numerals being equal, as a MIR value lookup leaves it (`Env.set` +compares value numbers): the branch the numerals pick. Definitional, since equality of numerals +decides by evaluation, so `dsimp` keeps the decision instance and the term type-correct. -/ +dsimproc_decl iteNatLit (ite _ _ _) := fun e => do + let_expr ite _ c _ a b := e | return .continue + let_expr Eq ty x y := c | return .continue + unless ty.isConstOf ``Nat do return .continue + let some m ← Nat.fromExpr? x | return .continue + let some n ← Nat.fromExpr? y | return .continue + return .done (if m == n then a else b) + +/-- Unfold a segment's step and its cut test. -/ +syntax "seg_eval" "[" Lean.Parser.Tactic.simpLemma,* "]" : tactic +macro_rules + | `(tactic| seg_eval [$ids,*]) => `(tactic| + dsimp only [seg_mk, seg_zero, SegRel, $ids,*, finValLit, boolLit, boolAndLit, iteNatLit, Nat.reduceBEq, ↓reduceIte, Bool.false_eq_true]) + +syntax "seg_norm" "[" Lean.Parser.Tactic.simpLemma,* "]" : tactic +macro_rules + | `(tactic| seg_norm [$ids,*]) => `(tactic| repeat (first | sym_eval | seg_eval [$ids,*] | sym_cond)) + +/-- The equation of two words, configurations or results, by evaluation and `sym_exec`'s leaf +procedures. -/ +macro "seg_word_eq" : tactic => `(tactic| ( + first + | with_reducible rfl + | (sym_norm; first + | with_reducible rfl + | (exfalso; bv_omega) + | (exfalso; sym_omega) + | (exfalso; sym_comm_contra) + | sym_select + | sym_agree))) + +/-- What a relation lemma asks of the target configuration: the variables only the target +names, given by unification, then its configuration and each condition. -/ +macro "seg_eq" : tactic => `(tactic| ( + repeat (apply Exists.intro) + repeat' (apply And.intro) + all_goals seg_word_eq)) + +/-- A leaf at two cut points, by one of the relation lemmas `mks` (each +`mk (words…) (state) (y') (h : y' = …) : ∃ Q ∈ rels, Q (…) y'`). -/ +syntax "seg_cut" "[" ident,* "]" : tactic +macro_rules + | `(tactic| seg_cut []) => `(tactic| fail "sym_seg: no relation relates the cut points") + | `(tactic| seg_cut [$m]) => `(tactic| (refine $m ?_; seg_eq)) + | `(tactic| seg_cut [$m, $ms,*]) => `(tactic| + first + | (refine $m ?_; seg_eq) + | seg_cut [$ms,*]) + +/-- One segment obligation, from configurations of variables: evaluate both segments, split +on the conditions they leave, and close each leaf. `unfolds` are the cut tests' definitions +and `mks` the relation lemmas. -/ +syntax "sym_seg" "[" Lean.Parser.Tactic.simpLemma,* "]" "[" ident,* "]" : tactic +set_option hygiene false in +macro_rules + | `(tactic| sym_seg [$us,*] [$ms,*]) => `(tactic| ( + obtain ⟨cd, hcd⟩ : ∃ cd, cd = calldataWord call := ⟨_, rfl⟩ + seg_norm [$us,*] + repeat' (split_cond <;> seg_norm [$us,*]) + all_goals first + | exact True.intro + | (apply agree_of_eq; seg_eq) + | seg_cut [$ms,*] + | (exfalso; bv_omega) + | (exfalso; sym_omega) + | (exfalso; sym_comm_contra) + | fail "sym_seg: the segments end differently on this path, or the procedure cannot tell")) + +end SolarTV.Milestone.W1 diff --git a/tv/W1Proofs/Stage.lean b/tv/W1Proofs/Stage.lean new file mode 100644 index 00000000..38c6fd5b --- /dev/null +++ b/tv/W1Proofs/Stage.lean @@ -0,0 +1,41 @@ +import SolarTV.Machine + +/-! A stage from two runs that end in the same result. + +The procedure of [Tactic.lean](Tactic.lean) proves, for concrete programs, that the first ends +at fuel `n` on every call in scope and that both programs give the same result there, at fuels +`n` and `m`. Since a layer's runs are deterministic and only gain ends with fuel, that is a +stage of their fuel-free semantics, whatever fuel the first program's result was reached at. -/ + +namespace SolarTV.Milestone.W1 + +open Machine + +/-- Every call: the w1 stages hold for any calldata, call value and storage. -/ +def anyCall : Call → Prop := fun _ => True + +theorem stage_of_runs {A B : Layer} {o : Oracle} {p : A.Prog} {q : B.Prog} + {scope : Call → Prop} (n m : Nat) + (ends : ∀ call, scope call → (A.run o p call n).isSome = true) + (same : ∀ call, scope call → A.run o p call n = B.run o q call m) : + Stage (A.sem o) (B.sem o) p q scope := by + apply stage_of_certified + intro call inScope r ran + obtain ⟨r0, h0⟩ := Option.isSome_iff_exists.mp (ends call inScope) + have e : r = r0 := A.ends_unique ran ⟨n, h0⟩ + subst e + refine ⟨r, ⟨m, ?_⟩, Agree.refl r⟩ + rw [← same call inScope] + exact h0 + +/-- The second program of such a pair ends where the first does. -/ +theorem ends_of_runs {A B : Layer} {o : Oracle} {p : A.Prog} {q : B.Prog} + {scope : Call → Prop} {n m : Nat} + (ends : ∀ call, scope call → (A.run o p call n).isSome = true) + (same : ∀ call, scope call → A.run o p call n = B.run o q call m) : + ∀ call, scope call → (B.run o q call m).isSome = true := by + intro call inScope + rw [← same call inScope] + exact ends call inScope + +end SolarTV.Milestone.W1 diff --git a/tv/W1Proofs/Stages.lean b/tv/W1Proofs/Stages.lean new file mode 100644 index 00000000..c0e649aa --- /dev/null +++ b/tv/W1Proofs/Stages.lean @@ -0,0 +1,99 @@ +-- Generated by solar-tv/milestone/certify.py; do not edit. +import W1Proofs.Runs.Stage0 +import W1Proofs.Runs.Sched +import W1Proofs.Runs.Evm1 +import W1Proofs.Runs.Evm2 +import W1Proofs.Runs.Evm3 +import W1Proofs.Runs.Evm4 +import W1Proofs.Stage +import SolarTV.Composition + +/-! The backend stages of `Main`, each proved on every call (`anyCall`: any calldata, call value and storage) under every oracle, and chained from the first lowered MIR `stage0` to the final EVM IR `evm4`. Fuels are the programs' block counts. -/ + +namespace SolarTV.Milestone.W1 + +open Machine SolarTV.Export.Main + +/-- `stack-schedule`: stage0 to sched. -/ +theorem stage_sched (o : Oracle) : Stage (mirSem o) (evmirSem o) stage0 sched anyCall := + stage_of_runs (A := MIR.Lowered.moduleLayer) (B := EVM.Program.layer) 9 9 (fun call _ => stage0_ends o call) + (fun call _ => sched_run o call) + +theorem sched_ends (o : Oracle) : ∀ call, anyCall call → + (EVM.Program.run o sched call 9).isSome = true := + ends_of_runs (A := MIR.Lowered.moduleLayer) (B := EVM.Program.layer) + (o := o) (p := stage0) (q := sched) (n := 9) (m := 9) (fun call _ => stage0_ends o call) + (fun call _ => sched_run o call) + +/-- `cfg-simplify-early`: sched to evm1. -/ +theorem stage_evm1 (o : Oracle) : Stage (evmirSem o) (evmirSem o) sched evm1 anyCall := + stage_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) 9 5 (sched_ends o) + (fun call _ => evm1_run o call) + +theorem evm1_ends (o : Oracle) : ∀ call, anyCall call → + (EVM.Program.run o evm1 call 5).isSome = true := + ends_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) + (o := o) (p := sched) (q := evm1) (n := 9) (m := 5) (sched_ends o) + (fun call _ => evm1_run o call) + +/-- `share-reverts`: evm1 to evm2. -/ +theorem stage_evm2 (o : Oracle) : Stage (evmirSem o) (evmirSem o) evm1 evm2 anyCall := + stage_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) 5 5 (evm1_ends o) + (fun call _ => evm2_run o call) + +theorem evm2_ends (o : Oracle) : ∀ call, anyCall call → + (EVM.Program.run o evm2 call 5).isSome = true := + ends_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) + (o := o) (p := evm1) (q := evm2) (n := 5) (m := 5) (evm1_ends o) + (fun call _ => evm2_run o call) + +/-- `terminal-dedup`: evm2 to evm3. -/ +theorem stage_evm3 (o : Oracle) : Stage (evmirSem o) (evmirSem o) evm2 evm3 anyCall := + stage_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) 5 5 (evm2_ends o) + (fun call _ => evm3_run o call) + +theorem evm3_ends (o : Oracle) : ∀ call, anyCall call → + (EVM.Program.run o evm3 call 5).isSome = true := + ends_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) + (o := o) (p := evm2) (q := evm3) (n := 5) (m := 5) (evm2_ends o) + (fun call _ => evm3_run o call) + +/-- `cfg-simplify-early`: evm3 to evm4. -/ +theorem stage_evm4 (o : Oracle) : Stage (evmirSem o) (evmirSem o) evm3 evm4 anyCall := + stage_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) 5 3 (evm3_ends o) + (fun call _ => evm4_run o call) + +/-- The compilation from the first lowered MIR to the final EVM IR. -/ +def compilation : Compilation := + ⟨stage0, [], sched, [evm1, evm2, evm3, evm4]⟩ + +/-- Every stage from the first lowered MIR to the final EVM IR, chained by the library's composition, on every call. -/ +theorem w1_mir_to_evmir (o : Oracle) : Stage (mirSem o) (evmirSem o) stage0 evm4 anyCall := + mir_to_evmir o anyCall compilation trivial (stage_sched o) + ⟨stage_evm1 o, stage_evm2 o, stage_evm3 o, stage_evm4 o, trivial⟩ + +/-- info: 'SolarTV.Milestone.W1.stage_sched' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms stage_sched + +/-- info: 'SolarTV.Milestone.W1.stage_evm1' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms stage_evm1 + +/-- info: 'SolarTV.Milestone.W1.stage_evm2' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms stage_evm2 + +/-- info: 'SolarTV.Milestone.W1.stage_evm3' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms stage_evm3 + +/-- info: 'SolarTV.Milestone.W1.stage_evm4' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms stage_evm4 + +/-- info: 'SolarTV.Milestone.W1.w1_mir_to_evmir' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms w1_mir_to_evmir + +end SolarTV.Milestone.W1 diff --git a/tv/W1Proofs/Tactic.lean b/tv/W1Proofs/Tactic.lean new file mode 100644 index 00000000..0774718f --- /dev/null +++ b/tv/W1Proofs/Tactic.lean @@ -0,0 +1,1108 @@ +import Lean +import EvmRules.Bits +import SolarTV.Machine +import SolarTV.MemorySymbolic +import SolarTV.MIR.Program +import SolarTV.EVMIR.Program + +/-! A kernel-only procedure for the stages of one loop-free contract. + +For two concrete programs, a stage holds when, on every call, the first ends at some fuel +and both end in the same result (`stage_of_runs`). `sym_exec` proves that equation, and the +first program's end, by symbolic execution over a symbolic call and oracle: + +- `dsimp` runs both programs block by block with the semantics' own equations and the + lookups below, all definitional, so the kernel checks a computed step by evaluation and + not by replaying a chain of rewrites. Calldata words, memory, the oracle and the word + operations stay opaque, so both programs build the same terms for the same values. +- A branch condition that the code cannot decide is turned into a proposition over those + terms by the `cond_*` lemmas (when the word an operation leaves is zero), and + `split_cond` case-splits on the first one left, rewriting both programs with the case. +- A leaf closes by reflexivity when both ends agree, and by `bv_omega` when its cases + contradict each other, as when the programs test one condition in different words. +- Shifts, `NOT` and the binary word operations of numerals fold to numerals, as passes respell + constants and an allocation's bounds checks compute on the constant free memory pointer, and + the tests the compiler spells an address check with (the word above the 160-bit mask, its high + bits shifted out, the word equal to its masked self) rewrite to one proposition, so that each + program's spelling meets the other's. +- A load at a constant address reads the word a store there wrote, reads past a store to + another word, and reads zero from the memory a call starts with, so that the checks that + fresh memory is zero are decided. + +Nothing here calls `bv_decide` or `native_decide`, and `decide` only runs on closed terms, +inside `dsimp`'s evaluation and in `BitVec.reduceEq` on two numerals, so the proofs rest on the +kernel and the standard axioms. A program that loops, reads a value the code does not pin, or +whose stage is false leaves a goal: the procedure fails closed. -/ + +namespace SolarTV.Milestone.W1 + +open EvmRules Machine + +/-! Branch conditions as propositions. A jump is taken on a nonzero word, so each lemma +says when the word an operation leaves is zero. -/ + +theorem cond_ne (a b : Word) : (Evm.ne a b = 0) = (a = b) := by + unfold Evm.ne + by_cases h : a = b + · simp [h] + · simp [h] + +theorem cond_eq (a b : Word) : (Evm.eq a b = 0) = ¬(b = a) := by + unfold Evm.eq + by_cases h : a = b + · simp [h] + · have h' : ¬b = a := fun e => h e.symm + simp [h, h'] + +theorem cond_sub (a b : Word) : (Evm.sub a b = 0) = (b = a) := by + unfold Evm.sub + apply propext + constructor + · intro h; bv_omega + · intro h; bv_omega + +theorem cond_lt (a b : Word) : (Evm.lt a b = 0) = ¬(a < b) := by + unfold Evm.lt + by_cases h : a < b + · simp [h, BitVec.ult_iff_lt] + · simp [h, BitVec.ult_iff_lt] + +theorem cond_gt (a b : Word) : (Evm.gt a b = 0) = ¬(b < a) := by + unfold Evm.gt + by_cases h : b < a + · simp [h, BitVec.ult_iff_lt] + · simp [h, BitVec.ult_iff_lt] + +theorem cond_iszero (a : Word) : (Evm.iszero a = 0) = ¬(a = 0) := by + unfold Evm.iszero + by_cases h : a = 0 + · simp only [h, beq_self_eq_true, Bool.cond_true, not_true_eq_false] + decide + · simp only [h, not_false_eq_true] + have : (a == 0) = false := by simpa using h + rw [this] + decide + +/-- A test compared with zero the other way round, as a fact a pass checks with `eq` reads +it (`cond_eq` puts the zero first): the same propositions as the lemmas above. -/ +theorem cond_zero_lt (a b : Word) : ((0 : Word) = Evm.lt a b) = ¬(a < b) := by + rw [← cond_lt]; exact propext ⟨Eq.symm, Eq.symm⟩ + +theorem cond_zero_gt (a b : Word) : ((0 : Word) = Evm.gt a b) = ¬(b < a) := by + rw [← cond_gt]; exact propext ⟨Eq.symm, Eq.symm⟩ + +theorem cond_zero_eq (a b : Word) : ((0 : Word) = Evm.eq a b) = ¬(b = a) := by + rw [← cond_eq]; exact propext ⟨Eq.symm, Eq.symm⟩ + +theorem cond_zero_ne (a b : Word) : ((0 : Word) = Evm.ne a b) = (a = b) := by + rw [show ((0 : Word) = Evm.ne a b) = (Evm.ne a b = 0) from propext ⟨Eq.symm, Eq.symm⟩, cond_ne] + +theorem cond_zero_iszero (a : Word) : ((0 : Word) = Evm.iszero a) = ¬(a = 0) := by + rw [← cond_iszero]; exact propext ⟨Eq.symm, Eq.symm⟩ + +/-- A disjunction of tests, as the dispatcher's guards combine them, is zero when both are. -/ +theorem cond_or (a b : Word) : (Evm.or a b = 0) = (a = 0 ∧ b = 0) := by + unfold Evm.or + exact propext BitVec.or_eq_zero_iff + +/-! An address is a word of at most 160 bits, the mask's own: masking it keeps it, so a test +that a word equals its masked self holds once a test that it fits passed. The caller is the +oracle's, any address, which fits. -/ + +theorem and_mask {x : Word} (h : ¬ (1461501637330902918203684832716283019655932542975 : Word) < x) : + Evm.and x 1461501637330902918203684832716283019655932542975 = x := by + unfold Evm.and + apply BitVec.eq_of_toNat_eq + have hm : (1461501637330902918203684832716283019655932542975 : Word).toNat = 2 ^ 160 - 1 := rfl + have hx : x.toNat ≤ 2 ^ 160 - 1 := by + rw [BitVec.lt_def, hm] at h; omega + rw [BitVec.toNat_and, hm, Nat.and_two_pow_sub_one_eq_mod] + exact Nat.mod_eq_of_lt (by omega) + +theorem mask_and {x : Word} (h : ¬ (1461501637330902918203684832716283019655932542975 : Word) < x) : + Evm.and 1461501637330902918203684832716283019655932542975 x = x := by + have := and_mask h + unfold Evm.and at this ⊢ + rw [BitVec.and_comm] + exact this + +theorem caller_le_mask (o : Oracle) : + ¬ (1461501637330902918203684832716283019655932542975 : Word) < o.caller.setWidth 256 := by + have hm : (1461501637330902918203684832716283019655932542975 : Word).toNat = 2 ^ 160 - 1 := rfl + have h := o.caller.isLt + rw [BitVec.lt_def, BitVec.toNat_setWidth, hm, Nat.mod_eq_of_lt (by omega)] + omega + +/-- An address immutable's `PUSH20` placeholder pushes 20 bytes, which fit. -/ +theorem immutable20_le_mask (o : Oracle) (id : Nat) : + ¬ (1461501637330902918203684832716283019655932542975 : Word) < immutableWord o id 20 := by + have hm : (1461501637330902918203684832716283019655932542975 : Word).toNat = 2 ^ 160 - 1 := rfl + have h := immutableWord_toNat o id 20 (by decide) (by decide) + have lt := Nat.mod_lt (immutableValue o id).toNat (by decide : 0 < 256 ^ 20) + rw [BitVec.lt_def, hm, h] + have : (256 : Nat) ^ 20 = 2 ^ 160 := by decide + omega + +/-- A width test as solar spells it, by shifting out the address bits, as the mask test. -/ +theorem shr160_eq_zero (x : Word) : + (Evm.shr 160 x = 0) = ¬ (1461501637330902918203684832716283019655932542975 : Word) < x := by + have hm : (1461501637330902918203684832716283019655932542975 : Word).toNat = 2 ^ 160 - 1 := rfl + have hs : Evm.shr 160 x = x >>> 160 := by + unfold Evm.shr + rw [show (160 : Word).ult 256 = true from rfl, Bool.cond_true, BitVec.ushiftRight_eq'] + rfl + rw [hs, BitVec.lt_def, hm] + apply propext + rw [BitVec.toNat_eq, BitVec.toNat_ushiftRight, Nat.shiftRight_eq_div_pow] + show x.toNat / 2 ^ 160 = 0 ↔ ¬2 ^ 160 - 1 < x.toNat + rw [Nat.div_eq_zero_iff] + have := x.isLt + omega + +theorem zero_eq_shr160 (x : Word) : + (0 = Evm.shr 160 x) = ¬ (1461501637330902918203684832716283019655932542975 : Word) < x := by + rw [← shr160_eq_zero] + exact propext eq_comm + +/-! Tests the cases decide, as the words they leave, and the arithmetic a select becomes: +`if-convert` turns a branch on a test `c` between `t` and `f` into `f + c * (t - f)`. -/ + +theorem lt_of_case {a b : Word} (h : a < b) : Evm.lt a b = 1 := by + simp [Evm.lt, BitVec.ult_iff_lt, h] +theorem lt_of_not_case {a b : Word} (h : ¬(a < b)) : Evm.lt a b = 0 := by + simp [Evm.lt, BitVec.ult_iff_lt, h] +theorem gt_of_case {a b : Word} (h : b < a) : Evm.gt a b = 1 := by + simp [Evm.gt, BitVec.ult_iff_lt, h] +theorem gt_of_not_case {a b : Word} (h : ¬(b < a)) : Evm.gt a b = 0 := by + simp [Evm.gt, BitVec.ult_iff_lt, h] +theorem eq_of_case {a b : Word} (h : b = a) : Evm.eq a b = 1 := by + subst h; simp [Evm.eq] +theorem eq_of_not_case {a b : Word} (h : ¬(b = a)) : Evm.eq a b = 0 := by + unfold Evm.eq + rw [beq_eq_false_iff_ne.mpr (fun e => h e.symm)] + rfl +theorem iszero_of_case {a : Word} (h : a = 0) : Evm.iszero a = 1 := by + subst h; simp [Evm.iszero] +theorem iszero_of_not_case {a : Word} (h : ¬(a = 0)) : Evm.iszero a = 0 := by + unfold Evm.iszero + rw [beq_eq_false_iff_ne.mpr h] + rfl + +theorem mul_word_one (a : Word) : Evm.mul a 1 = a := BitVec.mul_one a +theorem mul_one_word (a : Word) : Evm.mul 1 a = a := BitVec.one_mul a +theorem mul_word_zero (a : Word) : Evm.mul a 0 = 0 := BitVec.mul_zero +theorem mul_zero_word (a : Word) : Evm.mul 0 a = 0 := BitVec.zero_mul +theorem add_sub_word (a b : Word) : Evm.add b (Evm.sub a b) = a := by + unfold Evm.add Evm.sub + bv_omega +theorem add_word_zero (a : Word) : Evm.add a 0 = a := BitVec.add_zero a +theorem add_zero_word (a : Word) : Evm.add 0 a = a := BitVec.zero_add a + +/-! Commutative operations, which a pass may write either way round: the `word*Comm` +simprocs below rewrite with them towards one order of their operands, the same for both +programs. -/ + +theorem word_add_comm (a b : Word) : Evm.add a b = Evm.add b a := BitVec.add_comm a b +theorem word_mul_comm (a b : Word) : Evm.mul a b = Evm.mul b a := BitVec.mul_comm a b +theorem word_and_comm (a b : Word) : Evm.and a b = Evm.and b a := BitVec.and_comm a b +theorem word_or_comm (a b : Word) : Evm.or a b = Evm.or b a := BitVec.or_comm a b +theorem word_xor_comm (a b : Word) : Evm.xor a b = Evm.xor b a := BitVec.xor_comm a b + +/-! Evaluation steps, each definitional. -/ + +/-- One iteration from a configuration the code has built. Matching only a pair keeps +`dsimp` from unfolding the iterations after a step it cannot compute yet. -/ +@[defeq] theorem iterate_mk {α β : Type} (step : α × β → Option ((Halt × State) ⊕ (α × β))) + (n : Nat) (a : α) (b : β) : + iterate step (n + 1) (a, b) = + match step (a, b) with + | some (.inl result) => some result + | some (.inr next) => iterate step n next + | none => none := by + rw [iterate] + cases step (a, b) with + | none => rfl + | some v => cases v <;> rfl + +@[defeq] theorem iterate_zero {σ : Type} (step : σ → Option ((Halt × State) ⊕ σ)) (x : σ) : + iterate step 0 x = none := by + rw [iterate] + + +/-! Effects, one equation each. A calldata word is read through `cd`, a variable the procedure +binds to `calldataWord call` first, so that the kernel never unfolds the 32-byte read while it +checks a step. -/ + +section effects + +variable (o : Oracle) (call : Call) (s : State) + +@[defeq] theorem apply_mload (offset : Word) : Effect.apply o call .mload [offset] s = + some (some (s.memory.load offset.toNat), { s with memory := s.memory.expand offset.toNat 32 }) := rfl +@[defeq] theorem apply_mstore (offset value : Word) : Effect.apply o call .mstore [offset, value] s = + some (none, { s with memory := s.memory.store offset.toNat value }) := rfl +@[defeq] theorem apply_mstore8 (offset value : Word) : Effect.apply o call .mstore8 [offset, value] s = + some (none, { s with memory := s.memory.storeByte offset.toNat value }) := rfl +@[defeq] theorem apply_msize : Effect.apply o call .msize [] s = some (some s.memory.msize, s) := rfl +@[defeq] theorem apply_sload (key : Word) : Effect.apply o call .sload [key] s = + some (some (s.storage key), s) := rfl +@[defeq] theorem apply_sstore (key value : Word) : Effect.apply o call .sstore [key, value] s = + some (none, { s with storage := update s.storage key value }) := rfl +@[defeq] theorem apply_tload (key : Word) : Effect.apply o call .tload [key] s = + some (some (s.transient key), s) := rfl +@[defeq] theorem apply_tstore (key value : Word) : Effect.apply o call .tstore [key, value] s = + some (none, { s with transient := update s.transient key value }) := rfl +@[defeq] theorem apply_calldatasize : Effect.apply o call .calldatasize [] s = + some (some (BitVec.ofNat 256 call.calldata.size), s) := rfl +@[defeq] theorem apply_callvalue : Effect.apply o call .callvalue [] s = + some (some (BitVec.ofNat 256 call.callvalue), s) := rfl +@[defeq] theorem apply_caller : Effect.apply o call .caller [] s = + some (some (o.caller.setWidth 256), s) := rfl +@[defeq] theorem apply_address : Effect.apply o call .address [] s = + some (some (BitVec.ofNat 256 environment.callee), s) := rfl +@[defeq] theorem apply_returndatasize : Effect.apply o call .returndatasize [] s = + some (some (o.env "returndatasize" s.world []), s) := rfl +@[defeq] theorem apply_keccak256 (offset size : Word) : + Effect.apply o call .keccak256 [offset, size] s = + let memory := s.memory.expand offset.toNat size.toNat + some (some (o.keccak (memory.read offset.toNat size.toNat)), { s with memory }) := rfl + +@[defeq] theorem apply_immutable (id bytes : Nat) (read : ImmutableRead) : + Effect.apply o call (.immutable id bytes read) [] s = + some (some (read.apply (immutableWord o id bytes)), s) := rfl +@[defeq] theorem apply_codecopy (dest offset size : Word) : + Effect.apply o call .codecopy [dest, offset, size] s = + let memory := s.memory.write dest.toNat size.toNat (fun i => codeByte o (offset.toNat + i)) + some (none, { s with memory }) := rfl +@[defeq] theorem apply_create (value offset size : Word) : + Effect.apply o call .create [value, offset, size] s = some (created o s [value] offset size) := + rfl +@[defeq] theorem apply_create2 (value offset size salt : Word) : + Effect.apply o call .create2 [value, offset, size, salt] s = + some (created o s [value, salt] offset size) := rfl +@[defeq] theorem apply_gas : Effect.apply o call .gas [] s = + let world := s.world ++ [.read "gas"] + some (some (o.env "gas" world []), { s with world }) := rfl +@[defeq] theorem apply_env (name : String) (operands : List Word) : + Effect.apply o call (.env name) operands s = some (some (o.env name s.world operands), s) := rfl +@[defeq] theorem apply_calldatacopy (dest offset size : Word) : + Effect.apply o call .calldatacopy [dest, offset, size] s = + let memory := s.memory.write dest.toNat size.toNat + (fun i => calldataByte call (offset.toNat + i)) + some (none, { s with memory }) := rfl +@[defeq] theorem apply_mcopy (dest source size : Word) : + Effect.apply o call .mcopy [dest, source, size] s = + let read := s.memory.expand source.toNat size.toNat + let memory := read.write dest.toNat size.toNat (fun i => read.bytes (source.toNat + i)) + some (none, { s with memory }) := rfl +@[defeq] theorem apply_returndatacopy (dest offset size : Word) : + Effect.apply o call .returndatacopy [dest, offset, size] s = + if (returndataSize o s.world).toNat < offset.toNat + size.toNat then none + else + let memory := s.memory.write dest.toNat size.toNat + (fun i => returndataByte o s.world (offset.toNat + i)) + some (none, { s with memory }) := rfl + +/-- The memory a call sees, after the expansion of its input and output ranges. -/ +def callMemory (s : State) (inOffset inSize outOffset outSize : Word) : Mem := + (s.memory.expand inOffset.toNat inSize.toNat).expand outOffset.toNat outSize.toNat + +/-- The world after a call, which `sym_eval` unfolds. -/ +def callWorld (s : State) (kind : CallKind) (seen : List Word) + (inOffset inSize outOffset outSize : Word) : List Event := + s.world ++ [.call kind seen + ((callMemory s inOffset inSize outOffset outSize).read inOffset.toNat inSize.toNat) + s.storage s.transient] + +@[defeq] theorem apply_call (gas address value inOffset inSize outOffset outSize : Word) : + Effect.apply o call (.call .call) [gas, address, value, inOffset, inSize, outOffset, outSize] s = + let world := callWorld s .call [gas, address, value] inOffset inSize outOffset outSize + some (some (callFlag o world), called o .call s + (callMemory s inOffset inSize outOffset outSize) outOffset outSize world) := rfl +@[defeq] theorem apply_callcode (gas address value inOffset inSize outOffset outSize : Word) : + Effect.apply o call (.call .callcode) + [gas, address, value, inOffset, inSize, outOffset, outSize] s = + let world := callWorld s .callcode [gas, address, value] inOffset inSize outOffset outSize + some (some (callFlag o world), called o .callcode s + (callMemory s inOffset inSize outOffset outSize) outOffset outSize world) := rfl +@[defeq] theorem apply_delegatecall (gas address inOffset inSize outOffset outSize : Word) : + Effect.apply o call (.call .delegatecall) [gas, address, inOffset, inSize, outOffset, outSize] s = + let world := callWorld s .delegatecall [gas, address] inOffset inSize outOffset outSize + some (some (callFlag o world), called o .delegatecall s + (callMemory s inOffset inSize outOffset outSize) outOffset outSize world) := rfl +@[defeq] theorem apply_staticcall (gas address inOffset inSize outOffset outSize : Word) : + Effect.apply o call (.call .staticcall) [gas, address, inOffset, inSize, outOffset, outSize] s = + let world := callWorld s .staticcall [gas, address] inOffset inSize outOffset outSize + some (some (callFlag o world), called o .staticcall s + (callMemory s inOffset inSize outOffset outSize) outOffset outSize world) := rfl + +/-- The state after a log, which `sym_eval` unfolds. -/ +def logged (s : State) (offset size : Word) (topics : List Word) : State := + let memory := s.memory.expand offset.toNat size.toNat + { s with memory, world := s.world ++ [.log topics (memory.read offset.toNat size.toNat)] } + +@[defeq] theorem apply_log0 (offset size : Word) : + Effect.apply o call (.log 0) [offset, size] s = some (none, logged s offset size []) := rfl +@[defeq] theorem apply_log1 (offset size t0 : Word) : + Effect.apply o call (.log 1) [offset, size, t0] s = + some (none, logged s offset size [t0]) := rfl +@[defeq] theorem apply_log2 (offset size t0 t1 : Word) : + Effect.apply o call (.log 2) [offset, size, t0, t1] s = + some (none, logged s offset size [t0, t1]) := rfl +@[defeq] theorem apply_log3 (offset size t0 t1 t2 : Word) : + Effect.apply o call (.log 3) [offset, size, t0, t1, t2] s = + some (none, logged s offset size [t0, t1, t2]) := rfl +@[defeq] theorem apply_log4 (offset size t0 t1 t2 t3 : Word) : + Effect.apply o call (.log 4) [offset, size, t0, t1, t2, t3] s = + some (none, logged s offset size [t0, t1, t2, t3]) := rfl + +/-- A calldata read as a read of `cd`. Not definitional, so `simp` rewrites with its proof. -/ +theorem apply_calldataload {cd : Word → Word} (hcd : cd = calldataWord call) (offset : Word) : + Effect.apply o call .calldataload [offset] s = some (some (cd offset), s) := by + subst hcd + rfl + +end effects + +/-! EVM IR word operations, one equation each, by `rfl`. `sym_eval` rewrites a step with these +instead of unfolding `EVM.step`, whose match over every operation it would otherwise reduce on +every step of every path. `EVM.step` itself is unchanged, and an operation without an equation +here (`exchange`, or a stack too short for its operands) leaves the step unevaluated, so the +procedure fails rather than guesses. -/ + +section steps + +variable (ctx : EVM.Context) + +@[defeq] theorem step_add (a b : Word) (rest : List Word) : + EVM.step ctx .add (a :: b :: rest) = some (Evm.add a b :: rest) := rfl +@[defeq] theorem step_mul (a b : Word) (rest : List Word) : + EVM.step ctx .mul (a :: b :: rest) = some (Evm.mul a b :: rest) := rfl +@[defeq] theorem step_and (a b : Word) (rest : List Word) : + EVM.step ctx .and (a :: b :: rest) = some (Evm.and a b :: rest) := rfl +@[defeq] theorem step_or (a b : Word) (rest : List Word) : + EVM.step ctx .or (a :: b :: rest) = some (Evm.or a b :: rest) := rfl +@[defeq] theorem step_xor (a b : Word) (rest : List Word) : + EVM.step ctx .xor (a :: b :: rest) = some (Evm.xor a b :: rest) := rfl +@[defeq] theorem step_div (a b : Word) (rest : List Word) : + EVM.step ctx .div (a :: b :: rest) = some (Evm.div a b :: rest) := rfl +@[defeq] theorem step_sdiv (a b : Word) (rest : List Word) : + EVM.step ctx .sdiv (a :: b :: rest) = some (Evm.sdiv a b :: rest) := rfl +@[defeq] theorem step_mod (a b : Word) (rest : List Word) : + EVM.step ctx .mod (a :: b :: rest) = some (Evm.mod a b :: rest) := rfl +@[defeq] theorem step_smod (a b : Word) (rest : List Word) : + EVM.step ctx .smod (a :: b :: rest) = some (Evm.smod a b :: rest) := rfl +@[defeq] theorem step_signextend (a b : Word) (rest : List Word) : + EVM.step ctx .signextend (a :: b :: rest) = some (Evm.signextend a b :: rest) := rfl +@[defeq] theorem step_byte (a b : Word) (rest : List Word) : + EVM.step ctx .byte (a :: b :: rest) = some (Evm.byte a b :: rest) := rfl +@[defeq] theorem step_shl (a b : Word) (rest : List Word) : + EVM.step ctx .shl (a :: b :: rest) = some (Evm.shl a b :: rest) := rfl +@[defeq] theorem step_shr (a b : Word) (rest : List Word) : + EVM.step ctx .shr (a :: b :: rest) = some (Evm.shr a b :: rest) := rfl +@[defeq] theorem step_sar (a b : Word) (rest : List Word) : + EVM.step ctx .sar (a :: b :: rest) = some (Evm.sar a b :: rest) := rfl +@[defeq] theorem step_lt (a b : Word) (rest : List Word) : + EVM.step ctx .lt (a :: b :: rest) = some (Evm.lt a b :: rest) := rfl +@[defeq] theorem step_gt (a b : Word) (rest : List Word) : + EVM.step ctx .gt (a :: b :: rest) = some (Evm.gt a b :: rest) := rfl +@[defeq] theorem step_slt (a b : Word) (rest : List Word) : + EVM.step ctx .slt (a :: b :: rest) = some (Evm.slt a b :: rest) := rfl +@[defeq] theorem step_sgt (a b : Word) (rest : List Word) : + EVM.step ctx .sgt (a :: b :: rest) = some (Evm.sgt a b :: rest) := rfl +@[defeq] theorem step_eq (a b : Word) (rest : List Word) : + EVM.step ctx .eq (a :: b :: rest) = some (Evm.eq a b :: rest) := rfl +@[defeq] theorem step_sub (a b : Word) (rest : List Word) : + EVM.step ctx .sub (a :: b :: rest) = some (Evm.sub a b :: rest) := rfl +@[defeq] theorem step_exp (a b : Word) (rest : List Word) : + EVM.step ctx .exp (a :: b :: rest) = some (Word.power a b.toNat :: rest) := rfl +@[defeq] theorem step_addmod (a b n : Word) (rest : List Word) : + EVM.step ctx .addmod (a :: b :: n :: rest) = some (Evm.addmod a b n :: rest) := rfl +@[defeq] theorem step_mulmod (a b n : Word) (rest : List Word) : + EVM.step ctx .mulmod (a :: b :: n :: rest) = some (Evm.mulmod a b n :: rest) := rfl +@[defeq] theorem step_not (a : Word) (rest : List Word) : + EVM.step ctx .not (a :: rest) = some (Evm.not a :: rest) := rfl +@[defeq] theorem step_clz (a : Word) (rest : List Word) : + EVM.step ctx .clz (a :: rest) = some (Evm.clz a :: rest) := rfl +@[defeq] theorem step_iszero (a : Word) (rest : List Word) : + EVM.step ctx .iszero (a :: rest) = some (Evm.iszero a :: rest) := rfl +@[defeq] theorem step_pop (a : Word) (rest : List Word) : + EVM.step ctx .pop (a :: rest) = some rest := rfl +@[defeq] theorem step_dup (index : Fin 256) (stack : List Word) : + EVM.step ctx (.dup index) stack = (stack[index.val]?).map (fun value => value :: stack) := rfl +@[defeq] theorem step_swap (index : Fin 256) (a : Word) (rest : List Word) : + EVM.step ctx (.swap index) (a :: rest) = + (rest[index.val]?).map (fun value => value :: rest.set index.val a) := rfl +@[defeq] theorem step_calldatasize (rest : List Word) : + EVM.step ctx .calldatasize rest = some (ctx.calldataSize :: rest) := rfl +@[defeq] theorem step_returndatasize (rest : List Word) : + EVM.step ctx .returndatasize rest = some (ctx.returndataSize :: rest) := rfl +@[defeq] theorem step_push (value : Word) (rest : List Word) : + EVM.step ctx (.push value) rest = some (value :: rest) := rfl + +end steps + +/-! Stack positions of `dup` and `swap` as numbers. -/ + +open Lean Meta Simp in +/-- A stack position of `dup`, `swap` or `exchange`, a `Fin` numeral of any bound, as the +number it is, so that `dup` and `swap` read the stack at a literal index. -/ +dsimproc_decl finValue (Fin.val _) := fun e => do + let_expr Fin.val _ x := e | return .continue + let some ⟨_, value⟩ ← getFinValue? x | return .continue + return .done (mkNatLit value.val) + +open Lean Meta Simp in +/-- A list spelled out as a program constant's field, unfolded to its spine; any other list is +left as it is, so that a stack is only read once its words are computed. A long list literal +elaborates to chunks bound with `have`, which unfold to the same spine. -/ +def programSpine? (xs : Expr) : MetaM (Option Expr) := do + let xs := xs.consumeMData + if xs.isAppOfArity ``List.cons 3 || xs.isAppOfArity ``List.nil 1 then return some xs + if xs.isLet then return some (← whnfD xs) + let fn := xs.getAppFn + let some name := fn.constName? | return none + unless (← getEnv).isProjectionFn name do return none + let some arg := xs.getAppArgs.back? | return none + unless arg.consumeMData.isConst || (arg.getAppFn.isConst && + (← getEnv).isConstructor arg.getAppFn.constName!) do + return none + return some (← whnfD xs) + +open Lean Meta Simp in +/-- The element at a numeral index of a list the code spells out, as `some x` or `none`. It +reduces only the spine of a program's list, so a program stays a constant in the goal and only +the block a step enters is unfolded, and never evaluates a list it does not see. -/ +dsimproc_decl listLookup ((_ : List _)[_]?) := fun e => do + let_expr GetElem?.getElem? _ _ elem _ _ xs i := e | return .continue + let some n ← Nat.fromExpr? i | return .continue + let some spine ← programSpine? xs | return .continue + let mut spine := spine + for _ in [0:n] do + let_expr List.cons _ _ tail := spine | return .continue + let some tail' ← programSpine? tail | return .continue + spine := tail' + match_expr spine with + | List.cons _ head _ => return .done (← mkAppOptM ``Option.some #[elem, head]) + | List.nil _ => return .done (← mkAppOptM ``Option.none #[elem]) + | _ => return .continue + +open Lean Meta Simp in +/-- The length of a list the code spells out, as a numeral, such as a program's block count, +which a dynamic jump past the last block compares with. -/ +dsimproc_decl listLength (List.length _) := fun e => do + let_expr List.length _ xs := e | return .continue + let some spine ← programSpine? xs | return .continue + let mut spine := spine + let mut n := 0 + repeat + match_expr spine with + | List.cons _ _ tail => + let some tail' ← programSpine? tail | return .continue + spine := tail' + n := n + 1 + | List.nil _ => break + | _ => return .continue + return .done (mkNatLit n) + +open Lean Meta Simp in +/-- The entry function of a module the code spells out. -/ +dsimproc_decl moduleEntry (SolarTV.MIR.Lowered.Module.entry _) := fun e => do + let e' ← whnfD e + if (← Nat.fromExpr? e').isSome then return .done e' else return .continue + +open Lean Meta Simp in +/-- The parameters of a function the code spells out. -/ +dsimproc_decl functionParams (SolarTV.MIR.Lowered.Function.params _) := fun e => do + let e' ← whnfD e + match_expr e' with + | List.nil _ => return .done e' + | List.cons _ _ _ => return .done e' + | _ => return .continue + +open Lean Meta Simp in +/-- An `if` whose condition the code fixes: its `Decidable` instance evaluates to `isTrue` or +`isFalse`, so the `if` is its branch by definition. Conditions on the call stay. -/ +dsimproc_decl decideIte (ite _ _ _) := fun e => do + let_expr ite _ c inst yes no := e | return .continue + if c.hasFVar || c.hasMVar then return .continue + let inst ← whnfD inst + if inst.isAppOf ``Decidable.isTrue then return .visit yes + if inst.isAppOf ``Decidable.isFalse then return .visit no + return .continue + +open Lean Meta in +/-- The value of a numeral word. -/ +def wordLit? (e : Expr) : MetaM (Option Nat) := do + match ← getBitVecValue? e with + | some ⟨256, v⟩ => return some v.toNat + | _ => return none + +open Lean Meta Simp in +/-- A shift or `NOT` of numerals as the numeral it computes, as a pass spells a constant +(`compact-pushes` pushes the address mask as `shr(96, not(0))`), so that the lemmas about +the constant apply. The kernel checks the value by evaluation. -/ +dsimproc_decl foldNot (Evm.not _) := fun e => do + let_expr Evm.not a := e | return .continue + let some x ← wordLit? a | return .continue + return .done (← mkNumeral (mkConst ``EvmRules.Word) (2 ^ 256 - 1 - x)) + +open Lean Meta Simp in +/-- See `foldNot`. -/ +dsimproc_decl foldShl (Evm.shl _ _) := fun e => do + let_expr Evm.shl s v := e | return .continue + let some s ← wordLit? s | return .continue + let some v ← wordLit? v | return .continue + return .done (← mkNumeral (mkConst ``EvmRules.Word) (if s < 256 then (v <<< s) % 2 ^ 256 else 0)) + +open Lean Meta Simp in +/-- See `foldNot`. -/ +dsimproc_decl foldShr (Evm.shr _ _) := fun e => do + let_expr Evm.shr s v := e | return .continue + let some s ← wordLit? s | return .continue + let some v ← wordLit? v | return .continue + return .done (← mkNumeral (mkConst ``EvmRules.Word) (if s < 256 then v >>> s else 0)) + +open Lean Meta Simp in +/-- A binary word operation of two numerals as the numeral it computes, as the bounds checks of +a memory allocation compute on the constant free memory pointer (the end of an allocation, its +test against the pointer's 64-bit range), so that a test the constants decide is decided. The +kernel checks the value by evaluation. -/ +def foldWord2 (op : Name) (f : Nat → Nat → Nat) (e : Expr) : SimpM DStep := do + unless e.isAppOfArity op 2 do return .continue + let some a ← wordLit? (e.getArg! 0) | return .continue + let some b ← wordLit? (e.getArg! 1) | return .continue + return .done (← mkNumeral (mkConst ``EvmRules.Word) (f a b % 2 ^ 256)) + +dsimproc_decl foldAdd (Evm.add _ _) := foldWord2 ``Evm.add (· + ·) +dsimproc_decl foldSub (Evm.sub _ _) := foldWord2 ``Evm.sub (fun a b => a + 2 ^ 256 - b) +dsimproc_decl foldMul (Evm.mul _ _) := foldWord2 ``Evm.mul (· * ·) +dsimproc_decl foldAnd (Evm.and _ _) := foldWord2 ``Evm.and (· &&& ·) +dsimproc_decl foldOr (Evm.or _ _) := foldWord2 ``Evm.or (· ||| ·) +dsimproc_decl foldXor (Evm.xor _ _) := foldWord2 ``Evm.xor (· ^^^ ·) +dsimproc_decl foldLt (Evm.lt _ _) := foldWord2 ``Evm.lt (fun a b => if a < b then 1 else 0) +dsimproc_decl foldGt (Evm.gt _ _) := foldWord2 ``Evm.gt (fun a b => if a > b then 1 else 0) +dsimproc_decl foldEq (Evm.eq _ _) := foldWord2 ``Evm.eq (fun a b => if a = b then 1 else 0) + +open Lean Elab Tactic Meta in +/-- Case-split on the first `if` of the goal whose condition is closed, as `hc`, with `hcs` its +symmetric form when it is an equation or its negation, so that either program's orientation +of a test rewrites. A positive equation is oriented to rewrite its open side into its closed +side, and a side that contains the other into the other, as a word equal to its masked self +(an ABI address check) rewrites the masked word into the word: the other way would loop. It +fails when no such condition is left, or when one is already a hypothesis, which means the +rewrite with it did not reach its `if`. -/ +elab "split_cond" : tactic => withMainContext do + let target ← instantiateMVars (← getMainTarget) + let some cond := (target.find? fun e => + e.isAppOfArity ``ite 5 && !(e.getArg! 1).hasLooseBVars && !(e.getArg! 1).hasMVar).map + (·.getArg! 1) + | throwError "split_cond: no closed condition in the goal" + for decl in ← getLCtx do + if decl.isImplementationDetail then continue + let ty ← instantiateMVars decl.type + if ty == cond || ty == mkNot cond then + throwError "split_cond: the case {cond} is a hypothesis but its condition remains" + let stx ← Term.exprToSyntax cond + let hc := mkIdent `hc + let hcs := mkIdent `hcs + let closed (e : Expr) : Bool := !e.hasFVar && !e.hasMVar + let isEq := cond.isAppOfArity ``Eq 3 + -- x = f x rewrites as f x = x, which ends. + let pos ← if isEq && (closed (cond.getArg! 1) || (cond.getArg! 1).occurs (cond.getArg! 2)) then + `(tactic| (replace $hc:ident := Eq.symm $hc; have $hcs:ident := $hc)) + else `(tactic| have $hcs:ident := $hc) + let neg ← if isEq then `(tactic| have $hcs:ident := Ne.symm $hc) + else `(tactic| have $hcs:ident := $hc) + evalTactic (← `(tactic| by_cases $hc:ident : $stx)) + let goals ← getGoals + let (yes, no, rest) ← match goals with + | yes :: no :: rest => pure (yes, no, rest) + | _ => throwError "split_cond: by_cases did not give two cases" + setGoals [yes] + evalTactic pos + let yes' ← getGoals + setGoals [no] + evalTactic neg + setGoals (yes' ++ (← getGoals) ++ rest) + +/-! Jump tables. A table's lookup at an index the code does not fix becomes a chain of tests of +the index, one per entry, which `split_cond` splits like any branch. -/ + +/-- A jump table's entry at word index `i`, from entry `k`, as a chain of tests of the index. -/ +def tableEntry (i : Word) : Nat → List Nat → Option Nat + | _, [] => none + | k, x :: xs => if i = BitVec.ofNat 256 k then some x else tableEntry i (k + 1) xs + +theorem tableEntry_eq (i : Word) : ∀ (xs : List Nat) (k : Nat), k + xs.length ≤ 2 ^ 256 → + tableEntry i k xs = if k ≤ i.toNat then xs[i.toNat - k]? else none + | [], k, _ => by simp [tableEntry] + | x :: xs, k, h => by + simp only [List.length_cons] at h + have hk : k < 2 ^ 256 := by omega + have ih := tableEntry_eq i xs (k + 1) (by omega) + unfold tableEntry + by_cases e : i = BitVec.ofNat 256 k + · have hi : i.toNat = k := by rw [e, BitVec.toNat_ofNat]; exact Nat.mod_eq_of_lt hk + rw [if_pos e, if_pos (by omega), hi, Nat.sub_self, List.getElem?_cons_zero] + · have hi : i.toNat ≠ k := fun h' => e (by + apply BitVec.eq_of_toNat_eq + rw [h', BitVec.toNat_ofNat, Nat.mod_eq_of_lt hk]) + rw [if_neg e, ih] + by_cases h1 : k + 1 ≤ i.toNat + · rw [if_pos h1, if_pos (by omega), + show i.toNat - k = (i.toNat - (k + 1)) + 1 by omega, List.getElem?_cons_succ] + · rw [if_neg h1, if_neg (by omega)] + +/-- A table lookup at a word index is the chain of tests of `tableEntry`. -/ +theorem table_lookup (xs : List Nat) (i : Word) (h : xs.length ≤ 2 ^ 256) : + xs[i.toNat]? = tableEntry i 0 xs := by + rw [tableEntry_eq i xs 0 (by omega)] + simp + +open Lean Elab Tactic Meta in +/-- Rewrite the first lookup of a jump table the code spells out at an index it does not fix, +`xs[i.toNat]?`, to the chain of tests of `tableEntry` (`table_lookup`, its side condition +decided by the kernel). It fails when there is none. -/ +elab "split_table" : tactic => withMainContext do + let target ← instantiateMVars (← getMainTarget) + let some e := target.find? fun e => + e.isAppOfArity ``GetElem?.getElem? 7 && (e.getArg! 6).isAppOfArity ``BitVec.toNat 2 && + !(e.getArg! 5).hasFVar && !(e.getArg! 5).hasMVar && !(e.getArg! 5).hasLooseBVars && + (e.getArg! 6).hasFVar && !(e.getArg! 6).hasLooseBVars && !(e.getArg! 6).hasMVar + | throwError "split_table: no table lookup at an open index in the goal" + unless ← isDefEq (← inferType (e.getArg! 5)) (← mkAppM ``List #[mkConst ``Nat]) do + throwError "split_table: the lookup is in no list of block numbers" + let xs ← Term.exprToSyntax (e.getArg! 5) + let i ← Term.exprToSyntax ((e.getArg! 6).getArg! 1) + evalTactic (← `(tactic| simp only [table_lookup $xs $i (by decide)])) + +open Lean Meta Simp in +/-- A low mask of a natural number as its remainder, `a &&& (2^k - 1)` as `a % 2^k`, for a +literal mask on either side, so that `omega` reads the masks of narrow integers. -/ +simproc_decl natMask ((_ : Nat) &&& _) := fun e => do + let_expr HAnd.hAnd _ _ _ _ a b := e | return .continue + let (x, mask, swapped) ← match ← Nat.fromExpr? b with + | some n => pure (a, n, false) + | none => + match ← Nat.fromExpr? a with + | some n => pure (b, n, true) + | none => return .continue + let k := (mask + 1).log2 + unless 2 ^ k == mask + 1 do return .continue + let rhs ← mkAppM ``HMod.hMod #[x, mkNatLit (mask + 1)] + -- x &&& 2^k - 1 = x % 2^k, with both sides' literals computed by the kernel. + let low ← mkExpectedTypeHint (mkApp2 (mkConst ``Nat.and_two_pow_sub_one_eq_mod) x (mkNatLit k)) + (← mkEq (← mkAppM ``HAnd.hAnd #[x, mkNatLit mask]) rhs) + let proof ← if swapped then mkEqTrans (← mkAppM ``Nat.and_comm #[a, b]) low else pure low + return .done { expr := rhs, proof? := some proof } + +/-! A byte of a loaded word, as passes that share one memory read between neighbouring byte +reads spell it (`byte-run-loads`): `BYTE k` of the word loaded at `a` is the byte at +`a + k`, so that `byte 0 (mload (p + 1))` and `byte 1 (mload p)` meet. -/ + +/-- A fold of bytes into a word, as `Mem.load` folds them, bit by bit: the low `8 * n` bits +are the `n` bytes, the last lowest, and the bits above them the initial word's. -/ +theorem getLsbD_foldBytes (l : List SolarTV.Memory.Byte) (acc : BitVec 256) (j : Nat) : + (l.foldl (fun (acc : BitVec 256) (b : SolarTV.Memory.Byte) => (acc <<< 8) ||| b.setWidth 256) + acc).getLsbD j = + (decide (j < 256) && if j < 8 * l.length then + (l.getD (l.length - 1 - j / 8) 0).getLsbD (j % 8) else acc.getLsbD (j - 8 * l.length)) := by + induction l generalizing acc with + | nil => + simp only [List.foldl_nil, List.length_nil, Nat.mul_zero, Nat.not_lt_zero, ite_false, + Nat.sub_zero] + by_cases h : j < 256 + · simp [h] + · simp [h, BitVec.getLsbD_of_ge acc j (by omega)] + | cons b t ih => + rw [List.foldl_cons, ih] + simp only [List.length_cons] + by_cases h256 : j < 256 + · simp only [h256, decide_true, Bool.true_and] + by_cases ht : j < 8 * t.length + · have hl : j < 8 * (t.length + 1) := by omega + have e : t.length + 1 - 1 - j / 8 = (t.length - 1 - j / 8) + 1 := by omega + simp only [ht, hl, ite_true, e, List.getD_cons_succ] + · simp only [ht, ite_false, BitVec.getLsbD_or, BitVec.getLsbD_shiftLeft, + BitVec.getLsbD_setWidth] + by_cases hl : j < 8 * (t.length + 1) + · have e : t.length + 1 - 1 - j / 8 = 0 := by omega + have hlt : j - 8 * t.length < 8 := by omega + have hm : j % 8 = j - 8 * t.length := by omega + simp only [hl, ite_true, e, List.getD_cons_zero, hm, hlt, decide_true, + Bool.not_true, Bool.and_false, Bool.false_and, Bool.false_or] + simp only [show j - 8 * t.length < 256 by omega, decide_true, Bool.true_and] + · have hnot8 : ¬ j - 8 * t.length < 8 := by omega + have e : j - 8 * t.length - 8 = j - 8 * (t.length + 1) := by omega + simp only [hl, ite_false, hnot8, decide_false, Bool.not_false, Bool.and_true, e, + show j - 8 * t.length < 256 by omega, decide_true, Bool.true_and] + rw [BitVec.getLsbD_of_ge b _ (by omega)] + simp + · simp [h256] + +/-- Byte i of a loaded word is the byte at the load's address plus i. -/ +theorem byte_load (m : Mem) (a i : Nat) (hi : i < 32) : + SolarTV.Memory.byte (m.load a) i = m.bytes (a + i) := by + apply BitVec.eq_of_getLsbD_eq + intro j hj + unfold Mem.load Mem.read SolarTV.Memory.byte + rw [BitVec.getLsbD_setWidth, BitVec.getLsbD_ushiftRight, getLsbD_foldBytes] + have e1 : (32 - 1 - (8 * (31 - i) + j) / 8) = i := by omega + have e2 : (8 * (31 - i) + j) % 8 = j := by omega + have h3 : 8 * (31 - i) + j < 256 := by omega + simp only [List.length_map, List.length_range, e1, e2, hj, h3, decide_true, Bool.true_and, + ite_true, List.getD_eq_getElem?_getD, List.getElem?_map, List.getElem?_range hi, + Option.map_some, Option.getD_some] + +/-- BYTE of a loaded word at a position below 32: the byte at that offset from the load. -/ +theorem evm_byte_load (m : Mem) (a : Nat) (k : Word) (h : k.toNat < 32) : + Evm.byte k (m.load a) = (m.bytes (a + k.toNat)).setWidth 256 := by + rw [← byte_load m a k.toNat h] + unfold Evm.byte SolarTV.Memory.byte + have hk : k.ult 32 = true := by simp [BitVec.ult, h] + have hs : (31 - k) * 8 = BitVec.ofNat 256 (8 * (31 - k.toNat)) := by + apply BitVec.eq_of_toNat_eq + have h31 : (31 : Word).toNat = 31 := rfl + have h8 : (8 : Word).toNat = 8 := rfl + simp only [BitVec.toNat_mul, BitVec.toNat_sub, BitVec.toNat_ofNat, h31, h8] + omega + have hm : (255 : Word) = BitVec.ofNat 256 (2 ^ 8 - 1) := rfl + rw [hk, Bool.cond_true, hs, hm] + apply BitVec.eq_of_getLsbD_eq + intro j hj + simp only [BitVec.getLsbD_and, BitVec.getLsbD_setWidth, BitVec.ushiftRight_eq', + BitVec.getLsbD_ushiftRight, BitVec.getLsbD_ofNat, Nat.testBit_two_pow_sub_one, + BitVec.toNat_ofNat] + have hsh : 8 * (31 - k.toNat) % 2 ^ 256 = 8 * (31 - k.toNat) := Nat.mod_eq_of_lt (by omega) + rw [hsh] + by_cases hj8 : j < 8 <;> simp [hj8, hj] + +/-! A memory expansion within one an earlier expansion already reached, as a pass that drops a +load of a word the expanded memory already covers leaves it out. -/ + +/-- Expanding memory over a range that ends within the words an expansion already made active +changes nothing. -/ +theorem expand_expand_within (m : Mem) (a s b t : Nat) (hs : s ≠ 0) + (h : (b + t + 31) / 32 ≤ (a + s + 31) / 32) (hw : (a + s + 31) / 32 < 2 ^ 251) : + (m.expand a s).expand b t = m.expand a s := by + unfold Mem.expand + simp only [hs, ite_false] + split + · rfl + · congr 1 + unfold SolarTV.Memory.grow + have hb : (b + t + 31) / 32 < 2 ^ 251 := by omega + by_cases h1 : m.words.ult (BitVec.ofNat 251 ((a + s + 31) / 32)) = true + · have h2 : (BitVec.ofNat 251 ((a + s + 31) / 32)).ult (BitVec.ofNat 251 ((b + t + 31) / 32)) + = false := by + simp only [BitVec.ult, BitVec.toNat_ofNat, Nat.mod_eq_of_lt hw, Nat.mod_eq_of_lt hb] + exact decide_eq_false (by omega) + simp [h1, h2] + · have h1' : m.words.ult (BitVec.ofNat 251 ((a + s + 31) / 32)) = false := by simpa using h1 + have h2 : m.words.ult (BitVec.ofNat 251 ((b + t + 31) / 32)) = false := by + simp only [BitVec.ult, BitVec.toNat_ofNat, Nat.mod_eq_of_lt hw, Nat.mod_eq_of_lt hb, + decide_eq_false_iff_not, Nat.not_lt] at h1' ⊢ + omega + simp [h1', h2] + +/-- Cases that contradict each other: the words' bitwise and modular operations as +bit-vector ones, a word combined with itself or added to zero as the word it leaves, as +numbers, low masks as remainders and right shifts as quotients, then `omega`. -/ +macro "sym_omega" : tactic => `(tactic| ( + (try simp only [Evm.and, Evm.or, Evm.xor, Evm.add, Evm.sub, BitVec.xor_self, BitVec.and_self, + BitVec.or_self, BitVec.zero_add, BitVec.add_zero] at *) + -- The rewrites above may leave a false case already. + all_goals ( + (try simp -implicitDefEqProofs only [bitvec_to_nat] at *) + (try simp only [BitVec.toNat_and, toNat_shr, BitVec.toNat_ofNat, Nat.reducePow, Nat.reduceMod, + natMask] at *) + omega))) + +/-- Two words equal under the cases: with a word combined with itself or added to zero as the +word it leaves, as numbers, with low masks as remainders, right shifts as quotients and sums +under a mask as sums modulo the word size, by `omega`; else equal up to the order of the +operands of AND, OR, XOR and ADD, as the stack scheduler commutes them (`ac_rfl`). -/ +macro "sym_word" : tactic => `(tactic| ( + (try simp only [Evm.and, Evm.or, Evm.xor, Evm.add, Evm.sub, BitVec.xor_self, BitVec.and_self, + BitVec.or_self, BitVec.zero_add, BitVec.add_zero] at *) + -- A byte of a loaded word as the byte at its address, once the addresses are numerals. + (try simp (disch := decide) only [evm_byte_load, BitVec.reduceToNat, Nat.reduceAdd] at *) + -- The rewrites above may close the equation already. + all_goals first + | (apply BitVec.eq_of_toNat_eq + (try simp -implicitDefEqProofs only [bitvec_to_nat] at *) + (try simp only [BitVec.toNat_and, BitVec.toNat_add, toNat_shr, toNat_shl, BitVec.toNat_ofNat, Nat.reducePow, + Nat.reduceMod, natMask] at *) + omega) + | with_reducible ac_rfl)) + +open Lean Meta Elab Tactic in +/-- A proof that two ends are equal where they differ only in words: a parallel walk of both +terms that keeps what they share, proves each pair of differing words with `sym_word`, and +puts the proof together by congruence. -/ +partial def agree (a b : Expr) : TacticM Expr := do + -- Annotations, such as a case's, are no part of the terms. + let a := a.consumeMData + let b := b.consumeMData + if a == b then return ← mkEqRefl a + let ty ← whnfR (← inferType a) + if ty.isAppOfArity ``BitVec 1 then + let m ← mkFreshExprSyntheticOpaqueMVar (← mkEq a b) + -- Without error recovery, so that a pair it cannot prove fails rather than closes with an + -- error's `sorry`. + let rest ← Tactic.run m.mvarId! (withoutRecover (evalTactic (← `(tactic| sym_word)))) + let proof ← instantiateMVars m + unless rest.isEmpty && !proof.hasSorry do + throwError "sym_agree: cannot prove the words equal:{indentExpr a}\nand{indentExpr b}" + return proof + match a, b with + | .app f x, .app g y => + if x == y then return ← mkCongrFun (← agree f g) x + let hx ← agree x y + if f == g then return ← mkCongrArg f hx + mkCongr (← agree f g) hx + | _, _ => + if ← withReducible (isDefEq a b) then return ← mkEqRefl a + throwError "sym_agree: the ends differ beyond words:{indentExpr a}\nand{indentExpr b}" + +open Lean Meta Elab Tactic in +/-- Closes an equation of two ends that differ only in words a pass rewrote, as in an e-graph +or CSE stage, each pair proved equal from the cases. -/ +elab "sym_agree" : tactic => withMainContext do + let goal ← getMainGoal + let some (_, l, r) := (← instantiateMVars (← goal.getType)).consumeMData.eq? + | throwError "sym_agree: the goal is not an equation" + goal.assign (← agree l r) + replaceMainGoal [] + +/-- Two ends that differ in a select's arithmetic or in the order of a commutative operation's +operands, as stack scheduling may compute them: the tests the cases decide as their words, the +arithmetic on zero and one as the arm it picks, and the operands of additions, products and +bitwise operations in one order. -/ +macro "sym_select" : tactic => `(tactic| ( + (try simp (disch := first | assumption | (apply Classical.not_not.mp; assumption)) + only [lt_of_case, lt_of_not_case, gt_of_case, gt_of_not_case, eq_of_case, eq_of_not_case, + iszero_of_case, iszero_of_not_case, mul_word_one, mul_one_word, mul_word_zero, + mul_zero_word, add_sub_word, add_word_zero, add_zero_word]) + (try simp only [Evm.add, Evm.mul, Evm.and, Evm.or, Evm.xor, BitVec.add_comm, BitVec.mul_comm, + BitVec.and_comm, BitVec.or_comm, BitVec.xor_comm]) + all_goals first + | with_reducible rfl + | sym_agree)) + +/-- The proposition a hypothesis denies, for `¬ p` and `a ≠ b`. -/ +def deniedProp? (ty : Lean.Expr) : Option Lean.Expr := + if let some p := ty.not? then some p.consumeMData + else if ty.isAppOfArity ``Ne 3 then + some (Lean.mkApp3 (Lean.mkConst ``Eq ty.getAppFn.constLevels!) (ty.getArg! 0) (ty.getArg! 1) + (ty.getArg! 2)) + else none + +open Lean Meta Elab Tactic in +/-- Closes a goal whose hypotheses contradict each other as they are written: `False`, a +hypothesis `a ≠ a`, or a proposition and its negation. Unlike `contradiction`, it compares +the hypotheses' terms and never reduces them, so its cost is bounded by their size: on a path +whose ends differ, `contradiction` reduced the word terms of its hypotheses to weak head +normal form for minutes (mulx's `spell-width-tests` stage with a shift edited), so that the +procedure ran out of heartbeats rather than reporting the mismatch. -/ +elab "sym_absurd" : tactic => withMainContext do + let goal ← getMainGoal + let target ← instantiateMVars (← goal.getType) + let mut props : Array (Expr × Expr) := #[] + for decl in ← getLCtx do + if decl.isImplementationDetail then continue + props := props.push (decl.toExpr, (← instantiateMVars decl.type).consumeMData) + for (h, ty) in props do + if ty.isConstOf ``False then + goal.assign (← mkFalseElim target h) + replaceMainGoal [] + return + let some p := deniedProp? ty | continue + if let some (_, a, b) := p.eq? then + if a.consumeMData == b.consumeMData then + -- h rfl : False + goal.assign (← mkFalseElim target (mkApp h (← mkEqRefl a))) + replaceMainGoal [] + return + for (h', ty') in props do + if ty' == p then + -- absurd h' h + goal.assign (← mkAbsurd target h' h) + replaceMainGoal [] + return + throwError "sym_absurd: no two hypotheses contradict each other" + +open Lean Meta Elab Tactic in +/-- Orients the equations among the hypotheses as `split_cond` orients a positive case, so +that `simp_all` rewrites with them towards an end: an equation whose left side occurs in its +right side, or whose left side is closed and right side open, turns round, and a doubly +negated equation becomes the equation. `split_cond` leaves the case that a negated equation +fails as `¬¬(a = b)`; `simp_all` reads it as `a = b`, and for a word equal to its masked +self (`x = x &&& 255`, as `masks` tests a narrow argument) rewrote `x` into its mask +without end, so that an edited stage ran out of recursion depth rather than reporting the +mismatch. -/ +elab "sym_orient" : tactic => withMainContext do + let mut goal ← getMainGoal + for decl in ← getLCtx do + if decl.isImplementationDetail then continue + let ty := (← instantiateMVars decl.type).consumeMData + let (eq, proof) ← match ty.not? >>= fun p => p.consumeMData.not? with + -- byContradiction h : p, for h : ¬¬p + | some p => pure (p.consumeMData, mkApp2 (mkConst ``Classical.byContradiction) p decl.toExpr) + | none => pure (ty, decl.toExpr) + let some (_, a, b) := eq.eq? | continue + let closed (e : Expr) : Bool := !e.hasFVar && !e.hasMVar + let flip := (a != b && a.occurs b) || (closed a && !closed b) + if !flip && eq == ty then continue + -- h : a = b as h : b = a + let (ty', proof') ← if flip then + goal.withContext do pure (← mkEq b a, ← mkEqSymm proof) + else pure (eq, proof) + goal := (← goal.replace decl.fvarId proof' (some ty')).mvarId + replaceMainGoal [goal] + +/-- A path whose cases contradict each other once the operands of additions, products and +bitwise operations are in one order: the stack scheduler commutes them, so the two programs' +tests of one word can differ in that order alone (`mul a b` against `mul b a`). -/ +macro "sym_comm_contra" : tactic => `(tactic| ( + (try simp only [Evm.add, Evm.mul, Evm.and, Evm.or, Evm.xor, BitVec.add_comm, BitVec.mul_comm, + BitVec.and_comm, BitVec.or_comm, BitVec.xor_comm] at *) + first + | sym_absurd + | (sym_orient; simp_all; done))) + +open Lean Meta Simp in +/-- The operands of a commutative word operation `op` in one order, the structural order of +their terms, proved by `comm`. Permutation lemmas would order them the same way for both +programs too, but `simp` compares terms for them at a cost that grows with the goal (over +100 s for one call on mulx's `spell-width-tests` stage); this compares the terms as they +are. -/ +def wordCommStep (op comm : Name) (e : Expr) : SimpM Step := do + unless e.isAppOfArity op 2 do return .continue + let a := e.appFn!.appArg! + let b := e.appArg! + unless b.lt a do return .continue + -- op a b = op b a + return .visit { expr := mkApp2 (mkConst op) b a, proof? := some (mkApp2 (mkConst comm) a b) } + +simproc_decl wordAddComm (Evm.add _ _) := wordCommStep ``Evm.add ``word_add_comm +simproc_decl wordMulComm (Evm.mul _ _) := wordCommStep ``Evm.mul ``word_mul_comm +simproc_decl wordAndComm (Evm.and _ _) := wordCommStep ``Evm.and ``word_and_comm +simproc_decl wordOrComm (Evm.or _ _) := wordCommStep ``Evm.or ``word_or_comm +simproc_decl wordXorComm (Evm.xor _ _) := wordCommStep ``Evm.xor ``word_xor_comm + +open Lean Meta Simp in +/-- `not` of a literal as the literal it leaves, as `compact-pushes` spells a wide constant +(`push 255; not` for `~0xff`), so that both programs push the same word. -/ +dsimproc_decl evmNotLit (Evm.not _) := fun e => do + let_expr Evm.not a := e | return .continue + let_expr OfNat.ofNat ty lit _ := a | return .continue + let some n := lit.rawNatLit? | return .continue + return .done (← mkNumeral ty (~~~(BitVec.ofNat 256 n)).toNat) + +/-- The definitional evaluation of both layers. -/ +macro "sym_eval" : tactic => `(tactic| + dsimp only [iterate_mk, iterate_zero, listLookup, listLength, moduleEntry, functionParams, + foldNot, foldShl, foldShr, foldAdd, foldSub, foldMul, foldAnd, foldOr, foldXor, foldLt, foldGt, + foldEq, tableEntry, + MIR.Lowered.Module.run, MIR.Lowered.moduleBlock, MIR.Lowered.segment, + MIR.Lowered.splitCall, MIR.Lowered.bindResult, MIR.Lowered.bindResults, + MIR.Lowered.bindExtras, MIR.Lowered.publishResults, MIR.Lowered.publishWords, MIR.Lowered.bindPhis, + MIR.Lowered.bindParams, MIR.Lowered.execInsts, MIR.Lowered.Operand.eval, + MIR.Lowered.Env.set, MIR.Lowered.switchTarget, MIR.Lowered.halt, MIR.Lowered.evalPure, + MIR.Lowered.lowBits, MIR.Lowered.selectWord, MIR.Lowered.Function.start, + MIR.Lowered.Module.startState, List.find?_cons, List.find?_nil, Nat.reduceBEq, + EVM.Program.run, EVM.Program.block, EVM.Program.exec, EVM.Program.stepOp, + EVM.Program.output, EVM.Program.context, EVM.stepChecked, + step_add, step_mul, step_and, step_or, step_xor, step_div, step_sdiv, step_mod, step_smod, + step_signextend, step_byte, step_shl, step_shr, step_sar, step_lt, step_gt, step_slt, step_sgt, + step_eq, step_sub, step_exp, step_addmod, step_mulmod, step_not, step_clz, step_iszero, + step_pop, step_dup, step_swap, step_calldatasize, step_returndatasize, step_push, apply_mload, + apply_mstore, apply_mstore8, apply_msize, apply_sload, apply_sstore, apply_tload, + apply_tstore, apply_calldatasize, apply_callvalue, apply_caller, apply_address, + apply_returndatasize, apply_keccak256, apply_log0, apply_log1, apply_log2, apply_log3, + apply_log4, logged, apply_gas, apply_immutable, ImmutableRead.apply, apply_codecopy, apply_create, + apply_create2, created, apply_env, apply_calldatacopy, apply_mcopy, + apply_returndatacopy, apply_call, apply_callcode, apply_delegatecall, + apply_staticcall, called, returndataSize, BitVec.reduceToNat, + List.map, List.take, List.drop, List.set, List.length, List.find?, Nat.reduceBEq, + Except.map, Option.map, + Option.isSome, Nat.reduceAdd, Nat.reduceSub, Nat.reduceMul, evmNotLit, finValue]) + +set_option hygiene false in +/-- Branch conditions as propositions, decided by the cases split so far. -/ +macro "sym_cond" : tactic => `(tactic| + simp only [*, apply_calldataload _ _ _ hcd, Mem.load_expand, Mem.load_write_of_disjoint, + Mem.expand_store, Mem.load_store_same, Mem.load_store_of_disjoint, Mem.load_initial, + State.initial_memory, BitVec.reduceEq, + cond_ne, cond_eq, cond_sub, cond_lt, cond_gt, cond_iszero, cond_or, + cond_zero_lt, cond_zero_gt, cond_zero_eq, cond_zero_ne, cond_zero_iszero, + wordAddComm, wordMulComm, wordAndComm, wordOrComm, wordXorComm, and_mask, + mask_and, caller_le_mask, immutable20_le_mask, shr160_eq_zero, zero_eq_shr160, and_self, and_true, true_and, and_false, false_and, + ite_true, ite_false, + not_false_eq_true, not_true_eq_false, Classical.not_not, ↓reduceIte, Nat.reduceGT, Nat.reduceLT, + Nat.reduceEqDiff, Nat.reduceLeDiff, Nat.reduceAdd, Nat.reduceSub, Nat.lt_irrefl, + Bool.false_eq_true, gt_iff_lt, true_or, or_true]) + +/-- A range side condition by `omega` over the offsets' `toNat`s, as `sym_omega` reads +words, failing without logging so that `simp` leaves an unproved rewrite undone. -/ +macro "sym_mem_disch_core" : tactic => `(tactic| + ((try simp only [Evm.and, Evm.or, Evm.xor, Evm.add, Evm.sub, BitVec.zero_add, BitVec.add_zero] at *) + <;> (try simp -implicitDefEqProofs only [bitvec_to_nat] at *) + <;> (try simp only [BitVec.toNat_and, toNat_shr, BitVec.toNat_ofNat, Nat.reducePow, Nat.reduceMod, + natMask] at *) + <;> omega)) + +open Lean Elab Tactic in +/-- `sym_mem_disch_core` without error recovery, so a failed side condition is a plain failure. -/ +elab "sym_mem_disch" : tactic => do withoutRecover (evalTactic (← `(tactic| sym_mem_disch_core))) + +/-- Memory at computed offsets: a read or load moves past a store, byte store or copy only +when `sym_mem_disch` proves the two ranges disjoint (or the read inside the written range) from +the cases split so far, over the offsets' `toNat`s; a range read of more than a word splits +into words, so a hash of `abi.encode` output meets the stored words. Ranges it cannot place +keep the read over the write, so both programs must build the same term there. -/ +macro "sym_mem" : tactic => `(tactic| first + | simp (disch := sym_mem_disch) only [Mem.read_expand, Mem.read_store_at, + Mem.read_store_disjoint, Mem.load_store_at, Mem.load_store_disjoint, + Mem.read_storeByte_disjoint, Mem.load_storeByte_disjoint, Mem.read_write_disjoint, + Mem.load_write_of_disjoint, Mem.read_write_same, Mem.read_write_inside, + Mem.read_copy_inside, Mem.read_store_within, Mem.read_write_within, + Mem.read_of_eq_zero, Mem.read_write_at, List.append_nil, List.nil_append, List.append_assoc] + | simp only [Mem.read_split, Nat.reduceLT, Nat.reduceLeDiff, Nat.reduceSub, Nat.reduceAdd]) + +/-- Evaluate, decide conditions and move memory reads until none changes the goal. -/ +macro "sym_norm" : tactic => `(tactic| repeat (first | sym_eval | sym_cond | sym_mem)) + +/-- Two ends that differ in addresses and memory sizes alone: one program spells an address as +the sum of numerals its pass left unfolded (`(Evm.add 32 128).toNat`) where the other has the +numeral (`160`), or expands memory over a word an earlier access already made active, as when a +pass drops a load. The addresses become numerals, the redundant expansion goes, and the words +are compared. -/ +macro "sym_expand" : tactic => `(tactic| ( + simp (disch := decide) only [expand_expand_within, Evm.add, BitVec.reduceAdd, + BitVec.reduceToNat, Nat.reduceAdd] + all_goals first + | with_reducible rfl + | sym_agree)) + +set_option hygiene false in +/-- Symbolic execution to one result: evaluate, decide what the cases decide, split on the +next condition, and close each leaf by reflexivity or a contradiction between its cases. A leaf +it cannot close fails with its goal, the two ends on that path. -/ +macro "sym_exec" : tactic => `(tactic| ( + obtain ⟨cd, hcd⟩ : ∃ cd, cd = calldataWord call := ⟨_, rfl⟩ + sym_norm + repeat' ((first | split_cond | split_table) <;> sym_norm) + all_goals first + | with_reducible rfl + | (exfalso; bv_omega) + | (exfalso; sym_omega) + | (exfalso; sym_comm_contra) + | sym_select + | sym_agree + | sym_expand + | fail "sym_exec: the runs end in different results on this path, or the procedure cannot tell")) + +end SolarTV.Milestone.W1 diff --git a/vendor/evm-rules/EvmRules.lean b/vendor/evm-rules/EvmRules.lean new file mode 100644 index 00000000..89174c75 --- /dev/null +++ b/vendor/evm-rules/EvmRules.lean @@ -0,0 +1,10 @@ +import EvmRules.Word +import EvmRules.Bitblast +import EvmRules.Bits +import EvmRules.Casts +import EvmRules.Simp +import EvmRules.Reference +import EvmRules.Tactic +import EvmRules.Arith +import EvmRules.ArithTactic +import EvmRules.Lemmas diff --git a/vendor/evm-rules/EvmRules/Arith.lean b/vendor/evm-rules/EvmRules/Arith.lean new file mode 100644 index 00000000..1ea59255 --- /dev/null +++ b/vendor/evm-rules/EvmRules/Arith.lean @@ -0,0 +1,244 @@ +import EvmRules.Word + +/-! +# Word arithmetic as natural numbers + +The lemmas `evm_arith` (`ArithTactic.lean`) rewrites with. Comparison words become the +bits of decided propositions, each operation becomes a number with its wrapping, and the +readers' overflow preconditions become bounds on exact products and sums. The bounds the +tactic adds for every quotient and remainder, and the rewrites that remove wrapping and +quotients once those bounds allow it, follow. +-/ + +namespace EvmRules + +/-- The all-ones word, as the printer writes `MAX`. -/ +abbrev MAX : Word := 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff + +theorem toNat_max : MAX.toNat = 2 ^ 256 - 1 := rfl + +theorem toNat_pos {a : Word} (h : a ≠ 0) : 0 < a.toNat := by + rcases Nat.eq_zero_or_pos a.toNat with h₀ | h₀ + · exact absurd (BitVec.eq_of_toNat_eq (by simpa using h₀)) h + · exact h₀ + +/-! Comparison words are the bits of decided propositions about the numbers. -/ + +theorem lt_bits (a b : Word) : Evm.lt a b = bif decide (a.toNat < b.toNat) then 1 else 0 := by + simp [Evm.lt, BitVec.ult] + +theorem gt_bits (a b : Word) : Evm.gt a b = bif decide (b.toNat < a.toNat) then 1 else 0 := by + simp [Evm.gt, BitVec.ult] + +theorem eq_bits (a b : Word) : Evm.eq a b = bif decide (a.toNat = b.toNat) then 1 else 0 := by + simp [Evm.eq, ← BitVec.toNat_eq] + +theorem ne_bits (a b : Word) : Evm.ne a b = bif decide (a.toNat ≠ b.toNat) then 1 else 0 := by + by_cases h : a = b + · subst h + simp [Evm.ne] + · have h' : a.toNat ≠ b.toNat := fun e => h (BitVec.eq_of_toNat_eq e) + simp [Evm.ne, h, h'] + +theorem iszero_bits (a : Word) : Evm.iszero a = bif decide (a.toNat = 0) then 1 else 0 := by + by_cases h : a.toNat = 0 + · have ha : a = 0 := BitVec.eq_of_toNat_eq h + subst ha + rfl + · have hb : (a == 0) = false := by + rw [beq_eq_false_iff_ne] + exact fun e => h (by rw [e]; rfl) + rw [Evm.iszero, hb] + simp [h] + +theorem or_bits (p q : Bool) : + Evm.or (bif p then 1 else 0) (bif q then 1 else 0) = bif p || q then 1 else 0 := by + cases p <;> cases q <;> decide + +theorem bits_eq_bits (p q : Prop) [Decidable p] [Decidable q] : + (bif decide p then (1 : Word) else 0) = (bif decide q then 1 else 0) ↔ (p ↔ q) := by + by_cases hp : p <;> by_cases hq : q <;> simp [hp, hq] + +theorem bits_eq_one (p : Prop) [Decidable p] : (bif decide p then (1 : Word) else 0) = 1 ↔ p := by + by_cases hp : p <;> simp [hp] + +theorem bits_eq_zero (p : Prop) [Decidable p] : + (bif decide p then (1 : Word) else 0) = 0 ↔ ¬p := by + by_cases hp : p <;> simp [hp] + +/-! Each operation as a number, with its wrapping and EVM's zero divisor. -/ + +theorem toNat_div (a b : Word) : (Evm.div a b).toNat = a.toNat / b.toNat := + BitVec.toNat_udiv + +theorem toNat_mul (a b : Word) : (Evm.mul a b).toNat = a.toNat * b.toNat % 2 ^ 256 := + BitVec.toNat_mul .. + +theorem toNat_mod_ite (a b : Word) : + (Evm.mod a b).toNat = if b.toNat = 0 then 0 else a.toNat % b.toNat := by + by_cases h : b.toNat = 0 + · have hb : b = 0 := BitVec.eq_of_toNat_eq h + subst hb + simp [Evm.mod] + · have hb : (b == 0) = false := by + rw [beq_eq_false_iff_ne] + exact fun e => h (by rw [e]; rfl) + rw [ite_eq_right h, Evm.mod, hb, Bool.cond_false, BitVec.toNat_umod] + +theorem toNat_add_wrap (a b : Word) : (Evm.add a b).toNat = (a.toNat + b.toNat) % 2 ^ 256 := + BitVec.toNat_add .. + +theorem toNat_sub_wrap (a b : Word) : + (Evm.sub a b).toNat = (2 ^ 256 - b.toNat + a.toNat) % 2 ^ 256 := + BitVec.toNat_sub .. + +/-- `ADDMOD` as a number: the exact sum, reduced by a nonzero modulus. -/ +theorem toNat_addmod (a b n : Word) : + (Evm.addmod a b n).toNat = if n.toNat = 0 then 0 else (a.toNat + b.toNat) % n.toNat := by + have ha := a.isLt + have hb := b.isLt + have hn := n.isLt + by_cases h : n.toNat = 0 + · have : n = 0 := BitVec.eq_of_toNat_eq h + subst this + rfl + · have hz : (n == 0) = false := beq_eq_false_iff_ne.mpr fun e => h (by rw [e]; rfl) + rw [Evm.addmod, hz, Bool.cond_false] + simp only [h, ↓reduceIte] + rw [BitVec.toNat_setWidth, BitVec.toNat_umod, BitVec.toNat_add, BitVec.toNat_setWidth, + BitVec.toNat_setWidth, BitVec.toNat_setWidth] + have hr := Nat.mod_lt (a.toNat + b.toNat) (Nat.pos_of_ne_zero h) + rw [Nat.mod_eq_of_lt (by omega : a.toNat < 2 ^ 512), + Nat.mod_eq_of_lt (by omega : b.toNat < 2 ^ 512), + Nat.mod_eq_of_lt (by omega : n.toNat < 2 ^ 512), + Nat.mod_eq_of_lt (by omega : a.toNat + b.toNat < 2 ^ 512), + Nat.mod_eq_of_lt (by omega : (a.toNat + b.toNat) % n.toNat < 2 ^ 256)] + +set_option exponentiation.threshold 512 in +/-- `MULMOD` as a number: the exact product, reduced by a nonzero modulus. -/ +theorem toNat_mulmod (a b n : Word) : + (Evm.mulmod a b n).toNat = if n.toNat = 0 then 0 else a.toNat * b.toNat % n.toNat := by + have ha := a.isLt + have hb := b.isLt + have hn := n.isLt + have hab : a.toNat * b.toNat < 2 ^ 512 := + calc a.toNat * b.toNat < 2 ^ 256 * 2 ^ 256 := Nat.mul_lt_mul'' ha hb + _ = 2 ^ 512 := by rw [← Nat.pow_add] + by_cases h : n.toNat = 0 + · have : n = 0 := BitVec.eq_of_toNat_eq h + subst this + rfl + · have hz : (n == 0) = false := beq_eq_false_iff_ne.mpr fun e => h (by rw [e]; rfl) + rw [Evm.mulmod, hz, Bool.cond_false] + simp only [h, ↓reduceIte] + rw [BitVec.toNat_setWidth, BitVec.toNat_umod, BitVec.toNat_mul, BitVec.toNat_setWidth, + BitVec.toNat_setWidth, BitVec.toNat_setWidth] + have hr := Nat.mod_lt (a.toNat * b.toNat) (Nat.pos_of_ne_zero h) + rw [Nat.mod_eq_of_lt (by omega : a.toNat < 2 ^ 512), + Nat.mod_eq_of_lt (by omega : b.toNat < 2 ^ 512), + Nat.mod_eq_of_lt (by omega : n.toNat < 2 ^ 512), Nat.mod_eq_of_lt hab, + Nat.mod_eq_of_lt (by omega : a.toNat * b.toNat % n.toNat < 2 ^ 256)] + +/-! The readers' overflow preconditions as bounds on the exact product or sum. -/ + +/-- `u256_mul_fits a b`: the exact product is a word. -/ +theorem mul_fits_iff (a b : Word) : + (b ≠ 0 → a ≤ Evm.div MAX b) ↔ a.toNat * b.toNat < 2 ^ 256 := by + rw [BitVec.le_def, toNat_div, toNat_max] + constructor + · intro h + by_cases hb : b = 0 + · subst hb + simp + · have := (Nat.le_div_iff_mul_le (toNat_pos hb)).mp (h hb) + omega + · intro h hb + exact (Nat.le_div_iff_mul_le (toNat_pos hb)).mpr (by omega) + +/-- `u256_add_fits a b`: the exact sum is a word. -/ +theorem add_fits_iff (a b : Word) : a ≤ Evm.sub MAX b ↔ a.toNat + b.toNat < 2 ^ 256 := by + have hb := b.isLt + rw [BitVec.le_def, Evm.sub, BitVec.toNat_sub, toNat_max] + have : (2 ^ 256 - b.toNat + (2 ^ 256 - 1)) % 2 ^ 256 = 2 ^ 256 - 1 - b.toNat := by omega + omega + +/-- `a ≤ MAX / b`, as the readers state that the exact product is a word when `b ≠ 0` is a +separate precondition. -/ +theorem le_div_max_iff (a b : Word) : + a ≤ Evm.div MAX b ↔ a.toNat * b.toNat < 2 ^ 256 ∧ (b.toNat = 0 → a.toNat = 0) := by + rw [BitVec.le_def, toNat_div, toNat_max] + by_cases hb : b.toNat = 0 + · simp [hb] + · rw [Nat.le_div_iff_mul_le (Nat.pos_of_ne_zero hb)] + omega + +/-! Bounds that `evm_arith` adds for every quotient and remainder by a non-literal. -/ + +theorem div_le_half (a b : Nat) : 2 ≤ b → a / b ≤ a / 2 := fun h => Nat.div_le_div_left h (by decide) + +theorem lt_div_mul_add_of_pos (a b : Nat) : 0 < b → a < a / b * b + b := + fun h => Nat.lt_div_mul_add h + +theorem mod_lt_of_pos (a b : Nat) : 0 < b → a % b < b := fun h => Nat.mod_lt a h + +/-! Rewrites that remove wrapping and quotients once those bounds allow it. -/ + +theorem sub_wrap_of_le {a b n : Nat} (h : b ≤ a) (ha : a < n) : (n - b + a) % n = a - b := by + rw [show n - b + a = a - b + n by omega, Nat.add_mod_right, Nat.mod_eq_of_lt (by omega)] + +/-- Rounding down to a multiple of `y` and dividing by `y` again gives the quotient, also +when `y` is zero. -/ +theorem div_mul_div_cancel (x y : Nat) : x / y * y / y = x / y := by + by_cases h : y = 0 + · simp [h] + · rw [Nat.mul_div_cancel _ (Nat.pos_of_ne_zero h)] + +theorem lt_div_succ_iff {x c m : Nat} (hc : 0 < c) : x < m / c + 1 ↔ x * c ≤ m := by + rw [Nat.lt_succ_iff, Nat.le_div_iff_mul_le hc] + +/-- A product whose wrapped value divides back to its factor did not wrap. -/ +theorem wrapped_div_eq_iff {x c n : Nat} (hc : 0 < c) (hn : 0 < n) : + x * c % n / c = x ↔ x * c < n := by + constructor + · intro h + apply Classical.byContradiction + intro hlt + have hr : x * c % n < x * c := by + have := Nat.mod_lt (x * c) hn + omega + have := (Nat.div_lt_iff_lt_mul hc).mpr hr + omega + · intro h + rw [Nat.mod_eq_of_lt h, Nat.mul_div_cancel _ hc] + +theorem eq_wrapped_div_iff {x c n : Nat} (hc : 0 < c) (hn : 0 < n) : + x = x * c % n / c ↔ x * c < n := by + rw [eq_comm] + exact wrapped_div_eq_iff hc hn + +/-- The test of a checked product `c * x`, which divides by the variable factor. -/ +theorem checked_product_left {x c n : Nat} (hn : 0 < n) : + (x = 0 ∨ x * c % n / x = c) ↔ x * c < n := by + by_cases hx : x = 0 + · simp [hx, hn] + · simp only [hx, false_or] + rw [Nat.mul_comm] + exact wrapped_div_eq_iff (Nat.pos_of_ne_zero hx) hn + +theorem checked_product_left' {x c n : Nat} (hn : 0 < n) : + (x * c % n / x = c ∨ x = 0) ↔ x * c < n := by + rw [or_comm] + exact checked_product_left hn + +/-- A share `c / d ≤ 1` of `x` never exceeds `x`, also when `x * c` wraps: the wrapped +value is still at most `x * c ≤ x * d`. -/ +theorem not_lt_share {x c d n : Nat} (hcd : c ≤ d) : ¬x < x * c % n / d := by + rcases Nat.eq_zero_or_pos d with hd | hd + · simp [hd] + · have h₁ := Nat.mod_le (x * c) n + have h₂ := Nat.mul_le_mul_left x hcd + have h₃ : x * c % n / d ≤ x * d / d := Nat.div_le_div_right (by omega) + rw [Nat.mul_div_cancel _ hd] at h₃ + omega + +end EvmRules diff --git a/vendor/evm-rules/EvmRules/ArithTactic.lean b/vendor/evm-rules/EvmRules/ArithTactic.lean new file mode 100644 index 00000000..1fa5a06a --- /dev/null +++ b/vendor/evm-rules/EvmRules/ArithTactic.lean @@ -0,0 +1,112 @@ +import Lean.Elab.Tactic.Basic +import Lean.Meta.Tactic.Assert +import EvmRules.Arith +import EvmRules.Tactic + +/-! +# `evm_arith` + +`evm_arith` proves rules over products, quotients and remainders with symbolic operands, +which bit-blasting cannot. It works over natural numbers: + +1. It substitutes equal operands, states comparison words as decided propositions and + the readers' overflow preconditions as bounds on exact products and sums. +2. It states every word as its number, writing each operation with its wrapping + (`(a + b) % 2 ^ 256`) and EVM's zero divisor. +3. `evm_div_facts` adds the bounds of every quotient and remainder by a non-literal: + `a / b ≤ a`, `a / b * b ≤ a < a / b * b + b`, `a / b * b + a % b = a` and more. +4. Rewrites whose side conditions `omega` proves from those bounds remove the wrapping + that cannot happen and the quotients in comparisons. +5. After ordering every product the same way, `omega` closes the goal, treating the + remaining products, quotients and remainders as opaque terms. + +Each step is a proof Lean's kernel checks; nothing is trusted beyond the definitions. +-/ + +namespace EvmRules + +open Lean Meta Elab Tactic + +/-- Collects the natural-number quotients (`true`) and remainders (`false`) by a +non-literal in `e` that mention no bound variables; `omega` handles literal divisors. -/ +partial def natDivMods (e : Expr) (acc : Array (Bool × Expr × Expr)) : + Array (Bool × Expr × Expr) := + match e with + | .app .. => + let args := e.getAppArgs + let acc := args.foldl (fun acc a => natDivMods a acc) (natDivMods e.getAppFn acc) + let isDiv := e.isAppOfArity ``HDiv.hDiv 6 + if (isDiv || e.isAppOfArity ``HMod.hMod 6) && args[0]! == mkConst ``Nat + && !e.hasLooseBVars && args[5]!.nat?.isNone then + let entry := (isDiv, args[4]!, args[5]!) + if acc.contains entry then acc else acc.push entry + else acc + | .forallE _ d b _ | .lam _ d b _ => natDivMods b (natDivMods d acc) + | .mdata _ b | .proj _ _ b => natDivMods b acc + | .letE _ t v b _ => natDivMods b (natDivMods v (natDivMods t acc)) + | _ => acc + +/-- Adds the bounds of every natural-number quotient and remainder by a non-literal in +the goal and its hypotheses, so that `omega` can treat them as opaque terms. -/ +elab "evm_div_facts" : tactic => withMainContext do + let mut found := natDivMods (← instantiateMVars (← getMainTarget)) #[] + for decl in ← getLCtx do + unless decl.isImplementationDetail do + found := natDivMods (← instantiateMVars decl.type) found + for (isDiv, a, b) in found do + let lemmas := if isDiv then + #[``Nat.div_le_self, ``Nat.div_mul_le_self, ``div_le_half, ``lt_div_mul_add_of_pos] + else #[``Nat.mod_le, ``mod_lt_of_pos, ``Nat.div_add_mod'] + for lemma in lemmas do + let proof ← mkAppM lemma #[a, b] + let type ← inferType proof + liftMetaTactic fun goal => do + let goal ← goal.assert `bound type proof + let (_, goal) ← goal.intro1P + return [goal] + +end EvmRules + +/-- Proves a rule over products, quotients and remainders; see `EvmRules/ArithTactic.lean`. -/ +macro "evm_arith" : tactic => `(tactic| ( + subst_vars + try simp only [↓ EvmRules.mul_fits_iff, ↓ EvmRules.add_fits_iff, ↓ EvmRules.le_div_max_iff, + EvmRules.lt_bits, EvmRules.gt_bits, EvmRules.eq_bits, EvmRules.ne_bits, EvmRules.iszero_bits, + EvmRules.or_bits, ← Bool.decide_or, ite_true, ite_false, EvmRules.bits_eq_bits, + EvmRules.bits_eq_one, EvmRules.bits_eq_zero] at * + try simp only [BitVec.toNat_eq, BitVec.le_def, BitVec.lt_def, ne_eq, EvmRules.toNat_div, + EvmRules.toNat_mul, EvmRules.toNat_add_wrap, EvmRules.toNat_sub_wrap, + EvmRules.toNat_mod_ite, EvmRules.toNat_addmod, EvmRules.toNat_mulmod, Nat.add_zero, + Nat.zero_add, Nat.mul_one, Nat.one_mul, BitVec.ofNat_eq_ofNat, BitVec.toNat_ofNat, + Nat.reducePow, Nat.reduceMod] at * + all_goals evm_div_facts + try simp (disch := omega) only [Nat.mod_eq_of_lt, EvmRules.sub_wrap_of_le, ite_eq_left, + ite_eq_right, Nat.div_div_eq_div_mul, EvmRules.div_mul_div_cancel, Nat.div_lt_iff_lt_mul, + Nat.le_div_iff_mul_le, Nat.div_eq_zero_iff_lt, Nat.lt_div_iff_mul_lt, + Nat.div_le_iff_le_mul_add_pred, EvmRules.lt_div_succ_iff, EvmRules.wrapped_div_eq_iff, + EvmRules.eq_wrapped_div_iff, EvmRules.checked_product_left, + EvmRules.checked_product_left', EvmRules.not_lt_share, Nat.div_eq_of_lt, + Nat.mul_div_cancel, Nat.mul_div_cancel_left, not_false_eq_true, + not_true_eq_false, iff_self, false_iff, iff_false, true_iff, iff_true] at * + try simp only [Nat.mul_comm, Nat.mul_left_comm] at * + all_goals omega)) + +open Lean in +/-- Records the tactic that proved a theorem, for the verification report. -/ +elab "evm_proved_by " name:str : tactic => logInfo m!"proved by {name.getString}" + +/-- Tries `evm_arith`, `evm_decide` with a SAT limit of at most five seconds, `evm_bits`, +`evm_ring`, `evm_simp` with the same short limit, and finally `evm_decide` with a SAT limit of +`n` seconds, and records which one proved the goal. Most rules bit-blast within the short limit; +the tactics that avoid a SAT solver, and the lemmas of `Simp.lean`, run before a long search for +the shapes that bit-blasting handles poorly. The last attempt reports the counterexample of a +false rule. -/ +macro "evm_auto " n:num : tactic => do + let short := Lean.Syntax.mkNumLit (toString (min 5 n.getNat)) + `(tactic| first + | (evm_arith; evm_proved_by "evm_arith") + | (evm_decide $short; evm_proved_by "evm_decide") + | (evm_bits; evm_proved_by "evm_bits") + | (evm_ring; evm_proved_by "evm_ring") + | (evm_simp $short; evm_proved_by "evm_simp") + | (evm_decide $n; evm_proved_by "evm_decide")) diff --git a/vendor/evm-rules/EvmRules/Bitblast.lean b/vendor/evm-rules/EvmRules/Bitblast.lean new file mode 100644 index 00000000..aefaffd1 --- /dev/null +++ b/vendor/evm-rules/EvmRules/Bitblast.lean @@ -0,0 +1,42 @@ +import EvmRules.Word + +/-! +# Bit-blasting forms + +The shifts state the word-width case as the specification does. Lean's shifts by a +`BitVec` amount already saturate, so these forms are equal and need no comparison. +-/ + +namespace EvmRules.Evm + +theorem shl_eq (shift value : Word) : shl shift value = value <<< shift := by + unfold shl + by_cases h : shift.toNat < 256 + · simp [BitVec.ult, h] + · have h' : shift.ult 256 = false := by simp [BitVec.ult]; omega + rw [h', Bool.cond_false, BitVec.shiftLeft_eq', BitVec.shiftLeft_eq_zero (by omega)] + rfl + +theorem shr_eq (shift value : Word) : shr shift value = value >>> shift := by + unfold shr + by_cases h : shift.toNat < 256 + · simp [BitVec.ult, h] + · have h' : shift.ult 256 = false := by simp [BitVec.ult]; omega + rw [h', Bool.cond_false, BitVec.ushiftRight_eq', BitVec.ushiftRight_eq_zero (by omega)] + rfl + +theorem sar_eq (shift value : Word) : sar shift value = value.sshiftRight' shift := by + unfold sar + by_cases h : shift.toNat < 256 + · simp [BitVec.ult, h] + · have h' : shift.ult 256 = false := by simp [BitVec.ult]; omega + rw [h', Bool.cond_false] + apply BitVec.eq_of_getLsbD_eq + intro i hi + rw [BitVec.getLsbD_sshiftRight', ite_eq_right (by omega)] + cases hm : value.msb + · simp + · rw [Bool.cond_true, show (-1 : Word) = BitVec.allOnes 256 by decide, BitVec.getLsbD_allOnes] + simp [hi] + +end EvmRules.Evm diff --git a/vendor/evm-rules/EvmRules/Bits.lean b/vendor/evm-rules/EvmRules/Bits.lean new file mode 100644 index 00000000..3e84e1d2 --- /dev/null +++ b/vendor/evm-rules/EvmRules/Bits.lean @@ -0,0 +1,133 @@ +import EvmRules.Arith +import EvmRules.Bitblast + +/-! +# Word operations bit by bit + +Bit `i` of every word operation `evm_bits` (`Tactic.lean`) reads, as a bit of its operand at +an index computed from the shift count or byte index. Bit-blasting builds a barrel shifter for +every variable shift count and a 31-way choice for every variable `SIGNEXTEND` index, which +SAT solvers handle poorly once two of them interact. Stated bit by bit, a rule over variable +counts becomes linear arithmetic over the indices instead. +-/ + +namespace EvmRules + +theorem signExtend_low_bits (x : Word) (w : Nat) (hw : 0 < w) (i : Nat) (hi : i < 256) : + ((x.setWidth w).signExtend 256).getLsbD i = x.getLsbD (min i (w - 1)) := by + rw [BitVec.getLsbD_signExtend] + by_cases h : i < w + · simp [hi, h, Nat.min_eq_left (show i ≤ w - 1 by omega)] + · simp [hi, h, BitVec.msb_setWidth, Nat.min_eq_right (show w - 1 ≤ i by omega), hw] + +/-- `SIGNEXTEND n x` repeats bit `8n + 7` of `x` upward; every index from 31 on keeps `x`. -/ +theorem bits_signextend (n x : Word) (i : Nat) : + (Evm.signextend n x).getLsbD i = + (decide (i < 256) && x.getLsbD (min i (n.toNat * 8 + 7))) := by + by_cases hi : i < 256 + · simp only [hi, decide_true, Bool.true_and] + unfold Evm.signextend + by_cases h : n.toNat < 31 + · have hn : n = BitVec.ofNat 256 n.toNat := by simp + generalize n.toNat = k at h hn + subst hn + rcases k with _ | _ | _ | _ | _ | _ | _ | _ | _ | _ | _ | _ | _ | _ | _ | _ | _ | _ | _ | + _ | _ | _ | _ | _ | _ | _ | _ | _ | _ | _ | _ | k + all_goals first + | omega + | simp (disch := omega) [signExtend_low_bits, -BitVec.getLsbD_eq_getElem] + · have hne : ∀ k : Word, k.toNat < 31 → (n == k) = false := by + intro k hk + simp only [beq_eq_false_iff_ne, ne_eq, BitVec.toNat_eq] + omega + simp (disch := simp) only [hne, Bool.cond_false] + rw [Nat.min_eq_left (by omega)] + · simp [hi, BitVec.getLsbD_of_ge _ _ (by omega : 256 ≤ i)] + +theorem bits_shl (s x : Word) (i : Nat) : + (Evm.shl s x).getLsbD i = + (decide (i < 256) && !decide (i < s.toNat) && x.getLsbD (i - s.toNat)) := by + rw [Evm.shl_eq, BitVec.getLsbD_shiftLeft'] + +/-- Bits shifted in from beyond the word are zero, also once the count reaches the width. -/ +theorem bits_shr (s x : Word) (i : Nat) : (Evm.shr s x).getLsbD i = x.getLsbD (s.toNat + i) := by + rw [Evm.shr_eq, BitVec.ushiftRight_eq', BitVec.getLsbD_ushiftRight] + +/-- Bits shifted in from beyond the word copy the sign bit 255. -/ +theorem bits_sar (s x : Word) (i : Nat) : + (Evm.sar s x).getLsbD i = (decide (i < 256) && x.getLsbD (min (s.toNat + i) 255)) := by + rw [Evm.sar_eq, BitVec.getLsbD_sshiftRight', BitVec.msb_eq_getLsbD_last] + by_cases hi : i < 256 + · by_cases h : s.toNat + i < 256 + · simp [hi, h, Nat.min_eq_left (show s.toNat + i ≤ 255 by omega)] + · simp [hi, h, Nat.min_eq_right (show 255 ≤ s.toNat + i by omega)] + · simp [hi, show 256 ≤ i by omega] + +/-- The low-bits mask `(1 << n) - 1`: every bit below `n`, so all of them from 256 on. -/ +theorem bits_mask (n : Word) (i : Nat) : + (Evm.sub (Evm.shl n 1) 1).getLsbD i = (decide (i < 256) && decide (i < n.toNat)) := by + rw [Evm.sub, Evm.shl_eq, BitVec.shiftLeft_eq', show (1 : Word) = 1#256 from rfl, + ← BitVec.not_neg, ← BitVec.shiftLeft_neg] + simp only [BitVec.getLsbD_not, BitVec.getLsbD_shiftLeft, BitVec.neg_one_eq_allOnes, + BitVec.getLsbD_allOnes] + by_cases hi : i < 256 <;> simp [hi] <;> omega + +theorem bits_max (i : Nat) : + (0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff : Word).getLsbD i = + decide (i < 256) := by + rw [show (0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff : Word) = + BitVec.allOnes 256 from rfl, BitVec.getLsbD_allOnes] + +theorem bits_address_mask (i : Nat) : + (0xffffffffffffffffffffffffffffffffffffffff : Word).getLsbD i = decide (i < 160) := by + rw [show (0xffffffffffffffffffffffffffffffffffffffff : Word) = BitVec.ofNat 256 (2 ^ 160 - 1) + from rfl, BitVec.getLsbD_ofNat, Nat.testBit_two_pow_sub_one] + by_cases h : i < 160 <;> simp [h] <;> omega + +theorem bits_one (i : Nat) : (1 : Word).getLsbD i = decide (i = 0) := by + rw [show (1 : Word) = 1#256 from rfl, BitVec.getLsbD_one] + simp + +theorem bits_zero (i : Nat) : (0 : Word).getLsbD i = false := by + rw [show (0 : Word) = 0#256 from rfl, BitVec.getLsbD_zero] + +/-! The indices above are numbers; these state the counts the readers compute as numbers. -/ + +/-- The smaller of two words, as the e-graph selects it. -/ +theorem toNat_select_lt (a b : Word) : + (Evm.select (Evm.lt a b) a b).toNat = min a.toNat b.toNat := by + unfold Evm.select Evm.lt + by_cases h : a.toNat < b.toNat <;> simp [BitVec.ult, h] <;> omega + +/-- The larger of two words, as the e-graph selects it. -/ +theorem toNat_select_gt (a b : Word) : + (Evm.select (Evm.gt a b) a b).toNat = max a.toNat b.toNat := by + unfold Evm.select Evm.gt + by_cases h : b.toNat < a.toNat <;> simp [BitVec.ult, h] <;> omega + +theorem toNat_shr (s x : Word) : (Evm.shr s x).toNat = x.toNat / 2 ^ s.toNat := by + rw [Evm.shr_eq, BitVec.ushiftRight_eq', BitVec.toNat_ushiftRight, Nat.shiftRight_eq_div_pow] + +theorem toNat_shl (s x : Word) : (Evm.shl s x).toNat = x.toNat * 2 ^ s.toNat % 2 ^ 256 := by + rw [Evm.shl_eq, BitVec.shiftLeft_eq', BitVec.toNat_shiftLeft, Nat.shiftLeft_eq] + +theorem toNat_shl_one {k : Word} (h : k < 256) : (Evm.shl k 1).toNat = 2 ^ k.toNat := by + rw [toNat_shl, show (1 : Word).toNat = 1 from rfl, Nat.one_mul, + Nat.mod_eq_of_lt (Nat.pow_lt_pow_right (by decide) (show k.toNat < 256 from h))] + +/-- A count that is a whole number of bytes, as the readers test it. -/ +theorem and_seven_eq_zero (s : Word) : Evm.and s 7 = 0 ↔ s.toNat % 8 = 0 := by + rw [Evm.and, ← BitVec.toNat_inj, BitVec.toNat_and, show (7 : Word).toNat = 2 ^ 3 - 1 from rfl, + Nat.and_two_pow_sub_one_eq_mod] + rfl + +/-- Multiplication by the low-bits mask negates within those bits. -/ +theorem mul_low_mask {lo hi : Nat} (x : BitVec (hi + lo)) : + (x * (BitVec.allOnes lo).setWidth (hi + lo)) &&& (BitVec.allOnes lo).setWidth (hi + lo) = + (-x) &&& (BitVec.allOnes lo).setWidth (hi + lo) := by + rw [BitVec.and_setWidth_allOnes, BitVec.and_setWidth_allOnes] + congr 1 + rw [BitVec.setWidth_mul _ _ (by omega), BitVec.setWidth_neg_of_le (by omega)] + simp [← BitVec.neg_one_eq_allOnes, BitVec.mul_neg] + +end EvmRules diff --git a/vendor/evm-rules/EvmRules/Casts.lean b/vendor/evm-rules/EvmRules/Casts.lean new file mode 100644 index 00000000..5ac3631a --- /dev/null +++ b/vendor/evm-rules/EvmRules/Casts.lean @@ -0,0 +1,173 @@ +import EvmRules.Bits + +/-! +# Structural rewrites + +Identities that `evm_decide` (`Tactic.lean`) rewrites with before bit-blasting. Each replaces a +nest of variable shifts or extensions, which bit-blasting handles poorly, by one equivalent +operation, so that many rules over them hold syntactically afterwards. The reader states MIR +`sext value from to` as `(sar s (shl s value)) & ((1 << to) - 1)` with the count +`s = 256 - min(from, 256)`; the lemmas below match that form. +-/ + +namespace EvmRules + +/-- Bit `i` of the reader's `sext x n m`: the low `n` bits of `x` with the top one repeated, +cut to `m` bits; zero for a zero width. -/ +theorem bits_sext (n m x : Word) (i : Nat) : + (Evm.and + (Evm.sar (Evm.sub 256 (Evm.select (Evm.lt n 256) n 256)) + (Evm.shl (Evm.sub 256 (Evm.select (Evm.lt n 256) n 256)) x)) + (Evm.sub (Evm.shl m 1) 1)).getLsbD i = + (decide (i < 256) && decide (i < m.toNat) && decide (0 < n.toNat) && + x.getLsbD (min i (n.toNat - 1))) := by + have hs : (Evm.sub 256 (Evm.select (Evm.lt n 256) n 256)).toNat = 256 - min n.toNat 256 := by + rw [toNat_sub_wrap, toNat_select_lt, show (256 : Word).toNat = 256 from rfl] + omega + rw [Evm.and, BitVec.getLsbD_and, bits_mask, bits_sar, bits_shl, hs] + by_cases hi : i < 256 <;> by_cases hn : 0 < n.toNat <;> by_cases hm : i < m.toNat <;> + simp [hi, hn, hm] <;> grind + +/-- Nested `SIGNEXTEND`s keep the narrower extension. -/ +theorem signextend_signextend (a b x : Word) : + Evm.signextend a (Evm.signextend b x) = Evm.signextend (Evm.select (Evm.lt a b) a b) x := by + apply BitVec.eq_of_getLsbD_eq + intro i hi + simp only [bits_signextend, toNat_select_lt] + grind + +theorem select_same (c a : Word) : Evm.select c a a = a := by + unfold Evm.select + cases c == 0 <;> rfl + +/-- Extending the low `a` bits, then the low `b > a` bits of the result, extends the low `a` +bits once. -/ +theorem sext_sext (a b c x : Word) (h : a < b) : + Evm.and + (Evm.sar (Evm.sub 256 (Evm.select (Evm.lt b 256) b 256)) + (Evm.shl (Evm.sub 256 (Evm.select (Evm.lt b 256) b 256)) + (Evm.and + (Evm.sar (Evm.sub 256 (Evm.select (Evm.lt a 256) a 256)) + (Evm.shl (Evm.sub 256 (Evm.select (Evm.lt a 256) a 256)) x)) + (Evm.sub (Evm.shl b 1) 1)))) + (Evm.sub (Evm.shl c 1) 1) = + Evm.and + (Evm.sar (Evm.sub 256 (Evm.select (Evm.lt a 256) a 256)) + (Evm.shl (Evm.sub 256 (Evm.select (Evm.lt a 256) a 256)) x)) + (Evm.sub (Evm.shl c 1) 1) := by + rw [BitVec.lt_def] at h + apply BitVec.eq_of_getLsbD_eq + intro i hi + simp only [bits_sext] + grind + +/-- Equality words agree when the equalities they test are equivalent. -/ +theorem eq_congr_iff {a b c d : Word} (h : a = b ↔ c = d) : Evm.eq a b = Evm.eq c d := by + unfold Evm.eq + by_cases e : c = d + · rw [beq_iff_eq.mpr (h.mpr e), beq_iff_eq.mpr e] + · rw [beq_eq_false_iff_ne.mpr (mt h.mp e), beq_eq_false_iff_ne.mpr e] + +theorem ne_congr_iff {a b c d : Word} (h : a = b ↔ c = d) : Evm.ne a b = Evm.ne c d := by + unfold Evm.ne + by_cases e : c = d + · rw [beq_iff_eq.mpr (h.mpr e), beq_iff_eq.mpr e] + · rw [beq_eq_false_iff_ne.mpr (mt h.mp e), beq_eq_false_iff_ne.mpr e] + +/-- A value of at most `n` bits is recovered from its extension to more bits. -/ +theorem sext_inj (n m x y : Word) (h₁ : 1 ≤ n) (h₂ : n < m) + (hx : Evm.and x (Evm.sub (Evm.shl n 1) 1) = x) (hy : Evm.and y (Evm.sub (Evm.shl n 1) 1) = y) : + Evm.and + (Evm.sar (Evm.sub 256 (Evm.select (Evm.lt n 256) n 256)) + (Evm.shl (Evm.sub 256 (Evm.select (Evm.lt n 256) n 256)) x)) + (Evm.sub (Evm.shl m 1) 1) = + Evm.and + (Evm.sar (Evm.sub 256 (Evm.select (Evm.lt n 256) n 256)) + (Evm.shl (Evm.sub 256 (Evm.select (Evm.lt n 256) n 256)) y)) + (Evm.sub (Evm.shl m 1) 1) ↔ x = y := by + constructor + · intro h + rw [BitVec.le_def] at h₁ + rw [BitVec.lt_def] at h₂ + rw [BitVec.eq_of_getLsbD_eq_iff] at h hx hy ⊢ + intro i hi + have e := h i hi + have ex := hx i hi + have ey := hy i hi + rw [bits_sext, bits_sext] at e + simp only [Evm.and, BitVec.getLsbD_and, bits_mask] at ex ey + simp only [show (1 : Word).toNat = 1 from rfl] at h₁ + grind + · rintro rfl + rfl + +theorem eq_sext_sext (n m x y : Word) (h₁ : 1 ≤ n) (h₂ : n < m) + (hx : Evm.and x (Evm.sub (Evm.shl n 1) 1) = x) (hy : Evm.and y (Evm.sub (Evm.shl n 1) 1) = y) : + Evm.eq + (Evm.and + (Evm.sar (Evm.sub 256 (Evm.select (Evm.lt n 256) n 256)) + (Evm.shl (Evm.sub 256 (Evm.select (Evm.lt n 256) n 256)) x)) + (Evm.sub (Evm.shl m 1) 1)) + (Evm.and + (Evm.sar (Evm.sub 256 (Evm.select (Evm.lt n 256) n 256)) + (Evm.shl (Evm.sub 256 (Evm.select (Evm.lt n 256) n 256)) y)) + (Evm.sub (Evm.shl m 1) 1)) = Evm.eq x y := + eq_congr_iff (sext_inj n m x y h₁ h₂ hx hy) + +theorem ne_sext_sext (n m x y : Word) (h₁ : 1 ≤ n) (h₂ : n < m) + (hx : Evm.and x (Evm.sub (Evm.shl n 1) 1) = x) (hy : Evm.and y (Evm.sub (Evm.shl n 1) 1) = y) : + Evm.ne + (Evm.and + (Evm.sar (Evm.sub 256 (Evm.select (Evm.lt n 256) n 256)) + (Evm.shl (Evm.sub 256 (Evm.select (Evm.lt n 256) n 256)) x)) + (Evm.sub (Evm.shl m 1) 1)) + (Evm.and + (Evm.sar (Evm.sub 256 (Evm.select (Evm.lt n 256) n 256)) + (Evm.shl (Evm.sub 256 (Evm.select (Evm.lt n 256) n 256)) y)) + (Evm.sub (Evm.shl m 1) 1)) = Evm.ne x y := + ne_congr_iff (sext_inj n m x y h₁ h₂ hx hy) + +theorem eq_sext_zero (n m x : Word) (h₁ : 1 ≤ n) (h₂ : n < m) + (hx : Evm.and x (Evm.sub (Evm.shl n 1) 1) = x) : + Evm.eq + (Evm.and + (Evm.sar (Evm.sub 256 (Evm.select (Evm.lt n 256) n 256)) + (Evm.shl (Evm.sub 256 (Evm.select (Evm.lt n 256) n 256)) x)) + (Evm.sub (Evm.shl m 1) 1)) 0 = Evm.eq x 0 := by + simpa [Evm.shl, Evm.sar, Evm.and] using + eq_sext_sext n m x 0 h₁ h₂ hx (by simp [Evm.and]) + +theorem ne_sext_zero (n m x : Word) (h₁ : 1 ≤ n) (h₂ : n < m) + (hx : Evm.and x (Evm.sub (Evm.shl n 1) 1) = x) : + Evm.ne + (Evm.and + (Evm.sar (Evm.sub 256 (Evm.select (Evm.lt n 256) n 256)) + (Evm.shl (Evm.sub 256 (Evm.select (Evm.lt n 256) n 256)) x)) + (Evm.sub (Evm.shl m 1) 1)) 0 = Evm.ne x 0 := by + simpa [Evm.shl, Evm.sar, Evm.and] using + ne_sext_sext n m x 0 h₁ h₂ hx (by simp [Evm.and]) + +/-- Unsigned division by a power of two is a right shift, also once the count reaches the +word width and the divisor is zero. -/ +theorem div_shl_one (x n : Word) : Evm.div x (Evm.shl n 1) = Evm.shr n x := by + apply BitVec.eq_of_toNat_eq + rw [toNat_div, toNat_shr] + by_cases h : n < 256 + · rw [toNat_shl_one h] + · have hn : 256 ≤ n.toNat := by + have : ¬n.toNat < 256 := h + omega + have hz : Evm.shl n 1 = 0 := by + rw [Evm.shl, show n.ult 256 = false by simp [BitVec.ult]; omega] + rfl + rw [hz, show (0 : Word).toNat = 0 from rfl, Nat.div_zero, Nat.div_eq_of_lt] + exact Nat.lt_of_lt_of_le x.isLt (Nat.pow_le_pow_right (by decide) hn) + +/-- A word of at most one is a boolean, for `evm_ring` to split on. -/ +theorem le_one_iff (c : Word) : c ≤ 1 ↔ c = 0 ∨ c = 1 := by + constructor + · intro h + bv_omega + · rintro (rfl | rfl) <;> decide + +end EvmRules diff --git a/vendor/evm-rules/EvmRules/Lemmas.lean b/vendor/evm-rules/EvmRules/Lemmas.lean new file mode 100644 index 00000000..f1675d79 --- /dev/null +++ b/vendor/evm-rules/EvmRules/Lemmas.lean @@ -0,0 +1,130 @@ +import EvmRules.Tactic + +/-! +# Lemmas for hand-written rule proofs + +Facts about the `Evm` definitions that the scripts in `proofs/` share. +-/ + +namespace EvmRules + +/-- `EXP` of the all-ones word, which is `-1`: one for even exponents, itself for odd ones. -/ +theorem max_pow (k : Nat) : MAX ^ k = if k % 2 = 0 then 1 else MAX := by + induction k with + | zero => rfl + | succ k ih => + rw [BitVec.pow_succ, ih] + by_cases h : k % 2 = 0 + · rw [ite_eq_left h, ite_eq_right (by omega)] + exact BitVec.one_mul _ + · rw [ite_eq_right h, ite_eq_left (by omega)] + decide + +/-- A left shift that the same right shift undoes kept every bit: it multiplied by a power of +two without wrapping. -/ +theorem toNat_shl_of_shr_shl {s x : Word} (h : Evm.shr s (Evm.shl s x) = x) : + (Evm.shl s x).toNat = x.toNat * 2 ^ s.toNat := by + have hd := congrArg BitVec.toNat h + rw [toNat_shr] at hd + have hdvd : 2 ^ s.toNat ∣ (Evm.shl s x).toNat := by + rw [toNat_shl] + by_cases hs : s.toNat ≤ 256 + · rw [Nat.dvd_mod_iff (Nat.pow_dvd_pow 2 hs)] + exact Nat.dvd_mul_left _ _ + · rw [Nat.mod_eq_zero_of_dvd (Nat.dvd_mul_left_of_dvd (Nat.pow_dvd_pow 2 (by omega)) _)] + exact Nat.dvd_zero _ + rw [← Nat.div_mul_cancel hdvd, hd] + +theorem shr_shl (s x : Word) : Evm.shr s (Evm.shl s x) = Evm.and x (Evm.shr s MAX) := by + apply BitVec.eq_of_getLsbD_eq + intro i hi + simp only [bits_shr, bits_shl, Evm.and, BitVec.getLsbD_and, bits_max] + grind + +/-- With its top `s` bits clear, `x` survives a left shift by `s`. -/ +theorem shr_shl_of_clear {s x : Word} (h : Evm.and (Evm.shr s MAX) x = x) : + Evm.shr s (Evm.shl s x) = x := by + rw [shr_shl, Evm.and, BitVec.and_comm] + exact h + +/-- Multiplying by an odd word is invertible modulo 2²⁵⁶. -/ +theorem mul_odd_inj {c : Word} (hc : Evm.and c 1 = 1) (x y : Word) : + Evm.mul x c = Evm.mul y c ↔ x = y := by + constructor + · intro h + have hodd : c.toNat % 2 = 1 := by + have := congrArg BitVec.toNat hc + rwa [Evm.and, BitVec.toNat_and, show (1 : Word).toNat = 1 from rfl, + Nat.and_one_is_mod] at this + have hcop : Nat.Coprime (2 ^ 256) c.toNat := by + apply Nat.Coprime.pow_left + show Nat.gcd 2 c.toNat = 1 + rw [Nat.gcd_rec, hodd] + rfl + have h' := congrArg BitVec.toNat h + rw [toNat_mul, toNat_mul] at h' + have hx := x.isLt + have hy := y.isLt + apply BitVec.eq_of_toNat_eq + rcases Nat.le_total y.toNat x.toNat with hle | hle + · have hd : 2 ^ 256 ∣ (x.toNat - y.toNat) * c.toNat := by + rw [Nat.sub_mul] + exact Nat.dvd_of_mod_eq_zero (Nat.sub_mod_eq_zero_of_mod_eq h') + have := Nat.eq_zero_of_dvd_of_lt (hcop.dvd_of_dvd_mul_right hd) (by omega) + omega + · have hd : 2 ^ 256 ∣ (y.toNat - x.toNat) * c.toNat := by + rw [Nat.sub_mul] + exact Nat.dvd_of_mod_eq_zero (Nat.sub_mod_eq_zero_of_mod_eq h'.symm) + have := Nat.eq_zero_of_dvd_of_lt (hcop.dvd_of_dvd_mul_right hd) (by omega) + omega + · rintro rfl + rfl + +/-- A power of two up to the word width divides a word's signed value exactly when it divides +its unsigned value. -/ +theorem pow_dvd_toInt_iff (x : Word) {k : Nat} (hk : k ≤ 256) : + ((2 ^ k : Nat) : Int) ∣ x.toInt ↔ x.toNat % 2 ^ k = 0 := by + have hw : ((2 ^ k : Nat) : Int) ∣ ((2 ^ 256 : Nat) : Int) := + Int.natCast_dvd_natCast.mpr (Nat.pow_dvd_pow 2 hk) + rw [← Nat.dvd_iff_mod_eq_zero, ← Int.natCast_dvd_natCast, BitVec.toInt_eq_toNat_cond] + split + · exact Iff.rfl + · constructor + · intro h + simpa using Int.dvd_add h hw + · intro h + exact Int.dvd_sub h hw + +/-- The mask below a power of two `m = 1 << k`. -/ +theorem toNat_mask_of_pow {m k : Word} (h : k < 256) (hm : m = Evm.shl k 1) : + (Evm.sub m 1).toNat = 2 ^ k.toNat - 1 := by + subst hm + have hp : 2 ^ k.toNat < 2 ^ 256 := Nat.pow_lt_pow_right (by decide) (show k.toNat < 256 from h) + have h1 : 1 ≤ 2 ^ k.toNat := Nat.one_le_two_pow + rw [Evm.sub, BitVec.toNat_sub, toNat_shl_one h, show (1 : Word).toNat = 1 from rfl] + omega + +/-- A signed remainder by a power of two below the sign bit is zero exactly when the low bits +are. -/ +theorem smod_pow_eq_zero_iff (x m k : Word) (h₁ : k < 256) (h₂ : m = Evm.shl k 1) + (h₃ : k.toNat < 255) : Evm.smod x m = 0 ↔ Evm.and x (Evm.sub m 1) = 0 := by + have hmask := toNat_mask_of_pow h₁ h₂ + subst h₂ + have hc := toNat_shl_one h₁ + have hp : 2 ^ k.toNat < 2 ^ 255 := Nat.pow_lt_pow_right (by decide) h₃ + have hcm : (Evm.shl k 1).msb = false := by + rw [BitVec.msb_eq_false_iff_two_mul_lt, hc] + omega + have hm0 : Evm.shl k 1 ≠ 0 := by + intro e + have := congrArg BitVec.toNat e + rw [hc] at this + have := Nat.one_le_two_pow (n := k.toNat) + simp_all + rw [Evm.smod, beq_eq_false_iff_ne.mpr hm0, Bool.cond_false, ← BitVec.toInt_inj, + BitVec.toInt_srem, BitVec.toInt_eq_toNat_of_msb hcm, hc, show (0 : Word).toInt = 0 from rfl, + ← Int.dvd_iff_tmod_eq_zero, pow_dvd_toInt_iff x (by omega), ← BitVec.toNat_inj, Evm.and, + BitVec.toNat_and, hmask, Nat.and_two_pow_sub_one_eq_mod] + rfl + +end EvmRules diff --git a/vendor/evm-rules/EvmRules/Reference.lean b/vendor/evm-rules/EvmRules/Reference.lean new file mode 100644 index 00000000..24abdc99 --- /dev/null +++ b/vendor/evm-rules/EvmRules/Reference.lean @@ -0,0 +1,207 @@ +import EvmRules.Bits + +/-! +# A second transcription of the EVM semantics + +The definitions of paradigmxyz/solar#1648, which transcribed the same execution specifications +independently of `Word.lean`: shifts by a natural count, zero divisors as an explicit case, +`SIGNEXTEND` as a pair of shifts, and comparisons as the `if` terms that its printer wrote. +Every theorem below proves that the definition the rules are checked against agrees with this +one on all inputs, so a transcription error would have to be made twice, in two different +forms, to go unnoticed. The proofs avoid `bv_decide` and rely on Lean's kernel alone. +-/ + +namespace EvmRules.Reference + +def shl (count value : Word) : Word := + if count < 256#256 then value <<< count.toNat else 0#256 + +def shr (count value : Word) : Word := + if count < 256#256 then value >>> count.toNat else 0#256 + +def sar (count value : Word) : Word := + if count < 256#256 then value.sshiftRight count.toNat else value.sshiftRight 256 + +def div (a b : Word) : Word := if b = 0#256 then 0#256 else a / b + +def mod (a b : Word) : Word := if b = 0#256 then 0#256 else a % b + +def sdiv (a b : Word) : Word := if b = 0#256 then 0#256 else a.sdiv b + +def smod (a b : Word) : Word := if b = 0#256 then 0#256 else a.srem b + +def addmod (a b n : Word) : Word := + if n = 0#256 then 0#256 else ((a.setWidth 512 + b.setWidth 512) % n.setWidth 512).setWidth 256 + +def mulmod (a b n : Word) : Word := + if n = 0#256 then 0#256 else ((a.setWidth 512 * b.setWidth 512) % n.setWidth 512).setWidth 256 + +def exp (a b : Word) : Word := a ^ b.toNat + +def byte (index value : Word) : Word := + if index < 32#256 then shr ((31#256 - index) * 8#256) value &&& 255#256 else 0#256 + +def signextend (index value : Word) : Word := + if index < 31#256 then sar (248#256 - index * 8#256) (shl (248#256 - index * 8#256) value) + else value + +def clz (value : Word) : Word := value.clz + +/-! The comparison and selection terms #1648's printer wrote. -/ + +def lt (a b : Word) : Word := if a < b then 1 else 0 + +def gt (a b : Word) : Word := if a > b then 1 else 0 + +def slt (a b : Word) : Word := if BitVec.slt a b = true then 1 else 0 + +def sgt (a b : Word) : Word := if BitVec.slt b a = true then 1 else 0 + +def eq (a b : Word) : Word := if a = b then 1 else 0 + +def ne (a b : Word) : Word := if a ≠ b then 1 else 0 + +def iszero (a : Word) : Word := if a = 0 then 1 else 0 + +def select (c a b : Word) : Word := if c ≠ 0 then a else b + +end EvmRules.Reference + +namespace EvmRules + +/-! Every operation agrees with the second transcription. -/ + +theorem shl_agrees (count value : Word) : Evm.shl count value = Reference.shl count value := by + rw [Evm.shl_eq, BitVec.shiftLeft_eq'] + unfold Reference.shl + split + · rfl + · rename_i h + rw [BitVec.shiftLeft_eq_zero (by simp only [BitVec.lt_def] at h; simp at h; omega)] + +theorem shr_agrees (count value : Word) : Evm.shr count value = Reference.shr count value := by + rw [Evm.shr_eq, BitVec.ushiftRight_eq'] + unfold Reference.shr + split + · rfl + · rename_i h + rw [BitVec.ushiftRight_eq_zero (by simp only [BitVec.lt_def] at h; simp at h; omega)] + +theorem sar_agrees (count value : Word) : Evm.sar count value = Reference.sar count value := by + rw [Evm.sar_eq, BitVec.sshiftRight_eq'] + unfold Reference.sar + split + · rfl + · rename_i h + have hc : 256 ≤ count.toNat := by + simp only [BitVec.lt_def] at h + simp at h + omega + exact BitVec.sshiftRight_eq_sshiftRight_of_le hc (by omega) + +theorem div_agrees (a b : Word) : Evm.div a b = Reference.div a b := by + unfold Evm.div Reference.div + split + · rename_i h + subst h + exact BitVec.udiv_zero + · rfl + +theorem mod_agrees (a b : Word) : Evm.mod a b = Reference.mod a b := by + unfold Evm.mod Reference.mod + by_cases h : b = 0 <;> simp [h] + +theorem sdiv_agrees (a b : Word) : Evm.sdiv a b = Reference.sdiv a b := by + unfold Evm.sdiv Reference.sdiv + split + · rename_i h + subst h + exact BitVec.sdiv_zero + · rfl + +theorem smod_agrees (a b : Word) : Evm.smod a b = Reference.smod a b := by + unfold Evm.smod Reference.smod + by_cases h : b = 0 <;> simp [h] + +theorem addmod_agrees (a b n : Word) : Evm.addmod a b n = Reference.addmod a b n := by + unfold Evm.addmod Reference.addmod + by_cases h : n = 0 <;> simp [h] + +theorem mulmod_agrees (a b n : Word) : Evm.mulmod a b n = Reference.mulmod a b n := by + unfold Evm.mulmod Reference.mulmod + by_cases h : n = 0 <;> simp [h] + +theorem exp_agrees (a b : Word) : Evm.exp a b = Reference.exp a b := rfl + +theorem clz_agrees (a : Word) : Evm.clz a = Reference.clz a := rfl + +theorem byte_agrees (index value : Word) : Evm.byte index value = Reference.byte index value := by + unfold Evm.byte Reference.byte + by_cases h : index.toNat < 32 + · have hc : ((31#256 - index) * 8#256).toNat < 256 := by bv_omega + rw [show index.ult 32 = true by simp [BitVec.ult, h], + ite_eq_left (show index < 32#256 from h), ← shr_agrees, Evm.shr_eq] + rfl + · rw [show index.ult 32 = false by simp [BitVec.ult]; omega, + ite_eq_right (show ¬index < 32#256 from h)] + rfl + +theorem signextend_agrees (index value : Word) : + Evm.signextend index value = Reference.signextend index value := by + unfold Reference.signextend + rw [← shl_agrees, ← sar_agrees] + apply BitVec.eq_of_getLsbD_eq + intro i hi + rw [bits_signextend] + split + · rename_i h + have hn : index.toNat < 31 := h + have hs : (248#256 - index * 8#256).toNat = 248 - index.toNat * 8 := by bv_omega + rw [bits_sar, bits_shl, hs] + have e₁ : min (248 - index.toNat * 8 + i) 255 < 256 := by omega + have e₂ : ¬min (248 - index.toNat * 8 + i) 255 < 248 - index.toNat * 8 := by omega + have e₃ : min (248 - index.toNat * 8 + i) 255 - (248 - index.toNat * 8) = + min i (index.toNat * 8 + 7) := by omega + simp only [hi, e₁, e₂, e₃, decide_true, decide_false, Bool.not_false, Bool.true_and] + · rename_i h + have hn : 31 ≤ index.toNat := by + simp only [BitVec.lt_def] at h + simp at h + omega + simp [hi, Nat.min_eq_left (show i ≤ index.toNat * 8 + 7 by omega)] + +theorem lt_agrees (a b : Word) : Evm.lt a b = Reference.lt a b := by + unfold Evm.lt Reference.lt + rw [show a.ult b = decide (a < b) by simp [BitVec.ult, BitVec.lt_def]] + by_cases h : a < b <;> simp [h] + +theorem gt_agrees (a b : Word) : Evm.gt a b = Reference.gt a b := by + unfold Evm.gt Reference.gt + rw [show b.ult a = decide (a > b) by simp [BitVec.ult, BitVec.lt_def]] + by_cases h : a > b <;> simp [h] + +theorem slt_agrees (a b : Word) : Evm.slt a b = Reference.slt a b := by + unfold Evm.slt Reference.slt + cases a.slt b <;> rfl + +theorem sgt_agrees (a b : Word) : Evm.sgt a b = Reference.sgt a b := by + unfold Evm.sgt Reference.sgt + cases b.slt a <;> rfl + +theorem eq_agrees (a b : Word) : Evm.eq a b = Reference.eq a b := by + unfold Evm.eq Reference.eq + by_cases h : a = b <;> simp [h] + +theorem ne_agrees (a b : Word) : Evm.ne a b = Reference.ne a b := by + unfold Evm.ne Reference.ne + by_cases h : a = b <;> simp [h] + +theorem iszero_agrees (a : Word) : Evm.iszero a = Reference.iszero a := by + unfold Evm.iszero Reference.iszero + by_cases h : a = 0 <;> simp [h] + +theorem select_agrees (c a b : Word) : Evm.select c a b = Reference.select c a b := by + unfold Evm.select Reference.select + by_cases h : c = 0 <;> simp [h] + +end EvmRules diff --git a/vendor/evm-rules/EvmRules/Simp.lean b/vendor/evm-rules/EvmRules/Simp.lean new file mode 100644 index 00000000..d5a3e82a --- /dev/null +++ b/vendor/evm-rules/EvmRules/Simp.lean @@ -0,0 +1,234 @@ +import EvmRules.Casts + +/-! +# Simplification lemmas + +The `@[simp]` lemmas of paradigmxyz/solar#1648, restated for the definitions in `Word.lean`. +`evm_simp` (`Tactic.lean`) rewrites the goal and every hypothesis with them before deciding +what remains: products and quotients by powers of two become shifts, nested shifts become one, +a shift distributes over bitwise operations and addition, `EXP` with a literal base or exponent +folds, and a cast recovers its input. +-/ + +namespace EvmRules + +/-- A count clamped to the word width, as the e-graph's `shift_sum` clamps each count. -/ +theorem clamp_toNat (x : Word) : + (Evm.select (Evm.lt x 256) x 256).toNat = min x.toNat 256 := by + unfold Evm.select Evm.lt + by_cases hx : x.toNat < 256 <;> simp [BitVec.ult, hx] <;> omega + +/-- The count the e-graph gives two nested shifts by `a` then `b`: each count clamped to the +word width, then their sum clamped again. As a number, it is `min (a + b) 256`. -/ +theorem shift_sum_toNat (a b : Word) : + (Evm.select + (Evm.lt (Evm.add (Evm.select (Evm.lt a 256) a 256) (Evm.select (Evm.lt b 256) b 256)) + 256) + (Evm.add (Evm.select (Evm.lt a 256) a 256) (Evm.select (Evm.lt b 256) b 256)) + 256).toNat = min (a.toNat + b.toNat) 256 := by + rw [clamp_toNat] + have h₁ := clamp_toNat a + have h₂ := clamp_toNat b + generalize Evm.select (Evm.lt a 256) a 256 = t₁ at * + generalize Evm.select (Evm.lt b 256) b 256 = t₂ at * + have hsum : (Evm.add t₁ t₂).toNat = t₁.toNat + t₂.toNat := by + rw [Evm.add, BitVec.toNat_add] + apply Nat.mod_eq_of_lt + omega + omega + +theorem one_pow (n : Nat) : (1 : Word) ^ n = 1 := by + induction n with + | zero => rfl + | succ n ih => rw [BitVec.pow_succ, ih]; rfl + +theorem two_pow (n : Nat) : (2 : Word) ^ n = BitVec.twoPow 256 n := by + induction n with + | zero => rfl + | succ n ih => + rw [BitVec.pow_succ, ih, show (2 : Word) = BitVec.twoPow 256 1 from rfl, + BitVec.twoPow_mul_twoPow_eq] + +/-! Products, quotients and remainders. -/ + +theorem mul_shl_one (x c : Word) : Evm.mul x (Evm.shl c 1) = Evm.shl c x := by + rw [Evm.mul, Evm.shl_eq, Evm.shl_eq, BitVec.shiftLeft_eq', BitVec.shiftLeft_eq', + show (1 : Word) = 1#256 from rfl, ← BitVec.twoPow_eq, BitVec.mul_twoPow_eq_shiftLeft] + +theorem shl_one_mul (x c : Word) : Evm.mul (Evm.shl c 1) x = Evm.shl c x := by + rw [Evm.mul, BitVec.mul_comm, ← Evm.mul, mul_shl_one] + +theorem div_lt (x y : Word) (h : x < y) : Evm.div x y = 0 := by + apply BitVec.eq_of_toNat_eq + rw [Evm.div, BitVec.toNat_udiv, Nat.div_eq_of_lt h] + rfl + +theorem mod_lt (x y : Word) (h : x < y) : Evm.mod x y = x := by + have hy : (y == 0) = false := by + rw [beq_eq_false_iff_ne] + intro e + subst e + exact absurd h (by simp [BitVec.lt_def]) + rw [Evm.mod, hy, Bool.cond_false, BitVec.umod_eq_of_lt h] + +theorem mod_self (x : Word) : Evm.mod x x = 0 := by + unfold Evm.mod + cases x == 0 <;> simp [BitVec.umod_self] + +theorem smod_self (x : Word) : Evm.smod x x = 0 := by + unfold Evm.smod + cases x == 0 <;> simp + +/-- A remainder by a power of two below the word width keeps the low bits. -/ +theorem mod_shl_one (x c : Word) (h : c < 256) : + Evm.mod x (Evm.shl c 1) = Evm.and x (Evm.sub (Evm.shl c 1) 1) := by + have hc : c.toNat < 256 := h + have hn := toNat_shl_one h + have hp : 2 ^ c.toNat < 2 ^ 256 := Nat.pow_lt_pow_right (by decide) hc + have hz : (Evm.shl c 1 == 0) = false := by + rw [beq_eq_false_iff_ne] + intro e + rw [e] at hn + have := Nat.two_pow_pos c.toNat + simp at hn + omega + apply BitVec.eq_of_toNat_eq + rw [Evm.mod, hz, Bool.cond_false, BitVec.toNat_umod, Evm.and, BitVec.toNat_and, Evm.sub, + BitVec.toNat_sub, hn, show (1 : Word).toNat = 1 from rfl] + have h1 := Nat.one_le_two_pow (n := c.toNat) + rw [show (2 ^ 256 - 1 + 2 ^ c.toNat) % 2 ^ 256 = 2 ^ c.toNat - 1 by omega, + Nat.and_two_pow_sub_one_eq_mod] + +/-- `CLZ` is at most 256, so it is below any larger divisor. -/ +theorem div_clz (x b : Word) (h : 256 < b) : Evm.div (Evm.clz x) b = 0 := + div_lt _ _ (Nat.lt_of_le_of_lt BitVec.clz_le h) + +theorem mod_clz (x b : Word) (h : 256 < b) : Evm.mod (Evm.clz x) b = Evm.clz x := + mod_lt _ _ (Nat.lt_of_le_of_lt BitVec.clz_le h) + +/-! `EXP` with a literal base or exponent. -/ + +theorem exp_two (c : Word) : Evm.exp 2 c = Evm.shl c 1 := by + rw [Evm.exp, two_pow, Evm.shl_eq, BitVec.shiftLeft_eq', BitVec.twoPow_eq] + rfl + +theorem exp_square (x : Word) : Evm.exp x 2 = Evm.mul x x := by + rw [Evm.exp, Evm.mul, show (2 : Word).toNat = 2 from rfl, BitVec.pow_succ, BitVec.pow_succ, + BitVec.pow_zero, BitVec.one_mul] + +theorem exp_zero (x : Word) : Evm.exp x 0 = 1 := by + rw [Evm.exp, show (0 : Word).toNat = 0 from rfl, BitVec.pow_zero] + rfl + +theorem exp_one (x : Word) : Evm.exp x 1 = x := by + rw [Evm.exp, show (1 : Word).toNat = 1 from rfl, BitVec.pow_succ, BitVec.pow_zero, + BitVec.one_mul] + +theorem one_exp (x : Word) : Evm.exp 1 x = 1 := by + rw [Evm.exp, one_pow] + +/-! Nested shifts by `a`, then `b`, are one shift by their sum clamped to the word width. -/ + +/-- The clamped sum of two shift counts. -/ +def shiftSum (a b : Word) : Word := BitVec.ofNat 256 (min 256 (a.toNat + b.toNat)) + +theorem shiftSum_toNat (a b : Word) : (shiftSum a b).toNat = min 256 (a.toNat + b.toNat) := by + rw [shiftSum, BitVec.toNat_ofNat] + apply Nat.mod_eq_of_lt + have := Nat.min_le_left 256 (a.toNat + b.toNat) + omega + +/-- The e-graph's `shift_sum` of two counts is their clamped sum. -/ +theorem shift_sum_eq (a b : Word) : + Evm.select + (Evm.lt (Evm.add (Evm.select (Evm.lt a 256) a 256) (Evm.select (Evm.lt b 256) b 256)) + 256) + (Evm.add (Evm.select (Evm.lt a 256) a 256) (Evm.select (Evm.lt b 256) b 256)) + 256 = shiftSum a b := by + apply BitVec.eq_of_toNat_eq + rw [shift_sum_toNat, shiftSum_toNat, Nat.min_comm] + +theorem shl_shl (a b x : Word) : Evm.shl a (Evm.shl b x) = Evm.shl (shiftSum a b) x := by + simp only [Evm.shl_eq, BitVec.shiftLeft_eq', shiftSum_toNat, ← BitVec.shiftLeft_add] + by_cases h : a.toNat + b.toNat < 256 + · rw [Nat.min_eq_right (by omega), Nat.add_comm] + · rw [Nat.min_eq_left (by omega), BitVec.shiftLeft_eq_zero (by omega), + BitVec.shiftLeft_eq_zero (by omega)] + +theorem shr_shr (a b x : Word) : Evm.shr a (Evm.shr b x) = Evm.shr (shiftSum a b) x := by + simp only [Evm.shr_eq, BitVec.ushiftRight_eq', shiftSum_toNat, ← BitVec.shiftRight_add] + by_cases h : a.toNat + b.toNat < 256 + · rw [Nat.min_eq_right (by omega), Nat.add_comm] + · rw [Nat.min_eq_left (by omega), BitVec.ushiftRight_eq_zero (by omega), + BitVec.ushiftRight_eq_zero (by omega)] + +theorem sar_sar (a b x : Word) : Evm.sar a (Evm.sar b x) = Evm.sar (shiftSum a b) x := by + simp only [Evm.sar_eq, BitVec.sshiftRight_eq', shiftSum_toNat, ← BitVec.sshiftRight_add] + by_cases h : a.toNat + b.toNat < 256 + · rw [Nat.min_eq_right (by omega), Nat.add_comm] + · rw [Nat.min_eq_left (by omega)] + exact BitVec.sshiftRight_eq_sshiftRight_of_le (by omega) (by omega) + +/-! A shift by one count distributes over bitwise operations and addition. -/ + +theorem and_shl (n x y : Word) : + Evm.and (Evm.shl n x) (Evm.shl n y) = Evm.shl n (Evm.and x y) := by + simp only [Evm.and, Evm.shl_eq, BitVec.shiftLeft_eq', BitVec.shiftLeft_and_distrib] + +theorem or_shl (n x y : Word) : + Evm.or (Evm.shl n x) (Evm.shl n y) = Evm.shl n (Evm.or x y) := by + simp only [Evm.or, Evm.shl_eq, BitVec.shiftLeft_eq', BitVec.shiftLeft_or_distrib] + +theorem xor_shl (n x y : Word) : + Evm.xor (Evm.shl n x) (Evm.shl n y) = Evm.shl n (Evm.xor x y) := by + simp only [Evm.xor, Evm.shl_eq, BitVec.shiftLeft_eq', BitVec.shiftLeft_xor_distrib] + +theorem add_shl (n x y : Word) : + Evm.add (Evm.shl n x) (Evm.shl n y) = Evm.shl n (Evm.add x y) := by + simp only [Evm.add, Evm.shl_eq, BitVec.shiftLeft_eq', BitVec.shiftLeft_add_distrib] + +theorem and_shr (n x y : Word) : + Evm.and (Evm.shr n x) (Evm.shr n y) = Evm.shr n (Evm.and x y) := by + simp only [Evm.and, Evm.shr_eq, BitVec.ushiftRight_eq', BitVec.ushiftRight_and_distrib] + +theorem or_shr (n x y : Word) : + Evm.or (Evm.shr n x) (Evm.shr n y) = Evm.shr n (Evm.or x y) := by + simp only [Evm.or, Evm.shr_eq, BitVec.ushiftRight_eq', BitVec.ushiftRight_or_distrib] + +theorem xor_shr (n x y : Word) : + Evm.xor (Evm.shr n x) (Evm.shr n y) = Evm.shr n (Evm.xor x y) := by + simp only [Evm.xor, Evm.shr_eq, BitVec.ushiftRight_eq', BitVec.ushiftRight_xor_distrib] + +theorem and_sar (n x y : Word) : + Evm.and (Evm.sar n x) (Evm.sar n y) = Evm.sar n (Evm.and x y) := by + simp only [Evm.and, Evm.sar_eq, BitVec.sshiftRight_eq', BitVec.sshiftRight_and_distrib] + +theorem or_sar (n x y : Word) : + Evm.or (Evm.sar n x) (Evm.sar n y) = Evm.sar n (Evm.or x y) := by + simp only [Evm.or, Evm.sar_eq, BitVec.sshiftRight_eq', BitVec.sshiftRight_or_distrib] + +theorem xor_sar (n x y : Word) : + Evm.xor (Evm.sar n x) (Evm.sar n y) = Evm.sar n (Evm.xor x y) := by + simp only [Evm.xor, Evm.sar_eq, BitVec.sshiftRight_eq', BitVec.sshiftRight_xor_distrib] + +/-! A cast recovers a value that fits its source width (`signedMask_recover` in #1648). -/ + +theorem sext_recover (n m x : Word) (h₁ : 1 ≤ n) (h₂ : n < m) + (hx : Evm.and x (Evm.sub (Evm.shl n 1) 1) = x) : + Evm.and + (Evm.and + (Evm.sar (Evm.sub 256 (Evm.select (Evm.lt n 256) n 256)) + (Evm.shl (Evm.sub 256 (Evm.select (Evm.lt n 256) n 256)) x)) + (Evm.sub (Evm.shl m 1) 1)) + (Evm.sub (Evm.shl n 1) 1) = x := by + rw [BitVec.le_def] at h₁ + rw [BitVec.lt_def] at h₂ + apply BitVec.eq_of_getLsbD_eq + intro i hi + have ex := congrArg (BitVec.getLsbD · i) hx + simp only [Evm.and, BitVec.getLsbD_and, bits_mask] at ex + rw [Evm.and, BitVec.getLsbD_and, bits_sext, bits_mask] + simp only [show (1 : Word).toNat = 1 from rfl] at h₁ + grind + +end EvmRules diff --git a/vendor/evm-rules/EvmRules/Tactic.lean b/vendor/evm-rules/EvmRules/Tactic.lean new file mode 100644 index 00000000..38425997 --- /dev/null +++ b/vendor/evm-rules/EvmRules/Tactic.lean @@ -0,0 +1,101 @@ +import EvmRules.Simp + +/-! +# Automatic rule proofs + +`evm_decide` rewrites with the structural identities of `Casts.lean`, unfolds every EVM +operation into `BitVec` primitives and bit-blasts the goal with `bv_decide`, which checks the +SAT solver's LRAT certificate in Lean. An optional argument sets the SAT solver's limit in +seconds. + +Bit-blasting struggles with two shapes, which the other tactics prove without a SAT solver: + +* `evm_bits` proves an equation bit by bit with the lemmas of `Bits.lean`, turning variable + shift counts and extension widths into linear arithmetic over bit indices for `grind`. +* `evm_ring` lets `grind`'s commutative-ring normalization prove identities over products of + variables, such as distributivity, after splitting conditions that are known to be + booleans. + +`evm_simp` is the pipeline of paradigmxyz/solar#1648: it simplifies the goal and every +hypothesis with the lemmas of `Simp.lean` and `Casts.lean`, then decides what remains with +`bv_omega`, or bit-blasts it after normalizing associative and commutative operations. +-/ + +namespace EvmRules + +/-- Unfold the EVM operations in the goal and every hypothesis into `BitVec` primitives. -/ +macro "evm_unfold" : tactic => + `(tactic| ( + try simp only [Evm.add, Evm.sub, Evm.mul, Evm.div, Evm.mod, Evm.sdiv, Evm.smod, Evm.addmod, + Evm.mulmod, Evm.exp, Evm.and, Evm.or, Evm.xor, Evm.not, Evm.shl_eq, Evm.shr_eq, Evm.sar_eq, + Evm.lt, Evm.gt, Evm.slt, Evm.sgt, Evm.eq, Evm.ne, Evm.iszero, Evm.select, Evm.byte, + Evm.signextend, Evm.clz, Evm.address, Evm.balance, Evm.selfbalance] at *)) + +/-- Rewrite nested sign extensions and casts and divisions by powers of two with the +identities of `Casts.lean`, discharging their preconditions from the hypotheses. Only the side +goals substitute equal variables: the goal keeps every variable, so that a counterexample +`bv_decide` reports afterwards still assigns each of them. -/ +macro "evm_struct" : tactic => + `(tactic| ( + try simp (disch := (try subst_vars) <;> assumption) only [signextend_signextend, + select_same, sext_sext, eq_sext_sext, ne_sext_sext, eq_sext_zero, ne_sext_zero, + div_shl_one] at *)) + +/-- Rewrite structurally, unfold the EVM operations, then bit-blast whatever goal remains, +with an optional SAT limit in seconds. -/ +syntax "evm_decide" (ppSpace num)? : tactic + +macro_rules + | `(tactic| evm_decide) => `(tactic| evm_decide 10) + | `(tactic| evm_decide $timeout:num) => + `(tactic| ( + evm_struct + all_goals (evm_unfold <;> bv_decide (config := { timeout := $timeout })))) + +/-- Prove a word equation bit by bit: state the goal and every word equation among the +hypotheses as equalities of all 256 bits, write each bit of a shift, extension or mask as a bit +of its operand, and let `grind` relate the bit indices. -/ +macro "evm_bits" : tactic => + `(tactic| ( + subst_vars + try simp only [and_seven_eq_zero] at * + simp only [BitVec.eq_of_getLsbD_eq_iff, Evm.and, Evm.or, Evm.xor, Evm.not, + BitVec.getLsbD_and, BitVec.getLsbD_or, BitVec.getLsbD_xor, BitVec.getLsbD_not, bits_shl, + bits_shr, bits_sar, bits_mask, bits_signextend, bits_max, bits_address_mask, bits_one, + bits_zero, toNat_select_lt, toNat_select_gt, toNat_shr, toNat_add_wrap, toNat_sub_wrap, + toNat_mul, BitVec.lt_def, BitVec.le_def, Nat.add_sub_cancel, Nat.add_sub_cancel_left] at * + try simp only [BitVec.ofNat_eq_ofNat, BitVec.toNat_ofNat, Nat.reducePow, Nat.reduceMod] at * + grind)) + +/-- Prove a ring identity with `grind`: split boolean conditions, write left shifts as products +with powers of two and normalize both sides as commutative-ring polynomials. -/ +macro "evm_ring" : tactic => + `(tactic| ( + subst_vars + try simp only [le_one_iff] at * + try simp only [Evm.add, Evm.sub, Evm.mul, Evm.and, Evm.or, Evm.xor, Evm.not, Evm.shl_eq, + BitVec.shiftLeft_eq', BitVec.shiftLeft_eq_mul_twoPow, Evm.shr, Evm.sar, Evm.select, Evm.lt, + Evm.gt, Evm.eq, Evm.ne, Evm.iszero] at * + grind)) + +/-- Simplify with the lemmas of `Simp.lean` and `Casts.lean` everywhere, unfold the EVM +operations, then decide the rest over natural numbers with `bv_omega` or bit-blast it with +associative and commutative operations normalized, with an optional SAT limit in seconds. -/ +syntax "evm_simp" (ppSpace num)? : tactic + +macro_rules + | `(tactic| evm_simp) => `(tactic| evm_simp 10) + | `(tactic| evm_simp $timeout:num) => + `(tactic| ( + try subst_vars + try simp_all only [mul_shl_one, shl_one_mul, div_lt, mod_lt, mod_self, smod_self, + mod_shl_one, div_clz, mod_clz, exp_two, exp_square, exp_zero, exp_one, one_exp, + shift_sum_eq, shl_shl, shr_shr, sar_sar, and_shl, or_shl, xor_shl, add_shl, and_shr, + or_shr, xor_shr, and_sar, or_sar, xor_sar, sext_recover, signextend_signextend, + select_same, sext_sext, eq_sext_sext, ne_sext_sext, div_shl_one] + all_goals (evm_unfold; try simp only [shiftSum] at *) + all_goals first + | bv_omega + | bv_decide (config := { timeout := $timeout, acNf := true }))) + +end EvmRules diff --git a/vendor/evm-rules/EvmRules/Word.lean b/vendor/evm-rules/EvmRules/Word.lean new file mode 100644 index 00000000..6b096b88 --- /dev/null +++ b/vendor/evm-rules/EvmRules/Word.lean @@ -0,0 +1,141 @@ +import Std.Tactic.BVDecide + +/-! +# EVM word semantics + +The meaning of every word operation the rule checker reads, transcribed from the +[Ethereum execution specifications](https://github.com/ethereum/execution-specs/tree/master/src/ethereum/forks/cancun/vm/instructions). +Words are `BitVec 256` with wrapping arithmetic. Operands are in MIR / EVM pop order, so +shifts take the amount before the value. Rule theorems are stated over these definitions, +and the checker's regression tests evaluate them against the independent integer evaluator +in `evm_rules/expr.py`. Memory, storage, calls, gas and control flow are outside this model. +-/ + +namespace EvmRules + +/-- A 256-bit EVM word. -/ +abbrev Word := BitVec 256 + +namespace Evm + +def add (a b : Word) : Word := a + b + +def sub (a b : Word) : Word := a - b + +def mul (a b : Word) : Word := a * b + +/-- `DIV`. Lean's unsigned division already returns zero for a zero divisor. -/ +def div (a b : Word) : Word := a / b + +/-- `MOD`: zero for a zero divisor, where Lean's `%` keeps the dividend. -/ +def mod (a b : Word) : Word := bif b == 0 then 0 else a % b + +/-- `SDIV`, truncating toward zero. `BitVec.sdiv` returns zero for a zero divisor, and +`-2²⁵⁵ / -1` wraps to `-2²⁵⁵`, both as the EVM does. -/ +def sdiv (a b : Word) : Word := a.sdiv b + +/-- `SMOD`: the remainder takes the dividend's sign; zero for a zero divisor. -/ +def smod (a b : Word) : Word := bif b == 0 then 0 else a.srem b + +/-- `ADDMOD`: the sum is not reduced modulo 2²⁵⁶ before the modulus. -/ +def addmod (a b n : Word) : Word := + bif n == 0 then 0 else ((a.setWidth 512 + b.setWidth 512) % n.setWidth 512).setWidth 256 + +/-- `MULMOD`: the product is not reduced modulo 2²⁵⁶ before the modulus. -/ +def mulmod (a b n : Word) : Word := + bif n == 0 then 0 else ((a.setWidth 512 * b.setWidth 512) % n.setWidth 512).setWidth 256 + +/-- `EXP`, modulo 2²⁵⁶. -/ +def exp (a b : Word) : Word := a ^ b.toNat + +def and (a b : Word) : Word := a &&& b + +def or (a b : Word) : Word := a ||| b + +def xor (a b : Word) : Word := a ^^^ b + +def not (a : Word) : Word := ~~~a + +/-- `SHL`: zero once the shift reaches the word width. -/ +def shl (shift value : Word) : Word := bif shift.ult 256 then value <<< shift else 0 + +/-- `SHR`: zero once the shift reaches the word width. -/ +def shr (shift value : Word) : Word := bif shift.ult 256 then value >>> shift else 0 + +/-- `SAR`: every bit takes the sign once the shift reaches the word width. -/ +def sar (shift value : Word) : Word := + bif shift.ult 256 then value.sshiftRight' shift else bif value.msb then -1 else 0 + +def lt (a b : Word) : Word := bif a.ult b then 1 else 0 + +def gt (a b : Word) : Word := bif b.ult a then 1 else 0 + +def slt (a b : Word) : Word := bif a.slt b then 1 else 0 + +def sgt (a b : Word) : Word := bif b.slt a then 1 else 0 + +def eq (a b : Word) : Word := bif a == b then 1 else 0 + +/-- MIR `ne`, the word form of an inequality. -/ +def ne (a b : Word) : Word := bif a == b then 0 else 1 + +def iszero (a : Word) : Word := bif a == 0 then 1 else 0 + +/-- MIR `select`: the first arm for every nonzero condition word. -/ +def select (c a b : Word) : Word := bif c == 0 then b else a + +/-- `BYTE`: byte `i` counted from the most significant end, and zero from 32 on. -/ +def byte (i v : Word) : Word := bif i.ult 32 then (v >>> ((31 - i) * 8)) &&& 255 else 0 + +/-- `SIGNEXTEND`: extend the sign of the low `i + 1` bytes. Every index from 31 on is the +identity, however large. One case per byte keeps the definition free of variable shifts. -/ +def signextend (i v : Word) : Word := + bif i == 0 then (v.setWidth 8).signExtend 256 else + bif i == 1 then (v.setWidth 16).signExtend 256 else + bif i == 2 then (v.setWidth 24).signExtend 256 else + bif i == 3 then (v.setWidth 32).signExtend 256 else + bif i == 4 then (v.setWidth 40).signExtend 256 else + bif i == 5 then (v.setWidth 48).signExtend 256 else + bif i == 6 then (v.setWidth 56).signExtend 256 else + bif i == 7 then (v.setWidth 64).signExtend 256 else + bif i == 8 then (v.setWidth 72).signExtend 256 else + bif i == 9 then (v.setWidth 80).signExtend 256 else + bif i == 10 then (v.setWidth 88).signExtend 256 else + bif i == 11 then (v.setWidth 96).signExtend 256 else + bif i == 12 then (v.setWidth 104).signExtend 256 else + bif i == 13 then (v.setWidth 112).signExtend 256 else + bif i == 14 then (v.setWidth 120).signExtend 256 else + bif i == 15 then (v.setWidth 128).signExtend 256 else + bif i == 16 then (v.setWidth 136).signExtend 256 else + bif i == 17 then (v.setWidth 144).signExtend 256 else + bif i == 18 then (v.setWidth 152).signExtend 256 else + bif i == 19 then (v.setWidth 160).signExtend 256 else + bif i == 20 then (v.setWidth 168).signExtend 256 else + bif i == 21 then (v.setWidth 176).signExtend 256 else + bif i == 22 then (v.setWidth 184).signExtend 256 else + bif i == 23 then (v.setWidth 192).signExtend 256 else + bif i == 24 then (v.setWidth 200).signExtend 256 else + bif i == 25 then (v.setWidth 208).signExtend 256 else + bif i == 26 then (v.setWidth 216).signExtend 256 else + bif i == 27 then (v.setWidth 224).signExtend 256 else + bif i == 28 then (v.setWidth 232).signExtend 256 else + bif i == 29 then (v.setWidth 240).signExtend 256 else + bif i == 30 then (v.setWidth 248).signExtend 256 else + v + +/-- `CLZ` (EIP-7939): the number of leading zero bits, 256 for zero. -/ +def clz (v : Word) : Word := v.clz + +/-- `ADDRESS`: the executing account, zero-extended. -/ +def address (self : BitVec 160) : Word := self.setWidth 256 + +/-- `BALANCE` reads the snapshot balance of the account in the word's low 160 bits. -/ +def balance (balances : BitVec 160 → Word) (account : Word) : Word := + balances (account.setWidth 160) + +/-- `SELFBALANCE`: the snapshot balance of the executing account. -/ +def selfbalance (balances : BitVec 160 → Word) (self : BitVec 160) : Word := balances self + +end Evm + +end EvmRules diff --git a/vendor/evm-rules/README.md b/vendor/evm-rules/README.md new file mode 100644 index 00000000..85c1aa9d --- /dev/null +++ b/vendor/evm-rules/README.md @@ -0,0 +1,10 @@ +# EvmRules (vendored) + +solar's word semantics and rewrite-rule lemmas (`EvmRules`, `EvmRules.*`), which the SolarTV +library's MIR and EVM IR semantics are written in. Copied verbatim from +paradigmxyz/solar `scripts/evm-rules/lean/EvmRules.lean` and `scripts/evm-rules/lean/EvmRules/` +at main de3967800 (only the library: solar's rule checker, `Checker.lean`, and its generated rule +proofs stay in solar, which keeps its own copy for checking its ISLE rules). + +To update, copy those paths from the solar commit and update the commit above; +`scripts/check-evm-rules-vendor.sh ` reports any difference. From 0a20484f56cb7ee07e56c65a0d61acf17a3c0afb Mon Sep 17 00:00:00 2001 From: alpharush <0xalpharush@protonmail.com> Date: Fri, 13 Nov 2026 00:37:13 -0600 Subject: [PATCH 6/8] refactor(refinement): keep only the corpus proofs headlines import --- SolidCore/Refinement/Axioms/Contracts.lean | 39 ++ 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/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/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/W2.lean | 286 ----------- SolidCore/Refinement/Corpus/W3.lean | 198 -------- SolidCore/Refinement/Generic/SourceRun.lean | 2 +- SolidCore/Refinement/Headline.lean | 6 +- SolidCore/Refinement/Solar/Assemble.lean | 46 +- SolidCore/Refinement/Solar/AssembleFast.lean | 136 ++++-- .../Refinement/Solar/AssembleStackN.lean | 139 ++++++ .../Refinement/Solar/Bank/Certified.lean | 18 +- SolidCore/Refinement/Solar/C4/Certified.lean | 8 +- SolidCore/Refinement/Solar/C4/Lowering.lean | 2 +- .../Refinement/Solar/C4/LoweringGeneric.lean | 2 +- .../Refinement/Solar/Counter/Milestone.lean | 2 +- SolidCore/Refinement/Solar/Counter/Spec.lean | 4 +- .../Refinement/Solar/Events/Certified.lean | 8 +- SolidCore/Refinement/Solar/Lowering.lean | 2 +- .../Refinement/Solar/MulX/Certified.lean | 8 +- SolidCore/Refinement/Solar/W4/Milestone.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 ------- 297 files changed, 332 insertions(+), 9524 deletions(-) create mode 100644 SolidCore/Refinement/Axioms/Contracts.lean delete mode 100644 SolidCore/Refinement/Corpus/B1.lean delete mode 100644 SolidCore/Refinement/Corpus/B1/Defs.lean delete mode 100644 SolidCore/Refinement/Corpus/B1/Dirty.lean delete mode 100644 SolidCore/Refinement/Corpus/B1/Part0.lean delete mode 100644 SolidCore/Refinement/Corpus/B1/Seq.lean delete mode 100644 SolidCore/Refinement/Corpus/B1/SeqDefs.lean delete mode 100644 SolidCore/Refinement/Corpus/B1/SeqPart0.lean delete mode 100644 SolidCore/Refinement/Corpus/B1/SeqStates.lean delete mode 100644 SolidCore/Refinement/Corpus/B2.lean delete mode 100644 SolidCore/Refinement/Corpus/B2/Defs.lean delete mode 100644 SolidCore/Refinement/Corpus/B2/Dirty.lean delete mode 100644 SolidCore/Refinement/Corpus/B2/Part0.lean delete mode 100644 SolidCore/Refinement/Corpus/B2/Seq.lean delete mode 100644 SolidCore/Refinement/Corpus/B2/SeqDefs.lean delete mode 100644 SolidCore/Refinement/Corpus/B2/SeqPart0.lean delete mode 100644 SolidCore/Refinement/Corpus/B2/SeqStates.lean delete mode 100644 SolidCore/Refinement/Corpus/B3.lean delete mode 100644 SolidCore/Refinement/Corpus/B3/Defs.lean delete mode 100644 SolidCore/Refinement/Corpus/B3/Dirty.lean delete mode 100644 SolidCore/Refinement/Corpus/B3/Part0.lean delete mode 100644 SolidCore/Refinement/Corpus/B3/Seq.lean delete mode 100644 SolidCore/Refinement/Corpus/B3/SeqDefs.lean delete mode 100644 SolidCore/Refinement/Corpus/B3/SeqPart0.lean delete mode 100644 SolidCore/Refinement/Corpus/B3/SeqStates.lean delete mode 100644 SolidCore/Refinement/Corpus/B4.lean delete mode 100644 SolidCore/Refinement/Corpus/B4/Defs.lean delete mode 100644 SolidCore/Refinement/Corpus/B4/Dirty.lean delete mode 100644 SolidCore/Refinement/Corpus/B4/Part0.lean delete mode 100644 SolidCore/Refinement/Corpus/B4/Seq.lean delete mode 100644 SolidCore/Refinement/Corpus/B4/SeqDefs.lean delete mode 100644 SolidCore/Refinement/Corpus/B4/SeqPart0.lean delete mode 100644 SolidCore/Refinement/Corpus/B4/SeqStates.lean delete mode 100644 SolidCore/Refinement/Corpus/B5.lean delete mode 100644 SolidCore/Refinement/Corpus/B5/Defs.lean delete mode 100644 SolidCore/Refinement/Corpus/B5/Dirty.lean delete mode 100644 SolidCore/Refinement/Corpus/B5/Part0.lean delete mode 100644 SolidCore/Refinement/Corpus/B5/Seq.lean delete mode 100644 SolidCore/Refinement/Corpus/B5/SeqDefs.lean delete mode 100644 SolidCore/Refinement/Corpus/B5/SeqPart0.lean delete mode 100644 SolidCore/Refinement/Corpus/B5/SeqStates.lean delete mode 100644 SolidCore/Refinement/Corpus/B6.lean delete mode 100644 SolidCore/Refinement/Corpus/B6/Defs.lean delete mode 100644 SolidCore/Refinement/Corpus/B6/Dirty.lean delete mode 100644 SolidCore/Refinement/Corpus/B6/Part0.lean delete mode 100644 SolidCore/Refinement/Corpus/B6/Seq.lean delete mode 100644 SolidCore/Refinement/Corpus/B6/SeqDefs.lean delete mode 100644 SolidCore/Refinement/Corpus/B6/SeqPart0.lean delete mode 100644 SolidCore/Refinement/Corpus/B6/SeqStates.lean delete mode 100644 SolidCore/Refinement/Corpus/B7.lean delete mode 100644 SolidCore/Refinement/Corpus/B7/Defs.lean delete mode 100644 SolidCore/Refinement/Corpus/B7/Dirty.lean delete mode 100644 SolidCore/Refinement/Corpus/B7/Part0.lean delete mode 100644 SolidCore/Refinement/Corpus/B7/Seq.lean delete mode 100644 SolidCore/Refinement/Corpus/B7/SeqDefs.lean delete mode 100644 SolidCore/Refinement/Corpus/B7/SeqPart0.lean delete mode 100644 SolidCore/Refinement/Corpus/B7/SeqStates.lean delete mode 100644 SolidCore/Refinement/Corpus/C10.lean delete mode 100644 SolidCore/Refinement/Corpus/C10/Defs.lean delete mode 100644 SolidCore/Refinement/Corpus/C10/Dirty.lean delete mode 100644 SolidCore/Refinement/Corpus/C10/Part0.lean delete mode 100644 SolidCore/Refinement/Corpus/C10/Seq.lean delete mode 100644 SolidCore/Refinement/Corpus/C10/SeqDefs.lean delete mode 100644 SolidCore/Refinement/Corpus/C10/SeqPart0.lean delete mode 100644 SolidCore/Refinement/Corpus/C10/SeqStates.lean delete mode 100644 SolidCore/Refinement/Corpus/C11.lean delete mode 100644 SolidCore/Refinement/Corpus/C11/Defs.lean delete mode 100644 SolidCore/Refinement/Corpus/C11/Dirty.lean delete mode 100644 SolidCore/Refinement/Corpus/C11/Part0.lean delete mode 100644 SolidCore/Refinement/Corpus/C11/Seq.lean delete mode 100644 SolidCore/Refinement/Corpus/C11/SeqDefs.lean delete mode 100644 SolidCore/Refinement/Corpus/C11/SeqPart0.lean delete mode 100644 SolidCore/Refinement/Corpus/C11/SeqStates.lean delete mode 100644 SolidCore/Refinement/Corpus/C2.lean delete mode 100644 SolidCore/Refinement/Corpus/C2/Defs.lean delete mode 100644 SolidCore/Refinement/Corpus/C2/Dirty.lean delete mode 100644 SolidCore/Refinement/Corpus/C2/Part0.lean delete mode 100644 SolidCore/Refinement/Corpus/C2/Part1.lean delete mode 100644 SolidCore/Refinement/Corpus/C2/Part10.lean delete mode 100644 SolidCore/Refinement/Corpus/C2/Part11.lean delete mode 100644 SolidCore/Refinement/Corpus/C2/Part12.lean delete mode 100644 SolidCore/Refinement/Corpus/C2/Part13.lean delete mode 100644 SolidCore/Refinement/Corpus/C2/Part14.lean delete mode 100644 SolidCore/Refinement/Corpus/C2/Part15.lean delete mode 100644 SolidCore/Refinement/Corpus/C2/Part2.lean delete mode 100644 SolidCore/Refinement/Corpus/C2/Part3.lean delete mode 100644 SolidCore/Refinement/Corpus/C2/Part4.lean delete mode 100644 SolidCore/Refinement/Corpus/C2/Part5.lean delete mode 100644 SolidCore/Refinement/Corpus/C2/Part6.lean delete mode 100644 SolidCore/Refinement/Corpus/C2/Part7.lean delete mode 100644 SolidCore/Refinement/Corpus/C2/Part8.lean delete mode 100644 SolidCore/Refinement/Corpus/C2/Part9.lean delete mode 100644 SolidCore/Refinement/Corpus/C2/Seq.lean delete mode 100644 SolidCore/Refinement/Corpus/C2/SeqDefs.lean delete mode 100644 SolidCore/Refinement/Corpus/C2/SeqPart0.lean delete mode 100644 SolidCore/Refinement/Corpus/C2/SeqPart1.lean delete mode 100644 SolidCore/Refinement/Corpus/C2/SeqPart10.lean delete mode 100644 SolidCore/Refinement/Corpus/C2/SeqPart11.lean delete mode 100644 SolidCore/Refinement/Corpus/C2/SeqPart12.lean delete mode 100644 SolidCore/Refinement/Corpus/C2/SeqPart13.lean delete mode 100644 SolidCore/Refinement/Corpus/C2/SeqPart14.lean delete mode 100644 SolidCore/Refinement/Corpus/C2/SeqPart15.lean delete mode 100644 SolidCore/Refinement/Corpus/C2/SeqPart2.lean delete mode 100644 SolidCore/Refinement/Corpus/C2/SeqPart3.lean delete mode 100644 SolidCore/Refinement/Corpus/C2/SeqPart4.lean delete mode 100644 SolidCore/Refinement/Corpus/C2/SeqPart5.lean delete mode 100644 SolidCore/Refinement/Corpus/C2/SeqPart6.lean delete mode 100644 SolidCore/Refinement/Corpus/C2/SeqPart7.lean delete mode 100644 SolidCore/Refinement/Corpus/C2/SeqPart8.lean delete mode 100644 SolidCore/Refinement/Corpus/C2/SeqPart9.lean delete mode 100644 SolidCore/Refinement/Corpus/C2/SeqStates.lean delete mode 100644 SolidCore/Refinement/Corpus/C3.lean delete mode 100644 SolidCore/Refinement/Corpus/C3/Defs.lean delete mode 100644 SolidCore/Refinement/Corpus/C3/Dirty.lean delete mode 100644 SolidCore/Refinement/Corpus/C3/Part0.lean delete mode 100644 SolidCore/Refinement/Corpus/C3/Part1.lean delete mode 100644 SolidCore/Refinement/Corpus/C3/Part10.lean delete mode 100644 SolidCore/Refinement/Corpus/C3/Part11.lean delete mode 100644 SolidCore/Refinement/Corpus/C3/Part12.lean delete mode 100644 SolidCore/Refinement/Corpus/C3/Part13.lean delete mode 100644 SolidCore/Refinement/Corpus/C3/Part14.lean delete mode 100644 SolidCore/Refinement/Corpus/C3/Part15.lean delete mode 100644 SolidCore/Refinement/Corpus/C3/Part2.lean delete mode 100644 SolidCore/Refinement/Corpus/C3/Part3.lean delete mode 100644 SolidCore/Refinement/Corpus/C3/Part4.lean delete mode 100644 SolidCore/Refinement/Corpus/C3/Part5.lean delete mode 100644 SolidCore/Refinement/Corpus/C3/Part6.lean delete mode 100644 SolidCore/Refinement/Corpus/C3/Part7.lean delete mode 100644 SolidCore/Refinement/Corpus/C3/Part8.lean delete mode 100644 SolidCore/Refinement/Corpus/C3/Part9.lean delete mode 100644 SolidCore/Refinement/Corpus/C3/Seq.lean delete mode 100644 SolidCore/Refinement/Corpus/C3/SeqDefs.lean delete mode 100644 SolidCore/Refinement/Corpus/C3/SeqPart0.lean delete mode 100644 SolidCore/Refinement/Corpus/C3/SeqPart1.lean delete mode 100644 SolidCore/Refinement/Corpus/C3/SeqPart10.lean delete mode 100644 SolidCore/Refinement/Corpus/C3/SeqPart11.lean delete mode 100644 SolidCore/Refinement/Corpus/C3/SeqPart12.lean delete mode 100644 SolidCore/Refinement/Corpus/C3/SeqPart13.lean delete mode 100644 SolidCore/Refinement/Corpus/C3/SeqPart14.lean delete mode 100644 SolidCore/Refinement/Corpus/C3/SeqPart15.lean delete mode 100644 SolidCore/Refinement/Corpus/C3/SeqPart2.lean delete mode 100644 SolidCore/Refinement/Corpus/C3/SeqPart3.lean delete mode 100644 SolidCore/Refinement/Corpus/C3/SeqPart4.lean delete mode 100644 SolidCore/Refinement/Corpus/C3/SeqPart5.lean delete mode 100644 SolidCore/Refinement/Corpus/C3/SeqPart6.lean delete mode 100644 SolidCore/Refinement/Corpus/C3/SeqPart7.lean delete mode 100644 SolidCore/Refinement/Corpus/C3/SeqPart8.lean delete mode 100644 SolidCore/Refinement/Corpus/C3/SeqPart9.lean delete mode 100644 SolidCore/Refinement/Corpus/C3/SeqStates.lean delete mode 100644 SolidCore/Refinement/Corpus/C5.lean delete mode 100644 SolidCore/Refinement/Corpus/C5/Defs.lean delete mode 100644 SolidCore/Refinement/Corpus/C5/Dirty.lean delete mode 100644 SolidCore/Refinement/Corpus/C5/Part0.lean delete mode 100644 SolidCore/Refinement/Corpus/C5/Seq.lean delete mode 100644 SolidCore/Refinement/Corpus/C5/SeqDefs.lean delete mode 100644 SolidCore/Refinement/Corpus/C5/SeqPart0.lean delete mode 100644 SolidCore/Refinement/Corpus/C5/SeqPart1.lean delete mode 100644 SolidCore/Refinement/Corpus/C5/SeqPart10.lean delete mode 100644 SolidCore/Refinement/Corpus/C5/SeqPart11.lean delete mode 100644 SolidCore/Refinement/Corpus/C5/SeqPart12.lean delete mode 100644 SolidCore/Refinement/Corpus/C5/SeqPart13.lean delete mode 100644 SolidCore/Refinement/Corpus/C5/SeqPart14.lean delete mode 100644 SolidCore/Refinement/Corpus/C5/SeqPart15.lean delete mode 100644 SolidCore/Refinement/Corpus/C5/SeqPart16.lean delete mode 100644 SolidCore/Refinement/Corpus/C5/SeqPart2.lean delete mode 100644 SolidCore/Refinement/Corpus/C5/SeqPart3.lean delete mode 100644 SolidCore/Refinement/Corpus/C5/SeqPart4.lean delete mode 100644 SolidCore/Refinement/Corpus/C5/SeqPart5.lean delete mode 100644 SolidCore/Refinement/Corpus/C5/SeqPart6.lean delete mode 100644 SolidCore/Refinement/Corpus/C5/SeqPart7.lean delete mode 100644 SolidCore/Refinement/Corpus/C5/SeqPart8.lean delete mode 100644 SolidCore/Refinement/Corpus/C5/SeqPart9.lean delete mode 100644 SolidCore/Refinement/Corpus/C5/SeqStates.lean delete mode 100644 SolidCore/Refinement/Corpus/C6.lean delete mode 100644 SolidCore/Refinement/Corpus/C6/Defs.lean delete mode 100644 SolidCore/Refinement/Corpus/C6/Dirty.lean delete mode 100644 SolidCore/Refinement/Corpus/C6/Part0.lean delete mode 100644 SolidCore/Refinement/Corpus/C6/Seq.lean delete mode 100644 SolidCore/Refinement/Corpus/C6/SeqDefs.lean delete mode 100644 SolidCore/Refinement/Corpus/C6/SeqPart0.lean delete mode 100644 SolidCore/Refinement/Corpus/C6/SeqStates.lean delete mode 100644 SolidCore/Refinement/Corpus/C7.lean delete mode 100644 SolidCore/Refinement/Corpus/C7/Defs.lean delete mode 100644 SolidCore/Refinement/Corpus/C7/Dirty.lean delete mode 100644 SolidCore/Refinement/Corpus/C7/Part0.lean delete mode 100644 SolidCore/Refinement/Corpus/C7/Seq.lean delete mode 100644 SolidCore/Refinement/Corpus/C7/SeqDefs.lean delete mode 100644 SolidCore/Refinement/Corpus/C7/SeqPart0.lean delete mode 100644 SolidCore/Refinement/Corpus/C7/SeqStates.lean delete mode 100644 SolidCore/Refinement/Corpus/C8.lean delete mode 100644 SolidCore/Refinement/Corpus/C8/Defs.lean delete mode 100644 SolidCore/Refinement/Corpus/C8/Dirty.lean delete mode 100644 SolidCore/Refinement/Corpus/C8/Part0.lean delete mode 100644 SolidCore/Refinement/Corpus/C8/Seq.lean delete mode 100644 SolidCore/Refinement/Corpus/C8/SeqDefs.lean delete mode 100644 SolidCore/Refinement/Corpus/C8/SeqPart0.lean delete mode 100644 SolidCore/Refinement/Corpus/C8/SeqStates.lean delete mode 100644 SolidCore/Refinement/Corpus/C9.lean delete mode 100644 SolidCore/Refinement/Corpus/C9/Defs.lean delete mode 100644 SolidCore/Refinement/Corpus/C9/Dirty.lean delete mode 100644 SolidCore/Refinement/Corpus/C9/Part0.lean delete mode 100644 SolidCore/Refinement/Corpus/C9/Seq.lean delete mode 100644 SolidCore/Refinement/Corpus/C9/SeqDefs.lean delete mode 100644 SolidCore/Refinement/Corpus/C9/SeqPart0.lean delete mode 100644 SolidCore/Refinement/Corpus/C9/SeqPart1.lean delete mode 100644 SolidCore/Refinement/Corpus/C9/SeqPart10.lean delete mode 100644 SolidCore/Refinement/Corpus/C9/SeqPart11.lean delete mode 100644 SolidCore/Refinement/Corpus/C9/SeqPart12.lean delete mode 100644 SolidCore/Refinement/Corpus/C9/SeqPart13.lean delete mode 100644 SolidCore/Refinement/Corpus/C9/SeqPart14.lean delete mode 100644 SolidCore/Refinement/Corpus/C9/SeqPart15.lean delete mode 100644 SolidCore/Refinement/Corpus/C9/SeqPart16.lean delete mode 100644 SolidCore/Refinement/Corpus/C9/SeqPart2.lean delete mode 100644 SolidCore/Refinement/Corpus/C9/SeqPart3.lean delete mode 100644 SolidCore/Refinement/Corpus/C9/SeqPart4.lean delete mode 100644 SolidCore/Refinement/Corpus/C9/SeqPart5.lean delete mode 100644 SolidCore/Refinement/Corpus/C9/SeqPart6.lean delete mode 100644 SolidCore/Refinement/Corpus/C9/SeqPart7.lean delete mode 100644 SolidCore/Refinement/Corpus/C9/SeqPart8.lean delete mode 100644 SolidCore/Refinement/Corpus/C9/SeqPart9.lean delete mode 100644 SolidCore/Refinement/Corpus/C9/SeqStates.lean delete mode 100644 SolidCore/Refinement/Corpus/D1.lean delete mode 100644 SolidCore/Refinement/Corpus/D1/Defs.lean delete mode 100644 SolidCore/Refinement/Corpus/D1/Malformed.lean delete mode 100644 SolidCore/Refinement/Corpus/D1/Part0.lean delete mode 100644 SolidCore/Refinement/Corpus/D1/Part1.lean delete mode 100644 SolidCore/Refinement/Corpus/D1/Part10.lean delete mode 100644 SolidCore/Refinement/Corpus/D1/Part11.lean delete mode 100644 SolidCore/Refinement/Corpus/D1/Part12.lean delete mode 100644 SolidCore/Refinement/Corpus/D1/Part13.lean delete mode 100644 SolidCore/Refinement/Corpus/D1/Part14.lean delete mode 100644 SolidCore/Refinement/Corpus/D1/Part15.lean delete mode 100644 SolidCore/Refinement/Corpus/D1/Part16.lean delete mode 100644 SolidCore/Refinement/Corpus/D1/Part2.lean delete mode 100644 SolidCore/Refinement/Corpus/D1/Part3.lean delete mode 100644 SolidCore/Refinement/Corpus/D1/Part4.lean delete mode 100644 SolidCore/Refinement/Corpus/D1/Part5.lean delete mode 100644 SolidCore/Refinement/Corpus/D1/Part6.lean delete mode 100644 SolidCore/Refinement/Corpus/D1/Part7.lean delete mode 100644 SolidCore/Refinement/Corpus/D1/Part8.lean delete mode 100644 SolidCore/Refinement/Corpus/D1/Part9.lean delete mode 100644 SolidCore/Refinement/Corpus/D2.lean delete mode 100644 SolidCore/Refinement/Corpus/D2/Defs.lean delete mode 100644 SolidCore/Refinement/Corpus/D2/Malformed.lean delete mode 100644 SolidCore/Refinement/Corpus/D2/Part0.lean delete mode 100644 SolidCore/Refinement/Corpus/D2/Part1.lean delete mode 100644 SolidCore/Refinement/Corpus/D2/Part10.lean delete mode 100644 SolidCore/Refinement/Corpus/D2/Part11.lean delete mode 100644 SolidCore/Refinement/Corpus/D2/Part12.lean delete mode 100644 SolidCore/Refinement/Corpus/D2/Part13.lean delete mode 100644 SolidCore/Refinement/Corpus/D2/Part14.lean delete mode 100644 SolidCore/Refinement/Corpus/D2/Part15.lean delete mode 100644 SolidCore/Refinement/Corpus/D2/Part16.lean delete mode 100644 SolidCore/Refinement/Corpus/D2/Part2.lean delete mode 100644 SolidCore/Refinement/Corpus/D2/Part3.lean delete mode 100644 SolidCore/Refinement/Corpus/D2/Part4.lean delete mode 100644 SolidCore/Refinement/Corpus/D2/Part5.lean delete mode 100644 SolidCore/Refinement/Corpus/D2/Part6.lean delete mode 100644 SolidCore/Refinement/Corpus/D2/Part7.lean delete mode 100644 SolidCore/Refinement/Corpus/D2/Part8.lean delete mode 100644 SolidCore/Refinement/Corpus/D2/Part9.lean delete mode 100644 SolidCore/Refinement/Corpus/D3.lean delete mode 100644 SolidCore/Refinement/Corpus/D3/Defs.lean delete mode 100644 SolidCore/Refinement/Corpus/D3/Malformed.lean delete mode 100644 SolidCore/Refinement/Corpus/D3/Part0.lean delete mode 100644 SolidCore/Refinement/Corpus/D4.lean delete mode 100644 SolidCore/Refinement/Corpus/D4/Defs.lean delete mode 100644 SolidCore/Refinement/Corpus/D4/Malformed.lean delete mode 100644 SolidCore/Refinement/Corpus/D4/Part0.lean delete mode 100644 SolidCore/Refinement/Corpus/W2.lean delete mode 100644 SolidCore/Refinement/Corpus/W3.lean create mode 100644 SolidCore/Refinement/Solar/AssembleStackN.lean delete mode 100644 SolidCore/Verify.lean delete mode 100644 SolidCore/Verify/Abi.lean delete mode 100644 SolidCore/Verify/Basic.lean delete mode 100644 SolidCore/Verify/C1.lean delete mode 100644 SolidCore/Verify/C4.lean delete mode 100644 SolidCore/Verify/Finite.lean delete mode 100644 SolidCore/Verify/Run.lean delete mode 100644 SolidCore/Verify/Tactic.lean delete mode 100644 SolidCore/Verify/W1.lean delete mode 100644 SolidCore/Verify/W4.lean delete mode 100644 SolidCore/Verify/W5.lean diff --git a/SolidCore/Refinement/Axioms/Contracts.lean b/SolidCore/Refinement/Axioms/Contracts.lean new file mode 100644 index 00000000..36ec5005 --- /dev/null +++ b/SolidCore/Refinement/Axioms/Contracts.lean @@ -0,0 +1,39 @@ +import SolidCore.Refinement.Axioms.Audit +import Contracts.Counter.Headline +import Contracts.Counter.EndToEnd +import Contracts.Counter.Final +import Contracts.Counter.Verdict +import Contracts.Counter.VC.Inc +import Contracts.Counter.VC.Get +import Contracts.Counter.VC.Mutants +import Contracts.Token.VC.Burn +import Contracts.Token.VC.Transfer +import Contracts.Token.VC.Mutants +import Verify.LoomAxioms +import Verify.Spec.TrustedBase.Axioms + +/-! Axiom pass, part 6: the per-contract headlines under Contracts/ (Counter from source spec to +solar's bytecode, and the Counter and Token verification conditions), with the Loom and trusted +base pieces they build on. Every `#print axioms` below must report a subset of [propext, +Classical.choice, Quot.sound], and the sweep must report no violation. Run with +`scripts/refinement/axiom-audit.sh`. -/ + +-- Counter, source spec to bytecode. +#print axioms SolidCore.Refinement.Solar.Counter.Headline.spec_holds_of_bytecode +#print axioms SolidCore.Refinement.Solar.Counter.Headline.wrong_fails +#print axioms SolidCore.Refinement.Solar.Counter.EndToEnd.inc_spec_bytecode +#print axioms SolidCore.Refinement.Solar.Counter.EndToEnd.get_spec_bytecode +#print axioms SolidCore.Refinement.Solar.Counter.Final.certified +#print axioms SolidCore.Refinement.Solar.Counter.Final.certified_trace +#print axioms SolidCore.Refinement.Solar.Counter.Verdict.bytecode_spec_of_verdict +#print axioms SolidCore.Refinement.Solar.Counter.Verdict.bytecode_of_triple + +-- Verification conditions. +#print axioms SolidCore.Verify.VC.Counter.inc_triple +#print axioms SolidCore.Verify.VC.Counter.get_triple +#print axioms SolidCore.Verify.VC.Counter.srcMut_rejected +#print axioms SolidCore.Verify.VC.Counter.specMut_rejected +#print axioms SolidCore.Verify.VC.Token.burn_triple +#print axioms SolidCore.Verify.VC.Token.transfer_triple + +#axiom_audit ".lake/axiom-closure-contracts.txt" "Contracts" "Verify" "Loom" diff --git a/SolidCore/Refinement/Corpus/B1.lean b/SolidCore/Refinement/Corpus/B1.lean deleted file mode 100644 index 6aeff9bf..00000000 --- a/SolidCore/Refinement/Corpus/B1.lean +++ /dev/null @@ -1,65 +0,0 @@ --- 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 deleted file mode 100644 index ab3ab946..00000000 --- a/SolidCore/Refinement/Corpus/B1/Defs.lean +++ /dev/null @@ -1,50 +0,0 @@ --- 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 deleted file mode 100644 index 3b1d510f..00000000 --- a/SolidCore/Refinement/Corpus/B1/Dirty.lean +++ /dev/null @@ -1,31 +0,0 @@ --- 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 deleted file mode 100644 index e83ad1ca..00000000 --- a/SolidCore/Refinement/Corpus/B1/Part0.lean +++ /dev/null @@ -1,9 +0,0 @@ --- 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 deleted file mode 100644 index 87337af8..00000000 --- a/SolidCore/Refinement/Corpus/B1/Seq.lean +++ /dev/null @@ -1,54 +0,0 @@ --- 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 deleted file mode 100644 index b9d33049..00000000 --- a/SolidCore/Refinement/Corpus/B1/SeqDefs.lean +++ /dev/null @@ -1,59 +0,0 @@ --- 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 deleted file mode 100644 index b0bf68e4..00000000 --- a/SolidCore/Refinement/Corpus/B1/SeqPart0.lean +++ /dev/null @@ -1,9 +0,0 @@ --- 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 deleted file mode 100644 index 4987bb32..00000000 --- a/SolidCore/Refinement/Corpus/B1/SeqStates.lean +++ /dev/null @@ -1,22 +0,0 @@ --- 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 deleted file mode 100644 index 931f5e08..00000000 --- a/SolidCore/Refinement/Corpus/B2.lean +++ /dev/null @@ -1,65 +0,0 @@ --- 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 deleted file mode 100644 index b842e35c..00000000 --- a/SolidCore/Refinement/Corpus/B2/Defs.lean +++ /dev/null @@ -1,50 +0,0 @@ --- 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 deleted file mode 100644 index a94a4350..00000000 --- a/SolidCore/Refinement/Corpus/B2/Dirty.lean +++ /dev/null @@ -1,31 +0,0 @@ --- 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 deleted file mode 100644 index b186026e..00000000 --- a/SolidCore/Refinement/Corpus/B2/Part0.lean +++ /dev/null @@ -1,9 +0,0 @@ --- 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 deleted file mode 100644 index 76c4a007..00000000 --- a/SolidCore/Refinement/Corpus/B2/Seq.lean +++ /dev/null @@ -1,54 +0,0 @@ --- 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 deleted file mode 100644 index 633d7428..00000000 --- a/SolidCore/Refinement/Corpus/B2/SeqDefs.lean +++ /dev/null @@ -1,59 +0,0 @@ --- 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 deleted file mode 100644 index aaf5e8ec..00000000 --- a/SolidCore/Refinement/Corpus/B2/SeqPart0.lean +++ /dev/null @@ -1,9 +0,0 @@ --- 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 deleted file mode 100644 index edf01854..00000000 --- a/SolidCore/Refinement/Corpus/B2/SeqStates.lean +++ /dev/null @@ -1,23 +0,0 @@ --- 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 deleted file mode 100644 index a92a71c3..00000000 --- a/SolidCore/Refinement/Corpus/B3.lean +++ /dev/null @@ -1,65 +0,0 @@ --- 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 deleted file mode 100644 index 395c144b..00000000 --- a/SolidCore/Refinement/Corpus/B3/Defs.lean +++ /dev/null @@ -1,50 +0,0 @@ --- 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 deleted file mode 100644 index e50c6520..00000000 --- a/SolidCore/Refinement/Corpus/B3/Dirty.lean +++ /dev/null @@ -1,31 +0,0 @@ --- 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 deleted file mode 100644 index cf034674..00000000 --- a/SolidCore/Refinement/Corpus/B3/Part0.lean +++ /dev/null @@ -1,9 +0,0 @@ --- 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 deleted file mode 100644 index 274049d4..00000000 --- a/SolidCore/Refinement/Corpus/B3/Seq.lean +++ /dev/null @@ -1,54 +0,0 @@ --- 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 deleted file mode 100644 index 3a47d79c..00000000 --- a/SolidCore/Refinement/Corpus/B3/SeqDefs.lean +++ /dev/null @@ -1,59 +0,0 @@ --- 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 deleted file mode 100644 index 215e1b58..00000000 --- a/SolidCore/Refinement/Corpus/B3/SeqPart0.lean +++ /dev/null @@ -1,9 +0,0 @@ --- 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 deleted file mode 100644 index 295b3dc5..00000000 --- a/SolidCore/Refinement/Corpus/B3/SeqStates.lean +++ /dev/null @@ -1,21 +0,0 @@ --- 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 deleted file mode 100644 index 8976af3b..00000000 --- a/SolidCore/Refinement/Corpus/B4.lean +++ /dev/null @@ -1,65 +0,0 @@ --- 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 deleted file mode 100644 index a83ef5ce..00000000 --- a/SolidCore/Refinement/Corpus/B4/Defs.lean +++ /dev/null @@ -1,50 +0,0 @@ --- 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 deleted file mode 100644 index 56a976eb..00000000 --- a/SolidCore/Refinement/Corpus/B4/Dirty.lean +++ /dev/null @@ -1,31 +0,0 @@ --- 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 deleted file mode 100644 index ebc706a5..00000000 --- a/SolidCore/Refinement/Corpus/B4/Part0.lean +++ /dev/null @@ -1,9 +0,0 @@ --- 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 deleted file mode 100644 index 9405548d..00000000 --- a/SolidCore/Refinement/Corpus/B4/Seq.lean +++ /dev/null @@ -1,54 +0,0 @@ --- 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 deleted file mode 100644 index 730f635c..00000000 --- a/SolidCore/Refinement/Corpus/B4/SeqDefs.lean +++ /dev/null @@ -1,59 +0,0 @@ --- 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 deleted file mode 100644 index 9019c4e6..00000000 --- a/SolidCore/Refinement/Corpus/B4/SeqPart0.lean +++ /dev/null @@ -1,9 +0,0 @@ --- 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 deleted file mode 100644 index 8a2367bc..00000000 --- a/SolidCore/Refinement/Corpus/B4/SeqStates.lean +++ /dev/null @@ -1,21 +0,0 @@ --- 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 deleted file mode 100644 index 312e0342..00000000 --- a/SolidCore/Refinement/Corpus/B5.lean +++ /dev/null @@ -1,65 +0,0 @@ --- 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 deleted file mode 100644 index 24157132..00000000 --- a/SolidCore/Refinement/Corpus/B5/Defs.lean +++ /dev/null @@ -1,50 +0,0 @@ --- 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 deleted file mode 100644 index 93bbe297..00000000 --- a/SolidCore/Refinement/Corpus/B5/Dirty.lean +++ /dev/null @@ -1,31 +0,0 @@ --- 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 deleted file mode 100644 index b47172d6..00000000 --- a/SolidCore/Refinement/Corpus/B5/Part0.lean +++ /dev/null @@ -1,9 +0,0 @@ --- 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 deleted file mode 100644 index 585feee6..00000000 --- a/SolidCore/Refinement/Corpus/B5/Seq.lean +++ /dev/null @@ -1,54 +0,0 @@ --- 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 deleted file mode 100644 index 1e64e3dc..00000000 --- a/SolidCore/Refinement/Corpus/B5/SeqDefs.lean +++ /dev/null @@ -1,59 +0,0 @@ --- 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 deleted file mode 100644 index 09d36a82..00000000 --- a/SolidCore/Refinement/Corpus/B5/SeqPart0.lean +++ /dev/null @@ -1,9 +0,0 @@ --- 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 deleted file mode 100644 index 5887804e..00000000 --- a/SolidCore/Refinement/Corpus/B5/SeqStates.lean +++ /dev/null @@ -1,22 +0,0 @@ --- 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 deleted file mode 100644 index bbff2d58..00000000 --- a/SolidCore/Refinement/Corpus/B6.lean +++ /dev/null @@ -1,65 +0,0 @@ --- 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 deleted file mode 100644 index d7e06a94..00000000 --- a/SolidCore/Refinement/Corpus/B6/Defs.lean +++ /dev/null @@ -1,50 +0,0 @@ --- 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 deleted file mode 100644 index beede472..00000000 --- a/SolidCore/Refinement/Corpus/B6/Dirty.lean +++ /dev/null @@ -1,31 +0,0 @@ --- 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 deleted file mode 100644 index 53808cb2..00000000 --- a/SolidCore/Refinement/Corpus/B6/Part0.lean +++ /dev/null @@ -1,9 +0,0 @@ --- 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 deleted file mode 100644 index fbc09862..00000000 --- a/SolidCore/Refinement/Corpus/B6/Seq.lean +++ /dev/null @@ -1,54 +0,0 @@ --- 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 deleted file mode 100644 index 74e1ee39..00000000 --- a/SolidCore/Refinement/Corpus/B6/SeqDefs.lean +++ /dev/null @@ -1,59 +0,0 @@ --- 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 deleted file mode 100644 index 879b8f0d..00000000 --- a/SolidCore/Refinement/Corpus/B6/SeqPart0.lean +++ /dev/null @@ -1,9 +0,0 @@ --- 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 deleted file mode 100644 index 9d530d6f..00000000 --- a/SolidCore/Refinement/Corpus/B6/SeqStates.lean +++ /dev/null @@ -1,22 +0,0 @@ --- 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 deleted file mode 100644 index db5f5139..00000000 --- a/SolidCore/Refinement/Corpus/B7.lean +++ /dev/null @@ -1,65 +0,0 @@ --- 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 deleted file mode 100644 index a3462a48..00000000 --- a/SolidCore/Refinement/Corpus/B7/Defs.lean +++ /dev/null @@ -1,50 +0,0 @@ --- 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 deleted file mode 100644 index 64416e9f..00000000 --- a/SolidCore/Refinement/Corpus/B7/Dirty.lean +++ /dev/null @@ -1,31 +0,0 @@ --- 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 deleted file mode 100644 index c2fe0de9..00000000 --- a/SolidCore/Refinement/Corpus/B7/Part0.lean +++ /dev/null @@ -1,9 +0,0 @@ --- 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 deleted file mode 100644 index b9c490a1..00000000 --- a/SolidCore/Refinement/Corpus/B7/Seq.lean +++ /dev/null @@ -1,54 +0,0 @@ --- 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 deleted file mode 100644 index eec0010b..00000000 --- a/SolidCore/Refinement/Corpus/B7/SeqDefs.lean +++ /dev/null @@ -1,59 +0,0 @@ --- 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 deleted file mode 100644 index 65e41f34..00000000 --- a/SolidCore/Refinement/Corpus/B7/SeqPart0.lean +++ /dev/null @@ -1,9 +0,0 @@ --- 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 deleted file mode 100644 index 20c4b06b..00000000 --- a/SolidCore/Refinement/Corpus/B7/SeqStates.lean +++ /dev/null @@ -1,22 +0,0 @@ --- 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/C10.lean b/SolidCore/Refinement/Corpus/C10.lean deleted file mode 100644 index d03f7760..00000000 --- a/SolidCore/Refinement/Corpus/C10.lean +++ /dev/null @@ -1,65 +0,0 @@ --- 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 deleted file mode 100644 index 71259346..00000000 --- a/SolidCore/Refinement/Corpus/C10/Defs.lean +++ /dev/null @@ -1,50 +0,0 @@ --- 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 deleted file mode 100644 index f5bc973d..00000000 --- a/SolidCore/Refinement/Corpus/C10/Dirty.lean +++ /dev/null @@ -1,31 +0,0 @@ --- 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 deleted file mode 100644 index a23dadc2..00000000 --- a/SolidCore/Refinement/Corpus/C10/Part0.lean +++ /dev/null @@ -1,9 +0,0 @@ --- 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 deleted file mode 100644 index 3421d89d..00000000 --- a/SolidCore/Refinement/Corpus/C10/Seq.lean +++ /dev/null @@ -1,54 +0,0 @@ --- 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 deleted file mode 100644 index fdc02484..00000000 --- a/SolidCore/Refinement/Corpus/C10/SeqDefs.lean +++ /dev/null @@ -1,59 +0,0 @@ --- 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 deleted file mode 100644 index 1e8592d6..00000000 --- a/SolidCore/Refinement/Corpus/C10/SeqPart0.lean +++ /dev/null @@ -1,9 +0,0 @@ --- 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 deleted file mode 100644 index 6554737f..00000000 --- a/SolidCore/Refinement/Corpus/C10/SeqStates.lean +++ /dev/null @@ -1,21 +0,0 @@ --- 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 deleted file mode 100644 index 0ce147e1..00000000 --- a/SolidCore/Refinement/Corpus/C11.lean +++ /dev/null @@ -1,65 +0,0 @@ --- 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 deleted file mode 100644 index ed113032..00000000 --- a/SolidCore/Refinement/Corpus/C11/Defs.lean +++ /dev/null @@ -1,50 +0,0 @@ --- 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 deleted file mode 100644 index 90c9037f..00000000 --- a/SolidCore/Refinement/Corpus/C11/Dirty.lean +++ /dev/null @@ -1,31 +0,0 @@ --- 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 deleted file mode 100644 index 4b00dcbc..00000000 --- a/SolidCore/Refinement/Corpus/C11/Part0.lean +++ /dev/null @@ -1,9 +0,0 @@ --- 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 deleted file mode 100644 index 1f511eac..00000000 --- a/SolidCore/Refinement/Corpus/C11/Seq.lean +++ /dev/null @@ -1,54 +0,0 @@ --- 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 deleted file mode 100644 index 444e9749..00000000 --- a/SolidCore/Refinement/Corpus/C11/SeqDefs.lean +++ /dev/null @@ -1,59 +0,0 @@ --- 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 deleted file mode 100644 index 76c9b5d9..00000000 --- a/SolidCore/Refinement/Corpus/C11/SeqPart0.lean +++ /dev/null @@ -1,9 +0,0 @@ --- 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 deleted file mode 100644 index e8e2628f..00000000 --- a/SolidCore/Refinement/Corpus/C11/SeqStates.lean +++ /dev/null @@ -1,21 +0,0 @@ --- 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 deleted file mode 100644 index ebfbfdcd..00000000 --- a/SolidCore/Refinement/Corpus/C2.lean +++ /dev/null @@ -1,95 +0,0 @@ --- 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 deleted file mode 100644 index c8b5a729..00000000 --- a/SolidCore/Refinement/Corpus/C2/Defs.lean +++ /dev/null @@ -1,50 +0,0 @@ --- 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 deleted file mode 100644 index ccd032b8..00000000 --- a/SolidCore/Refinement/Corpus/C2/Dirty.lean +++ /dev/null @@ -1,31 +0,0 @@ --- 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 deleted file mode 100644 index d497c42c..00000000 --- a/SolidCore/Refinement/Corpus/C2/Part0.lean +++ /dev/null @@ -1,9 +0,0 @@ --- 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 deleted file mode 100644 index 7f9d240c..00000000 --- a/SolidCore/Refinement/Corpus/C2/Part1.lean +++ /dev/null @@ -1,9 +0,0 @@ --- 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 deleted file mode 100644 index bc1f9ed0..00000000 --- a/SolidCore/Refinement/Corpus/C2/Part10.lean +++ /dev/null @@ -1,9 +0,0 @@ --- 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 deleted file mode 100644 index 688c8311..00000000 --- a/SolidCore/Refinement/Corpus/C2/Part11.lean +++ /dev/null @@ -1,9 +0,0 @@ --- 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 deleted file mode 100644 index 64b66795..00000000 --- a/SolidCore/Refinement/Corpus/C2/Part12.lean +++ /dev/null @@ -1,9 +0,0 @@ --- 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 deleted file mode 100644 index e4efe2fa..00000000 --- a/SolidCore/Refinement/Corpus/C2/Part13.lean +++ /dev/null @@ -1,9 +0,0 @@ --- 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 deleted file mode 100644 index 520f44dd..00000000 --- a/SolidCore/Refinement/Corpus/C2/Part14.lean +++ /dev/null @@ -1,9 +0,0 @@ --- 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 deleted file mode 100644 index f5e7642d..00000000 --- a/SolidCore/Refinement/Corpus/C2/Part15.lean +++ /dev/null @@ -1,9 +0,0 @@ --- 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 deleted file mode 100644 index 1492cd3b..00000000 --- a/SolidCore/Refinement/Corpus/C2/Part2.lean +++ /dev/null @@ -1,9 +0,0 @@ --- 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 deleted file mode 100644 index 189c8894..00000000 --- a/SolidCore/Refinement/Corpus/C2/Part3.lean +++ /dev/null @@ -1,9 +0,0 @@ --- 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 deleted file mode 100644 index 09d0fbd7..00000000 --- a/SolidCore/Refinement/Corpus/C2/Part4.lean +++ /dev/null @@ -1,9 +0,0 @@ --- 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 deleted file mode 100644 index e2ce9248..00000000 --- a/SolidCore/Refinement/Corpus/C2/Part5.lean +++ /dev/null @@ -1,9 +0,0 @@ --- 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 deleted file mode 100644 index 6ce43a04..00000000 --- a/SolidCore/Refinement/Corpus/C2/Part6.lean +++ /dev/null @@ -1,9 +0,0 @@ --- 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 deleted file mode 100644 index 24d0f533..00000000 --- a/SolidCore/Refinement/Corpus/C2/Part7.lean +++ /dev/null @@ -1,9 +0,0 @@ --- 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 deleted file mode 100644 index 043cabe7..00000000 --- a/SolidCore/Refinement/Corpus/C2/Part8.lean +++ /dev/null @@ -1,9 +0,0 @@ --- 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 deleted file mode 100644 index a3e82f9e..00000000 --- a/SolidCore/Refinement/Corpus/C2/Part9.lean +++ /dev/null @@ -1,9 +0,0 @@ --- 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 deleted file mode 100644 index 1114e146..00000000 --- a/SolidCore/Refinement/Corpus/C2/Seq.lean +++ /dev/null @@ -1,84 +0,0 @@ --- 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 deleted file mode 100644 index 72327ac0..00000000 --- a/SolidCore/Refinement/Corpus/C2/SeqDefs.lean +++ /dev/null @@ -1,59 +0,0 @@ --- 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 deleted file mode 100644 index 30a2dbce..00000000 --- a/SolidCore/Refinement/Corpus/C2/SeqPart0.lean +++ /dev/null @@ -1,9 +0,0 @@ --- 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 deleted file mode 100644 index ad396bda..00000000 --- a/SolidCore/Refinement/Corpus/C2/SeqPart1.lean +++ /dev/null @@ -1,9 +0,0 @@ --- 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 deleted file mode 100644 index aa86436f..00000000 --- a/SolidCore/Refinement/Corpus/C2/SeqPart10.lean +++ /dev/null @@ -1,9 +0,0 @@ --- 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 deleted file mode 100644 index 8851a270..00000000 --- a/SolidCore/Refinement/Corpus/C2/SeqPart11.lean +++ /dev/null @@ -1,9 +0,0 @@ --- 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 deleted file mode 100644 index e1727504..00000000 --- a/SolidCore/Refinement/Corpus/C2/SeqPart12.lean +++ /dev/null @@ -1,9 +0,0 @@ --- 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 deleted file mode 100644 index a09cb6e1..00000000 --- a/SolidCore/Refinement/Corpus/C2/SeqPart13.lean +++ /dev/null @@ -1,9 +0,0 @@ --- 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 deleted file mode 100644 index f40dfe1c..00000000 --- a/SolidCore/Refinement/Corpus/C2/SeqPart14.lean +++ /dev/null @@ -1,9 +0,0 @@ --- 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 deleted file mode 100644 index d5cf0d81..00000000 --- a/SolidCore/Refinement/Corpus/C2/SeqPart15.lean +++ /dev/null @@ -1,9 +0,0 @@ --- 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 deleted file mode 100644 index 4e9fa528..00000000 --- a/SolidCore/Refinement/Corpus/C2/SeqPart2.lean +++ /dev/null @@ -1,9 +0,0 @@ --- 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 deleted file mode 100644 index 89d30db5..00000000 --- a/SolidCore/Refinement/Corpus/C2/SeqPart3.lean +++ /dev/null @@ -1,9 +0,0 @@ --- 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 deleted file mode 100644 index 7004e6c5..00000000 --- a/SolidCore/Refinement/Corpus/C2/SeqPart4.lean +++ /dev/null @@ -1,9 +0,0 @@ --- 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 deleted file mode 100644 index f8af8c8f..00000000 --- a/SolidCore/Refinement/Corpus/C2/SeqPart5.lean +++ /dev/null @@ -1,9 +0,0 @@ --- 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 deleted file mode 100644 index 230a765c..00000000 --- a/SolidCore/Refinement/Corpus/C2/SeqPart6.lean +++ /dev/null @@ -1,9 +0,0 @@ --- 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 deleted file mode 100644 index e991492e..00000000 --- a/SolidCore/Refinement/Corpus/C2/SeqPart7.lean +++ /dev/null @@ -1,9 +0,0 @@ --- 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 deleted file mode 100644 index 04ed66f0..00000000 --- a/SolidCore/Refinement/Corpus/C2/SeqPart8.lean +++ /dev/null @@ -1,9 +0,0 @@ --- 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 deleted file mode 100644 index 3f9348ad..00000000 --- a/SolidCore/Refinement/Corpus/C2/SeqPart9.lean +++ /dev/null @@ -1,9 +0,0 @@ --- 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 deleted file mode 100644 index 66108c4f..00000000 --- a/SolidCore/Refinement/Corpus/C2/SeqStates.lean +++ /dev/null @@ -1,21 +0,0 @@ --- 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 deleted file mode 100644 index 16a4a01e..00000000 --- a/SolidCore/Refinement/Corpus/C3.lean +++ /dev/null @@ -1,95 +0,0 @@ --- 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 deleted file mode 100644 index 3b234adb..00000000 --- a/SolidCore/Refinement/Corpus/C3/Defs.lean +++ /dev/null @@ -1,50 +0,0 @@ --- 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 deleted file mode 100644 index 787d4c50..00000000 --- a/SolidCore/Refinement/Corpus/C3/Dirty.lean +++ /dev/null @@ -1,31 +0,0 @@ --- 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 deleted file mode 100644 index ac3cd274..00000000 --- a/SolidCore/Refinement/Corpus/C3/Part0.lean +++ /dev/null @@ -1,9 +0,0 @@ --- 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 deleted file mode 100644 index f7abc7fe..00000000 --- a/SolidCore/Refinement/Corpus/C3/Part1.lean +++ /dev/null @@ -1,9 +0,0 @@ --- 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 deleted file mode 100644 index 486867eb..00000000 --- a/SolidCore/Refinement/Corpus/C3/Part10.lean +++ /dev/null @@ -1,9 +0,0 @@ --- 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 deleted file mode 100644 index 75d6046b..00000000 --- a/SolidCore/Refinement/Corpus/C3/Part11.lean +++ /dev/null @@ -1,9 +0,0 @@ --- 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 deleted file mode 100644 index bec2d51a..00000000 --- a/SolidCore/Refinement/Corpus/C3/Part12.lean +++ /dev/null @@ -1,9 +0,0 @@ --- 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 deleted file mode 100644 index 15e8f079..00000000 --- a/SolidCore/Refinement/Corpus/C3/Part13.lean +++ /dev/null @@ -1,9 +0,0 @@ --- 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 deleted file mode 100644 index a278da8e..00000000 --- a/SolidCore/Refinement/Corpus/C3/Part14.lean +++ /dev/null @@ -1,9 +0,0 @@ --- 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 deleted file mode 100644 index d6cd500f..00000000 --- a/SolidCore/Refinement/Corpus/C3/Part15.lean +++ /dev/null @@ -1,9 +0,0 @@ --- 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 deleted file mode 100644 index f552840d..00000000 --- a/SolidCore/Refinement/Corpus/C3/Part2.lean +++ /dev/null @@ -1,9 +0,0 @@ --- 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 deleted file mode 100644 index a5ca39e6..00000000 --- a/SolidCore/Refinement/Corpus/C3/Part3.lean +++ /dev/null @@ -1,9 +0,0 @@ --- 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 deleted file mode 100644 index 8f675648..00000000 --- a/SolidCore/Refinement/Corpus/C3/Part4.lean +++ /dev/null @@ -1,9 +0,0 @@ --- 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 deleted file mode 100644 index 226cbfc7..00000000 --- a/SolidCore/Refinement/Corpus/C3/Part5.lean +++ /dev/null @@ -1,9 +0,0 @@ --- 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 deleted file mode 100644 index 93ddb00d..00000000 --- a/SolidCore/Refinement/Corpus/C3/Part6.lean +++ /dev/null @@ -1,9 +0,0 @@ --- 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 deleted file mode 100644 index 0008c4f3..00000000 --- a/SolidCore/Refinement/Corpus/C3/Part7.lean +++ /dev/null @@ -1,9 +0,0 @@ --- 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 deleted file mode 100644 index 3f2026cb..00000000 --- a/SolidCore/Refinement/Corpus/C3/Part8.lean +++ /dev/null @@ -1,9 +0,0 @@ --- 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 deleted file mode 100644 index 38d7761c..00000000 --- a/SolidCore/Refinement/Corpus/C3/Part9.lean +++ /dev/null @@ -1,9 +0,0 @@ --- 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 deleted file mode 100644 index c514cc6f..00000000 --- a/SolidCore/Refinement/Corpus/C3/Seq.lean +++ /dev/null @@ -1,84 +0,0 @@ --- 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 deleted file mode 100644 index ab1c067c..00000000 --- a/SolidCore/Refinement/Corpus/C3/SeqDefs.lean +++ /dev/null @@ -1,59 +0,0 @@ --- 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 deleted file mode 100644 index 2ac73d82..00000000 --- a/SolidCore/Refinement/Corpus/C3/SeqPart0.lean +++ /dev/null @@ -1,9 +0,0 @@ --- 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 deleted file mode 100644 index 4002c624..00000000 --- a/SolidCore/Refinement/Corpus/C3/SeqPart1.lean +++ /dev/null @@ -1,9 +0,0 @@ --- 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 deleted file mode 100644 index ae290d1e..00000000 --- a/SolidCore/Refinement/Corpus/C3/SeqPart10.lean +++ /dev/null @@ -1,9 +0,0 @@ --- 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 deleted file mode 100644 index 1f3b1993..00000000 --- a/SolidCore/Refinement/Corpus/C3/SeqPart11.lean +++ /dev/null @@ -1,9 +0,0 @@ --- 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 deleted file mode 100644 index 2526a199..00000000 --- a/SolidCore/Refinement/Corpus/C3/SeqPart12.lean +++ /dev/null @@ -1,9 +0,0 @@ --- 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 deleted file mode 100644 index 9fb41340..00000000 --- a/SolidCore/Refinement/Corpus/C3/SeqPart13.lean +++ /dev/null @@ -1,9 +0,0 @@ --- 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 deleted file mode 100644 index fb64ac60..00000000 --- a/SolidCore/Refinement/Corpus/C3/SeqPart14.lean +++ /dev/null @@ -1,9 +0,0 @@ --- 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 deleted file mode 100644 index d4952a6d..00000000 --- a/SolidCore/Refinement/Corpus/C3/SeqPart15.lean +++ /dev/null @@ -1,9 +0,0 @@ --- 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 deleted file mode 100644 index 1d7bdf68..00000000 --- a/SolidCore/Refinement/Corpus/C3/SeqPart2.lean +++ /dev/null @@ -1,9 +0,0 @@ --- 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 deleted file mode 100644 index dd39ae1a..00000000 --- a/SolidCore/Refinement/Corpus/C3/SeqPart3.lean +++ /dev/null @@ -1,9 +0,0 @@ --- 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 deleted file mode 100644 index 7cad1bbe..00000000 --- a/SolidCore/Refinement/Corpus/C3/SeqPart4.lean +++ /dev/null @@ -1,9 +0,0 @@ --- 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 deleted file mode 100644 index 0d1af8d9..00000000 --- a/SolidCore/Refinement/Corpus/C3/SeqPart5.lean +++ /dev/null @@ -1,9 +0,0 @@ --- 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 deleted file mode 100644 index 365ef535..00000000 --- a/SolidCore/Refinement/Corpus/C3/SeqPart6.lean +++ /dev/null @@ -1,9 +0,0 @@ --- 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 deleted file mode 100644 index 2c486234..00000000 --- a/SolidCore/Refinement/Corpus/C3/SeqPart7.lean +++ /dev/null @@ -1,9 +0,0 @@ --- 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 deleted file mode 100644 index a016b855..00000000 --- a/SolidCore/Refinement/Corpus/C3/SeqPart8.lean +++ /dev/null @@ -1,9 +0,0 @@ --- 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 deleted file mode 100644 index dc618995..00000000 --- a/SolidCore/Refinement/Corpus/C3/SeqPart9.lean +++ /dev/null @@ -1,9 +0,0 @@ --- 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 deleted file mode 100644 index dfcbf4b4..00000000 --- a/SolidCore/Refinement/Corpus/C3/SeqStates.lean +++ /dev/null @@ -1,21 +0,0 @@ --- 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/C5.lean b/SolidCore/Refinement/Corpus/C5.lean deleted file mode 100644 index f21df63e..00000000 --- a/SolidCore/Refinement/Corpus/C5.lean +++ /dev/null @@ -1,65 +0,0 @@ --- 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 deleted file mode 100644 index 3e170f24..00000000 --- a/SolidCore/Refinement/Corpus/C5/Defs.lean +++ /dev/null @@ -1,50 +0,0 @@ --- 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 deleted file mode 100644 index 05ea00f9..00000000 --- a/SolidCore/Refinement/Corpus/C5/Dirty.lean +++ /dev/null @@ -1,31 +0,0 @@ --- 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 deleted file mode 100644 index bdb59842..00000000 --- a/SolidCore/Refinement/Corpus/C5/Part0.lean +++ /dev/null @@ -1,9 +0,0 @@ --- 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 deleted file mode 100644 index a8b26975..00000000 --- a/SolidCore/Refinement/Corpus/C5/Seq.lean +++ /dev/null @@ -1,89 +0,0 @@ --- 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 deleted file mode 100644 index 0c3a3c9d..00000000 --- a/SolidCore/Refinement/Corpus/C5/SeqDefs.lean +++ /dev/null @@ -1,60 +0,0 @@ --- 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 deleted file mode 100644 index 7e93e5ca..00000000 --- a/SolidCore/Refinement/Corpus/C5/SeqPart0.lean +++ /dev/null @@ -1,9 +0,0 @@ --- 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 deleted file mode 100644 index 4b4a04e6..00000000 --- a/SolidCore/Refinement/Corpus/C5/SeqPart1.lean +++ /dev/null @@ -1,9 +0,0 @@ --- 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 deleted file mode 100644 index a20b88a0..00000000 --- a/SolidCore/Refinement/Corpus/C5/SeqPart10.lean +++ /dev/null @@ -1,9 +0,0 @@ --- 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 deleted file mode 100644 index 73c56d95..00000000 --- a/SolidCore/Refinement/Corpus/C5/SeqPart11.lean +++ /dev/null @@ -1,9 +0,0 @@ --- 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 deleted file mode 100644 index 4a66e6f6..00000000 --- a/SolidCore/Refinement/Corpus/C5/SeqPart12.lean +++ /dev/null @@ -1,9 +0,0 @@ --- 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 deleted file mode 100644 index e5008ec2..00000000 --- a/SolidCore/Refinement/Corpus/C5/SeqPart13.lean +++ /dev/null @@ -1,9 +0,0 @@ --- 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 deleted file mode 100644 index dc22fb1f..00000000 --- a/SolidCore/Refinement/Corpus/C5/SeqPart14.lean +++ /dev/null @@ -1,9 +0,0 @@ --- 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 deleted file mode 100644 index 6d6834aa..00000000 --- a/SolidCore/Refinement/Corpus/C5/SeqPart15.lean +++ /dev/null @@ -1,9 +0,0 @@ --- 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 deleted file mode 100644 index 3c556066..00000000 --- a/SolidCore/Refinement/Corpus/C5/SeqPart16.lean +++ /dev/null @@ -1,9 +0,0 @@ --- 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 deleted file mode 100644 index f47c8817..00000000 --- a/SolidCore/Refinement/Corpus/C5/SeqPart2.lean +++ /dev/null @@ -1,9 +0,0 @@ --- 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 deleted file mode 100644 index 3eb489dd..00000000 --- a/SolidCore/Refinement/Corpus/C5/SeqPart3.lean +++ /dev/null @@ -1,9 +0,0 @@ --- 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 deleted file mode 100644 index 4f601ad7..00000000 --- a/SolidCore/Refinement/Corpus/C5/SeqPart4.lean +++ /dev/null @@ -1,9 +0,0 @@ --- 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 deleted file mode 100644 index a8187c62..00000000 --- a/SolidCore/Refinement/Corpus/C5/SeqPart5.lean +++ /dev/null @@ -1,9 +0,0 @@ --- 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 deleted file mode 100644 index 073bf7a1..00000000 --- a/SolidCore/Refinement/Corpus/C5/SeqPart6.lean +++ /dev/null @@ -1,9 +0,0 @@ --- 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 deleted file mode 100644 index cc15a359..00000000 --- a/SolidCore/Refinement/Corpus/C5/SeqPart7.lean +++ /dev/null @@ -1,9 +0,0 @@ --- 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 deleted file mode 100644 index 53a6649a..00000000 --- a/SolidCore/Refinement/Corpus/C5/SeqPart8.lean +++ /dev/null @@ -1,9 +0,0 @@ --- 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 deleted file mode 100644 index a630763b..00000000 --- a/SolidCore/Refinement/Corpus/C5/SeqPart9.lean +++ /dev/null @@ -1,9 +0,0 @@ --- 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 deleted file mode 100644 index f5ba86f9..00000000 --- a/SolidCore/Refinement/Corpus/C5/SeqStates.lean +++ /dev/null @@ -1,277 +0,0 @@ --- 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 deleted file mode 100644 index 75cd0722..00000000 --- a/SolidCore/Refinement/Corpus/C6.lean +++ /dev/null @@ -1,65 +0,0 @@ --- 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 deleted file mode 100644 index 50001e64..00000000 --- a/SolidCore/Refinement/Corpus/C6/Defs.lean +++ /dev/null @@ -1,50 +0,0 @@ --- 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 deleted file mode 100644 index c2c407f1..00000000 --- a/SolidCore/Refinement/Corpus/C6/Dirty.lean +++ /dev/null @@ -1,31 +0,0 @@ --- 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 deleted file mode 100644 index 4e0c0f19..00000000 --- a/SolidCore/Refinement/Corpus/C6/Part0.lean +++ /dev/null @@ -1,9 +0,0 @@ --- 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 deleted file mode 100644 index ce3cdde4..00000000 --- a/SolidCore/Refinement/Corpus/C6/Seq.lean +++ /dev/null @@ -1,54 +0,0 @@ --- 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 deleted file mode 100644 index f3c95e32..00000000 --- a/SolidCore/Refinement/Corpus/C6/SeqDefs.lean +++ /dev/null @@ -1,59 +0,0 @@ --- 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 deleted file mode 100644 index 92b0aa23..00000000 --- a/SolidCore/Refinement/Corpus/C6/SeqPart0.lean +++ /dev/null @@ -1,9 +0,0 @@ --- 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 deleted file mode 100644 index ed3226fa..00000000 --- a/SolidCore/Refinement/Corpus/C6/SeqStates.lean +++ /dev/null @@ -1,21 +0,0 @@ --- 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 deleted file mode 100644 index 0fde8c57..00000000 --- a/SolidCore/Refinement/Corpus/C7.lean +++ /dev/null @@ -1,65 +0,0 @@ --- 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 deleted file mode 100644 index 89b583e1..00000000 --- a/SolidCore/Refinement/Corpus/C7/Defs.lean +++ /dev/null @@ -1,50 +0,0 @@ --- 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 deleted file mode 100644 index 2fdd8153..00000000 --- a/SolidCore/Refinement/Corpus/C7/Dirty.lean +++ /dev/null @@ -1,31 +0,0 @@ --- 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 deleted file mode 100644 index df4bd2df..00000000 --- a/SolidCore/Refinement/Corpus/C7/Part0.lean +++ /dev/null @@ -1,9 +0,0 @@ --- 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 deleted file mode 100644 index 3b7b4577..00000000 --- a/SolidCore/Refinement/Corpus/C7/Seq.lean +++ /dev/null @@ -1,54 +0,0 @@ --- 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 deleted file mode 100644 index 5c757258..00000000 --- a/SolidCore/Refinement/Corpus/C7/SeqDefs.lean +++ /dev/null @@ -1,59 +0,0 @@ --- 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 deleted file mode 100644 index 6941bb8d..00000000 --- a/SolidCore/Refinement/Corpus/C7/SeqPart0.lean +++ /dev/null @@ -1,9 +0,0 @@ --- 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 deleted file mode 100644 index 0ddaa6d3..00000000 --- a/SolidCore/Refinement/Corpus/C7/SeqStates.lean +++ /dev/null @@ -1,21 +0,0 @@ --- 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 deleted file mode 100644 index 79f4c1e9..00000000 --- a/SolidCore/Refinement/Corpus/C8.lean +++ /dev/null @@ -1,65 +0,0 @@ --- 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 deleted file mode 100644 index d32b1ed9..00000000 --- a/SolidCore/Refinement/Corpus/C8/Defs.lean +++ /dev/null @@ -1,50 +0,0 @@ --- 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 deleted file mode 100644 index bf367a2b..00000000 --- a/SolidCore/Refinement/Corpus/C8/Dirty.lean +++ /dev/null @@ -1,31 +0,0 @@ --- 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 deleted file mode 100644 index c6bff256..00000000 --- a/SolidCore/Refinement/Corpus/C8/Part0.lean +++ /dev/null @@ -1,9 +0,0 @@ --- 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 deleted file mode 100644 index 9415f47d..00000000 --- a/SolidCore/Refinement/Corpus/C8/Seq.lean +++ /dev/null @@ -1,54 +0,0 @@ --- 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 deleted file mode 100644 index df562c0d..00000000 --- a/SolidCore/Refinement/Corpus/C8/SeqDefs.lean +++ /dev/null @@ -1,59 +0,0 @@ --- 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 deleted file mode 100644 index 11403560..00000000 --- a/SolidCore/Refinement/Corpus/C8/SeqPart0.lean +++ /dev/null @@ -1,9 +0,0 @@ --- 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 deleted file mode 100644 index 2f8331ad..00000000 --- a/SolidCore/Refinement/Corpus/C8/SeqStates.lean +++ /dev/null @@ -1,21 +0,0 @@ --- 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 deleted file mode 100644 index 9c61dbbf..00000000 --- a/SolidCore/Refinement/Corpus/C9.lean +++ /dev/null @@ -1,65 +0,0 @@ --- 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 deleted file mode 100644 index 95e83b65..00000000 --- a/SolidCore/Refinement/Corpus/C9/Defs.lean +++ /dev/null @@ -1,50 +0,0 @@ --- 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 deleted file mode 100644 index bef67f6c..00000000 --- a/SolidCore/Refinement/Corpus/C9/Dirty.lean +++ /dev/null @@ -1,31 +0,0 @@ --- 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 deleted file mode 100644 index e911e6d4..00000000 --- a/SolidCore/Refinement/Corpus/C9/Part0.lean +++ /dev/null @@ -1,9 +0,0 @@ --- 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 deleted file mode 100644 index 6b9e4015..00000000 --- a/SolidCore/Refinement/Corpus/C9/Seq.lean +++ /dev/null @@ -1,89 +0,0 @@ --- 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 deleted file mode 100644 index 8e80dab8..00000000 --- a/SolidCore/Refinement/Corpus/C9/SeqDefs.lean +++ /dev/null @@ -1,60 +0,0 @@ --- 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 deleted file mode 100644 index 54f346c0..00000000 --- a/SolidCore/Refinement/Corpus/C9/SeqPart0.lean +++ /dev/null @@ -1,9 +0,0 @@ --- 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 deleted file mode 100644 index 0355aabc..00000000 --- a/SolidCore/Refinement/Corpus/C9/SeqPart1.lean +++ /dev/null @@ -1,9 +0,0 @@ --- 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 deleted file mode 100644 index 30c0c05d..00000000 --- a/SolidCore/Refinement/Corpus/C9/SeqPart10.lean +++ /dev/null @@ -1,9 +0,0 @@ --- 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 deleted file mode 100644 index 027ab8ec..00000000 --- a/SolidCore/Refinement/Corpus/C9/SeqPart11.lean +++ /dev/null @@ -1,9 +0,0 @@ --- 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 deleted file mode 100644 index 07bd6ca0..00000000 --- a/SolidCore/Refinement/Corpus/C9/SeqPart12.lean +++ /dev/null @@ -1,9 +0,0 @@ --- 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 deleted file mode 100644 index 9afe4ea4..00000000 --- a/SolidCore/Refinement/Corpus/C9/SeqPart13.lean +++ /dev/null @@ -1,9 +0,0 @@ --- 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 deleted file mode 100644 index cbe7a953..00000000 --- a/SolidCore/Refinement/Corpus/C9/SeqPart14.lean +++ /dev/null @@ -1,9 +0,0 @@ --- 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 deleted file mode 100644 index 72b90cfe..00000000 --- a/SolidCore/Refinement/Corpus/C9/SeqPart15.lean +++ /dev/null @@ -1,9 +0,0 @@ --- 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 deleted file mode 100644 index 592e4ddf..00000000 --- a/SolidCore/Refinement/Corpus/C9/SeqPart16.lean +++ /dev/null @@ -1,9 +0,0 @@ --- 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 deleted file mode 100644 index 762bb38d..00000000 --- a/SolidCore/Refinement/Corpus/C9/SeqPart2.lean +++ /dev/null @@ -1,9 +0,0 @@ --- 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 deleted file mode 100644 index d5d7d62a..00000000 --- a/SolidCore/Refinement/Corpus/C9/SeqPart3.lean +++ /dev/null @@ -1,9 +0,0 @@ --- 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 deleted file mode 100644 index df7c321a..00000000 --- a/SolidCore/Refinement/Corpus/C9/SeqPart4.lean +++ /dev/null @@ -1,9 +0,0 @@ --- 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 deleted file mode 100644 index d389a597..00000000 --- a/SolidCore/Refinement/Corpus/C9/SeqPart5.lean +++ /dev/null @@ -1,9 +0,0 @@ --- 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 deleted file mode 100644 index 11ed46f2..00000000 --- a/SolidCore/Refinement/Corpus/C9/SeqPart6.lean +++ /dev/null @@ -1,9 +0,0 @@ --- 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 deleted file mode 100644 index 27c30521..00000000 --- a/SolidCore/Refinement/Corpus/C9/SeqPart7.lean +++ /dev/null @@ -1,9 +0,0 @@ --- 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 deleted file mode 100644 index b709b442..00000000 --- a/SolidCore/Refinement/Corpus/C9/SeqPart8.lean +++ /dev/null @@ -1,9 +0,0 @@ --- 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 deleted file mode 100644 index d7a38cc7..00000000 --- a/SolidCore/Refinement/Corpus/C9/SeqPart9.lean +++ /dev/null @@ -1,9 +0,0 @@ --- 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 deleted file mode 100644 index 3a62ff21..00000000 --- a/SolidCore/Refinement/Corpus/C9/SeqStates.lean +++ /dev/null @@ -1,277 +0,0 @@ --- 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 deleted file mode 100644 index db4c3a4f..00000000 --- a/SolidCore/Refinement/Corpus/D1.lean +++ /dev/null @@ -1,95 +0,0 @@ --- 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 deleted file mode 100644 index a86905ff..00000000 --- a/SolidCore/Refinement/Corpus/D1/Defs.lean +++ /dev/null @@ -1,51 +0,0 @@ --- 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 deleted file mode 100644 index 5c11a3d0..00000000 --- a/SolidCore/Refinement/Corpus/D1/Malformed.lean +++ /dev/null @@ -1,30 +0,0 @@ --- 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 deleted file mode 100644 index 8f5b598d..00000000 --- a/SolidCore/Refinement/Corpus/D1/Part0.lean +++ /dev/null @@ -1,9 +0,0 @@ --- 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 deleted file mode 100644 index ef43133b..00000000 --- a/SolidCore/Refinement/Corpus/D1/Part1.lean +++ /dev/null @@ -1,9 +0,0 @@ --- 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 deleted file mode 100644 index 07d896d9..00000000 --- a/SolidCore/Refinement/Corpus/D1/Part10.lean +++ /dev/null @@ -1,9 +0,0 @@ --- 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 deleted file mode 100644 index 74d68793..00000000 --- a/SolidCore/Refinement/Corpus/D1/Part11.lean +++ /dev/null @@ -1,9 +0,0 @@ --- 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 deleted file mode 100644 index c3742064..00000000 --- a/SolidCore/Refinement/Corpus/D1/Part12.lean +++ /dev/null @@ -1,9 +0,0 @@ --- 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 deleted file mode 100644 index bd733988..00000000 --- a/SolidCore/Refinement/Corpus/D1/Part13.lean +++ /dev/null @@ -1,9 +0,0 @@ --- 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 deleted file mode 100644 index 52d67eda..00000000 --- a/SolidCore/Refinement/Corpus/D1/Part14.lean +++ /dev/null @@ -1,9 +0,0 @@ --- 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 deleted file mode 100644 index 8b3caca7..00000000 --- a/SolidCore/Refinement/Corpus/D1/Part15.lean +++ /dev/null @@ -1,9 +0,0 @@ --- 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 deleted file mode 100644 index 16957d78..00000000 --- a/SolidCore/Refinement/Corpus/D1/Part16.lean +++ /dev/null @@ -1,9 +0,0 @@ --- 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 deleted file mode 100644 index 1ad1ca7f..00000000 --- a/SolidCore/Refinement/Corpus/D1/Part2.lean +++ /dev/null @@ -1,9 +0,0 @@ --- 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 deleted file mode 100644 index 3a0b415d..00000000 --- a/SolidCore/Refinement/Corpus/D1/Part3.lean +++ /dev/null @@ -1,9 +0,0 @@ --- 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 deleted file mode 100644 index 27cfff8c..00000000 --- a/SolidCore/Refinement/Corpus/D1/Part4.lean +++ /dev/null @@ -1,9 +0,0 @@ --- 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 deleted file mode 100644 index 17eac74b..00000000 --- a/SolidCore/Refinement/Corpus/D1/Part5.lean +++ /dev/null @@ -1,9 +0,0 @@ --- 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 deleted file mode 100644 index 0731bd93..00000000 --- a/SolidCore/Refinement/Corpus/D1/Part6.lean +++ /dev/null @@ -1,9 +0,0 @@ --- 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 deleted file mode 100644 index 78dff669..00000000 --- a/SolidCore/Refinement/Corpus/D1/Part7.lean +++ /dev/null @@ -1,9 +0,0 @@ --- 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 deleted file mode 100644 index 2d8590d1..00000000 --- a/SolidCore/Refinement/Corpus/D1/Part8.lean +++ /dev/null @@ -1,9 +0,0 @@ --- 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 deleted file mode 100644 index 0e3dac4b..00000000 --- a/SolidCore/Refinement/Corpus/D1/Part9.lean +++ /dev/null @@ -1,9 +0,0 @@ --- 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 deleted file mode 100644 index 0c71b83b..00000000 --- a/SolidCore/Refinement/Corpus/D2.lean +++ /dev/null @@ -1,95 +0,0 @@ --- 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 deleted file mode 100644 index 22ffe037..00000000 --- a/SolidCore/Refinement/Corpus/D2/Defs.lean +++ /dev/null @@ -1,51 +0,0 @@ --- 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 deleted file mode 100644 index dc54974d..00000000 --- a/SolidCore/Refinement/Corpus/D2/Malformed.lean +++ /dev/null @@ -1,30 +0,0 @@ --- 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 deleted file mode 100644 index 0b8bf1ac..00000000 --- a/SolidCore/Refinement/Corpus/D2/Part0.lean +++ /dev/null @@ -1,9 +0,0 @@ --- 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 deleted file mode 100644 index d8f09352..00000000 --- a/SolidCore/Refinement/Corpus/D2/Part1.lean +++ /dev/null @@ -1,9 +0,0 @@ --- 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 deleted file mode 100644 index e7f9e752..00000000 --- a/SolidCore/Refinement/Corpus/D2/Part10.lean +++ /dev/null @@ -1,9 +0,0 @@ --- 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 deleted file mode 100644 index 6ce078c6..00000000 --- a/SolidCore/Refinement/Corpus/D2/Part11.lean +++ /dev/null @@ -1,9 +0,0 @@ --- 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 deleted file mode 100644 index b3a019d3..00000000 --- a/SolidCore/Refinement/Corpus/D2/Part12.lean +++ /dev/null @@ -1,9 +0,0 @@ --- 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 deleted file mode 100644 index a4b370dd..00000000 --- a/SolidCore/Refinement/Corpus/D2/Part13.lean +++ /dev/null @@ -1,9 +0,0 @@ --- 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 deleted file mode 100644 index 3c489f0f..00000000 --- a/SolidCore/Refinement/Corpus/D2/Part14.lean +++ /dev/null @@ -1,9 +0,0 @@ --- 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 deleted file mode 100644 index 4008c211..00000000 --- a/SolidCore/Refinement/Corpus/D2/Part15.lean +++ /dev/null @@ -1,9 +0,0 @@ --- 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 deleted file mode 100644 index d5e106f2..00000000 --- a/SolidCore/Refinement/Corpus/D2/Part16.lean +++ /dev/null @@ -1,9 +0,0 @@ --- 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 deleted file mode 100644 index d6e840d5..00000000 --- a/SolidCore/Refinement/Corpus/D2/Part2.lean +++ /dev/null @@ -1,9 +0,0 @@ --- 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 deleted file mode 100644 index 08f3eaf4..00000000 --- a/SolidCore/Refinement/Corpus/D2/Part3.lean +++ /dev/null @@ -1,9 +0,0 @@ --- 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 deleted file mode 100644 index ee799f06..00000000 --- a/SolidCore/Refinement/Corpus/D2/Part4.lean +++ /dev/null @@ -1,9 +0,0 @@ --- 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 deleted file mode 100644 index 50ab8df5..00000000 --- a/SolidCore/Refinement/Corpus/D2/Part5.lean +++ /dev/null @@ -1,9 +0,0 @@ --- 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 deleted file mode 100644 index 8754b37f..00000000 --- a/SolidCore/Refinement/Corpus/D2/Part6.lean +++ /dev/null @@ -1,9 +0,0 @@ --- 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 deleted file mode 100644 index 4366a15e..00000000 --- a/SolidCore/Refinement/Corpus/D2/Part7.lean +++ /dev/null @@ -1,9 +0,0 @@ --- 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 deleted file mode 100644 index 95b68710..00000000 --- a/SolidCore/Refinement/Corpus/D2/Part8.lean +++ /dev/null @@ -1,9 +0,0 @@ --- 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 deleted file mode 100644 index 76ec1ae5..00000000 --- a/SolidCore/Refinement/Corpus/D2/Part9.lean +++ /dev/null @@ -1,9 +0,0 @@ --- 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 deleted file mode 100644 index 01740ea8..00000000 --- a/SolidCore/Refinement/Corpus/D3.lean +++ /dev/null @@ -1,63 +0,0 @@ --- 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 deleted file mode 100644 index f25a56eb..00000000 --- a/SolidCore/Refinement/Corpus/D3/Defs.lean +++ /dev/null @@ -1,51 +0,0 @@ --- 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 deleted file mode 100644 index 719454d6..00000000 --- a/SolidCore/Refinement/Corpus/D3/Malformed.lean +++ /dev/null @@ -1,30 +0,0 @@ --- 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 deleted file mode 100644 index 05116671..00000000 --- a/SolidCore/Refinement/Corpus/D3/Part0.lean +++ /dev/null @@ -1,9 +0,0 @@ --- 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 deleted file mode 100644 index c70287dd..00000000 --- a/SolidCore/Refinement/Corpus/D4.lean +++ /dev/null @@ -1,63 +0,0 @@ --- 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 deleted file mode 100644 index baee5e56..00000000 --- a/SolidCore/Refinement/Corpus/D4/Defs.lean +++ /dev/null @@ -1,51 +0,0 @@ --- 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 deleted file mode 100644 index f19688cf..00000000 --- a/SolidCore/Refinement/Corpus/D4/Malformed.lean +++ /dev/null @@ -1,30 +0,0 @@ --- 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 deleted file mode 100644 index 921ef9f5..00000000 --- a/SolidCore/Refinement/Corpus/D4/Part0.lean +++ /dev/null @@ -1,9 +0,0 @@ --- 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/W2.lean b/SolidCore/Refinement/Corpus/W2.lean deleted file mode 100644 index da0978ba..00000000 --- a/SolidCore/Refinement/Corpus/W2.lean +++ /dev/null @@ -1,286 +0,0 @@ --- 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 deleted file mode 100644 index 2bcb7fb6..00000000 --- a/SolidCore/Refinement/Corpus/W3.lean +++ /dev/null @@ -1,198 +0,0 @@ --- 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/Generic/SourceRun.lean b/SolidCore/Refinement/Generic/SourceRun.lean index 843dcb80..1525865c 100644 --- a/SolidCore/Refinement/Generic/SourceRun.lean +++ b/SolidCore/Refinement/Generic/SourceRun.lean @@ -1,5 +1,5 @@ import SolidCore.Refinement.Generic.SourceCall -import SolidCore.Verify.Run +import Verify.Run import SolidCore.Refinement.Dirty.Source /-! diff --git a/SolidCore/Refinement/Headline.lean b/SolidCore/Refinement/Headline.lean index cfb4ea57..0923f037 100644 --- a/SolidCore/Refinement/Headline.lean +++ b/SolidCore/Refinement/Headline.lean @@ -4,9 +4,9 @@ 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 +import Verify +import Verify.C4 +import Verify.W5 /-! # Verified source, verified bytecode diff --git a/SolidCore/Refinement/Solar/Assemble.lean b/SolidCore/Refinement/Solar/Assemble.lean index e13c353b..ff9ba54b 100644 --- a/SolidCore/Refinement/Solar/Assemble.lean +++ b/SolidCore/Refinement/Solar/Assemble.lean @@ -1,6 +1,7 @@ import SolidCore.Refinement.Evm.Wide import SolarTV.Composition import SolarTV.Stages.AssemblyCheck +import SolidCore.Refinement.Solar.AssembleStackN /-! # EVM IR to bytecode, once for every program @@ -389,18 +390,8 @@ theorem byteAt_toNat (code : ByteArray) (i : Nat) : 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⟩ + obtain ⟨hb, -, -, -, hn⟩ := decode_op_inv h + exact ⟨hb, hn⟩ theorem decode_push {code : List Nat} {pc next v : Nat} (h : decode code pc = some (.push v, next)) : @@ -424,7 +415,8 @@ theorem decode_push {code : List Nat} {pc next v : Nat} 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 + repeat' split at h + all_goals simp at h theorem decode_pushByte : ∀ b : Fin 32, Op.decode (UInt8.ofNat (0x60 + b.val)) = some (.push ⟨b.val + 1, by omega⟩) := by @@ -844,4 +836,32 @@ theorem stack_rule {op : SolarTV.EVM.Op} {byte : Nat} {stack next : List Word} end Rules +/-! ## DUPN, SWAPN and EXCHANGE are outside the fragment + +The fragment runs at Fusaka, where EIP-8024's DUPN, SWAPN and EXCHANGE are no instruction +(`stackN_fusaka`), so the check refuses every `dup` and `swap` past the sixteenth word and every +`exchange`: the program solar's assembler lowers with them is not the bytecode this stage proves. -/ + +theorem blockStep_dup {p : Program} {c : Cert} {ok : Nat → List Word → List Ty → Nat → Bool} + {h : Nat} {known : List Word} {ty : List Ty} {k : Nat} {i : Fin 256} + (hc : blockStep p c ok h known ty k (.op (.stack (.dup i))) = true) : i.val < 16 := by + simp only [blockStep, Bool.and_eq_true, decide_eq_true_eq] at hc + exact hc.1.1.2 + +theorem blockStep_swap {p : Program} {c : Cert} {ok : Nat → List Word → List Ty → Nat → Bool} + {h : Nat} {known : List Word} {ty : List Ty} {k : Nat} {i : Fin 256} + (hc : blockStep p c ok h known ty k (.op (.stack (.swap i))) = true) : i.val < 16 := by + simp only [blockStep, Bool.and_eq_true, decide_eq_true_eq] at hc + exact hc.1.1.2 + +theorem blockStep_exchange {p : Program} {c : Cert} {ok : Nat → List Word → List Ty → Nat → Bool} + {h : Nat} {known : List Word} {ty : List Ty} {k : Nat} {n m : Fin 32} : + blockStep p c ok h known ty k (.op (.stack (.exchange n m))) = false := by + simp [blockStep, stackNeed] + +/-- The lowering never spells an instruction with an immediate: `dup` and `swap` past the +sixteenth word and `exchange` are INVALID, which the check refuses. -/ +theorem lowerInstr_no_opImm (i : Instr) (b imm : Nat) : Item.opImm b imm ∉ lowerInstr i := by + cases i <;> simp [lowerInstr] <;> split <;> simp + end SolidCore.Refinement.Solar.Assemble diff --git a/SolidCore/Refinement/Solar/AssembleFast.lean b/SolidCore/Refinement/Solar/AssembleFast.lean index 24acd54b..beb1c02a 100644 --- a/SolidCore/Refinement/Solar/AssembleFast.lean +++ b/SolidCore/Refinement/Solar/AssembleFast.lean @@ -41,6 +41,10 @@ def decodeS : List Nat → Nat → Option (SolarTV.Assembly.Instr × Nat × List some (.push (bigEndian (tl.take (byte - PUSH1 + 1))), pc + 1 + (byte - PUSH1 + 1), tl.drop (byte - PUSH1 + 1)) else none + else if hasImmediate byte then + match tl with + | imm :: tl => if immediateOk byte imm then some (.opImm byte imm, pc + 2, tl) else none + | [] => none else some (.op byte, pc + 1, tl) /-- `walk` from offset `pc` of the code whose rest from `pc` is the list: whether the walk @@ -96,26 +100,44 @@ theorem decodeS_drop (code : List Nat) (pc : Nat) : have h3 : ¬byte - PUSH1 + 1 ≤ tl.length := by omega simp [h0, h1, h3] omega - · simp [h0, h1, htl] + · by_cases h2 : hasImmediate byte = true + · rcases tl with _ | ⟨imm, tl⟩ + · have h3 : code[pc + 1]? = none := List.getElem?_eq_none (by simp at hlen; omega) + simp [h0, h1, h2, h3] + · have h3 : code[pc + 1]? = some imm := by + rw [← List.head?_drop, htl] + rfl + have h4 : code.drop (pc + 2) = tl := by + rw [← List.drop_drop, h] + rfl + by_cases h5 : immediateOk byte imm = true <;> simp [h0, h1, h2, h3, h4, h5] + · simp [h0, h1, h2, htl] /-- A successful decode ends within the code. -/ -theorem decode_next_le {code : List Nat} {pc next : Nat} {i : SolarTV.Assembly.Instr} - (h : decode code pc = some (i, next)) : next ≤ code.length := by +theorem decode_lt' {code : List Nat} {pc next : Nat} {i : SolarTV.Assembly.Instr} + (h : decode code pc = some (i, next)) : pc < code.length := by unfold decode at h split at h · cases h · rename_i byte hb - have hlt := (List.getElem?_eq_some_iff.1 hb).1 - split at h - · cases h + exact (List.getElem?_eq_some_iff.1 hb).1 + +theorem decode_next_le {code : List Nat} {pc next : Nat} {i : SolarTV.Assembly.Instr} + (h : decode code pc = some (i, next)) : next ≤ code.length := by + cases i with + | op b => + obtain ⟨hb, -, -, -, rfl⟩ := decode_op_inv h + have := (List.getElem?_eq_some_iff.1 hb).1 + omega + | opImm b imm => + obtain ⟨-, -, hi, -, rfl⟩ := decode_opImm_inv h + have := (List.getElem?_eq_some_iff.1 hi).1 + omega + | push v => + obtain ⟨b, hb, ⟨-, -, rfl⟩ | ⟨-, -, -, hle, -⟩⟩ := decode_push h + · have := (List.getElem?_eq_some_iff.1 hb).1 omega - · split at h - · split at h - · cases h - assumption - · cases h - · cases h - omega + · exact hle theorem walkS_drop (code : List Nat) (offset : Nat → Nat) : ∀ (items : List Item) (pc : Nat), pc ≤ code.length → @@ -169,42 +191,64 @@ theorem opLen_eq (b : UInt8) : 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) +/-- The walk steps from an instruction to the next opcode, as EthLib's scan does: over a push +and its data, over one byte, or over an opcode and its immediate, which the scan steps over as +an opcode of its own, since no immediate that decodes is a push (`immediateOk_not_push`). -/ +theorem decode_boundary {code : ByteArray} {pc next : Nat} {i : SolarTV.Assembly.Instr} + (h : decode (bytesOf code) pc = some (i, next)) : + pc < code.size ∧ (BoundaryFrom code 0 pc → next < code.size → BoundaryFrom code 0 next) := by + have hpc : pc < code.size := by + have := decode_lt' h + rwa [length_bytesOf] at this + refine ⟨hpc, fun hb hn => ?_⟩ + have hbyteOf : ∀ q byte, (bytesOf code)[q]? = some byte → (byteAt code q).toNat = byte := + fun q byte hq => by + rw [byteAt_toNat, List.getD_eq_getElem?_getD, hq] + rfl + have step : ∀ q, BoundaryFrom code 0 q → (byteAt code q).toNat < 0x60 ∨ 0x7f < (byteAt code q).toNat → + q + 1 < code.size → BoundaryFrom code 0 (q + 1) := fun q hq hnp hlt => by + have e : nextOpcode code q = q + 1 := by + rw [nextOpcode_eq_opLen, opLen_eq] + have : ¬(0x60 ≤ (byteAt code q).toNat ∧ (byteAt code q).toNat ≤ 0x7f) := by omega + simp only [this, ↓reduceIte] + have := boundary_next hq (by rw [e]; exact hlt) + rwa [e] at this + cases i with + | op b => + obtain ⟨hb', -, h1, -, rfl⟩ := decode_op_inv h + have := hbyteOf pc b hb' + unfold PUSH1 PUSH32 at h1 + exact step pc hb (by omega) hn + | opImm b imm => + obtain ⟨hb', him, hi, hok, rfl⟩ := decode_opImm_inv h + have e1 := hbyteOf pc b hb' + have e2 := hbyteOf (pc + 1) imm hi + have hnp := immediateOk_not_push hok + have hb1 : b = 0xe6 ∨ b = 0xe7 ∨ b = 0xe8 := by + simp only [hasImmediate, DUPN, SWAPN, EXCHANGE, Bool.or_eq_true, beq_iff_eq] at him + omega + have h1 := step pc hb (by omega) (by omega) + exact step (pc + 1) h1 (by omega) hn + | push v => + obtain ⟨b, hb', ⟨h0, -, rfl⟩ | ⟨h1, h2, rfl, -, -⟩⟩ := decode_push h + · have := hbyteOf pc b hb' + unfold PUSH0 at h0 + exact step pc hb (by omega) hn + · have e := hbyteOf pc b hb' + have e' : nextOpcode code pc = pc + 1 + (b - PUSH1 + 1) := by + rw [nextOpcode_eq_opLen, opLen_eq, e] + unfold PUSH1 PUSH32 at h1 h2 ⊢ + simp only [h1, h2, and_self, ↓reduceIte] + omega + have := boundary_next hb (by rw [e']; exact hn) + rwa [e'] at this + /-- Each label a successful walk from an opcode boundary reaches is a valid jump destination. -/ theorem walk_labels {code : ByteArray} {offset : Nat → Nat} : ∀ (items : List Item) (pc : Nat), (walk (bytesOf code) offset pc items).isSome = true → @@ -223,7 +267,7 @@ theorem walk_labels {code : ByteArray} {offset : Nat → Nat} : · 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 + obtain ⟨hpc, hnext⟩ := decode_boundary hd have hbpc := hb hpc rcases List.mem_cons.1 hl with rfl | hl · have hoff : offset l = pc := by simpa [labelAt] using ok.2 @@ -235,9 +279,7 @@ theorem walk_labels {code : ByteArray} {offset : Nat → Nat} : 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 + · exact walk_labels items next hw' (hnext hbpc) l hl · simp only [ok, ↓reduceIte] at hw simp at hw diff --git a/SolidCore/Refinement/Solar/AssembleStackN.lean b/SolidCore/Refinement/Solar/AssembleStackN.lean new file mode 100644 index 00000000..6c21d23a --- /dev/null +++ b/SolidCore/Refinement/Solar/AssembleStackN.lean @@ -0,0 +1,139 @@ +import EthLib.Execution.Evm.Instructions.StackOnly +import EthLib.Execution.Proofs.Evm.Logic.Rules +import SolarTV.Stages.Assembly +import SolarTV.EVMIR.Ops + +/-! +# DUPN, SWAPN and EXCHANGE against EthLib + +SolarTV's EVM IR takes `dup` and `swap` positions up to 255 and `exchange` pairs up to 31. +DUP1 to DUP16 and SWAP1 to SWAP16 reach the first sixteen; deeper ones, and EXCHANGE, are +EIP-8024's DUPN, SWAPN and EXCHANGE, opcodes with a one-byte immediate that exist from +Glamsterdam. This file ties SolarTV's encoding of them (`SolarTV.Assembly.encodeDepth`, +`encodePair`, as solar's assembler writes them) to EthLib's: + +* the immediates are EthLib's, byte for byte, both ways (`decodeSingle_eq`, `encodeSingle_eq`, + `decodePair_eq`, `encodePair_eq`); +* from Glamsterdam, DUPN, SWAPN and EXCHANGE at the immediate of an EVM IR `dup i`, `swap i` or + `exchange n m` do what SolarTV's `step` does, two bytes on, for 3 gas (`dupn_step`, + `swapn_step`, `exchange_step`); +* before Glamsterdam none of the three is an instruction (`stackN_fusaka`), so the assembly + check at Fusaka (`Assemble.check`) refuses every `dup` and `swap` past the sixteenth word and + every `exchange` (`Assemble.blockStep_dup`, `blockStep_swap`, `blockStep_exchange`). +-/ + +namespace SolidCore.Refinement.Solar.Assemble + +open EthLib.Base EthLib.Execution EthLib.Execution.Evm GasCosts +open SolarTV.Assembly (encodeDepth decodeDepth depthOk encodePair decodePair pairOk) + +/-! ## The immediates are EthLib's -/ + +theorem decodeSingle_eq (x : UInt8) : decodeSingle x = decodeDepth x.toNat := rfl + +theorem encodeSingle_eq (n : Nat) : encodeSingle n = (encodeDepth n).toUInt8 := rfl + +theorem decodePair_eq (x : UInt8) : Evm.decodePair x = SolarTV.Assembly.decodePair x.toNat := rfl + +theorem encodePair_eq (n m : Nat) : + Evm.encodePair n m = (SolarTV.Assembly.encodePair n m).toUInt8 := rfl + +theorem toNat_encodeDepth (n : Nat) : (encodeDepth n).toUInt8.toNat = encodeDepth n := by + have := SolarTV.Assembly.encodeDepth_lt n + simp [Nat.toUInt8, Nat.mod_eq_of_lt this] + +/-! ## Before Glamsterdam the three are no instruction -/ + +theorem stackN_fusaka : + stackOnlyStep (Meter := Nat) .fusaka .dupn = none ∧ + stackOnlyStep (Meter := Nat) .fusaka .swapn = none ∧ + stackOnlyStep (Meter := Nat) .fusaka .exchange = none := by + refine ⟨?_, ?_, ?_⟩ <;> simp [stackOnlyStep] <;> decide + +/-! ## From Glamsterdam they do what SolarTV's step does -/ + +variable {fork : Fork} + +/-- DUPN at the immediate of EVM IR's `dup i` (depth `i + 1`, past the sixteenth) pushes the +word at position `i`, as `SolarTV.EVM.step` does, two bytes on, for 3 gas. -/ +theorem dupn_step {evm : Evm fork Nat} {i : Nat} {x : U256} + (hd : depthOk (i + 1) = true) + (himm : immediateByte evm.code evm.pc = (encodeDepth (i + 1)).toUInt8) + (hgas : 3 ≤ evm.gas) (hx : evm.stack.val[i]? = some x) + (hlen : evm.stack.val.length < STACK_LIMIT) : + ∃ after, dupnStep evm = .ok after ∧ after.stack.val = x :: evm.stack.val ∧ + after.pc = evm.pc + 2 ∧ after.gas = evm.gas - 3 := by + have hdec : decodeSingle (immediateByte evm.code evm.pc) = some (i + 1) := by + rw [himm, decodeSingle_eq, toNat_encodeDepth] + exact SolarTV.Assembly.decodeDepth_encodeDepth hd + have hne : evm.stack.val.length ≠ STACK_LIMIT := by omega + simp only [dupnStep, chargeGas, OPCODE_DUPN, VERY_LOW, Logic.charge_nat hgas, bind, Except.bind, + pure, Except.pure, hdec, Nat.add_sub_cancel, hx, pushWord, Stack.push, hne, dite_false] + exact ⟨_, rfl, rfl, rfl, rfl⟩ + +/-- SWAPN at the immediate of EVM IR's `swap i` (depth `i + 1`, past the sixteenth) exchanges the +top with the word below it at position `i`, as `SolarTV.EVM.step` does, two bytes on, for 3 gas. -/ +theorem swapn_step {evm : Evm fork Nat} {i : Nat} {top x : U256} {rest : List U256} + (hd : depthOk (i + 1) = true) + (himm : immediateByte evm.code evm.pc = (encodeDepth (i + 1)).toUInt8) + (hgas : 3 ≤ evm.gas) (hs : evm.stack.val = top :: rest) (hx : rest[i]? = some x) : + ∃ after, swapnStep evm = .ok after ∧ after.stack.val = x :: rest.set i top ∧ + after.pc = evm.pc + 2 ∧ after.gas = evm.gas - 3 := by + have hdec : decodeSingle (immediateByte evm.code evm.pc) = some (i + 1) := by + rw [himm, decodeSingle_eq, toNat_encodeDepth] + exact SolarTV.Assembly.decodeDepth_encodeDepth hd + have h0 : evm.stack.val[0]? = some top := by rw [hs]; rfl + have h1 : evm.stack.val[i + 1]? = some x := by rw [hs]; exact hx + simp only [swapnStep, chargeGas, OPCODE_SWAPN, VERY_LOW, Logic.charge_nat hgas, bind, + Except.bind, pure, Except.pure, hdec, exchangeItems, h0, h1] + refine ⟨_, rfl, ?_, rfl, rfl⟩ + simp only [advance, hs, List.set_cons_zero, List.set_cons_succ] + +/-- EXCHANGE at the immediate of EVM IR's `exchange n m` exchanges the words at positions `n` and +`m`, as `SolarTV.EVM.step` does, two bytes on, for 3 gas. -/ +theorem exchange_step {evm : Evm fork Nat} {n m : Nat} {a b : U256} + (hp : pairOk n m = true) + (himm : immediateByte evm.code evm.pc = (SolarTV.Assembly.encodePair n m).toUInt8) + (hgas : 3 ≤ evm.gas) (ha : evm.stack.val[n]? = some a) (hb : evm.stack.val[m]? = some b) : + ∃ after, exchangeStep evm = .ok after ∧ + after.stack.val = (evm.stack.val.set n b).set m a ∧ + after.pc = evm.pc + 2 ∧ after.gas = evm.gas - 3 := by + obtain ⟨hdp, hlt⟩ := SolarTV.Assembly.decodePair_encodePair hp + have hdec : Evm.decodePair (immediateByte evm.code evm.pc) = some (n, m) := by + rw [himm, decodePair_eq] + simpa [Nat.toUInt8, Nat.mod_eq_of_lt hlt] using hdp + simp only [exchangeStep, chargeGas, OPCODE_EXCHANGE, VERY_LOW, Logic.charge_nat hgas, bind, + Except.bind, pure, Except.pure, hdec, exchangeItems, ha, hb] + exact ⟨_, rfl, rfl, rfl, rfl⟩ + +/-- SolarTV's `step` of `exchange` is the exchange EthLib's EXCHANGE makes. -/ +theorem step_exchange (ctx : SolarTV.EVM.Context) (n m : Fin 32) (stack : List EvmRules.Word) + {a b : EvmRules.Word} (ha : stack[n.val]? = some a) (hb : stack[m.val]? = some b) : + SolarTV.EVM.step ctx (.exchange n m) stack = some ((stack.set n.val b).set m.val a) := by + simp [SolarTV.EVM.step, ha, hb] + +/-- SolarTV's `step` of `dup i` pushes the word at position `i`. -/ +theorem step_dup (ctx : SolarTV.EVM.Context) (i : Fin 256) (stack : List EvmRules.Word) + {x : EvmRules.Word} (hx : stack[i.val]? = some x) : + SolarTV.EVM.step ctx (.dup i) stack = some (x :: stack) := by + simp [SolarTV.EVM.step, hx] + +/-- SolarTV's `step` of `swap i` exchanges the top with the word below it at position `i`. -/ +theorem step_swap (ctx : SolarTV.EVM.Context) (i : Fin 256) (top : EvmRules.Word) + (rest : List EvmRules.Word) {x : EvmRules.Word} (hx : rest[i.val]? = some x) : + SolarTV.EVM.step ctx (.swap i) (top :: rest) = some (x :: rest.set i.val top) := by + simp [SolarTV.EVM.step, hx] + +/-- info: 'SolidCore.Refinement.Solar.Assemble.dupn_step' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms dupn_step + +/-- info: 'SolidCore.Refinement.Solar.Assemble.swapn_step' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms swapn_step + +/-- info: 'SolidCore.Refinement.Solar.Assemble.exchange_step' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms exchange_step + +end SolidCore.Refinement.Solar.Assemble diff --git a/SolidCore/Refinement/Solar/Bank/Certified.lean b/SolidCore/Refinement/Solar/Bank/Certified.lean index bf83b3f9..4cf8810d 100644 --- a/SolidCore/Refinement/Solar/Bank/Certified.lean +++ b/SolidCore/Refinement/Solar/Bank/Certified.lean @@ -108,7 +108,7 @@ theorem mutant_hex_rejected : 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 +(path and sha256), solar's version with the commit its manifest records (ebdc3376), 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 @@ -117,11 +117,11 @@ of two words (`EthKeccakAgree`, kept explicit here; `certifiedManifest'` dischar `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", + Manifest.sources = [("Certified/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.compiler = "0.8.38+commit.ebdc3376.solar.0.3.0-dev" ∧ + Manifest.arguments = ["Certified/bank/bank.sol", "-Ogas", "--evm-version", "osaka", + "--emit=bin-runtime", "-Zemit-lean-stages=Certified/bank/gen"] ∧ Manifest.optimization = "Gas" ∧ Manifest.evmVersion = "osaka" ∧ Manifest.bytecodeSha256 = "bff0578068ce4ab4a041f226e4e960c13d358c8b430718fefe9ce3a22d760543" ∧ Manifest.bytecodeHex = bytecodeHex ∧ @@ -159,11 +159,11 @@ open SolarTV.Export.Bank Hex in 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", + Manifest.sources = [("Certified/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.compiler = "0.8.38+commit.ebdc3376.solar.0.3.0-dev" ∧ + Manifest.arguments = ["Certified/bank/bank.sol", "-Ogas", "--evm-version", "osaka", + "--emit=bin-runtime", "-Zemit-lean-stages=Certified/bank/gen"] ∧ Manifest.optimization = "Gas" ∧ Manifest.evmVersion = "osaka" ∧ Manifest.bytecodeSha256 = "bff0578068ce4ab4a041f226e4e960c13d358c8b430718fefe9ce3a22d760543" ∧ Manifest.bytecodeHex = bytecodeHex ∧ diff --git a/SolidCore/Refinement/Solar/C4/Certified.lean b/SolidCore/Refinement/Solar/C4/Certified.lean index 76a77f58..e2e3a79c 100644 --- a/SolidCore/Refinement/Solar/C4/Certified.lean +++ b/SolidCore/Refinement/Solar/C4/Certified.lean @@ -132,11 +132,11 @@ storage and from any storage that writes slot 0, with no value and with any valu 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", + Manifest.sources = [("Certified/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.compiler = "0.8.38+commit.ebdc3376.solar.0.3.0-dev" ∧ + Manifest.arguments = ["Certified/c4/c4.sol", "-Zcheck-analyses=false", + "--emit=bin-runtime", "-Zemit-lean-stages=Certified/c4/gen"] ∧ Manifest.optimization = "Gas" ∧ Manifest.evmVersion = "osaka" ∧ Manifest.bytecodeSha256 = "8a21bc207d9dd8be48d921a717eda3ecb7e5bfcb5397850bc3d64a29037fac47" ∧ Manifest.bytecodeHex = bytecodeHex ∧ hexBytes (codes Manifest.bytecodeHex) = some bytecode ∧ diff --git a/SolidCore/Refinement/Solar/C4/Lowering.lean b/SolidCore/Refinement/Solar/C4/Lowering.lean index badaa9a4..8bd1ec8d 100644 --- a/SolidCore/Refinement/Solar/C4/Lowering.lean +++ b/SolidCore/Refinement/Solar/C4/Lowering.lean @@ -1,4 +1,4 @@ -import SolidCore.Verify.C4 +import Verify.C4 import SolidCore.Refinement.Spec import SolidCore.Refinement.Evm.WideStorage import W1Proofs.Tactic diff --git a/SolidCore/Refinement/Solar/C4/LoweringGeneric.lean b/SolidCore/Refinement/Solar/C4/LoweringGeneric.lean index 762892ca..c68d4a55 100644 --- a/SolidCore/Refinement/Solar/C4/LoweringGeneric.lean +++ b/SolidCore/Refinement/Solar/C4/LoweringGeneric.lean @@ -1,5 +1,5 @@ import SolidCore.Refinement.Generic.Value -import SolidCore.Verify.C4 +import Verify.C4 import c4.gen.Main.Stage0 /-! diff --git a/SolidCore/Refinement/Solar/Counter/Milestone.lean b/SolidCore/Refinement/Solar/Counter/Milestone.lean index 53b9f024..7d183a4e 100644 --- a/SolidCore/Refinement/Solar/Counter/Milestone.lean +++ b/SolidCore/Refinement/Solar/Counter/Milestone.lean @@ -88,7 +88,7 @@ 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.compiler = "0.8.38+commit.ebdc3376.solar.0.3.0-dev" ∧ SolarTV.Export.Counter.Manifest.optimization = "Gas" ∧ SolarTV.Export.Counter.Manifest.evmVersion = "osaka" ∧ Satisfies ethLib code scope pre post := by diff --git a/SolidCore/Refinement/Solar/Counter/Spec.lean b/SolidCore/Refinement/Solar/Counter/Spec.lean index f237b55b..ec19fb8c 100644 --- a/SolidCore/Refinement/Solar/Counter/Spec.lean +++ b/SolidCore/Refinement/Solar/Counter/Spec.lean @@ -1,4 +1,4 @@ -import SolidCore.Verify.Tactic +import Verify.Tactic import SolidCore.Refinement.Wide.Refines import SolidCore.Refinement.KernelCopies import SolidCore.Refinement.KernelRfl @@ -7,7 +7,7 @@ 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 +The contract (scripts/refinement/counter/counter.sol; Certified/counter/counter.sol in solar's tree, the same file), contract Counter { uint256 x; function inc(uint256 d) external { x += d; } diff --git a/SolidCore/Refinement/Solar/Events/Certified.lean b/SolidCore/Refinement/Solar/Events/Certified.lean index a30e0d50..07a47952 100644 --- a/SolidCore/Refinement/Solar/Events/Certified.lean +++ b/SolidCore/Refinement/Solar/Events/Certified.lean @@ -94,11 +94,11 @@ from SolidCore's checked `Events` to those bytes, with no value and with any val 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", + Manifest.sources = [("Certified/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.compiler = "0.8.38+commit.ebdc3376.solar.0.3.0-dev" ∧ + Manifest.arguments = ["Certified/events/events.sol", "-Ogas", "--evm-version", "osaka", + "--emit=bin-runtime", "-Zemit-lean-stages=Certified/events/gen"] ∧ Manifest.optimization = "Gas" ∧ Manifest.evmVersion = "osaka" ∧ Manifest.bytecodeSha256 = "5ad38c8bca24e0ca8c4a5e95f1f07bf993aad9a02ac3bc0872fc41fab8a6298b" ∧ Manifest.bytecodeHex = bytecodeHex ∧ diff --git a/SolidCore/Refinement/Solar/Lowering.lean b/SolidCore/Refinement/Solar/Lowering.lean index cbc757ac..75c6c135 100644 --- a/SolidCore/Refinement/Solar/Lowering.lean +++ b/SolidCore/Refinement/Solar/Lowering.lean @@ -1,5 +1,5 @@ import SolidCore.Refinement.Solar.W1 -import SolidCore.Verify.W5 +import Verify.W5 import W1Proofs.Tactic import gen.Main.Stage0 diff --git a/SolidCore/Refinement/Solar/MulX/Certified.lean b/SolidCore/Refinement/Solar/MulX/Certified.lean index bd716e62..ddfd9074 100644 --- a/SolidCore/Refinement/Solar/MulX/Certified.lean +++ b/SolidCore/Refinement/Solar/MulX/Certified.lean @@ -111,11 +111,11 @@ as that bytecode, and the stage from SolidCore's checked Main to those bytes, fr 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", + Manifest.sources = [("Certified/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.compiler = "0.8.38+commit.ebdc3376.solar.0.3.0-dev" ∧ + Manifest.arguments = ["Certified/mulx/mulx.sol", "-Zcheck-analyses=false", + "--emit=bin-runtime", "-Zemit-lean-stages=Certified/mulx/gen"] ∧ Manifest.optimization = "Gas" ∧ Manifest.evmVersion = "osaka" ∧ Manifest.bytecodeSha256 = "42ecdc71b09d339299d2b7ce61e121c77b141c5386eb9cbf18792a9ba9ca4cfe" ∧ Manifest.bytecodeHex = bytecodeHex ∧ hexBytes (codes Manifest.bytecodeHex) = some bytecode ∧ diff --git a/SolidCore/Refinement/Solar/W4/Milestone.lean b/SolidCore/Refinement/Solar/W4/Milestone.lean index 1350aaef..38581af3 100644 --- a/SolidCore/Refinement/Solar/W4/Milestone.lean +++ b/SolidCore/Refinement/Solar/W4/Milestone.lean @@ -1,5 +1,5 @@ import SolidCore.Refinement.Solar.W4Lowering -import SolidCore.Verify.W4 +import Verify.W4 import SolidCore.Refinement.Evm.WideStorage import SolidCore.Refinement.Spec import w4.Proofs diff --git a/SolidCore/Verify.lean b/SolidCore/Verify.lean deleted file mode 100644 index 02f4b06e..00000000 --- a/SolidCore/Verify.lean +++ /dev/null @@ -1,10 +0,0 @@ -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 deleted file mode 100644 index 388295c8..00000000 --- a/SolidCore/Verify/Abi.lean +++ /dev/null @@ -1,38 +0,0 @@ -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 deleted file mode 100644 index 78d10502..00000000 --- a/SolidCore/Verify/Basic.lean +++ /dev/null @@ -1,189 +0,0 @@ -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 deleted file mode 100644 index 79afadda..00000000 --- a/SolidCore/Verify/C1.lean +++ /dev/null @@ -1,222 +0,0 @@ -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 deleted file mode 100644 index 977b5365..00000000 --- a/SolidCore/Verify/C4.lean +++ /dev/null @@ -1,458 +0,0 @@ -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 deleted file mode 100644 index b3e975b4..00000000 --- a/SolidCore/Verify/Finite.lean +++ /dev/null @@ -1,75 +0,0 @@ -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 deleted file mode 100644 index 90fce1b6..00000000 --- a/SolidCore/Verify/Run.lean +++ /dev/null @@ -1,132 +0,0 @@ -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 deleted file mode 100644 index ce8e5f4e..00000000 --- a/SolidCore/Verify/Tactic.lean +++ /dev/null @@ -1,110 +0,0 @@ -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 deleted file mode 100644 index 876032a5..00000000 --- a/SolidCore/Verify/W1.lean +++ /dev/null @@ -1,98 +0,0 @@ -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 deleted file mode 100644 index e23082c5..00000000 --- a/SolidCore/Verify/W4.lean +++ /dev/null @@ -1,173 +0,0 @@ -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 deleted file mode 100644 index 95775752..00000000 --- a/SolidCore/Verify/W5.lean +++ /dev/null @@ -1,173 +0,0 @@ -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 From 394311d72718c77d6a2b0b75fb85795c7fc884aa Mon Sep 17 00:00:00 2001 From: alpharush <0xalpharush@protonmail.com> Date: Fri, 13 Nov 2026 00:39:32 -0600 Subject: [PATCH 7/8] feat: merge verification, discharge, Contracts headlines and regenerated Certified contracts --- Certified/bank/Proofs.lean | 2 +- Certified/bank/Proofs/Assembly.lean | 2 +- Certified/bank/Proofs/Runs/Evm1.lean | 2 +- Certified/bank/Proofs/Runs/Evm10.lean | 2 +- Certified/bank/Proofs/Runs/Evm11.lean | 2 +- Certified/bank/Proofs/Runs/Evm2.lean | 2 +- Certified/bank/Proofs/Runs/Evm3.lean | 2 +- Certified/bank/Proofs/Runs/Evm4.lean | 2 +- Certified/bank/Proofs/Runs/Evm5.lean | 2 +- Certified/bank/Proofs/Runs/Evm6.lean | 2 +- Certified/bank/Proofs/Runs/Evm7.lean | 2 +- Certified/bank/Proofs/Runs/Evm8.lean | 2 +- Certified/bank/Proofs/Runs/Evm9.lean | 2 +- Certified/bank/Proofs/Runs/Mir1.lean | 2 +- Certified/bank/Proofs/Runs/Mir2.lean | 2 +- Certified/bank/Proofs/Runs/Mir3.lean | 2 +- Certified/bank/Proofs/Runs/Mir4.lean | 2 +- Certified/bank/Proofs/Runs/Sched.lean | 2 +- Certified/bank/Proofs/Runs/Stage0.lean | 2 +- Certified/bank/Proofs/Stages.lean | 2 +- Certified/bank/gen/Bank/Manifest.lean | 8 +- Certified/bank/gen/Bank/Schedule.json | 49 ++ Certified/bank/gen/Bank/manifest.json | 10 +- Certified/c4/Proofs.lean | 2 +- Certified/c4/Proofs/Assembly.lean | 2 +- Certified/c4/Proofs/Runs/Evm1.lean | 2 +- Certified/c4/Proofs/Runs/Evm2.lean | 2 +- Certified/c4/Proofs/Runs/Evm3.lean | 2 +- Certified/c4/Proofs/Runs/Evm4.lean | 2 +- Certified/c4/Proofs/Runs/Evm5.lean | 2 +- Certified/c4/Proofs/Runs/Mir1.lean | 2 +- Certified/c4/Proofs/Runs/Mir2.lean | 2 +- Certified/c4/Proofs/Runs/Sched.lean | 2 +- Certified/c4/Proofs/Runs/Stage0.lean | 2 +- Certified/c4/Proofs/Stages.lean | 2 +- Certified/c4/gen/Main/Manifest.lean | 8 +- Certified/c4/gen/Main/Schedule.json | 17 + Certified/c4/gen/Main/manifest.json | 10 +- Certified/counter/Proofs.lean | 2 +- Certified/counter/Proofs/Assembly.lean | 2 +- Certified/counter/Proofs/Runs/Evm1.lean | 2 +- Certified/counter/Proofs/Runs/Evm2.lean | 2 +- Certified/counter/Proofs/Runs/Evm3.lean | 2 +- Certified/counter/Proofs/Runs/Evm4.lean | 2 +- Certified/counter/Proofs/Runs/Evm5.lean | 2 +- Certified/counter/Proofs/Runs/Sched.lean | 2 +- Certified/counter/Proofs/Runs/Stage0.lean | 2 +- Certified/counter/Proofs/Stages.lean | 2 +- Certified/counter/gen/Counter/Manifest.lean | 8 +- Certified/counter/gen/Counter/Schedule.json | 21 + Certified/counter/gen/Counter/manifest.json | 10 +- Certified/counter/headline | 4 + Certified/events/Proofs.lean | 2 +- Certified/events/Proofs/Assembly.lean | 2 +- Certified/events/Proofs/Runs/Evm1.lean | 2 +- Certified/events/Proofs/Runs/Evm2.lean | 2 +- Certified/events/Proofs/Runs/Evm3.lean | 2 +- Certified/events/Proofs/Runs/Evm4.lean | 2 +- Certified/events/Proofs/Runs/Evm5.lean | 2 +- Certified/events/Proofs/Runs/Mir1.lean | 2 +- Certified/events/Proofs/Runs/Sched.lean | 2 +- Certified/events/Proofs/Runs/Stage0.lean | 2 +- Certified/events/Proofs/Stages.lean | 2 +- Certified/events/gen/Events/Manifest.lean | 8 +- Certified/events/gen/Events/Schedule.json | 18 + Certified/events/gen/Events/manifest.json | 10 +- Certified/masks/Proofs.lean | 2 +- Certified/masks/Proofs/Assembly.lean | 2 +- Certified/masks/Proofs/Runs/Evm1.lean | 2 +- Certified/masks/Proofs/Runs/Evm2.lean | 2 +- Certified/masks/Proofs/Runs/Evm3.lean | 2 +- Certified/masks/Proofs/Runs/Evm4.lean | 2 +- Certified/masks/Proofs/Runs/Evm5.lean | 2 +- Certified/masks/Proofs/Runs/Evm6.lean | 2 +- Certified/masks/Proofs/Runs/Mir1.lean | 2 +- Certified/masks/Proofs/Runs/Mir2.lean | 2 +- Certified/masks/Proofs/Runs/Sched.lean | 2 +- Certified/masks/Proofs/Runs/Stage0.lean | 2 +- Certified/masks/Proofs/Stages.lean | 2 +- Certified/masks/gen/Masks/Manifest.lean | 8 +- Certified/masks/gen/Masks/Schedule.json | 30 + Certified/masks/gen/Masks/manifest.json | 10 +- Certified/mulx/Proofs.lean | 2 +- Certified/mulx/Proofs/Assembly.lean | 2 +- Certified/mulx/Proofs/Runs/Evm1.lean | 2 +- Certified/mulx/Proofs/Runs/Evm2.lean | 2 +- Certified/mulx/Proofs/Runs/Evm3.lean | 2 +- Certified/mulx/Proofs/Runs/Evm4.lean | 2 +- Certified/mulx/Proofs/Runs/Evm5.lean | 2 +- Certified/mulx/Proofs/Runs/Evm6.lean | 2 +- Certified/mulx/Proofs/Runs/Evm7.lean | 2 +- Certified/mulx/Proofs/Runs/Evm8.lean | 2 +- Certified/mulx/Proofs/Runs/Mir1.lean | 2 +- Certified/mulx/Proofs/Runs/Mir2.lean | 2 +- Certified/mulx/Proofs/Runs/Mir3.lean | 2 +- Certified/mulx/Proofs/Runs/Sched.lean | 2 +- Certified/mulx/Proofs/Runs/Stage0.lean | 2 +- Certified/mulx/Proofs/Stages.lean | 2 +- Certified/mulx/gen/Main/Manifest.lean | 8 +- Certified/mulx/gen/Main/Schedule.json | 25 + Certified/mulx/gen/Main/manifest.json | 10 +- Certified/reader/Proofs.lean | 2 +- Certified/reader/Proofs/Assembly.lean | 2 +- Certified/reader/Proofs/Runs/Evm1.lean | 2 +- Certified/reader/Proofs/Runs/Evm2.lean | 2 +- Certified/reader/Proofs/Runs/Evm3.lean | 2 +- Certified/reader/Proofs/Runs/Evm4.lean | 2 +- Certified/reader/Proofs/Runs/Evm5.lean | 2 +- Certified/reader/Proofs/Runs/Evm6.lean | 2 +- Certified/reader/Proofs/Runs/Evm7.lean | 2 +- Certified/reader/Proofs/Runs/Mir1.lean | 2 +- Certified/reader/Proofs/Runs/Mir2.lean | 2 +- Certified/reader/Proofs/Runs/Mir3.lean | 2 +- Certified/reader/Proofs/Runs/Sched.lean | 2 +- Certified/reader/Proofs/Runs/Stage0.lean | 2 +- Certified/reader/Proofs/Stages.lean | 2 +- Certified/reader/gen/Reader/Manifest.lean | 8 +- Certified/reader/gen/Reader/Schedule.json | 20 + Certified/reader/gen/Reader/manifest.json | 10 +- Certified/w4/Proofs.lean | 2 +- Certified/w4/Proofs/Assembly.lean | 2 +- Certified/w4/Proofs/Runs/Evm1.lean | 2 +- Certified/w4/Proofs/Runs/Evm2.lean | 2 +- Certified/w4/Proofs/Runs/Evm3.lean | 2 +- Certified/w4/Proofs/Runs/Evm4.lean | 2 +- Certified/w4/Proofs/Runs/Sched.lean | 2 +- Certified/w4/Proofs/Runs/Stage0.lean | 2 +- Certified/w4/Proofs/Stages.lean | 2 +- Certified/w4/gen/Main/Manifest.lean | 8 +- Certified/w4/gen/Main/Schedule.json | 15 + Certified/w4/gen/Main/manifest.json | 10 +- Contracts/ArrayMax/Audit.lean | 22 + Contracts/ArrayMax/Bounded.lean | 158 ++++ Contracts/ArrayMax/Proofs/ArrayMax/clamp.lean | 16 + Contracts/ArrayMax/Proofs/ArrayMax/max.lean | 72 ++ .../ArrayMax/Proofs/ArrayMaxEntry/max.lean | 24 + Contracts/ArrayMax/README.md | 29 + Contracts/ArrayMax/Vc/ArrayMax/clamp.lean | 74 ++ Contracts/ArrayMax/Vc/ArrayMax/max.lean | 210 +++++ .../Vc/ArrayMaxEntry/constructor.lean | 60 ++ Contracts/ArrayMax/Vc/ArrayMaxEntry/max.lean | 92 ++ Contracts/ArrayMax/Vc/frozen.sha256 | 5 + Contracts/ArrayMax/Vc/manifest.json | 760 ++++++++++++++++ Contracts/C4/Spec/Axioms.lean | 22 + Contracts/C4/Spec/Bytecode.lean | 260 ++++++ Contracts/C4/Spec/Export.lean | 51 ++ Contracts/C4/Spec/ExportWrong.lean | 51 ++ Contracts/Counter/EndToEnd.lean | 99 +++ Contracts/Counter/Final.lean | 248 ++++++ Contracts/Counter/Headline.lean | 276 ++++++ Contracts/Counter/Spec/Export.lean | 48 + Contracts/Counter/Spec/ExportWrong.lean | 48 + Contracts/Counter/VC/Bind.lean | 17 + Contracts/Counter/VC/Export.lean | 331 +++++++ Contracts/Counter/VC/ExportMilestone.lean | 169 ++++ Contracts/Counter/VC/Generic.lean | 65 ++ Contracts/Counter/VC/Get.lean | 79 ++ Contracts/Counter/VC/Inc.lean | 279 ++++++ Contracts/Counter/VC/Mutant/SpecMut.lean | 169 ++++ Contracts/Counter/VC/Mutant/SrcMut.lean | 173 ++++ Contracts/Counter/VC/Mutants.lean | 28 + Contracts/Counter/Verdict.lean | 81 ++ Contracts/Counter/Verify.lean | 180 ++++ Contracts/Token/VC/Bind.lean | 15 + Contracts/Token/VC/Burn.lean | 329 +++++++ Contracts/Token/VC/Export.lean | 354 ++++++++ Contracts/Token/VC/Mutant/SpecMut.lean | 354 ++++++++ Contracts/Token/VC/Mutant/SrcMut.lean | 358 ++++++++ Contracts/Token/VC/Mutants.lean | 43 + Contracts/Token/VC/Source.lean | 101 +++ Contracts/Token/VC/Transfer.lean | 683 +++++++++++++++ Contracts/Vault/Audit.lean | 24 + Contracts/Vault/Proofs/Vacuous.lean | 41 + Contracts/Vault/Proofs/Vault/constructor.lean | 20 + Contracts/Vault/Proofs/Vault/deposit.lean | 40 + Contracts/Vault/Proofs/Vault/withdraw.lean | 44 + Contracts/Vault/README.md | 28 + Contracts/Vault/Vc/Vault/constructor.lean | 78 ++ Contracts/Vault/Vc/Vault/deposit.lean | 237 +++++ Contracts/Vault/Vc/Vault/withdraw.lean | 252 ++++++ Contracts/Vault/Vc/frozen.sha256 | 4 + Contracts/Vault/Vc/manifest.json | 716 +++++++++++++++ Loom.lean | 12 + {vendor/loom => Loom}/LICENSE | 0 .../Loom => Loom}/MonadAlgebras/Defs.lean | 0 Loom/MonadAlgebras/Instances/Basic.lean | 123 +++ Loom/MonadAlgebras/Instances/ExceptT.lean | 150 ++++ Loom/MonadAlgebras/Instances/ExceptTErr.lean | 102 +++ Loom/MonadAlgebras/Instances/Gen.lean | 19 + Loom/MonadAlgebras/Instances/ReaderT.lean | 117 +++ Loom/MonadAlgebras/Instances/StateT.lean | 122 +++ Loom/MonadAlgebras/WP/Basic.lean | 537 ++++++++++++ Loom/MonadAlgebras/WP/Liberal.lean | 222 +++++ Loom/MonadAlgebras/WP/Variant.lean | 107 +++ {vendor/loom/Loom => Loom}/MonadUtil.lean | 0 Loom/README.md | 61 ++ {vendor/loom/Loom => Loom}/SpecMonad.lean | 0 Verify.lean | 13 + Verify/Abi.lean | 38 + Verify/Basic.lean | 306 +++++++ Verify/C1.lean | 222 +++++ Verify/C4.lean | 458 ++++++++++ Verify/CounterBump.lean | 110 +++ Verify/Discharge.lean | 20 + Verify/Discharge/Leaf.lean | 9 + Verify/Discharge/Lemmas.lean | 65 ++ Verify/Discharge/README.md | 48 + Verify/Discharge/Sat.lean | 4 + Verify/Discharge/Sat/Cnf.lean | 74 ++ Verify/Discharge/Sat/Ground.lean | 73 ++ Verify/Discharge/Sat/Load.lean | 218 +++++ Verify/Discharge/Sat/Lrat.lean | 410 +++++++++ Verify/Discharge/Search.lean | 409 +++++++++ Verify/Discharge/Valid.lean | 241 ++++++ Verify/Discharge/discharge.sh | 310 +++++++ Verify/Discharge/frozen/ArrayMax.sha256 | 5 + Verify/Discharge/frozen/Counter.sha256 | 5 + Verify/Discharge/frozen/PINS | 8 + Verify/Discharge/frozen/Token.sha256 | 5 + Verify/Discharge/frozen/Vault.sha256 | 4 + Verify/Discharge/frozen/v2/ArrayMax.sha256 | 6 + Verify/Discharge/frozen/v2/Counter.sha256 | 6 + Verify/Discharge/frozen/v2/PINS | 10 + Verify/Discharge/frozen/v2/Token.sha256 | 6 + Verify/Discharge/frozen/v2/Vault.sha256 | 5 + Verify/Discharge/test/negatives.sh | 95 ++ Verify/Discharge/test/sat/Sat.lean | 58 ++ Verify/Discharge/test/sat/b8.cnf | 348 ++++++++ Verify/Discharge/test/sat/b8.lrat | 240 +++++ Verify/Final.lean | 631 ++++++++++++++ Verify/Finite.lean | 75 ++ Verify/Fuel.lean | 159 ++++ Verify/FuelStable.lean | 181 ++++ Verify/Infer/README.md | 41 + Verify/Infer/Reconstruct.lean | 107 +++ Verify/Infer/SHA256SUMS | 19 + Verify/Infer/SpacerPath.lean | 64 ++ Verify/Infer/chc/counter_int.smt2 | 21 + Verify/Infer/chc/counter_int.spacer.out | 9 + Verify/Infer/chc/counter_u256.smt2 | 21 + Verify/Infer/chc/counter_u256.spacer.out | 9 + Verify/Infer/chc/drain_int.smt2 | 10 + Verify/Infer/chc/drain_int.spacer.out | 8 + Verify/Infer/chc/drain_u256.smt2 | 10 + Verify/Infer/chc/drain_u256.spacer.out | 8 + Verify/Infer/chc/okwhile_int.smt2 | 10 + Verify/Infer/chc/okwhile_int.spacer.out | 5 + Verify/Infer/chc/okwhile_u256.smt2 | 10 + Verify/Infer/chc/okwhile_u256.spacer.out | 5 + Verify/Infer/flex-4.35-bump.diff | 216 +++++ Verify/Infer/gen_reconstruct.sh | 82 ++ Verify/Infer/reconstruct-4.35.axioms.txt | 18 + Verify/Infer/smt2lean_inv.py | 59 ++ Verify/Infer/spacerpath-4.35.out | 21 + Verify/LoomAxioms.lean | 39 + Verify/LoomImports.lean | 16 + Verify/Obligation.lean | 7 + Verify/Obligation/Model.lean | 67 ++ Verify/Obligation/Smt.lean | 470 ++++++++++ Verify/Obligation/Vc.lean | 38 + Verify/Reconstruct/.gitignore | 1 + Verify/Reconstruct/Tactic.lean | 42 + Verify/Reconstruct/lake-manifest.json | 46 + Verify/Reconstruct/lakefile.lean | 16 + Verify/Reconstruct/lean-toolchain | 1 + Verify/Run.lean | 132 +++ Verify/Spec/Contract.lean | 186 ++++ Verify/Spec/Ghost.lean | 635 ++++++++++++++ Verify/Spec/GhostFree.lean | 168 ++++ Verify/Spec/README.md | 91 ++ Verify/Spec/Semantics.lean | 263 ++++++ Verify/Spec/Syntax.lean | 162 ++++ Verify/Spec/TrustedBase.lean | 103 +++ Verify/Spec/TrustedBase/Axioms.lean | 45 + Verify/Spec/TrustedBase/Hypotheses.lean | 657 ++++++++++++++ Verify/Spec/TrustedBase/Instances.lean | 60 ++ Verify/Spec/TrustedBase/Interface.lean | 98 +++ Verify/Tactic.lean | 110 +++ Verify/VC.lean | 56 ++ Verify/VC/Check.lean | 818 ++++++++++++++++++ Verify/VC/KernelIdx.lean | 59 ++ Verify/VC/Model.lean | 127 +++ Verify/VC/Obligations.lean | 92 ++ Verify/VC/Term.lean | 318 +++++++ Verify/W1.lean | 98 +++ Verify/W4.lean | 173 ++++ Verify/W5.lean | 173 ++++ lakefile.lean | 101 ++- scripts/refinement/axiom-audit.sh | 7 +- scripts/refinement/spec/c4.sol | 11 + scripts/refinement/spec/c4_wrong.sol | 11 + scripts/refinement/spec/check.sh | 47 + scripts/solc_ast_to_lean_source.py | 4 +- scripts/verify/Counter.sol | 37 + scripts/verify/CounterMilestone.sol | 8 + scripts/verify/MANIFEST | 9 + scripts/verify/Token.sol | 50 ++ scripts/verify/check.sh | 91 ++ scripts/verify/mutant/CounterSpecMut.sol | 8 + scripts/verify/mutant/CounterSrcMut.sol | 8 + scripts/verify/mutant/MANIFEST | 12 + scripts/verify/mutant/TokenSpecMut.sol | 50 ++ scripts/verify/mutant/TokenSrcMut.sol | 50 ++ tv/SolarTV/Stages/Assembly.lean | 205 ++++- tv/SolarTV/Stages/Link.lean | 17 +- tv/W1Proofs/Items.lean | 77 +- vendor/loom/Loom.lean | 1 - .../Loom/MonadAlgebras/Instances/Basic.lean | 26 - vendor/loom/Loom/MonadAlgebras/WP/Basic.lean | 148 ---- vendor/loom/README.md | 39 - 310 files changed, 21627 insertions(+), 429 deletions(-) create mode 100644 Certified/bank/gen/Bank/Schedule.json create mode 100644 Certified/c4/gen/Main/Schedule.json create mode 100644 Certified/counter/gen/Counter/Schedule.json create mode 100644 Certified/counter/headline create mode 100644 Certified/events/gen/Events/Schedule.json create mode 100644 Certified/masks/gen/Masks/Schedule.json create mode 100644 Certified/mulx/gen/Main/Schedule.json create mode 100644 Certified/reader/gen/Reader/Schedule.json create mode 100644 Certified/w4/gen/Main/Schedule.json create mode 100644 Contracts/ArrayMax/Audit.lean create mode 100644 Contracts/ArrayMax/Bounded.lean create mode 100644 Contracts/ArrayMax/Proofs/ArrayMax/clamp.lean create mode 100644 Contracts/ArrayMax/Proofs/ArrayMax/max.lean create mode 100644 Contracts/ArrayMax/Proofs/ArrayMaxEntry/max.lean create mode 100644 Contracts/ArrayMax/README.md create mode 100644 Contracts/ArrayMax/Vc/ArrayMax/clamp.lean create mode 100644 Contracts/ArrayMax/Vc/ArrayMax/max.lean create mode 100644 Contracts/ArrayMax/Vc/ArrayMaxEntry/constructor.lean create mode 100644 Contracts/ArrayMax/Vc/ArrayMaxEntry/max.lean create mode 100644 Contracts/ArrayMax/Vc/frozen.sha256 create mode 100644 Contracts/ArrayMax/Vc/manifest.json create mode 100644 Contracts/C4/Spec/Axioms.lean create mode 100644 Contracts/C4/Spec/Bytecode.lean create mode 100644 Contracts/C4/Spec/Export.lean create mode 100644 Contracts/C4/Spec/ExportWrong.lean create mode 100644 Contracts/Counter/EndToEnd.lean create mode 100644 Contracts/Counter/Final.lean create mode 100644 Contracts/Counter/Headline.lean create mode 100644 Contracts/Counter/Spec/Export.lean create mode 100644 Contracts/Counter/Spec/ExportWrong.lean create mode 100644 Contracts/Counter/VC/Bind.lean create mode 100644 Contracts/Counter/VC/Export.lean create mode 100644 Contracts/Counter/VC/ExportMilestone.lean create mode 100644 Contracts/Counter/VC/Generic.lean create mode 100644 Contracts/Counter/VC/Get.lean create mode 100644 Contracts/Counter/VC/Inc.lean create mode 100644 Contracts/Counter/VC/Mutant/SpecMut.lean create mode 100644 Contracts/Counter/VC/Mutant/SrcMut.lean create mode 100644 Contracts/Counter/VC/Mutants.lean create mode 100644 Contracts/Counter/Verdict.lean create mode 100644 Contracts/Counter/Verify.lean create mode 100644 Contracts/Token/VC/Bind.lean create mode 100644 Contracts/Token/VC/Burn.lean create mode 100644 Contracts/Token/VC/Export.lean create mode 100644 Contracts/Token/VC/Mutant/SpecMut.lean create mode 100644 Contracts/Token/VC/Mutant/SrcMut.lean create mode 100644 Contracts/Token/VC/Mutants.lean create mode 100644 Contracts/Token/VC/Source.lean create mode 100644 Contracts/Token/VC/Transfer.lean create mode 100644 Contracts/Vault/Audit.lean create mode 100644 Contracts/Vault/Proofs/Vacuous.lean create mode 100644 Contracts/Vault/Proofs/Vault/constructor.lean create mode 100644 Contracts/Vault/Proofs/Vault/deposit.lean create mode 100644 Contracts/Vault/Proofs/Vault/withdraw.lean create mode 100644 Contracts/Vault/README.md create mode 100644 Contracts/Vault/Vc/Vault/constructor.lean create mode 100644 Contracts/Vault/Vc/Vault/deposit.lean create mode 100644 Contracts/Vault/Vc/Vault/withdraw.lean create mode 100644 Contracts/Vault/Vc/frozen.sha256 create mode 100644 Contracts/Vault/Vc/manifest.json create mode 100644 Loom.lean rename {vendor/loom => Loom}/LICENSE (100%) rename {vendor/loom/Loom => Loom}/MonadAlgebras/Defs.lean (100%) create mode 100644 Loom/MonadAlgebras/Instances/Basic.lean create mode 100644 Loom/MonadAlgebras/Instances/ExceptT.lean create mode 100644 Loom/MonadAlgebras/Instances/ExceptTErr.lean create mode 100644 Loom/MonadAlgebras/Instances/Gen.lean create mode 100644 Loom/MonadAlgebras/Instances/ReaderT.lean create mode 100644 Loom/MonadAlgebras/Instances/StateT.lean create mode 100644 Loom/MonadAlgebras/WP/Basic.lean create mode 100644 Loom/MonadAlgebras/WP/Liberal.lean create mode 100644 Loom/MonadAlgebras/WP/Variant.lean rename {vendor/loom/Loom => Loom}/MonadUtil.lean (100%) create mode 100644 Loom/README.md rename {vendor/loom/Loom => Loom}/SpecMonad.lean (100%) create mode 100644 Verify.lean create mode 100644 Verify/Abi.lean create mode 100644 Verify/Basic.lean create mode 100644 Verify/C1.lean create mode 100644 Verify/C4.lean create mode 100644 Verify/CounterBump.lean create mode 100644 Verify/Discharge.lean create mode 100644 Verify/Discharge/Leaf.lean create mode 100644 Verify/Discharge/Lemmas.lean create mode 100644 Verify/Discharge/README.md create mode 100644 Verify/Discharge/Sat.lean create mode 100644 Verify/Discharge/Sat/Cnf.lean create mode 100644 Verify/Discharge/Sat/Ground.lean create mode 100644 Verify/Discharge/Sat/Load.lean create mode 100644 Verify/Discharge/Sat/Lrat.lean create mode 100644 Verify/Discharge/Search.lean create mode 100644 Verify/Discharge/Valid.lean create mode 100755 Verify/Discharge/discharge.sh create mode 100644 Verify/Discharge/frozen/ArrayMax.sha256 create mode 100644 Verify/Discharge/frozen/Counter.sha256 create mode 100644 Verify/Discharge/frozen/PINS create mode 100644 Verify/Discharge/frozen/Token.sha256 create mode 100644 Verify/Discharge/frozen/Vault.sha256 create mode 100644 Verify/Discharge/frozen/v2/ArrayMax.sha256 create mode 100644 Verify/Discharge/frozen/v2/Counter.sha256 create mode 100644 Verify/Discharge/frozen/v2/PINS create mode 100644 Verify/Discharge/frozen/v2/Token.sha256 create mode 100644 Verify/Discharge/frozen/v2/Vault.sha256 create mode 100755 Verify/Discharge/test/negatives.sh create mode 100644 Verify/Discharge/test/sat/Sat.lean create mode 100644 Verify/Discharge/test/sat/b8.cnf create mode 100644 Verify/Discharge/test/sat/b8.lrat create mode 100644 Verify/Final.lean create mode 100644 Verify/Finite.lean create mode 100644 Verify/Fuel.lean create mode 100644 Verify/FuelStable.lean create mode 100644 Verify/Infer/README.md create mode 100644 Verify/Infer/Reconstruct.lean create mode 100644 Verify/Infer/SHA256SUMS create mode 100644 Verify/Infer/SpacerPath.lean create mode 100644 Verify/Infer/chc/counter_int.smt2 create mode 100644 Verify/Infer/chc/counter_int.spacer.out create mode 100644 Verify/Infer/chc/counter_u256.smt2 create mode 100644 Verify/Infer/chc/counter_u256.spacer.out create mode 100644 Verify/Infer/chc/drain_int.smt2 create mode 100644 Verify/Infer/chc/drain_int.spacer.out create mode 100644 Verify/Infer/chc/drain_u256.smt2 create mode 100644 Verify/Infer/chc/drain_u256.spacer.out create mode 100644 Verify/Infer/chc/okwhile_int.smt2 create mode 100644 Verify/Infer/chc/okwhile_int.spacer.out create mode 100644 Verify/Infer/chc/okwhile_u256.smt2 create mode 100644 Verify/Infer/chc/okwhile_u256.spacer.out create mode 100644 Verify/Infer/flex-4.35-bump.diff create mode 100755 Verify/Infer/gen_reconstruct.sh create mode 100644 Verify/Infer/reconstruct-4.35.axioms.txt create mode 100644 Verify/Infer/smt2lean_inv.py create mode 100644 Verify/Infer/spacerpath-4.35.out create mode 100644 Verify/LoomAxioms.lean create mode 100644 Verify/LoomImports.lean create mode 100644 Verify/Obligation.lean create mode 100644 Verify/Obligation/Model.lean create mode 100644 Verify/Obligation/Smt.lean create mode 100644 Verify/Obligation/Vc.lean create mode 100644 Verify/Reconstruct/.gitignore create mode 100644 Verify/Reconstruct/Tactic.lean create mode 100644 Verify/Reconstruct/lake-manifest.json create mode 100644 Verify/Reconstruct/lakefile.lean create mode 100644 Verify/Reconstruct/lean-toolchain create mode 100644 Verify/Run.lean create mode 100644 Verify/Spec/Contract.lean create mode 100644 Verify/Spec/Ghost.lean create mode 100644 Verify/Spec/GhostFree.lean create mode 100644 Verify/Spec/README.md create mode 100644 Verify/Spec/Semantics.lean create mode 100644 Verify/Spec/Syntax.lean create mode 100644 Verify/Spec/TrustedBase.lean create mode 100644 Verify/Spec/TrustedBase/Axioms.lean create mode 100644 Verify/Spec/TrustedBase/Hypotheses.lean create mode 100644 Verify/Spec/TrustedBase/Instances.lean create mode 100644 Verify/Spec/TrustedBase/Interface.lean create mode 100644 Verify/Tactic.lean create mode 100644 Verify/VC.lean create mode 100644 Verify/VC/Check.lean create mode 100644 Verify/VC/KernelIdx.lean create mode 100644 Verify/VC/Model.lean create mode 100644 Verify/VC/Obligations.lean create mode 100644 Verify/VC/Term.lean create mode 100644 Verify/W1.lean create mode 100644 Verify/W4.lean create mode 100644 Verify/W5.lean create mode 100644 scripts/refinement/spec/c4.sol create mode 100644 scripts/refinement/spec/c4_wrong.sol create mode 100755 scripts/refinement/spec/check.sh create mode 100644 scripts/verify/Counter.sol create mode 100644 scripts/verify/CounterMilestone.sol create mode 100644 scripts/verify/MANIFEST create mode 100644 scripts/verify/Token.sol create mode 100755 scripts/verify/check.sh create mode 100644 scripts/verify/mutant/CounterSpecMut.sol create mode 100644 scripts/verify/mutant/CounterSrcMut.sol create mode 100644 scripts/verify/mutant/MANIFEST create mode 100644 scripts/verify/mutant/TokenSpecMut.sol create mode 100644 scripts/verify/mutant/TokenSrcMut.sol delete mode 100644 vendor/loom/Loom.lean delete mode 100644 vendor/loom/Loom/MonadAlgebras/Instances/Basic.lean delete mode 100644 vendor/loom/Loom/MonadAlgebras/WP/Basic.lean delete mode 100644 vendor/loom/README.md diff --git a/Certified/bank/Proofs.lean b/Certified/bank/Proofs.lean index b3f5f79b..763927f7 100644 --- a/Certified/bank/Proofs.lean +++ b/Certified/bank/Proofs.lean @@ -1,3 +1,3 @@ --- Generated by solar-tv/milestone/certify.py; do not edit. +-- Generated by solar's tools/certify/certify.py; do not edit. import bank.Proofs.Stages import bank.Proofs.Assembly diff --git a/Certified/bank/Proofs/Assembly.lean b/Certified/bank/Proofs/Assembly.lean index ecd79b90..44027393 100644 --- a/Certified/bank/Proofs/Assembly.lean +++ b/Certified/bank/Proofs/Assembly.lean @@ -1,4 +1,4 @@ --- Generated by solar-tv/milestone/certify.py; do not edit. +-- Generated by solar's tools/certify/certify.py; do not edit. import W1Proofs.Items import bank.gen.Bank.Evm11 import bank.gen.Bank.Bytecode diff --git a/Certified/bank/Proofs/Runs/Evm1.lean b/Certified/bank/Proofs/Runs/Evm1.lean index 730c801b..ef5d66d6 100644 --- a/Certified/bank/Proofs/Runs/Evm1.lean +++ b/Certified/bank/Proofs/Runs/Evm1.lean @@ -1,4 +1,4 @@ --- Generated by solar-tv/milestone/certify.py; do not edit. +-- Generated by solar's tools/certify/certify.py; do not edit. import W1Proofs.Tactic import W1Proofs.Axioms import bank.gen.Bank.Evm1 diff --git a/Certified/bank/Proofs/Runs/Evm10.lean b/Certified/bank/Proofs/Runs/Evm10.lean index fcc2d70b..54d647bc 100644 --- a/Certified/bank/Proofs/Runs/Evm10.lean +++ b/Certified/bank/Proofs/Runs/Evm10.lean @@ -1,4 +1,4 @@ --- Generated by solar-tv/milestone/certify.py; do not edit. +-- Generated by solar's tools/certify/certify.py; do not edit. import W1Proofs.Tactic import W1Proofs.Axioms import bank.gen.Bank.Evm10 diff --git a/Certified/bank/Proofs/Runs/Evm11.lean b/Certified/bank/Proofs/Runs/Evm11.lean index 87302e0d..2efcab59 100644 --- a/Certified/bank/Proofs/Runs/Evm11.lean +++ b/Certified/bank/Proofs/Runs/Evm11.lean @@ -1,4 +1,4 @@ --- Generated by solar-tv/milestone/certify.py; do not edit. +-- Generated by solar's tools/certify/certify.py; do not edit. import W1Proofs.Tactic import W1Proofs.Axioms import bank.gen.Bank.Evm11 diff --git a/Certified/bank/Proofs/Runs/Evm2.lean b/Certified/bank/Proofs/Runs/Evm2.lean index ec8a5797..fbca6035 100644 --- a/Certified/bank/Proofs/Runs/Evm2.lean +++ b/Certified/bank/Proofs/Runs/Evm2.lean @@ -1,4 +1,4 @@ --- Generated by solar-tv/milestone/certify.py; do not edit. +-- Generated by solar's tools/certify/certify.py; do not edit. import W1Proofs.Tactic import W1Proofs.Axioms import bank.gen.Bank.Evm2 diff --git a/Certified/bank/Proofs/Runs/Evm3.lean b/Certified/bank/Proofs/Runs/Evm3.lean index bbf5841d..041aa8f4 100644 --- a/Certified/bank/Proofs/Runs/Evm3.lean +++ b/Certified/bank/Proofs/Runs/Evm3.lean @@ -1,4 +1,4 @@ --- Generated by solar-tv/milestone/certify.py; do not edit. +-- Generated by solar's tools/certify/certify.py; do not edit. import W1Proofs.Tactic import W1Proofs.Axioms import bank.gen.Bank.Evm3 diff --git a/Certified/bank/Proofs/Runs/Evm4.lean b/Certified/bank/Proofs/Runs/Evm4.lean index 1f15c4de..e5a0d2f3 100644 --- a/Certified/bank/Proofs/Runs/Evm4.lean +++ b/Certified/bank/Proofs/Runs/Evm4.lean @@ -1,4 +1,4 @@ --- Generated by solar-tv/milestone/certify.py; do not edit. +-- Generated by solar's tools/certify/certify.py; do not edit. import W1Proofs.Tactic import W1Proofs.Axioms import bank.gen.Bank.Evm4 diff --git a/Certified/bank/Proofs/Runs/Evm5.lean b/Certified/bank/Proofs/Runs/Evm5.lean index 74ded001..3a8fae1b 100644 --- a/Certified/bank/Proofs/Runs/Evm5.lean +++ b/Certified/bank/Proofs/Runs/Evm5.lean @@ -1,4 +1,4 @@ --- Generated by solar-tv/milestone/certify.py; do not edit. +-- Generated by solar's tools/certify/certify.py; do not edit. import W1Proofs.Tactic import W1Proofs.Axioms import bank.gen.Bank.Evm5 diff --git a/Certified/bank/Proofs/Runs/Evm6.lean b/Certified/bank/Proofs/Runs/Evm6.lean index 26b6757d..dc18c1c9 100644 --- a/Certified/bank/Proofs/Runs/Evm6.lean +++ b/Certified/bank/Proofs/Runs/Evm6.lean @@ -1,4 +1,4 @@ --- Generated by solar-tv/milestone/certify.py; do not edit. +-- Generated by solar's tools/certify/certify.py; do not edit. import W1Proofs.Tactic import W1Proofs.Axioms import bank.gen.Bank.Evm6 diff --git a/Certified/bank/Proofs/Runs/Evm7.lean b/Certified/bank/Proofs/Runs/Evm7.lean index 7affbe1d..077839ee 100644 --- a/Certified/bank/Proofs/Runs/Evm7.lean +++ b/Certified/bank/Proofs/Runs/Evm7.lean @@ -1,4 +1,4 @@ --- Generated by solar-tv/milestone/certify.py; do not edit. +-- Generated by solar's tools/certify/certify.py; do not edit. import W1Proofs.Tactic import W1Proofs.Axioms import bank.gen.Bank.Evm7 diff --git a/Certified/bank/Proofs/Runs/Evm8.lean b/Certified/bank/Proofs/Runs/Evm8.lean index 793328db..4632acfc 100644 --- a/Certified/bank/Proofs/Runs/Evm8.lean +++ b/Certified/bank/Proofs/Runs/Evm8.lean @@ -1,4 +1,4 @@ --- Generated by solar-tv/milestone/certify.py; do not edit. +-- Generated by solar's tools/certify/certify.py; do not edit. import W1Proofs.Tactic import W1Proofs.Axioms import bank.gen.Bank.Evm8 diff --git a/Certified/bank/Proofs/Runs/Evm9.lean b/Certified/bank/Proofs/Runs/Evm9.lean index 52c307e7..a2cad2ac 100644 --- a/Certified/bank/Proofs/Runs/Evm9.lean +++ b/Certified/bank/Proofs/Runs/Evm9.lean @@ -1,4 +1,4 @@ --- Generated by solar-tv/milestone/certify.py; do not edit. +-- Generated by solar's tools/certify/certify.py; do not edit. import W1Proofs.Tactic import W1Proofs.Axioms import bank.gen.Bank.Evm9 diff --git a/Certified/bank/Proofs/Runs/Mir1.lean b/Certified/bank/Proofs/Runs/Mir1.lean index 1d7e3dc8..e3104b39 100644 --- a/Certified/bank/Proofs/Runs/Mir1.lean +++ b/Certified/bank/Proofs/Runs/Mir1.lean @@ -1,4 +1,4 @@ --- Generated by solar-tv/milestone/certify.py; do not edit. +-- Generated by solar's tools/certify/certify.py; do not edit. import W1Proofs.Tactic import W1Proofs.Axioms import bank.gen.Bank.Mir1 diff --git a/Certified/bank/Proofs/Runs/Mir2.lean b/Certified/bank/Proofs/Runs/Mir2.lean index 652758b4..3639fa98 100644 --- a/Certified/bank/Proofs/Runs/Mir2.lean +++ b/Certified/bank/Proofs/Runs/Mir2.lean @@ -1,4 +1,4 @@ --- Generated by solar-tv/milestone/certify.py; do not edit. +-- Generated by solar's tools/certify/certify.py; do not edit. import W1Proofs.Tactic import W1Proofs.Axioms import bank.gen.Bank.Mir2 diff --git a/Certified/bank/Proofs/Runs/Mir3.lean b/Certified/bank/Proofs/Runs/Mir3.lean index d7680337..feb75f59 100644 --- a/Certified/bank/Proofs/Runs/Mir3.lean +++ b/Certified/bank/Proofs/Runs/Mir3.lean @@ -1,4 +1,4 @@ --- Generated by solar-tv/milestone/certify.py; do not edit. +-- Generated by solar's tools/certify/certify.py; do not edit. import W1Proofs.Tactic import W1Proofs.Axioms import bank.gen.Bank.Mir3 diff --git a/Certified/bank/Proofs/Runs/Mir4.lean b/Certified/bank/Proofs/Runs/Mir4.lean index 0c4a23d9..9799d1e8 100644 --- a/Certified/bank/Proofs/Runs/Mir4.lean +++ b/Certified/bank/Proofs/Runs/Mir4.lean @@ -1,4 +1,4 @@ --- Generated by solar-tv/milestone/certify.py; do not edit. +-- Generated by solar's tools/certify/certify.py; do not edit. import W1Proofs.Tactic import W1Proofs.Axioms import bank.gen.Bank.Mir4 diff --git a/Certified/bank/Proofs/Runs/Sched.lean b/Certified/bank/Proofs/Runs/Sched.lean index 60b04044..134c4694 100644 --- a/Certified/bank/Proofs/Runs/Sched.lean +++ b/Certified/bank/Proofs/Runs/Sched.lean @@ -1,4 +1,4 @@ --- Generated by solar-tv/milestone/certify.py; do not edit. +-- Generated by solar's tools/certify/certify.py; do not edit. import W1Proofs.Tactic import W1Proofs.Axioms import bank.gen.Bank.Sched diff --git a/Certified/bank/Proofs/Runs/Stage0.lean b/Certified/bank/Proofs/Runs/Stage0.lean index b583b1ca..028bee66 100644 --- a/Certified/bank/Proofs/Runs/Stage0.lean +++ b/Certified/bank/Proofs/Runs/Stage0.lean @@ -1,4 +1,4 @@ --- Generated by solar-tv/milestone/certify.py; do not edit. +-- Generated by solar's tools/certify/certify.py; do not edit. import W1Proofs.Tactic import W1Proofs.Axioms import bank.gen.Bank.Stage0 diff --git a/Certified/bank/Proofs/Stages.lean b/Certified/bank/Proofs/Stages.lean index cf1368d4..48345a72 100644 --- a/Certified/bank/Proofs/Stages.lean +++ b/Certified/bank/Proofs/Stages.lean @@ -1,4 +1,4 @@ --- Generated by solar-tv/milestone/certify.py; do not edit. +-- Generated by solar's tools/certify/certify.py; do not edit. import bank.Proofs.Runs.Stage0 import bank.Proofs.Runs.Mir1 import bank.Proofs.Runs.Mir2 diff --git a/Certified/bank/gen/Bank/Manifest.lean b/Certified/bank/gen/Bank/Manifest.lean index fb9d324e..797dca4a 100644 --- a/Certified/bank/gen/Bank/Manifest.lean +++ b/Certified/bank/gen/Bank/Manifest.lean @@ -8,17 +8,17 @@ stage's file, its definition, the pass whose output it is, and the SHA-256 of th namespace SolarTV.Export.Bank.Manifest def sources : List (String × String) := - [("solar-tv/milestone/bank/bank.sol", "513398d47335b204a6b047493dd86e9c05066e950ba1300ba5d25850a5f8cb1f")] + [("Certified/bank/bank.sol", "513398d47335b204a6b047493dd86e9c05066e950ba1300ba5d25850a5f8cb1f")] -def compiler : String := "0.8.38+commit.4a7d9ede.solar.0.3.0-dev" +def compiler : String := "0.8.38+commit.ebdc3376.solar.0.3.0-dev" def arguments : List String := - ["solar-tv/milestone/bank/bank.sol", + ["Certified/bank/bank.sol", "-Ogas", "--evm-version", "osaka", "--emit=bin-runtime", - "-Zemit-lean-stages=solar-tv/milestone/bank/gen"] + "-Zemit-lean-stages=Certified/bank/gen"] def evmVersion : String := "osaka" diff --git a/Certified/bank/gen/Bank/Schedule.json b/Certified/bank/gen/Bank/Schedule.json new file mode 100644 index 00000000..40a43ffa --- /dev/null +++ b/Certified/bank/gen/Bank/Schedule.json @@ -0,0 +1,49 @@ +{ + "functions": [ + {"function": 4, "entry": null, "returns": false, "rebuilt": false, "unsupported": null, "blocks": [ + {"block": 0, "start": [0, 0], "layout": [], "floating": true, "continues": null}, + {"block": 1, "start": [1, 0], "layout": [], "floating": true, "continues": null}, + {"block": 2, "start": [4, 0], "layout": [], "floating": true, "continues": null}, + {"block": 3, "start": [3, 0], "layout": [], "floating": true, "continues": null}, + {"block": 4, "start": [2, 0], "layout": [], "floating": true, "continues": null}, + {"block": 5, "start": [5, 0], "layout": [], "floating": true, "continues": null} + ]}, + {"function": 1, "entry": 6, "returns": false, "rebuilt": false, "unsupported": null, "blocks": [ + {"block": 0, "start": [6, 0], "layout": [], "floating": true, "continues": null}, + {"block": 1, "start": [14, 0], "layout": [], "floating": true, "continues": null}, + {"block": 2, "start": [7, 0], "layout": [], "floating": true, "continues": null}, + {"block": 3, "start": [13, 0], "layout": ["v25", "v26", "v27"], "floating": true, "continues": null}, + {"block": 4, "start": [12, 0], "layout": [], "floating": true, "continues": null}, + {"block": 5, "start": [9, 0], "layout": [], "floating": true, "continues": null}, + {"block": 6, "start": [11, 0], "layout": [], "floating": true, "continues": null}, + {"block": 7, "start": [10, 0], "layout": [], "floating": true, "continues": null} + ]}, + {"function": 2, "entry": 15, "returns": false, "rebuilt": false, "unsupported": null, "blocks": [ + {"block": 0, "start": [15, 0], "layout": [], "floating": true, "continues": null}, + {"block": 1, "start": [23, 0], "layout": [], "floating": true, "continues": null}, + {"block": 2, "start": [16, 0], "layout": [], "floating": true, "continues": null}, + {"block": 3, "start": [22, 0], "layout": ["v37", "v36", "v35"], "floating": true, "continues": null}, + {"block": 4, "start": [21, 0], "layout": ["v22", "junk"], "floating": true, "continues": null}, + {"block": 5, "start": [18, 0], "layout": ["v22", "v19"], "floating": true, "continues": null}, + {"block": 6, "start": [20, 0], "layout": ["v22", "v19"], "floating": true, "continues": null}, + {"block": 7, "start": [19, 0], "layout": [], "floating": true, "continues": null} + ]}, + {"function": 3, "entry": 24, "returns": false, "rebuilt": false, "unsupported": null, "blocks": [ + {"block": 0, "start": [24, 0], "layout": [], "floating": true, "continues": null}, + {"block": 1, "start": [29, 0], "layout": [], "floating": true, "continues": null}, + {"block": 2, "start": [25, 0], "layout": [], "floating": true, "continues": null}, + {"block": 3, "start": [28, 0], "layout": ["v39", "v38", "v37"], "floating": true, "continues": null}, + {"block": 4, "start": [27, 0], "layout": ["v26", "v24"], "floating": true, "continues": null}, + {"block": 5, "start": [26, 0], "layout": [], "floating": true, "continues": null} + ]}, + {"function": 0, "entry": 30, "returns": true, "rebuilt": false, "unsupported": null, "blocks": [ + {"block": 0, "start": [30, 0], "layout": ["v1", "v0", "ret"], "floating": false, "continues": null}, + {"block": 1, "start": [34, 0], "layout": [], "floating": true, "continues": null}, + {"block": 2, "start": [32, 0], "layout": ["v1", "junk", "ret", "v29", "v15"], "floating": false, "continues": null}, + {"block": 3, "start": [33, 0], "layout": ["v23", "junk", "ret", "v29"], "floating": false, "continues": null}, + {"block": 4, "start": [36, 0], "layout": ["v35", "v34", "v36"], "floating": true, "continues": null}, + {"block": 5, "start": [35, 0], "layout": ["v0", "junk", "junk", "junk", "junk"], "floating": true, "continues": null}, + {"block": 6, "start": [31, 0], "layout": ["v1", "junk", "ret", "v29", "v15", "v16"], "floating": false, "continues": null} + ]} + ] +} diff --git a/Certified/bank/gen/Bank/manifest.json b/Certified/bank/gen/Bank/manifest.json index de1bacdb..6d0a9011 100644 --- a/Certified/bank/gen/Bank/manifest.json +++ b/Certified/bank/gen/Bank/manifest.json @@ -1,22 +1,22 @@ { "arguments": [ - "solar-tv/milestone/bank/bank.sol", + "Certified/bank/bank.sol", "-Ogas", "--evm-version", "osaka", "--emit=bin-runtime", - "-Zemit-lean-stages=solar-tv/milestone/bank/gen" + "-Zemit-lean-stages=Certified/bank/gen" ], "bytecode": "346028575f3560e01c80632f4f21e21460f857806370a0823114610161578063b6b55f2514603e575b5f5ffd5b6011602052634e487b715f526024601cfd5b60243610602857600435803360875b815f525f60205260405f2080548481019081105f1960601c85116101a657602c578155600154938401938410602c57926001559154905090565b905f52337fe1fffcc4923d04b559f4d29a8bfc6cda04eb5b0d3c460751c2402c5c5cc9109c60205fa25f525f1960601c331160cb575f1960601c331160cb5760205ff35b690417000000010000000260201b335f1960601c915b6020525b60405260605263ed572b275f526064601cfd5b60043560a01c60443610176028576004355f1960601c81166024358261011b604d565b5f525f1960601c8211610147578181036101345760205ff35b6d010200000002000000020000000760e1565b505f1960601c906d041700000002000000020000000960e1565b60043560a01c60243610176028576004355f1960601c8116815f525f60205260405f20545f528181036101935760205ff35b6d010200000003000000020000000960e1565b505050505f1960601c6d04170000000000000000800000006020529060e556", "bytecode_sha256": "bff0578068ce4ab4a041f226e4e960c13d358c8b430718fefe9ce3a22d760543", - "compiler": "0.8.38+commit.4a7d9ede.solar.0.3.0-dev", + "compiler": "0.8.38+commit.ebdc3376.solar.0.3.0-dev", "contract": "Bank", "evm_version": "osaka", "optimization": "Gas", - "options": "CompileOpts { input: [\"solar-tv/milestone/bank/bank.sol\"], import_remappings: [], base_path: None, include_paths: [], allow_paths: [], no_import_callback: false, language: Solidity, threads: 4, evm_version: Osaka, stop_after: None, optimization: Gas, optimizer_runs: None, revert_strings: Default, libraries: [], out_dir: None, emit: [BinRuntime], standard_json: false, color: Auto, verbose: false, pretty_json: false, pretty_json_err: false, error_format: Human, error_format_human: Unicode, diagnostic_width: None, no_warnings: false, allow: [], _unstable: [\"emit-lean-stages=solar-tv/milestone/bank/gen\"], unstable: UnstableOpts { ui_testing: false, track_diagnostics: false, parse_yul: false, no_resolve_imports: false, recover_incomplete_input: false, dump: None, ast_stats: false, hir_stats: false, standard_json_stats: false, span_visitor: false, print_max_storage_sizes: false, print_natspec: false, mir_pipeline: None, evm_ir_pipeline: None, print_after_each: false, pass_diff: false, debugify: None, debugify_output: None, solar_tv: None, validate_ir: None, time_passes: false, codegen_all_functions: false, switch_lowering: Auto, switch_max_gas_code_growth: None, switch_max_bit_slice_gas_code_growth: None, tune: None, pack_wide_jump_tables: false, check_analyses: None, prove_analyses: None, validate_passes: None, validate_passes_fault: None, validate_backend: None, validate_backend_fault: None, validate_evm_ir_passes: None, validate_assembly: false, validate_assembly_fault: None, emit_lean_stages: Some(\"solar-tv/milestone/bank/gen\"), forget_gcx: true, help: (), _non_exhaustive: () }, _non_exhaustive: () }", + "options": "CompileOpts { input: [\"Certified/bank/bank.sol\"], import_remappings: [], base_path: None, include_paths: [], allow_paths: [], no_import_callback: false, language: Solidity, threads: 4, evm_version: Osaka, stop_after: None, optimization: Gas, optimizer_runs: None, revert_strings: Default, libraries: [], out_dir: None, emit: [BinRuntime], standard_json: false, color: Auto, verbose: false, pretty_json: false, pretty_json_err: false, error_format: Human, error_format_human: Unicode, diagnostic_width: None, no_warnings: false, allow: [], _unstable: [\"emit-lean-stages=Certified/bank/gen\"], unstable: UnstableOpts { ui_testing: false, track_diagnostics: false, parse_yul: false, no_resolve_imports: false, recover_incomplete_input: false, dump: None, ast_stats: false, hir_stats: false, standard_json_stats: false, span_visitor: false, print_max_storage_sizes: false, print_natspec: false, mir_pipeline: None, evm_ir_pipeline: None, print_after_each: false, pass_diff: false, debugify: None, debugify_output: None, solar_tv: None, validate_ir: None, time_passes: false, codegen_all_functions: false, switch_lowering: Auto, switch_max_gas_code_growth: None, switch_max_bit_slice_gas_code_growth: None, tune: None, pack_wide_jump_tables: false, check_analyses: None, prove_analyses: None, validate_passes: None, validate_passes_fault: None, validate_backend: None, validate_backend_fault: None, validate_evm_ir_passes: None, validate_assembly: false, validate_assembly_fault: None, emit_lean_stages: Some(\"Certified/bank/gen\"), forget_gcx: true, help: (), _non_exhaustive: () }, _non_exhaustive: () }", "sources": [ { - "path": "solar-tv/milestone/bank/bank.sol", + "path": "Certified/bank/bank.sol", "sha256": "513398d47335b204a6b047493dd86e9c05066e950ba1300ba5d25850a5f8cb1f" } ], diff --git a/Certified/c4/Proofs.lean b/Certified/c4/Proofs.lean index 917eee10..0166581d 100644 --- a/Certified/c4/Proofs.lean +++ b/Certified/c4/Proofs.lean @@ -1,3 +1,3 @@ --- Generated by solar-tv/milestone/certify.py; do not edit. +-- Generated by solar's tools/certify/certify.py; do not edit. import c4.Proofs.Stages import c4.Proofs.Assembly diff --git a/Certified/c4/Proofs/Assembly.lean b/Certified/c4/Proofs/Assembly.lean index 2c390c0a..067b07e9 100644 --- a/Certified/c4/Proofs/Assembly.lean +++ b/Certified/c4/Proofs/Assembly.lean @@ -1,4 +1,4 @@ --- Generated by solar-tv/milestone/certify.py; do not edit. +-- Generated by solar's tools/certify/certify.py; do not edit. import W1Proofs.Items import c4.gen.Main.Evm5 import c4.gen.Main.Bytecode diff --git a/Certified/c4/Proofs/Runs/Evm1.lean b/Certified/c4/Proofs/Runs/Evm1.lean index b75819fc..cc48770f 100644 --- a/Certified/c4/Proofs/Runs/Evm1.lean +++ b/Certified/c4/Proofs/Runs/Evm1.lean @@ -1,4 +1,4 @@ --- Generated by solar-tv/milestone/certify.py; do not edit. +-- Generated by solar's tools/certify/certify.py; do not edit. import W1Proofs.Tactic import W1Proofs.Axioms import c4.gen.Main.Evm1 diff --git a/Certified/c4/Proofs/Runs/Evm2.lean b/Certified/c4/Proofs/Runs/Evm2.lean index b7cf671b..4d360647 100644 --- a/Certified/c4/Proofs/Runs/Evm2.lean +++ b/Certified/c4/Proofs/Runs/Evm2.lean @@ -1,4 +1,4 @@ --- Generated by solar-tv/milestone/certify.py; do not edit. +-- Generated by solar's tools/certify/certify.py; do not edit. import W1Proofs.Tactic import W1Proofs.Axioms import c4.gen.Main.Evm2 diff --git a/Certified/c4/Proofs/Runs/Evm3.lean b/Certified/c4/Proofs/Runs/Evm3.lean index ed72962b..9c3c08a1 100644 --- a/Certified/c4/Proofs/Runs/Evm3.lean +++ b/Certified/c4/Proofs/Runs/Evm3.lean @@ -1,4 +1,4 @@ --- Generated by solar-tv/milestone/certify.py; do not edit. +-- Generated by solar's tools/certify/certify.py; do not edit. import W1Proofs.Tactic import W1Proofs.Axioms import c4.gen.Main.Evm3 diff --git a/Certified/c4/Proofs/Runs/Evm4.lean b/Certified/c4/Proofs/Runs/Evm4.lean index c32ed649..b56776e1 100644 --- a/Certified/c4/Proofs/Runs/Evm4.lean +++ b/Certified/c4/Proofs/Runs/Evm4.lean @@ -1,4 +1,4 @@ --- Generated by solar-tv/milestone/certify.py; do not edit. +-- Generated by solar's tools/certify/certify.py; do not edit. import W1Proofs.Tactic import W1Proofs.Axioms import c4.gen.Main.Evm4 diff --git a/Certified/c4/Proofs/Runs/Evm5.lean b/Certified/c4/Proofs/Runs/Evm5.lean index 67b7aca4..0043a221 100644 --- a/Certified/c4/Proofs/Runs/Evm5.lean +++ b/Certified/c4/Proofs/Runs/Evm5.lean @@ -1,4 +1,4 @@ --- Generated by solar-tv/milestone/certify.py; do not edit. +-- Generated by solar's tools/certify/certify.py; do not edit. import W1Proofs.Tactic import W1Proofs.Axioms import c4.gen.Main.Evm5 diff --git a/Certified/c4/Proofs/Runs/Mir1.lean b/Certified/c4/Proofs/Runs/Mir1.lean index db851e68..b3d9d612 100644 --- a/Certified/c4/Proofs/Runs/Mir1.lean +++ b/Certified/c4/Proofs/Runs/Mir1.lean @@ -1,4 +1,4 @@ --- Generated by solar-tv/milestone/certify.py; do not edit. +-- Generated by solar's tools/certify/certify.py; do not edit. import W1Proofs.Tactic import W1Proofs.Axioms import c4.gen.Main.Mir1 diff --git a/Certified/c4/Proofs/Runs/Mir2.lean b/Certified/c4/Proofs/Runs/Mir2.lean index 2d539034..ec549d08 100644 --- a/Certified/c4/Proofs/Runs/Mir2.lean +++ b/Certified/c4/Proofs/Runs/Mir2.lean @@ -1,4 +1,4 @@ --- Generated by solar-tv/milestone/certify.py; do not edit. +-- Generated by solar's tools/certify/certify.py; do not edit. import W1Proofs.Tactic import W1Proofs.Axioms import c4.gen.Main.Mir2 diff --git a/Certified/c4/Proofs/Runs/Sched.lean b/Certified/c4/Proofs/Runs/Sched.lean index 8761487d..8ecd9cbe 100644 --- a/Certified/c4/Proofs/Runs/Sched.lean +++ b/Certified/c4/Proofs/Runs/Sched.lean @@ -1,4 +1,4 @@ --- Generated by solar-tv/milestone/certify.py; do not edit. +-- Generated by solar's tools/certify/certify.py; do not edit. import W1Proofs.Tactic import W1Proofs.Axioms import c4.gen.Main.Sched diff --git a/Certified/c4/Proofs/Runs/Stage0.lean b/Certified/c4/Proofs/Runs/Stage0.lean index 66d35e89..9aac8097 100644 --- a/Certified/c4/Proofs/Runs/Stage0.lean +++ b/Certified/c4/Proofs/Runs/Stage0.lean @@ -1,4 +1,4 @@ --- Generated by solar-tv/milestone/certify.py; do not edit. +-- Generated by solar's tools/certify/certify.py; do not edit. import W1Proofs.Tactic import W1Proofs.Axioms import c4.gen.Main.Stage0 diff --git a/Certified/c4/Proofs/Stages.lean b/Certified/c4/Proofs/Stages.lean index 3e15b1bf..e747a283 100644 --- a/Certified/c4/Proofs/Stages.lean +++ b/Certified/c4/Proofs/Stages.lean @@ -1,4 +1,4 @@ --- Generated by solar-tv/milestone/certify.py; do not edit. +-- Generated by solar's tools/certify/certify.py; do not edit. import c4.Proofs.Runs.Stage0 import c4.Proofs.Runs.Mir1 import c4.Proofs.Runs.Mir2 diff --git a/Certified/c4/gen/Main/Manifest.lean b/Certified/c4/gen/Main/Manifest.lean index fa2e01b2..28e0c15f 100644 --- a/Certified/c4/gen/Main/Manifest.lean +++ b/Certified/c4/gen/Main/Manifest.lean @@ -8,15 +8,15 @@ stage's file, its definition, the pass whose output it is, and the SHA-256 of th namespace SolarTV.Export.Main.Manifest def sources : List (String × String) := - [("solar-tv/milestone/c4/c4.sol", "31c39cd4e9c5cba0f78aff3a986d69be40c5f68cdb36fbf05ad3d0a5e950e858")] + [("Certified/c4/c4.sol", "31c39cd4e9c5cba0f78aff3a986d69be40c5f68cdb36fbf05ad3d0a5e950e858")] -def compiler : String := "0.8.38+commit.a8179dfc.solar.0.3.0-dev" +def compiler : String := "0.8.38+commit.ebdc3376.solar.0.3.0-dev" def arguments : List String := - ["solar-tv/milestone/c4/c4.sol", + ["Certified/c4/c4.sol", "-Zcheck-analyses=false", "--emit=bin-runtime", - "-Zemit-lean-stages=solar-tv/milestone/c4/gen"] + "-Zemit-lean-stages=Certified/c4/gen"] def evmVersion : String := "osaka" diff --git a/Certified/c4/gen/Main/Schedule.json b/Certified/c4/gen/Main/Schedule.json new file mode 100644 index 00000000..6f6c293b --- /dev/null +++ b/Certified/c4/gen/Main/Schedule.json @@ -0,0 +1,17 @@ +{ + "functions": [ + {"function": 2, "entry": null, "returns": false, "rebuilt": false, "unsupported": null, "blocks": [ + {"block": 0, "start": [0, 0], "layout": [], "floating": true, "continues": null}, + {"block": 1, "start": [1, 0], "layout": [], "floating": true, "continues": null}, + {"block": 2, "start": [2, 0], "layout": [], "floating": true, "continues": null}, + {"block": 3, "start": [3, 0], "layout": [], "floating": true, "continues": null} + ]}, + {"function": 0, "entry": 4, "returns": false, "rebuilt": false, "unsupported": null, "blocks": [ + {"block": 0, "start": [4, 0], "layout": [], "floating": true, "continues": null}, + {"block": 1, "start": [7, 0], "layout": [], "floating": true, "continues": null}, + {"block": 2, "start": [6, 0], "layout": ["v72", "v2", "v34"], "floating": true, "continues": null}, + {"block": 3, "start": [8, 0], "layout": [], "floating": true, "continues": null}, + {"block": 4, "start": [5, 0], "layout": [], "floating": true, "continues": null} + ]} + ] +} diff --git a/Certified/c4/gen/Main/manifest.json b/Certified/c4/gen/Main/manifest.json index e366f591..5f7763f2 100644 --- a/Certified/c4/gen/Main/manifest.json +++ b/Certified/c4/gen/Main/manifest.json @@ -1,20 +1,20 @@ { "arguments": [ - "solar-tv/milestone/c4/c4.sol", + "Certified/c4/c4.sol", "-Zcheck-analyses=false", "--emit=bin-runtime", - "-Zemit-lean-stages=solar-tv/milestone/c4/gen" + "-Zemit-lean-stages=Certified/c4/gen" ], "bytecode": "346055575f3560e01c806302067e6a036055576024361060ff60043511176055576004355f5460ff8116820160ff81116059579060ff1916179081601e1a1860081b9061ff00191617805f5560ff165f5260205ff35b5f5ffd5b6011602052634e487b715f526024601cfd", "bytecode_sha256": "8a21bc207d9dd8be48d921a717eda3ecb7e5bfcb5397850bc3d64a29037fac47", - "compiler": "0.8.38+commit.a8179dfc.solar.0.3.0-dev", + "compiler": "0.8.38+commit.ebdc3376.solar.0.3.0-dev", "contract": "Main", "evm_version": "osaka", "optimization": "Gas", - "options": "CompileOpts { input: [\"solar-tv/milestone/c4/c4.sol\"], import_remappings: [], base_path: None, include_paths: [], allow_paths: [], no_import_callback: false, language: Solidity, threads: 4, evm_version: Osaka, stop_after: None, optimization: Gas, optimizer_runs: None, revert_strings: Default, libraries: [], out_dir: None, emit: [BinRuntime], standard_json: false, color: Auto, verbose: false, pretty_json: false, pretty_json_err: false, error_format: Human, error_format_human: Unicode, diagnostic_width: None, no_warnings: false, allow: [], _unstable: [\"check-analyses=false\", \"emit-lean-stages=solar-tv/milestone/c4/gen\"], unstable: UnstableOpts { ui_testing: false, track_diagnostics: false, parse_yul: false, no_resolve_imports: false, recover_incomplete_input: false, dump: None, ast_stats: false, hir_stats: false, standard_json_stats: false, span_visitor: false, print_max_storage_sizes: false, print_natspec: false, mir_pipeline: None, evm_ir_pipeline: None, print_after_each: false, pass_diff: false, debugify: None, debugify_output: None, solar_tv: None, validate_ir: None, time_passes: false, codegen_all_functions: false, switch_lowering: Auto, switch_max_gas_code_growth: None, switch_max_bit_slice_gas_code_growth: None, tune: None, pack_wide_jump_tables: false, check_analyses: Some(false), prove_analyses: None, validate_passes: None, validate_passes_fault: None, validate_backend: None, validate_backend_fault: None, validate_evm_ir_passes: None, validate_assembly: false, validate_assembly_fault: None, emit_lean_stages: Some(\"solar-tv/milestone/c4/gen\"), forget_gcx: true, help: (), _non_exhaustive: () }, _non_exhaustive: () }", + "options": "CompileOpts { input: [\"Certified/c4/c4.sol\"], import_remappings: [], base_path: None, include_paths: [], allow_paths: [], no_import_callback: false, language: Solidity, threads: 4, evm_version: Osaka, stop_after: None, optimization: Gas, optimizer_runs: None, revert_strings: Default, libraries: [], out_dir: None, emit: [BinRuntime], standard_json: false, color: Auto, verbose: false, pretty_json: false, pretty_json_err: false, error_format: Human, error_format_human: Unicode, diagnostic_width: None, no_warnings: false, allow: [], _unstable: [\"check-analyses=false\", \"emit-lean-stages=Certified/c4/gen\"], unstable: UnstableOpts { ui_testing: false, track_diagnostics: false, parse_yul: false, no_resolve_imports: false, recover_incomplete_input: false, dump: None, ast_stats: false, hir_stats: false, standard_json_stats: false, span_visitor: false, print_max_storage_sizes: false, print_natspec: false, mir_pipeline: None, evm_ir_pipeline: None, print_after_each: false, pass_diff: false, debugify: None, debugify_output: None, solar_tv: None, validate_ir: None, time_passes: false, codegen_all_functions: false, switch_lowering: Auto, switch_max_gas_code_growth: None, switch_max_bit_slice_gas_code_growth: None, tune: None, pack_wide_jump_tables: false, check_analyses: Some(false), prove_analyses: None, validate_passes: None, validate_passes_fault: None, validate_backend: None, validate_backend_fault: None, validate_evm_ir_passes: None, validate_assembly: false, validate_assembly_fault: None, emit_lean_stages: Some(\"Certified/c4/gen\"), forget_gcx: true, help: (), _non_exhaustive: () }, _non_exhaustive: () }", "sources": [ { - "path": "solar-tv/milestone/c4/c4.sol", + "path": "Certified/c4/c4.sol", "sha256": "31c39cd4e9c5cba0f78aff3a986d69be40c5f68cdb36fbf05ad3d0a5e950e858" } ], diff --git a/Certified/counter/Proofs.lean b/Certified/counter/Proofs.lean index ca069136..701668e1 100644 --- a/Certified/counter/Proofs.lean +++ b/Certified/counter/Proofs.lean @@ -1,3 +1,3 @@ --- Generated by solar-tv/milestone/certify.py; do not edit. +-- Generated by solar's tools/certify/certify.py; do not edit. import counter.Proofs.Stages import counter.Proofs.Assembly diff --git a/Certified/counter/Proofs/Assembly.lean b/Certified/counter/Proofs/Assembly.lean index 318bc818..1b985613 100644 --- a/Certified/counter/Proofs/Assembly.lean +++ b/Certified/counter/Proofs/Assembly.lean @@ -1,4 +1,4 @@ --- Generated by solar-tv/milestone/certify.py; do not edit. +-- Generated by solar's tools/certify/certify.py; do not edit. import W1Proofs.Items import counter.gen.Counter.Evm5 import counter.gen.Counter.Bytecode diff --git a/Certified/counter/Proofs/Runs/Evm1.lean b/Certified/counter/Proofs/Runs/Evm1.lean index a5dbb270..3713dac3 100644 --- a/Certified/counter/Proofs/Runs/Evm1.lean +++ b/Certified/counter/Proofs/Runs/Evm1.lean @@ -1,4 +1,4 @@ --- Generated by solar-tv/milestone/certify.py; do not edit. +-- Generated by solar's tools/certify/certify.py; do not edit. import W1Proofs.Tactic import W1Proofs.Axioms import counter.gen.Counter.Evm1 diff --git a/Certified/counter/Proofs/Runs/Evm2.lean b/Certified/counter/Proofs/Runs/Evm2.lean index ae5b491c..93a4bccb 100644 --- a/Certified/counter/Proofs/Runs/Evm2.lean +++ b/Certified/counter/Proofs/Runs/Evm2.lean @@ -1,4 +1,4 @@ --- Generated by solar-tv/milestone/certify.py; do not edit. +-- Generated by solar's tools/certify/certify.py; do not edit. import W1Proofs.Tactic import W1Proofs.Axioms import counter.gen.Counter.Evm2 diff --git a/Certified/counter/Proofs/Runs/Evm3.lean b/Certified/counter/Proofs/Runs/Evm3.lean index 04fc3dd8..bfbfb0c8 100644 --- a/Certified/counter/Proofs/Runs/Evm3.lean +++ b/Certified/counter/Proofs/Runs/Evm3.lean @@ -1,4 +1,4 @@ --- Generated by solar-tv/milestone/certify.py; do not edit. +-- Generated by solar's tools/certify/certify.py; do not edit. import W1Proofs.Tactic import W1Proofs.Axioms import counter.gen.Counter.Evm3 diff --git a/Certified/counter/Proofs/Runs/Evm4.lean b/Certified/counter/Proofs/Runs/Evm4.lean index 5ef315d8..9105ddf9 100644 --- a/Certified/counter/Proofs/Runs/Evm4.lean +++ b/Certified/counter/Proofs/Runs/Evm4.lean @@ -1,4 +1,4 @@ --- Generated by solar-tv/milestone/certify.py; do not edit. +-- Generated by solar's tools/certify/certify.py; do not edit. import W1Proofs.Tactic import W1Proofs.Axioms import counter.gen.Counter.Evm4 diff --git a/Certified/counter/Proofs/Runs/Evm5.lean b/Certified/counter/Proofs/Runs/Evm5.lean index 4fd13129..52b3db31 100644 --- a/Certified/counter/Proofs/Runs/Evm5.lean +++ b/Certified/counter/Proofs/Runs/Evm5.lean @@ -1,4 +1,4 @@ --- Generated by solar-tv/milestone/certify.py; do not edit. +-- Generated by solar's tools/certify/certify.py; do not edit. import W1Proofs.Tactic import W1Proofs.Axioms import counter.gen.Counter.Evm5 diff --git a/Certified/counter/Proofs/Runs/Sched.lean b/Certified/counter/Proofs/Runs/Sched.lean index 21088a28..4c21fb61 100644 --- a/Certified/counter/Proofs/Runs/Sched.lean +++ b/Certified/counter/Proofs/Runs/Sched.lean @@ -1,4 +1,4 @@ --- Generated by solar-tv/milestone/certify.py; do not edit. +-- Generated by solar's tools/certify/certify.py; do not edit. import W1Proofs.Tactic import W1Proofs.Axioms import counter.gen.Counter.Sched diff --git a/Certified/counter/Proofs/Runs/Stage0.lean b/Certified/counter/Proofs/Runs/Stage0.lean index 887491d0..a95eccf4 100644 --- a/Certified/counter/Proofs/Runs/Stage0.lean +++ b/Certified/counter/Proofs/Runs/Stage0.lean @@ -1,4 +1,4 @@ --- Generated by solar-tv/milestone/certify.py; do not edit. +-- Generated by solar's tools/certify/certify.py; do not edit. import W1Proofs.Tactic import W1Proofs.Axioms import counter.gen.Counter.Stage0 diff --git a/Certified/counter/Proofs/Stages.lean b/Certified/counter/Proofs/Stages.lean index c3be22b8..dcc9b0cf 100644 --- a/Certified/counter/Proofs/Stages.lean +++ b/Certified/counter/Proofs/Stages.lean @@ -1,4 +1,4 @@ --- Generated by solar-tv/milestone/certify.py; do not edit. +-- Generated by solar's tools/certify/certify.py; do not edit. import counter.Proofs.Runs.Stage0 import counter.Proofs.Runs.Sched import counter.Proofs.Runs.Evm1 diff --git a/Certified/counter/gen/Counter/Manifest.lean b/Certified/counter/gen/Counter/Manifest.lean index bdb31633..28b5e701 100644 --- a/Certified/counter/gen/Counter/Manifest.lean +++ b/Certified/counter/gen/Counter/Manifest.lean @@ -8,17 +8,17 @@ stage's file, its definition, the pass whose output it is, and the SHA-256 of th namespace SolarTV.Export.Counter.Manifest def sources : List (String × String) := - [("solar-tv/milestone/counter/counter.sol", "28af3c6bf35e4bde0636e2861c1f3eb6a5791d6f944a96af70b00fa46df54ad5")] + [("Certified/counter/counter.sol", "28af3c6bf35e4bde0636e2861c1f3eb6a5791d6f944a96af70b00fa46df54ad5")] -def compiler : String := "0.8.38+commit.1134e61f.solar.0.3.0-dev" +def compiler : String := "0.8.38+commit.ebdc3376.solar.0.3.0-dev" def arguments : List String := - ["solar-tv/milestone/counter/counter.sol", + ["Certified/counter/counter.sol", "-Ogas", "--evm-version", "osaka", "--emit=bin-runtime", - "-Zemit-lean-stages=solar-tv/milestone/counter/gen"] + "-Zemit-lean-stages=Certified/counter/gen"] def evmVersion : String := "osaka" diff --git a/Certified/counter/gen/Counter/Schedule.json b/Certified/counter/gen/Counter/Schedule.json new file mode 100644 index 00000000..a80e8d23 --- /dev/null +++ b/Certified/counter/gen/Counter/Schedule.json @@ -0,0 +1,21 @@ +{ + "functions": [ + {"function": 2, "entry": null, "returns": false, "rebuilt": false, "unsupported": null, "blocks": [ + {"block": 0, "start": [0, 0], "layout": [], "floating": true, "continues": null}, + {"block": 1, "start": [1, 0], "layout": [], "floating": true, "continues": null}, + {"block": 2, "start": [3, 0], "layout": [], "floating": true, "continues": null}, + {"block": 3, "start": [2, 0], "layout": [], "floating": true, "continues": null}, + {"block": 4, "start": [4, 0], "layout": [], "floating": true, "continues": null} + ]}, + {"function": 0, "entry": 5, "returns": false, "rebuilt": false, "unsupported": null, "blocks": [ + {"block": 0, "start": [5, 0], "layout": [], "floating": true, "continues": null}, + {"block": 1, "start": [8, 0], "layout": [], "floating": true, "continues": null}, + {"block": 2, "start": [7, 0], "layout": ["v4"], "floating": true, "continues": null}, + {"block": 3, "start": [9, 0], "layout": [], "floating": true, "continues": null}, + {"block": 4, "start": [6, 0], "layout": [], "floating": true, "continues": null} + ]}, + {"function": 1, "entry": 10, "returns": false, "rebuilt": false, "unsupported": null, "blocks": [ + {"block": 0, "start": [10, 0], "layout": [], "floating": true, "continues": null} + ]} + ] +} diff --git a/Certified/counter/gen/Counter/manifest.json b/Certified/counter/gen/Counter/manifest.json index 3a8d94c9..4646d07a 100644 --- a/Certified/counter/gen/Counter/manifest.json +++ b/Certified/counter/gen/Counter/manifest.json @@ -1,22 +1,22 @@ { "arguments": [ - "solar-tv/milestone/counter/counter.sol", + "Certified/counter/counter.sol", "-Ogas", "--evm-version", "osaka", "--emit=bin-runtime", - "-Zemit-lean-stages=solar-tv/milestone/counter/gen" + "-Zemit-lean-stages=Certified/counter/gen" ], "bytecode": "346034575f3560e01c80636d4ce63c146038578063812600df03603457602436106034575f5460043581019081106041575f55005b5f5ffd5b5f545f5260205ff35b6011602052634e487b715f526024601cfd", "bytecode_sha256": "daed21b0c790bb2c08bcf999c9ebc6fea950c213ea0a799418552aa14c18f6ec", - "compiler": "0.8.38+commit.1134e61f.solar.0.3.0-dev", + "compiler": "0.8.38+commit.ebdc3376.solar.0.3.0-dev", "contract": "Counter", "evm_version": "osaka", "optimization": "Gas", - "options": "CompileOpts { input: [\"solar-tv/milestone/counter/counter.sol\"], import_remappings: [], base_path: None, include_paths: [], allow_paths: [], no_import_callback: false, language: Solidity, threads: 4, evm_version: Osaka, stop_after: None, optimization: Gas, optimizer_runs: None, revert_strings: Default, libraries: [], out_dir: None, emit: [BinRuntime], standard_json: false, color: Auto, verbose: false, pretty_json: false, pretty_json_err: false, error_format: Human, error_format_human: Unicode, diagnostic_width: None, no_warnings: false, allow: [], _unstable: [\"emit-lean-stages=solar-tv/milestone/counter/gen\"], unstable: UnstableOpts { ui_testing: false, track_diagnostics: false, parse_yul: false, no_resolve_imports: false, recover_incomplete_input: false, dump: None, ast_stats: false, hir_stats: false, standard_json_stats: false, span_visitor: false, print_max_storage_sizes: false, print_natspec: false, mir_pipeline: None, evm_ir_pipeline: None, print_after_each: false, pass_diff: false, debugify: None, debugify_output: None, solar_tv: None, validate_ir: None, time_passes: false, codegen_all_functions: false, switch_lowering: Auto, switch_max_gas_code_growth: None, switch_max_bit_slice_gas_code_growth: None, tune: None, pack_wide_jump_tables: false, check_analyses: None, prove_analyses: None, validate_passes: None, validate_passes_fault: None, validate_backend: None, validate_backend_fault: None, validate_evm_ir_passes: None, validate_assembly: false, validate_assembly_fault: None, emit_lean_stages: Some(\"solar-tv/milestone/counter/gen\"), forget_gcx: true, help: (), _non_exhaustive: () }, _non_exhaustive: () }", + "options": "CompileOpts { input: [\"Certified/counter/counter.sol\"], import_remappings: [], base_path: None, include_paths: [], allow_paths: [], no_import_callback: false, language: Solidity, threads: 4, evm_version: Osaka, stop_after: None, optimization: Gas, optimizer_runs: None, revert_strings: Default, libraries: [], out_dir: None, emit: [BinRuntime], standard_json: false, color: Auto, verbose: false, pretty_json: false, pretty_json_err: false, error_format: Human, error_format_human: Unicode, diagnostic_width: None, no_warnings: false, allow: [], _unstable: [\"emit-lean-stages=Certified/counter/gen\"], unstable: UnstableOpts { ui_testing: false, track_diagnostics: false, parse_yul: false, no_resolve_imports: false, recover_incomplete_input: false, dump: None, ast_stats: false, hir_stats: false, standard_json_stats: false, span_visitor: false, print_max_storage_sizes: false, print_natspec: false, mir_pipeline: None, evm_ir_pipeline: None, print_after_each: false, pass_diff: false, debugify: None, debugify_output: None, solar_tv: None, validate_ir: None, time_passes: false, codegen_all_functions: false, switch_lowering: Auto, switch_max_gas_code_growth: None, switch_max_bit_slice_gas_code_growth: None, tune: None, pack_wide_jump_tables: false, check_analyses: None, prove_analyses: None, validate_passes: None, validate_passes_fault: None, validate_backend: None, validate_backend_fault: None, validate_evm_ir_passes: None, validate_assembly: false, validate_assembly_fault: None, emit_lean_stages: Some(\"Certified/counter/gen\"), forget_gcx: true, help: (), _non_exhaustive: () }, _non_exhaustive: () }", "sources": [ { - "path": "solar-tv/milestone/counter/counter.sol", + "path": "Certified/counter/counter.sol", "sha256": "28af3c6bf35e4bde0636e2861c1f3eb6a5791d6f944a96af70b00fa46df54ad5" } ], diff --git a/Certified/counter/headline b/Certified/counter/headline new file mode 100644 index 00000000..2c586680 --- /dev/null +++ b/Certified/counter/headline @@ -0,0 +1,4 @@ +Contracts.Counter.Headline SolidCore.Refinement.Solar.Counter.Headline.spec_holds_of_bytecode +Contracts.Counter.Headline SolidCore.Refinement.Solar.Counter.Headline.wrong_fails +Contracts.Counter.EndToEnd SolidCore.Refinement.Solar.Counter.EndToEnd.inc_spec_bytecode +Contracts.Counter.EndToEnd SolidCore.Refinement.Solar.Counter.EndToEnd.get_spec_bytecode diff --git a/Certified/events/Proofs.lean b/Certified/events/Proofs.lean index 7169ff3c..6f3fcc7a 100644 --- a/Certified/events/Proofs.lean +++ b/Certified/events/Proofs.lean @@ -1,3 +1,3 @@ --- Generated by solar-tv/milestone/certify.py; do not edit. +-- Generated by solar's tools/certify/certify.py; do not edit. import events.Proofs.Stages import events.Proofs.Assembly diff --git a/Certified/events/Proofs/Assembly.lean b/Certified/events/Proofs/Assembly.lean index fefb7aa2..803d3e58 100644 --- a/Certified/events/Proofs/Assembly.lean +++ b/Certified/events/Proofs/Assembly.lean @@ -1,4 +1,4 @@ --- Generated by solar-tv/milestone/certify.py; do not edit. +-- Generated by solar's tools/certify/certify.py; do not edit. import W1Proofs.Items import events.gen.Events.Evm5 import events.gen.Events.Bytecode diff --git a/Certified/events/Proofs/Runs/Evm1.lean b/Certified/events/Proofs/Runs/Evm1.lean index c61f28f4..bb9b9852 100644 --- a/Certified/events/Proofs/Runs/Evm1.lean +++ b/Certified/events/Proofs/Runs/Evm1.lean @@ -1,4 +1,4 @@ --- Generated by solar-tv/milestone/certify.py; do not edit. +-- Generated by solar's tools/certify/certify.py; do not edit. import W1Proofs.Tactic import W1Proofs.Axioms import events.gen.Events.Evm1 diff --git a/Certified/events/Proofs/Runs/Evm2.lean b/Certified/events/Proofs/Runs/Evm2.lean index 7d44755c..c5b0b495 100644 --- a/Certified/events/Proofs/Runs/Evm2.lean +++ b/Certified/events/Proofs/Runs/Evm2.lean @@ -1,4 +1,4 @@ --- Generated by solar-tv/milestone/certify.py; do not edit. +-- Generated by solar's tools/certify/certify.py; do not edit. import W1Proofs.Tactic import W1Proofs.Axioms import events.gen.Events.Evm2 diff --git a/Certified/events/Proofs/Runs/Evm3.lean b/Certified/events/Proofs/Runs/Evm3.lean index f67143bf..4cce876c 100644 --- a/Certified/events/Proofs/Runs/Evm3.lean +++ b/Certified/events/Proofs/Runs/Evm3.lean @@ -1,4 +1,4 @@ --- Generated by solar-tv/milestone/certify.py; do not edit. +-- Generated by solar's tools/certify/certify.py; do not edit. import W1Proofs.Tactic import W1Proofs.Axioms import events.gen.Events.Evm3 diff --git a/Certified/events/Proofs/Runs/Evm4.lean b/Certified/events/Proofs/Runs/Evm4.lean index 26dba659..012cdb84 100644 --- a/Certified/events/Proofs/Runs/Evm4.lean +++ b/Certified/events/Proofs/Runs/Evm4.lean @@ -1,4 +1,4 @@ --- Generated by solar-tv/milestone/certify.py; do not edit. +-- Generated by solar's tools/certify/certify.py; do not edit. import W1Proofs.Tactic import W1Proofs.Axioms import events.gen.Events.Evm4 diff --git a/Certified/events/Proofs/Runs/Evm5.lean b/Certified/events/Proofs/Runs/Evm5.lean index cd6beaab..78777881 100644 --- a/Certified/events/Proofs/Runs/Evm5.lean +++ b/Certified/events/Proofs/Runs/Evm5.lean @@ -1,4 +1,4 @@ --- Generated by solar-tv/milestone/certify.py; do not edit. +-- Generated by solar's tools/certify/certify.py; do not edit. import W1Proofs.Tactic import W1Proofs.Axioms import events.gen.Events.Evm5 diff --git a/Certified/events/Proofs/Runs/Mir1.lean b/Certified/events/Proofs/Runs/Mir1.lean index a401b50d..623ccc1e 100644 --- a/Certified/events/Proofs/Runs/Mir1.lean +++ b/Certified/events/Proofs/Runs/Mir1.lean @@ -1,4 +1,4 @@ --- Generated by solar-tv/milestone/certify.py; do not edit. +-- Generated by solar's tools/certify/certify.py; do not edit. import W1Proofs.Tactic import W1Proofs.Axioms import events.gen.Events.Mir1 diff --git a/Certified/events/Proofs/Runs/Sched.lean b/Certified/events/Proofs/Runs/Sched.lean index 9b8e620f..0464b86e 100644 --- a/Certified/events/Proofs/Runs/Sched.lean +++ b/Certified/events/Proofs/Runs/Sched.lean @@ -1,4 +1,4 @@ --- Generated by solar-tv/milestone/certify.py; do not edit. +-- Generated by solar's tools/certify/certify.py; do not edit. import W1Proofs.Tactic import W1Proofs.Axioms import events.gen.Events.Sched diff --git a/Certified/events/Proofs/Runs/Stage0.lean b/Certified/events/Proofs/Runs/Stage0.lean index d92a90d1..d3a1da5f 100644 --- a/Certified/events/Proofs/Runs/Stage0.lean +++ b/Certified/events/Proofs/Runs/Stage0.lean @@ -1,4 +1,4 @@ --- Generated by solar-tv/milestone/certify.py; do not edit. +-- Generated by solar's tools/certify/certify.py; do not edit. import W1Proofs.Tactic import W1Proofs.Axioms import events.gen.Events.Stage0 diff --git a/Certified/events/Proofs/Stages.lean b/Certified/events/Proofs/Stages.lean index f652182d..f36b79a6 100644 --- a/Certified/events/Proofs/Stages.lean +++ b/Certified/events/Proofs/Stages.lean @@ -1,4 +1,4 @@ --- Generated by solar-tv/milestone/certify.py; do not edit. +-- Generated by solar's tools/certify/certify.py; do not edit. import events.Proofs.Runs.Stage0 import events.Proofs.Runs.Mir1 import events.Proofs.Runs.Sched diff --git a/Certified/events/gen/Events/Manifest.lean b/Certified/events/gen/Events/Manifest.lean index f7a522e1..247c321b 100644 --- a/Certified/events/gen/Events/Manifest.lean +++ b/Certified/events/gen/Events/Manifest.lean @@ -8,17 +8,17 @@ stage's file, its definition, the pass whose output it is, and the SHA-256 of th namespace SolarTV.Export.Events.Manifest def sources : List (String × String) := - [("solar-tv/milestone/events/events.sol", "8b951679cab695d07c193e56dd5d96d14a1c63976673c79a72c690f07c50b5b0")] + [("Certified/events/events.sol", "8b951679cab695d07c193e56dd5d96d14a1c63976673c79a72c690f07c50b5b0")] -def compiler : String := "0.8.38+commit.0a455fda.solar.0.3.0-dev" +def compiler : String := "0.8.38+commit.ebdc3376.solar.0.3.0-dev" def arguments : List String := - ["solar-tv/milestone/events/events.sol", + ["Certified/events/events.sol", "-Ogas", "--evm-version", "osaka", "--emit=bin-runtime", - "-Zemit-lean-stages=solar-tv/milestone/events/gen"] + "-Zemit-lean-stages=Certified/events/gen"] def evmVersion : String := "osaka" diff --git a/Certified/events/gen/Events/Schedule.json b/Certified/events/gen/Events/Schedule.json new file mode 100644 index 00000000..2e5696b8 --- /dev/null +++ b/Certified/events/gen/Events/Schedule.json @@ -0,0 +1,18 @@ +{ + "functions": [ + {"function": 1, "entry": null, "returns": false, "rebuilt": false, "unsupported": null, "blocks": [ + {"block": 0, "start": [0, 0], "layout": [], "floating": true, "continues": null}, + {"block": 1, "start": [1, 0], "layout": [], "floating": true, "continues": null}, + {"block": 2, "start": [2, 0], "layout": [], "floating": true, "continues": null}, + {"block": 3, "start": [3, 0], "layout": [], "floating": true, "continues": null} + ]}, + {"function": 0, "entry": 4, "returns": false, "rebuilt": false, "unsupported": null, "blocks": [ + {"block": 0, "start": [4, 0], "layout": [], "floating": true, "continues": null}, + {"block": 1, "start": [9, 0], "layout": [], "floating": true, "continues": null}, + {"block": 2, "start": [5, 0], "layout": [], "floating": true, "continues": null}, + {"block": 3, "start": [8, 0], "layout": ["v20", "v21", "v22"], "floating": true, "continues": null}, + {"block": 4, "start": [7, 0], "layout": [], "floating": true, "continues": null}, + {"block": 5, "start": [6, 0], "layout": [], "floating": true, "continues": null} + ]} + ] +} diff --git a/Certified/events/gen/Events/manifest.json b/Certified/events/gen/Events/manifest.json index 15090bc3..d27b034b 100644 --- a/Certified/events/gen/Events/manifest.json +++ b/Certified/events/gen/Events/manifest.json @@ -1,22 +1,22 @@ { "arguments": [ - "solar-tv/milestone/events/events.sol", + "Certified/events/events.sol", "-Ogas", "--evm-version", "osaka", "--emit=bin-runtime", - "-Zemit-lean-stages=solar-tv/milestone/events/gen" + "-Zemit-lean-stages=Certified/events/gen" ], "bytecode": "346053575f3560e01c80630cf79e0a03605357604436106053576024355f52600435337f7fa9aafeb8bb803d77de5d84bc2f2edbd842ca91b20cd5020aa21dfe26ab0be960205fa35f1960601c3311605757005b5f5ffd5b690417000000000000000260201b335f1960601c9160205260405260605263ed572b275f526064601cfd", "bytecode_sha256": "5ad38c8bca24e0ca8c4a5e95f1f07bf993aad9a02ac3bc0872fc41fab8a6298b", - "compiler": "0.8.38+commit.0a455fda.solar.0.3.0-dev", + "compiler": "0.8.38+commit.ebdc3376.solar.0.3.0-dev", "contract": "Events", "evm_version": "osaka", "optimization": "Gas", - "options": "CompileOpts { input: [\"solar-tv/milestone/events/events.sol\"], import_remappings: [], base_path: None, include_paths: [], allow_paths: [], no_import_callback: false, language: Solidity, threads: 4, evm_version: Osaka, stop_after: None, optimization: Gas, optimizer_runs: None, revert_strings: Default, libraries: [], out_dir: None, emit: [BinRuntime], standard_json: false, color: Auto, verbose: false, pretty_json: false, pretty_json_err: false, error_format: Human, error_format_human: Unicode, diagnostic_width: None, no_warnings: false, allow: [], _unstable: [\"emit-lean-stages=solar-tv/milestone/events/gen\"], unstable: UnstableOpts { ui_testing: false, track_diagnostics: false, parse_yul: false, no_resolve_imports: false, recover_incomplete_input: false, dump: None, ast_stats: false, hir_stats: false, standard_json_stats: false, span_visitor: false, print_max_storage_sizes: false, print_natspec: false, mir_pipeline: None, evm_ir_pipeline: None, print_after_each: false, pass_diff: false, debugify: None, debugify_output: None, solar_tv: None, validate_ir: None, time_passes: false, codegen_all_functions: false, switch_lowering: Auto, switch_max_gas_code_growth: None, switch_max_bit_slice_gas_code_growth: None, tune: None, pack_wide_jump_tables: false, check_analyses: None, prove_analyses: None, validate_passes: None, validate_passes_fault: None, validate_backend: None, validate_backend_fault: None, validate_evm_ir_passes: None, validate_assembly: false, validate_assembly_fault: None, emit_lean_stages: Some(\"solar-tv/milestone/events/gen\"), forget_gcx: true, help: (), _non_exhaustive: () }, _non_exhaustive: () }", + "options": "CompileOpts { input: [\"Certified/events/events.sol\"], import_remappings: [], base_path: None, include_paths: [], allow_paths: [], no_import_callback: false, language: Solidity, threads: 4, evm_version: Osaka, stop_after: None, optimization: Gas, optimizer_runs: None, revert_strings: Default, libraries: [], out_dir: None, emit: [BinRuntime], standard_json: false, color: Auto, verbose: false, pretty_json: false, pretty_json_err: false, error_format: Human, error_format_human: Unicode, diagnostic_width: None, no_warnings: false, allow: [], _unstable: [\"emit-lean-stages=Certified/events/gen\"], unstable: UnstableOpts { ui_testing: false, track_diagnostics: false, parse_yul: false, no_resolve_imports: false, recover_incomplete_input: false, dump: None, ast_stats: false, hir_stats: false, standard_json_stats: false, span_visitor: false, print_max_storage_sizes: false, print_natspec: false, mir_pipeline: None, evm_ir_pipeline: None, print_after_each: false, pass_diff: false, debugify: None, debugify_output: None, solar_tv: None, validate_ir: None, time_passes: false, codegen_all_functions: false, switch_lowering: Auto, switch_max_gas_code_growth: None, switch_max_bit_slice_gas_code_growth: None, tune: None, pack_wide_jump_tables: false, check_analyses: None, prove_analyses: None, validate_passes: None, validate_passes_fault: None, validate_backend: None, validate_backend_fault: None, validate_evm_ir_passes: None, validate_assembly: false, validate_assembly_fault: None, emit_lean_stages: Some(\"Certified/events/gen\"), forget_gcx: true, help: (), _non_exhaustive: () }, _non_exhaustive: () }", "sources": [ { - "path": "solar-tv/milestone/events/events.sol", + "path": "Certified/events/events.sol", "sha256": "8b951679cab695d07c193e56dd5d96d14a1c63976673c79a72c690f07c50b5b0" } ], diff --git a/Certified/masks/Proofs.lean b/Certified/masks/Proofs.lean index 55be915f..1b901319 100644 --- a/Certified/masks/Proofs.lean +++ b/Certified/masks/Proofs.lean @@ -1,3 +1,3 @@ --- Generated by solar-tv/milestone/certify.py; do not edit. +-- Generated by solar's tools/certify/certify.py; do not edit. import masks.Proofs.Stages import masks.Proofs.Assembly diff --git a/Certified/masks/Proofs/Assembly.lean b/Certified/masks/Proofs/Assembly.lean index d958e4f2..1015a411 100644 --- a/Certified/masks/Proofs/Assembly.lean +++ b/Certified/masks/Proofs/Assembly.lean @@ -1,4 +1,4 @@ --- Generated by solar-tv/milestone/certify.py; do not edit. +-- Generated by solar's tools/certify/certify.py; do not edit. import W1Proofs.Items import masks.gen.Masks.Evm6 import masks.gen.Masks.Bytecode diff --git a/Certified/masks/Proofs/Runs/Evm1.lean b/Certified/masks/Proofs/Runs/Evm1.lean index 1951d905..5f919b07 100644 --- a/Certified/masks/Proofs/Runs/Evm1.lean +++ b/Certified/masks/Proofs/Runs/Evm1.lean @@ -1,4 +1,4 @@ --- Generated by solar-tv/milestone/certify.py; do not edit. +-- Generated by solar's tools/certify/certify.py; do not edit. import W1Proofs.Tactic import W1Proofs.Axioms import masks.gen.Masks.Evm1 diff --git a/Certified/masks/Proofs/Runs/Evm2.lean b/Certified/masks/Proofs/Runs/Evm2.lean index 2852f520..ba010a04 100644 --- a/Certified/masks/Proofs/Runs/Evm2.lean +++ b/Certified/masks/Proofs/Runs/Evm2.lean @@ -1,4 +1,4 @@ --- Generated by solar-tv/milestone/certify.py; do not edit. +-- Generated by solar's tools/certify/certify.py; do not edit. import W1Proofs.Tactic import W1Proofs.Axioms import masks.gen.Masks.Evm2 diff --git a/Certified/masks/Proofs/Runs/Evm3.lean b/Certified/masks/Proofs/Runs/Evm3.lean index ecb2e72d..28c54a8e 100644 --- a/Certified/masks/Proofs/Runs/Evm3.lean +++ b/Certified/masks/Proofs/Runs/Evm3.lean @@ -1,4 +1,4 @@ --- Generated by solar-tv/milestone/certify.py; do not edit. +-- Generated by solar's tools/certify/certify.py; do not edit. import W1Proofs.Tactic import W1Proofs.Axioms import masks.gen.Masks.Evm3 diff --git a/Certified/masks/Proofs/Runs/Evm4.lean b/Certified/masks/Proofs/Runs/Evm4.lean index 09b3b60d..91af1354 100644 --- a/Certified/masks/Proofs/Runs/Evm4.lean +++ b/Certified/masks/Proofs/Runs/Evm4.lean @@ -1,4 +1,4 @@ --- Generated by solar-tv/milestone/certify.py; do not edit. +-- Generated by solar's tools/certify/certify.py; do not edit. import W1Proofs.Tactic import W1Proofs.Axioms import masks.gen.Masks.Evm4 diff --git a/Certified/masks/Proofs/Runs/Evm5.lean b/Certified/masks/Proofs/Runs/Evm5.lean index bfe00fbd..2fe64ff4 100644 --- a/Certified/masks/Proofs/Runs/Evm5.lean +++ b/Certified/masks/Proofs/Runs/Evm5.lean @@ -1,4 +1,4 @@ --- Generated by solar-tv/milestone/certify.py; do not edit. +-- Generated by solar's tools/certify/certify.py; do not edit. import W1Proofs.Tactic import W1Proofs.Axioms import masks.gen.Masks.Evm5 diff --git a/Certified/masks/Proofs/Runs/Evm6.lean b/Certified/masks/Proofs/Runs/Evm6.lean index f4a45a28..eee09728 100644 --- a/Certified/masks/Proofs/Runs/Evm6.lean +++ b/Certified/masks/Proofs/Runs/Evm6.lean @@ -1,4 +1,4 @@ --- Generated by solar-tv/milestone/certify.py; do not edit. +-- Generated by solar's tools/certify/certify.py; do not edit. import W1Proofs.Tactic import W1Proofs.Axioms import masks.gen.Masks.Evm6 diff --git a/Certified/masks/Proofs/Runs/Mir1.lean b/Certified/masks/Proofs/Runs/Mir1.lean index 51a356e2..51875c1d 100644 --- a/Certified/masks/Proofs/Runs/Mir1.lean +++ b/Certified/masks/Proofs/Runs/Mir1.lean @@ -1,4 +1,4 @@ --- Generated by solar-tv/milestone/certify.py; do not edit. +-- Generated by solar's tools/certify/certify.py; do not edit. import W1Proofs.Tactic import W1Proofs.Axioms import masks.gen.Masks.Mir1 diff --git a/Certified/masks/Proofs/Runs/Mir2.lean b/Certified/masks/Proofs/Runs/Mir2.lean index 178daa27..ae2c7827 100644 --- a/Certified/masks/Proofs/Runs/Mir2.lean +++ b/Certified/masks/Proofs/Runs/Mir2.lean @@ -1,4 +1,4 @@ --- Generated by solar-tv/milestone/certify.py; do not edit. +-- Generated by solar's tools/certify/certify.py; do not edit. import W1Proofs.Tactic import W1Proofs.Axioms import masks.gen.Masks.Mir2 diff --git a/Certified/masks/Proofs/Runs/Sched.lean b/Certified/masks/Proofs/Runs/Sched.lean index 32370923..fdd354df 100644 --- a/Certified/masks/Proofs/Runs/Sched.lean +++ b/Certified/masks/Proofs/Runs/Sched.lean @@ -1,4 +1,4 @@ --- Generated by solar-tv/milestone/certify.py; do not edit. +-- Generated by solar's tools/certify/certify.py; do not edit. import W1Proofs.Tactic import W1Proofs.Axioms import masks.gen.Masks.Sched diff --git a/Certified/masks/Proofs/Runs/Stage0.lean b/Certified/masks/Proofs/Runs/Stage0.lean index 4a46fe52..9c63848e 100644 --- a/Certified/masks/Proofs/Runs/Stage0.lean +++ b/Certified/masks/Proofs/Runs/Stage0.lean @@ -1,4 +1,4 @@ --- Generated by solar-tv/milestone/certify.py; do not edit. +-- Generated by solar's tools/certify/certify.py; do not edit. import W1Proofs.Tactic import W1Proofs.Axioms import masks.gen.Masks.Stage0 diff --git a/Certified/masks/Proofs/Stages.lean b/Certified/masks/Proofs/Stages.lean index 881b3fb6..013e718d 100644 --- a/Certified/masks/Proofs/Stages.lean +++ b/Certified/masks/Proofs/Stages.lean @@ -1,4 +1,4 @@ --- Generated by solar-tv/milestone/certify.py; do not edit. +-- Generated by solar's tools/certify/certify.py; do not edit. import masks.Proofs.Runs.Stage0 import masks.Proofs.Runs.Mir1 import masks.Proofs.Runs.Mir2 diff --git a/Certified/masks/gen/Masks/Manifest.lean b/Certified/masks/gen/Masks/Manifest.lean index 608b12a5..9ccef5cd 100644 --- a/Certified/masks/gen/Masks/Manifest.lean +++ b/Certified/masks/gen/Masks/Manifest.lean @@ -8,17 +8,17 @@ stage's file, its definition, the pass whose output it is, and the SHA-256 of th namespace SolarTV.Export.Masks.Manifest def sources : List (String × String) := - [("solar-tv/milestone/masks/masks.sol", "07aea44de99801385666f8de90ffb4edfba9f7ce9c874a89392f7d19fcd34d8e")] + [("Certified/masks/masks.sol", "07aea44de99801385666f8de90ffb4edfba9f7ce9c874a89392f7d19fcd34d8e")] -def compiler : String := "0.8.38+commit.4a7d9ede.solar.0.3.0-dev" +def compiler : String := "0.8.38+commit.ebdc3376.solar.0.3.0-dev" def arguments : List String := - ["solar-tv/milestone/masks/masks.sol", + ["Certified/masks/masks.sol", "-Ogas", "--evm-version", "osaka", "--emit=bin-runtime", - "-Zemit-lean-stages=solar-tv/milestone/masks/gen"] + "-Zemit-lean-stages=Certified/masks/gen"] def evmVersion : String := "osaka" diff --git a/Certified/masks/gen/Masks/Schedule.json b/Certified/masks/gen/Masks/Schedule.json new file mode 100644 index 00000000..2b797197 --- /dev/null +++ b/Certified/masks/gen/Masks/Schedule.json @@ -0,0 +1,30 @@ +{ + "functions": [ + {"function": 3, "entry": null, "returns": false, "rebuilt": false, "unsupported": null, "blocks": [ + {"block": 0, "start": [0, 0], "layout": [], "floating": true, "continues": null}, + {"block": 1, "start": [1, 0], "layout": [], "floating": true, "continues": null}, + {"block": 2, "start": [4, 0], "layout": [], "floating": true, "continues": null}, + {"block": 3, "start": [3, 0], "layout": [], "floating": true, "continues": null}, + {"block": 4, "start": [2, 0], "layout": [], "floating": true, "continues": null}, + {"block": 5, "start": [5, 0], "layout": [], "floating": true, "continues": null} + ]}, + {"function": 0, "entry": 6, "returns": false, "rebuilt": false, "unsupported": null, "blocks": [ + {"block": 0, "start": [6, 0], "layout": [], "floating": true, "continues": null}, + {"block": 1, "start": [9, 0], "layout": [], "floating": true, "continues": null}, + {"block": 2, "start": [8, 0], "layout": ["v4"], "floating": true, "continues": null}, + {"block": 3, "start": [10, 0], "layout": [], "floating": true, "continues": null}, + {"block": 4, "start": [7, 0], "layout": [], "floating": true, "continues": null} + ]}, + {"function": 1, "entry": 11, "returns": false, "rebuilt": false, "unsupported": null, "blocks": [ + {"block": 0, "start": [11, 0], "layout": [], "floating": true, "continues": null} + ]}, + {"function": 2, "entry": 12, "returns": false, "rebuilt": false, "unsupported": null, "blocks": [ + {"block": 0, "start": [12, 0], "layout": [], "floating": true, "continues": null}, + {"block": 1, "start": [17, 0], "layout": [], "floating": true, "continues": null}, + {"block": 2, "start": [13, 0], "layout": [], "floating": true, "continues": null}, + {"block": 3, "start": [16, 0], "layout": ["v29", "v28", "v27"], "floating": true, "continues": null}, + {"block": 4, "start": [15, 0], "layout": ["v24", "v19"], "floating": true, "continues": null}, + {"block": 5, "start": [14, 0], "layout": [], "floating": true, "continues": null} + ]} + ] +} diff --git a/Certified/masks/gen/Masks/manifest.json b/Certified/masks/gen/Masks/manifest.json index e1d9de40..dc032a39 100644 --- a/Certified/masks/gen/Masks/manifest.json +++ b/Certified/masks/gen/Masks/manifest.json @@ -1,22 +1,22 @@ { "arguments": [ - "solar-tv/milestone/masks/masks.sol", + "Certified/masks/masks.sol", "-Ogas", "--evm-version", "osaka", "--emit=bin-runtime", - "-Zemit-lean-stages=solar-tv/milestone/masks/gen" + "-Zemit-lean-stages=Certified/masks/gen" ], "bytecode": "34603e575f3560e01c806341fa8d2d14604b5780636d4ce63c146042578063812600df03603e5760243610603e575f5460043581019081106071575f55005b5f5ffd5b5f545f5260205ff35b6024361060ff6004351117603e5760043560ff8116600f82165f5281810360835760205ff35b6011602052634e487b715f526024601cfd5b6d010200000002000000020000000760205260405260605263ed572b275f526064601cfd", "bytecode_sha256": "43bd25ba9b579f0623a2d7181e6cf0f1094c31f96143a747470cd125d735dfe7", - "compiler": "0.8.38+commit.4a7d9ede.solar.0.3.0-dev", + "compiler": "0.8.38+commit.ebdc3376.solar.0.3.0-dev", "contract": "Masks", "evm_version": "osaka", "optimization": "Gas", - "options": "CompileOpts { input: [\"solar-tv/milestone/masks/masks.sol\"], import_remappings: [], base_path: None, include_paths: [], allow_paths: [], no_import_callback: false, language: Solidity, threads: 4, evm_version: Osaka, stop_after: None, optimization: Gas, optimizer_runs: None, revert_strings: Default, libraries: [], out_dir: None, emit: [BinRuntime], standard_json: false, color: Auto, verbose: false, pretty_json: false, pretty_json_err: false, error_format: Human, error_format_human: Unicode, diagnostic_width: None, no_warnings: false, allow: [], _unstable: [\"emit-lean-stages=solar-tv/milestone/masks/gen\"], unstable: UnstableOpts { ui_testing: false, track_diagnostics: false, parse_yul: false, no_resolve_imports: false, recover_incomplete_input: false, dump: None, ast_stats: false, hir_stats: false, standard_json_stats: false, span_visitor: false, print_max_storage_sizes: false, print_natspec: false, mir_pipeline: None, evm_ir_pipeline: None, print_after_each: false, pass_diff: false, debugify: None, debugify_output: None, solar_tv: None, validate_ir: None, time_passes: false, codegen_all_functions: false, switch_lowering: Auto, switch_max_gas_code_growth: None, switch_max_bit_slice_gas_code_growth: None, tune: None, pack_wide_jump_tables: false, check_analyses: None, prove_analyses: None, validate_passes: None, validate_passes_fault: None, validate_backend: None, validate_backend_fault: None, validate_evm_ir_passes: None, validate_assembly: false, validate_assembly_fault: None, emit_lean_stages: Some(\"solar-tv/milestone/masks/gen\"), forget_gcx: true, help: (), _non_exhaustive: () }, _non_exhaustive: () }", + "options": "CompileOpts { input: [\"Certified/masks/masks.sol\"], import_remappings: [], base_path: None, include_paths: [], allow_paths: [], no_import_callback: false, language: Solidity, threads: 4, evm_version: Osaka, stop_after: None, optimization: Gas, optimizer_runs: None, revert_strings: Default, libraries: [], out_dir: None, emit: [BinRuntime], standard_json: false, color: Auto, verbose: false, pretty_json: false, pretty_json_err: false, error_format: Human, error_format_human: Unicode, diagnostic_width: None, no_warnings: false, allow: [], _unstable: [\"emit-lean-stages=Certified/masks/gen\"], unstable: UnstableOpts { ui_testing: false, track_diagnostics: false, parse_yul: false, no_resolve_imports: false, recover_incomplete_input: false, dump: None, ast_stats: false, hir_stats: false, standard_json_stats: false, span_visitor: false, print_max_storage_sizes: false, print_natspec: false, mir_pipeline: None, evm_ir_pipeline: None, print_after_each: false, pass_diff: false, debugify: None, debugify_output: None, solar_tv: None, validate_ir: None, time_passes: false, codegen_all_functions: false, switch_lowering: Auto, switch_max_gas_code_growth: None, switch_max_bit_slice_gas_code_growth: None, tune: None, pack_wide_jump_tables: false, check_analyses: None, prove_analyses: None, validate_passes: None, validate_passes_fault: None, validate_backend: None, validate_backend_fault: None, validate_evm_ir_passes: None, validate_assembly: false, validate_assembly_fault: None, emit_lean_stages: Some(\"Certified/masks/gen\"), forget_gcx: true, help: (), _non_exhaustive: () }, _non_exhaustive: () }", "sources": [ { - "path": "solar-tv/milestone/masks/masks.sol", + "path": "Certified/masks/masks.sol", "sha256": "07aea44de99801385666f8de90ffb4edfba9f7ce9c874a89392f7d19fcd34d8e" } ], diff --git a/Certified/mulx/Proofs.lean b/Certified/mulx/Proofs.lean index 9c08ead2..ff615c87 100644 --- a/Certified/mulx/Proofs.lean +++ b/Certified/mulx/Proofs.lean @@ -1,3 +1,3 @@ --- Generated by solar-tv/milestone/certify.py; do not edit. +-- Generated by solar's tools/certify/certify.py; do not edit. import mulx.Proofs.Stages import mulx.Proofs.Assembly diff --git a/Certified/mulx/Proofs/Assembly.lean b/Certified/mulx/Proofs/Assembly.lean index 331d063b..a64cd972 100644 --- a/Certified/mulx/Proofs/Assembly.lean +++ b/Certified/mulx/Proofs/Assembly.lean @@ -1,4 +1,4 @@ --- Generated by solar-tv/milestone/certify.py; do not edit. +-- Generated by solar's tools/certify/certify.py; do not edit. import W1Proofs.Items import mulx.gen.Main.Evm8 import mulx.gen.Main.Bytecode diff --git a/Certified/mulx/Proofs/Runs/Evm1.lean b/Certified/mulx/Proofs/Runs/Evm1.lean index a5e5511f..6db1ec4d 100644 --- a/Certified/mulx/Proofs/Runs/Evm1.lean +++ b/Certified/mulx/Proofs/Runs/Evm1.lean @@ -1,4 +1,4 @@ --- Generated by solar-tv/milestone/certify.py; do not edit. +-- Generated by solar's tools/certify/certify.py; do not edit. import W1Proofs.Tactic import W1Proofs.Axioms import mulx.gen.Main.Evm1 diff --git a/Certified/mulx/Proofs/Runs/Evm2.lean b/Certified/mulx/Proofs/Runs/Evm2.lean index 2f227c2c..50a946d9 100644 --- a/Certified/mulx/Proofs/Runs/Evm2.lean +++ b/Certified/mulx/Proofs/Runs/Evm2.lean @@ -1,4 +1,4 @@ --- Generated by solar-tv/milestone/certify.py; do not edit. +-- Generated by solar's tools/certify/certify.py; do not edit. import W1Proofs.Tactic import W1Proofs.Axioms import mulx.gen.Main.Evm2 diff --git a/Certified/mulx/Proofs/Runs/Evm3.lean b/Certified/mulx/Proofs/Runs/Evm3.lean index ff7ae833..e5d3e22e 100644 --- a/Certified/mulx/Proofs/Runs/Evm3.lean +++ b/Certified/mulx/Proofs/Runs/Evm3.lean @@ -1,4 +1,4 @@ --- Generated by solar-tv/milestone/certify.py; do not edit. +-- Generated by solar's tools/certify/certify.py; do not edit. import W1Proofs.Tactic import W1Proofs.Axioms import mulx.gen.Main.Evm3 diff --git a/Certified/mulx/Proofs/Runs/Evm4.lean b/Certified/mulx/Proofs/Runs/Evm4.lean index 9a7543a8..d3932d18 100644 --- a/Certified/mulx/Proofs/Runs/Evm4.lean +++ b/Certified/mulx/Proofs/Runs/Evm4.lean @@ -1,4 +1,4 @@ --- Generated by solar-tv/milestone/certify.py; do not edit. +-- Generated by solar's tools/certify/certify.py; do not edit. import W1Proofs.Tactic import W1Proofs.Axioms import mulx.gen.Main.Evm4 diff --git a/Certified/mulx/Proofs/Runs/Evm5.lean b/Certified/mulx/Proofs/Runs/Evm5.lean index 6b065a64..bb92f5b6 100644 --- a/Certified/mulx/Proofs/Runs/Evm5.lean +++ b/Certified/mulx/Proofs/Runs/Evm5.lean @@ -1,4 +1,4 @@ --- Generated by solar-tv/milestone/certify.py; do not edit. +-- Generated by solar's tools/certify/certify.py; do not edit. import W1Proofs.Tactic import W1Proofs.Axioms import mulx.gen.Main.Evm5 diff --git a/Certified/mulx/Proofs/Runs/Evm6.lean b/Certified/mulx/Proofs/Runs/Evm6.lean index afb061af..6f035447 100644 --- a/Certified/mulx/Proofs/Runs/Evm6.lean +++ b/Certified/mulx/Proofs/Runs/Evm6.lean @@ -1,4 +1,4 @@ --- Generated by solar-tv/milestone/certify.py; do not edit. +-- Generated by solar's tools/certify/certify.py; do not edit. import W1Proofs.Tactic import W1Proofs.Axioms import mulx.gen.Main.Evm6 diff --git a/Certified/mulx/Proofs/Runs/Evm7.lean b/Certified/mulx/Proofs/Runs/Evm7.lean index 7f7a77bb..abfcfae9 100644 --- a/Certified/mulx/Proofs/Runs/Evm7.lean +++ b/Certified/mulx/Proofs/Runs/Evm7.lean @@ -1,4 +1,4 @@ --- Generated by solar-tv/milestone/certify.py; do not edit. +-- Generated by solar's tools/certify/certify.py; do not edit. import W1Proofs.Tactic import W1Proofs.Axioms import mulx.gen.Main.Evm7 diff --git a/Certified/mulx/Proofs/Runs/Evm8.lean b/Certified/mulx/Proofs/Runs/Evm8.lean index 4f64de03..5ef159d6 100644 --- a/Certified/mulx/Proofs/Runs/Evm8.lean +++ b/Certified/mulx/Proofs/Runs/Evm8.lean @@ -1,4 +1,4 @@ --- Generated by solar-tv/milestone/certify.py; do not edit. +-- Generated by solar's tools/certify/certify.py; do not edit. import W1Proofs.Tactic import W1Proofs.Axioms import mulx.gen.Main.Evm8 diff --git a/Certified/mulx/Proofs/Runs/Mir1.lean b/Certified/mulx/Proofs/Runs/Mir1.lean index 9eeab531..41bf84c4 100644 --- a/Certified/mulx/Proofs/Runs/Mir1.lean +++ b/Certified/mulx/Proofs/Runs/Mir1.lean @@ -1,4 +1,4 @@ --- Generated by solar-tv/milestone/certify.py; do not edit. +-- Generated by solar's tools/certify/certify.py; do not edit. import W1Proofs.Tactic import W1Proofs.Axioms import mulx.gen.Main.Mir1 diff --git a/Certified/mulx/Proofs/Runs/Mir2.lean b/Certified/mulx/Proofs/Runs/Mir2.lean index a1cc5560..a5ef4485 100644 --- a/Certified/mulx/Proofs/Runs/Mir2.lean +++ b/Certified/mulx/Proofs/Runs/Mir2.lean @@ -1,4 +1,4 @@ --- Generated by solar-tv/milestone/certify.py; do not edit. +-- Generated by solar's tools/certify/certify.py; do not edit. import W1Proofs.Tactic import W1Proofs.Axioms import mulx.gen.Main.Mir2 diff --git a/Certified/mulx/Proofs/Runs/Mir3.lean b/Certified/mulx/Proofs/Runs/Mir3.lean index 6a1c903e..5f062332 100644 --- a/Certified/mulx/Proofs/Runs/Mir3.lean +++ b/Certified/mulx/Proofs/Runs/Mir3.lean @@ -1,4 +1,4 @@ --- Generated by solar-tv/milestone/certify.py; do not edit. +-- Generated by solar's tools/certify/certify.py; do not edit. import W1Proofs.Tactic import W1Proofs.Axioms import mulx.gen.Main.Mir3 diff --git a/Certified/mulx/Proofs/Runs/Sched.lean b/Certified/mulx/Proofs/Runs/Sched.lean index d2e2b813..ef4a673c 100644 --- a/Certified/mulx/Proofs/Runs/Sched.lean +++ b/Certified/mulx/Proofs/Runs/Sched.lean @@ -1,4 +1,4 @@ --- Generated by solar-tv/milestone/certify.py; do not edit. +-- Generated by solar's tools/certify/certify.py; do not edit. import W1Proofs.Tactic import W1Proofs.Axioms import mulx.gen.Main.Sched diff --git a/Certified/mulx/Proofs/Runs/Stage0.lean b/Certified/mulx/Proofs/Runs/Stage0.lean index b0f63512..dea977a2 100644 --- a/Certified/mulx/Proofs/Runs/Stage0.lean +++ b/Certified/mulx/Proofs/Runs/Stage0.lean @@ -1,4 +1,4 @@ --- Generated by solar-tv/milestone/certify.py; do not edit. +-- Generated by solar's tools/certify/certify.py; do not edit. import W1Proofs.Tactic import W1Proofs.Axioms import mulx.gen.Main.Stage0 diff --git a/Certified/mulx/Proofs/Stages.lean b/Certified/mulx/Proofs/Stages.lean index 2f21028a..c4bccf49 100644 --- a/Certified/mulx/Proofs/Stages.lean +++ b/Certified/mulx/Proofs/Stages.lean @@ -1,4 +1,4 @@ --- Generated by solar-tv/milestone/certify.py; do not edit. +-- Generated by solar's tools/certify/certify.py; do not edit. import mulx.Proofs.Runs.Stage0 import mulx.Proofs.Runs.Mir1 import mulx.Proofs.Runs.Mir2 diff --git a/Certified/mulx/gen/Main/Manifest.lean b/Certified/mulx/gen/Main/Manifest.lean index b62ce15a..f1884d68 100644 --- a/Certified/mulx/gen/Main/Manifest.lean +++ b/Certified/mulx/gen/Main/Manifest.lean @@ -8,15 +8,15 @@ stage's file, its definition, the pass whose output it is, and the SHA-256 of th namespace SolarTV.Export.Main.Manifest def sources : List (String × String) := - [("solar-tv/milestone/mulx/mulx.sol", "50ef03a3c5724105509c3ed40b7ee7d92ea43b5d48a67d0e6722b26806dd4980")] + [("Certified/mulx/mulx.sol", "50ef03a3c5724105509c3ed40b7ee7d92ea43b5d48a67d0e6722b26806dd4980")] -def compiler : String := "0.8.38+commit.4a7d9ede.solar.0.3.0-dev" +def compiler : String := "0.8.38+commit.ebdc3376.solar.0.3.0-dev" def arguments : List String := - ["solar-tv/milestone/mulx/mulx.sol", + ["Certified/mulx/mulx.sol", "-Zcheck-analyses=false", "--emit=bin-runtime", - "-Zemit-lean-stages=solar-tv/milestone/mulx/gen"] + "-Zemit-lean-stages=Certified/mulx/gen"] def evmVersion : String := "osaka" diff --git a/Certified/mulx/gen/Main/Schedule.json b/Certified/mulx/gen/Main/Schedule.json new file mode 100644 index 00000000..08ffd2ed --- /dev/null +++ b/Certified/mulx/gen/Main/Schedule.json @@ -0,0 +1,25 @@ +{ + "functions": [ + {"function": 3, "entry": null, "returns": false, "rebuilt": false, "unsupported": null, "blocks": [ + {"block": 0, "start": [0, 0], "layout": [], "floating": true, "continues": null}, + {"block": 1, "start": [1, 0], "layout": [], "floating": true, "continues": null}, + {"block": 2, "start": [3, 0], "layout": [], "floating": true, "continues": null}, + {"block": 3, "start": [2, 0], "layout": [], "floating": true, "continues": null}, + {"block": 4, "start": [4, 0], "layout": [], "floating": true, "continues": null} + ]}, + {"function": 0, "entry": 5, "returns": false, "rebuilt": false, "unsupported": null, "blocks": [ + {"block": 0, "start": [5, 0], "layout": [], "floating": true, "continues": null}, + {"block": 1, "start": [8, 0], "layout": [], "floating": true, "continues": null}, + {"block": 2, "start": [7, 0], "layout": ["v43", "v12"], "floating": true, "continues": null}, + {"block": 3, "start": [9, 0], "layout": [], "floating": true, "continues": null}, + {"block": 4, "start": [6, 0], "layout": [], "floating": true, "continues": null} + ]}, + {"function": 1, "entry": 10, "returns": false, "rebuilt": false, "unsupported": null, "blocks": [ + {"block": 0, "start": [10, 0], "layout": [], "floating": true, "continues": null}, + {"block": 1, "start": [13, 0], "layout": [], "floating": true, "continues": null}, + {"block": 2, "start": [12, 0], "layout": ["v11"], "floating": true, "continues": null}, + {"block": 3, "start": [14, 0], "layout": [], "floating": true, "continues": null}, + {"block": 4, "start": [11, 0], "layout": [], "floating": true, "continues": null} + ]} + ] +} diff --git a/Certified/mulx/gen/Main/manifest.json b/Certified/mulx/gen/Main/manifest.json index 557f81ac..6172d0e2 100644 --- a/Certified/mulx/gen/Main/manifest.json +++ b/Certified/mulx/gen/Main/manifest.json @@ -1,20 +1,20 @@ { "arguments": [ - "solar-tv/milestone/mulx/mulx.sol", + "Certified/mulx/mulx.sol", "-Zcheck-analyses=false", "--emit=bin-runtime", - "-Zemit-lean-stages=solar-tv/milestone/mulx/gen" + "-Zemit-lean-stages=Certified/mulx/gen" ], "bytecode": "34601d575f3560e01c806316ea58cb14606d5780639db20e58146033575b5f5ffd5b6011602052634e487b715f526024601cfd5b60243560101c6064361060ff600435111717601d576004602435604435913502808280159202928304141715602157806001555f5260205ff35b60243560101c6044361060ff600435111717601d575f5460ff81166004350260ff81119160ff1916178060081c61ffff16602435028060101c90921760215762ffff0019169060081b175f55", "bytecode_sha256": "42ecdc71b09d339299d2b7ce61e121c77b141c5386eb9cbf18792a9ba9ca4cfe", - "compiler": "0.8.38+commit.4a7d9ede.solar.0.3.0-dev", + "compiler": "0.8.38+commit.ebdc3376.solar.0.3.0-dev", "contract": "Main", "evm_version": "osaka", "optimization": "Gas", - "options": "CompileOpts { input: [\"solar-tv/milestone/mulx/mulx.sol\"], import_remappings: [], base_path: None, include_paths: [], allow_paths: [], no_import_callback: false, language: Solidity, threads: 4, evm_version: Osaka, stop_after: None, optimization: Gas, optimizer_runs: None, revert_strings: Default, libraries: [], out_dir: None, emit: [BinRuntime], standard_json: false, color: Auto, verbose: false, pretty_json: false, pretty_json_err: false, error_format: Human, error_format_human: Unicode, diagnostic_width: None, no_warnings: false, allow: [], _unstable: [\"check-analyses=false\", \"emit-lean-stages=solar-tv/milestone/mulx/gen\"], unstable: UnstableOpts { ui_testing: false, track_diagnostics: false, parse_yul: false, no_resolve_imports: false, recover_incomplete_input: false, dump: None, ast_stats: false, hir_stats: false, standard_json_stats: false, span_visitor: false, print_max_storage_sizes: false, print_natspec: false, mir_pipeline: None, evm_ir_pipeline: None, print_after_each: false, pass_diff: false, debugify: None, debugify_output: None, solar_tv: None, validate_ir: None, time_passes: false, codegen_all_functions: false, switch_lowering: Auto, switch_max_gas_code_growth: None, switch_max_bit_slice_gas_code_growth: None, tune: None, pack_wide_jump_tables: false, check_analyses: Some(false), prove_analyses: None, validate_passes: None, validate_passes_fault: None, validate_backend: None, validate_backend_fault: None, validate_evm_ir_passes: None, validate_assembly: false, validate_assembly_fault: None, emit_lean_stages: Some(\"solar-tv/milestone/mulx/gen\"), forget_gcx: true, help: (), _non_exhaustive: () }, _non_exhaustive: () }", + "options": "CompileOpts { input: [\"Certified/mulx/mulx.sol\"], import_remappings: [], base_path: None, include_paths: [], allow_paths: [], no_import_callback: false, language: Solidity, threads: 4, evm_version: Osaka, stop_after: None, optimization: Gas, optimizer_runs: None, revert_strings: Default, libraries: [], out_dir: None, emit: [BinRuntime], standard_json: false, color: Auto, verbose: false, pretty_json: false, pretty_json_err: false, error_format: Human, error_format_human: Unicode, diagnostic_width: None, no_warnings: false, allow: [], _unstable: [\"check-analyses=false\", \"emit-lean-stages=Certified/mulx/gen\"], unstable: UnstableOpts { ui_testing: false, track_diagnostics: false, parse_yul: false, no_resolve_imports: false, recover_incomplete_input: false, dump: None, ast_stats: false, hir_stats: false, standard_json_stats: false, span_visitor: false, print_max_storage_sizes: false, print_natspec: false, mir_pipeline: None, evm_ir_pipeline: None, print_after_each: false, pass_diff: false, debugify: None, debugify_output: None, solar_tv: None, validate_ir: None, time_passes: false, codegen_all_functions: false, switch_lowering: Auto, switch_max_gas_code_growth: None, switch_max_bit_slice_gas_code_growth: None, tune: None, pack_wide_jump_tables: false, check_analyses: Some(false), prove_analyses: None, validate_passes: None, validate_passes_fault: None, validate_backend: None, validate_backend_fault: None, validate_evm_ir_passes: None, validate_assembly: false, validate_assembly_fault: None, emit_lean_stages: Some(\"Certified/mulx/gen\"), forget_gcx: true, help: (), _non_exhaustive: () }, _non_exhaustive: () }", "sources": [ { - "path": "solar-tv/milestone/mulx/mulx.sol", + "path": "Certified/mulx/mulx.sol", "sha256": "50ef03a3c5724105509c3ed40b7ee7d92ea43b5d48a67d0e6722b26806dd4980" } ], diff --git a/Certified/reader/Proofs.lean b/Certified/reader/Proofs.lean index 346ab2d2..33ee215c 100644 --- a/Certified/reader/Proofs.lean +++ b/Certified/reader/Proofs.lean @@ -1,3 +1,3 @@ --- Generated by solar-tv/milestone/certify.py; do not edit. +-- Generated by solar's tools/certify/certify.py; do not edit. import reader.Proofs.Stages import reader.Proofs.Assembly diff --git a/Certified/reader/Proofs/Assembly.lean b/Certified/reader/Proofs/Assembly.lean index 4833a07e..02620836 100644 --- a/Certified/reader/Proofs/Assembly.lean +++ b/Certified/reader/Proofs/Assembly.lean @@ -1,4 +1,4 @@ --- Generated by solar-tv/milestone/certify.py; do not edit. +-- Generated by solar's tools/certify/certify.py; do not edit. import W1Proofs.Items import reader.gen.Reader.Evm7 import reader.gen.Reader.Bytecode diff --git a/Certified/reader/Proofs/Runs/Evm1.lean b/Certified/reader/Proofs/Runs/Evm1.lean index fa95c919..a4ea4817 100644 --- a/Certified/reader/Proofs/Runs/Evm1.lean +++ b/Certified/reader/Proofs/Runs/Evm1.lean @@ -1,4 +1,4 @@ --- Generated by solar-tv/milestone/certify.py; do not edit. +-- Generated by solar's tools/certify/certify.py; do not edit. import W1Proofs.Tactic import W1Proofs.Axioms import reader.gen.Reader.Evm1 diff --git a/Certified/reader/Proofs/Runs/Evm2.lean b/Certified/reader/Proofs/Runs/Evm2.lean index 524dcf8a..9df61b91 100644 --- a/Certified/reader/Proofs/Runs/Evm2.lean +++ b/Certified/reader/Proofs/Runs/Evm2.lean @@ -1,4 +1,4 @@ --- Generated by solar-tv/milestone/certify.py; do not edit. +-- Generated by solar's tools/certify/certify.py; do not edit. import W1Proofs.Tactic import W1Proofs.Axioms import reader.gen.Reader.Evm2 diff --git a/Certified/reader/Proofs/Runs/Evm3.lean b/Certified/reader/Proofs/Runs/Evm3.lean index 2e1d1f0d..5082a9eb 100644 --- a/Certified/reader/Proofs/Runs/Evm3.lean +++ b/Certified/reader/Proofs/Runs/Evm3.lean @@ -1,4 +1,4 @@ --- Generated by solar-tv/milestone/certify.py; do not edit. +-- Generated by solar's tools/certify/certify.py; do not edit. import W1Proofs.Tactic import W1Proofs.Axioms import reader.gen.Reader.Evm3 diff --git a/Certified/reader/Proofs/Runs/Evm4.lean b/Certified/reader/Proofs/Runs/Evm4.lean index 6195570f..32b0d6c9 100644 --- a/Certified/reader/Proofs/Runs/Evm4.lean +++ b/Certified/reader/Proofs/Runs/Evm4.lean @@ -1,4 +1,4 @@ --- Generated by solar-tv/milestone/certify.py; do not edit. +-- Generated by solar's tools/certify/certify.py; do not edit. import W1Proofs.Tactic import W1Proofs.Axioms import reader.gen.Reader.Evm4 diff --git a/Certified/reader/Proofs/Runs/Evm5.lean b/Certified/reader/Proofs/Runs/Evm5.lean index cff6874c..27bcf7a1 100644 --- a/Certified/reader/Proofs/Runs/Evm5.lean +++ b/Certified/reader/Proofs/Runs/Evm5.lean @@ -1,4 +1,4 @@ --- Generated by solar-tv/milestone/certify.py; do not edit. +-- Generated by solar's tools/certify/certify.py; do not edit. import W1Proofs.Tactic import W1Proofs.Axioms import reader.gen.Reader.Evm5 diff --git a/Certified/reader/Proofs/Runs/Evm6.lean b/Certified/reader/Proofs/Runs/Evm6.lean index bafd5bf6..3b5f6f1c 100644 --- a/Certified/reader/Proofs/Runs/Evm6.lean +++ b/Certified/reader/Proofs/Runs/Evm6.lean @@ -1,4 +1,4 @@ --- Generated by solar-tv/milestone/certify.py; do not edit. +-- Generated by solar's tools/certify/certify.py; do not edit. import W1Proofs.Tactic import W1Proofs.Axioms import reader.gen.Reader.Evm6 diff --git a/Certified/reader/Proofs/Runs/Evm7.lean b/Certified/reader/Proofs/Runs/Evm7.lean index 92dfe058..a91013f3 100644 --- a/Certified/reader/Proofs/Runs/Evm7.lean +++ b/Certified/reader/Proofs/Runs/Evm7.lean @@ -1,4 +1,4 @@ --- Generated by solar-tv/milestone/certify.py; do not edit. +-- Generated by solar's tools/certify/certify.py; do not edit. import W1Proofs.Tactic import W1Proofs.Axioms import reader.gen.Reader.Evm7 diff --git a/Certified/reader/Proofs/Runs/Mir1.lean b/Certified/reader/Proofs/Runs/Mir1.lean index f3ebd2c5..bda91c4e 100644 --- a/Certified/reader/Proofs/Runs/Mir1.lean +++ b/Certified/reader/Proofs/Runs/Mir1.lean @@ -1,4 +1,4 @@ --- Generated by solar-tv/milestone/certify.py; do not edit. +-- Generated by solar's tools/certify/certify.py; do not edit. import W1Proofs.Tactic import W1Proofs.Axioms import reader.gen.Reader.Mir1 diff --git a/Certified/reader/Proofs/Runs/Mir2.lean b/Certified/reader/Proofs/Runs/Mir2.lean index 1ac8eb7a..383de90c 100644 --- a/Certified/reader/Proofs/Runs/Mir2.lean +++ b/Certified/reader/Proofs/Runs/Mir2.lean @@ -1,4 +1,4 @@ --- Generated by solar-tv/milestone/certify.py; do not edit. +-- Generated by solar's tools/certify/certify.py; do not edit. import W1Proofs.Tactic import W1Proofs.Axioms import reader.gen.Reader.Mir2 diff --git a/Certified/reader/Proofs/Runs/Mir3.lean b/Certified/reader/Proofs/Runs/Mir3.lean index 261318f3..15d9688e 100644 --- a/Certified/reader/Proofs/Runs/Mir3.lean +++ b/Certified/reader/Proofs/Runs/Mir3.lean @@ -1,4 +1,4 @@ --- Generated by solar-tv/milestone/certify.py; do not edit. +-- Generated by solar's tools/certify/certify.py; do not edit. import W1Proofs.Tactic import W1Proofs.Axioms import reader.gen.Reader.Mir3 diff --git a/Certified/reader/Proofs/Runs/Sched.lean b/Certified/reader/Proofs/Runs/Sched.lean index eaec8867..7e4cda57 100644 --- a/Certified/reader/Proofs/Runs/Sched.lean +++ b/Certified/reader/Proofs/Runs/Sched.lean @@ -1,4 +1,4 @@ --- Generated by solar-tv/milestone/certify.py; do not edit. +-- Generated by solar's tools/certify/certify.py; do not edit. import W1Proofs.Tactic import W1Proofs.Axioms import reader.gen.Reader.Sched diff --git a/Certified/reader/Proofs/Runs/Stage0.lean b/Certified/reader/Proofs/Runs/Stage0.lean index 76261936..a20b4226 100644 --- a/Certified/reader/Proofs/Runs/Stage0.lean +++ b/Certified/reader/Proofs/Runs/Stage0.lean @@ -1,4 +1,4 @@ --- Generated by solar-tv/milestone/certify.py; do not edit. +-- Generated by solar's tools/certify/certify.py; do not edit. import W1Proofs.Tactic import W1Proofs.Axioms import reader.gen.Reader.Stage0 diff --git a/Certified/reader/Proofs/Stages.lean b/Certified/reader/Proofs/Stages.lean index 093fa2a4..023c0b5f 100644 --- a/Certified/reader/Proofs/Stages.lean +++ b/Certified/reader/Proofs/Stages.lean @@ -1,4 +1,4 @@ --- Generated by solar-tv/milestone/certify.py; do not edit. +-- Generated by solar's tools/certify/certify.py; do not edit. import reader.Proofs.Runs.Stage0 import reader.Proofs.Runs.Mir1 import reader.Proofs.Runs.Mir2 diff --git a/Certified/reader/gen/Reader/Manifest.lean b/Certified/reader/gen/Reader/Manifest.lean index 5ea2fd47..78b9fdd9 100644 --- a/Certified/reader/gen/Reader/Manifest.lean +++ b/Certified/reader/gen/Reader/Manifest.lean @@ -8,17 +8,17 @@ stage's file, its definition, the pass whose output it is, and the SHA-256 of th namespace SolarTV.Export.Reader.Manifest def sources : List (String × String) := - [("solar-tv/milestone/reader/reader.sol", "bff96eb4b5b33ebc37c3dd379d4d55388525e9787dd991afa41cc0b809b89a7e")] + [("Certified/reader/reader.sol", "bff96eb4b5b33ebc37c3dd379d4d55388525e9787dd991afa41cc0b809b89a7e")] -def compiler : String := "0.8.38+commit.4a7d9ede.solar.0.3.0-dev" +def compiler : String := "0.8.38+commit.ebdc3376.solar.0.3.0-dev" def arguments : List String := - ["solar-tv/milestone/reader/reader.sol", + ["Certified/reader/reader.sol", "-Ogas", "--evm-version", "osaka", "--emit=bin-runtime", - "-Zemit-lean-stages=solar-tv/milestone/reader/gen"] + "-Zemit-lean-stages=Certified/reader/gen"] def evmVersion : String := "osaka" diff --git a/Certified/reader/gen/Reader/Schedule.json b/Certified/reader/gen/Reader/Schedule.json new file mode 100644 index 00000000..371817b0 --- /dev/null +++ b/Certified/reader/gen/Reader/Schedule.json @@ -0,0 +1,20 @@ +{ + "functions": [ + {"function": 1, "entry": null, "returns": false, "rebuilt": false, "unsupported": null, "blocks": [ + {"block": 0, "start": [0, 0], "layout": [], "floating": true, "continues": null}, + {"block": 1, "start": [1, 0], "layout": [], "floating": true, "continues": null}, + {"block": 2, "start": [2, 0], "layout": [], "floating": true, "continues": null}, + {"block": 3, "start": [3, 0], "layout": [], "floating": true, "continues": null} + ]}, + {"function": 0, "entry": 4, "returns": false, "rebuilt": false, "unsupported": null, "blocks": [ + {"block": 0, "start": [4, 3], "layout": [], "floating": true, "continues": null}, + {"block": 1, "start": [9, 0], "layout": [], "floating": true, "continues": null}, + {"block": 2, "start": [6, 0], "layout": [], "floating": true, "continues": null}, + {"block": 3, "start": [11, 0], "layout": [], "floating": true, "continues": null}, + {"block": 4, "start": [7, 0], "layout": [], "floating": true, "continues": null}, + {"block": 5, "start": [10, 0], "layout": [], "floating": true, "continues": null}, + {"block": 6, "start": [8, 0], "layout": ["v19"], "floating": true, "continues": null}, + {"block": 7, "start": [5, 0], "layout": [], "floating": true, "continues": null} + ]} + ] +} diff --git a/Certified/reader/gen/Reader/manifest.json b/Certified/reader/gen/Reader/manifest.json index e2d8b12d..7a4060b2 100644 --- a/Certified/reader/gen/Reader/manifest.json +++ b/Certified/reader/gen/Reader/manifest.json @@ -1,22 +1,22 @@ { "arguments": [ - "solar-tv/milestone/reader/reader.sol", + "Certified/reader/reader.sol", "-Ogas", "--evm-version", "osaka", "--emit=bin-runtime", - "-Zemit-lean-stages=solar-tv/milestone/reader/gen" + "-Zemit-lean-stages=Certified/reader/gen" ], "bytecode": "346053575f3560e01c8063a087a87e03605357608060405260043560a01c602436101760535763a035b1fe5f5260205f6004601c81355afa156057573d6020116053575f516001018015605f575f5260205ff35b5f5ffd5b3d5f5f3e3d5ffd5b6011602052634e487b715f526024601cfd", "bytecode_sha256": "7e4fced8401133d842f58d3d310e8b78a32039960170ea5d8ad75a53a7b36626", - "compiler": "0.8.38+commit.4a7d9ede.solar.0.3.0-dev", + "compiler": "0.8.38+commit.ebdc3376.solar.0.3.0-dev", "contract": "Reader", "evm_version": "osaka", "optimization": "Gas", - "options": "CompileOpts { input: [\"solar-tv/milestone/reader/reader.sol\"], import_remappings: [], base_path: None, include_paths: [], allow_paths: [], no_import_callback: false, language: Solidity, threads: 4, evm_version: Osaka, stop_after: None, optimization: Gas, optimizer_runs: None, revert_strings: Default, libraries: [], out_dir: None, emit: [BinRuntime], standard_json: false, color: Auto, verbose: false, pretty_json: false, pretty_json_err: false, error_format: Human, error_format_human: Unicode, diagnostic_width: None, no_warnings: false, allow: [], _unstable: [\"emit-lean-stages=solar-tv/milestone/reader/gen\"], unstable: UnstableOpts { ui_testing: false, track_diagnostics: false, parse_yul: false, no_resolve_imports: false, recover_incomplete_input: false, dump: None, ast_stats: false, hir_stats: false, standard_json_stats: false, span_visitor: false, print_max_storage_sizes: false, print_natspec: false, mir_pipeline: None, evm_ir_pipeline: None, print_after_each: false, pass_diff: false, debugify: None, debugify_output: None, solar_tv: None, validate_ir: None, time_passes: false, codegen_all_functions: false, switch_lowering: Auto, switch_max_gas_code_growth: None, switch_max_bit_slice_gas_code_growth: None, tune: None, pack_wide_jump_tables: false, check_analyses: None, prove_analyses: None, validate_passes: None, validate_passes_fault: None, validate_backend: None, validate_backend_fault: None, validate_evm_ir_passes: None, validate_assembly: false, validate_assembly_fault: None, emit_lean_stages: Some(\"solar-tv/milestone/reader/gen\"), forget_gcx: true, help: (), _non_exhaustive: () }, _non_exhaustive: () }", + "options": "CompileOpts { input: [\"Certified/reader/reader.sol\"], import_remappings: [], base_path: None, include_paths: [], allow_paths: [], no_import_callback: false, language: Solidity, threads: 4, evm_version: Osaka, stop_after: None, optimization: Gas, optimizer_runs: None, revert_strings: Default, libraries: [], out_dir: None, emit: [BinRuntime], standard_json: false, color: Auto, verbose: false, pretty_json: false, pretty_json_err: false, error_format: Human, error_format_human: Unicode, diagnostic_width: None, no_warnings: false, allow: [], _unstable: [\"emit-lean-stages=Certified/reader/gen\"], unstable: UnstableOpts { ui_testing: false, track_diagnostics: false, parse_yul: false, no_resolve_imports: false, recover_incomplete_input: false, dump: None, ast_stats: false, hir_stats: false, standard_json_stats: false, span_visitor: false, print_max_storage_sizes: false, print_natspec: false, mir_pipeline: None, evm_ir_pipeline: None, print_after_each: false, pass_diff: false, debugify: None, debugify_output: None, solar_tv: None, validate_ir: None, time_passes: false, codegen_all_functions: false, switch_lowering: Auto, switch_max_gas_code_growth: None, switch_max_bit_slice_gas_code_growth: None, tune: None, pack_wide_jump_tables: false, check_analyses: None, prove_analyses: None, validate_passes: None, validate_passes_fault: None, validate_backend: None, validate_backend_fault: None, validate_evm_ir_passes: None, validate_assembly: false, validate_assembly_fault: None, emit_lean_stages: Some(\"Certified/reader/gen\"), forget_gcx: true, help: (), _non_exhaustive: () }, _non_exhaustive: () }", "sources": [ { - "path": "solar-tv/milestone/reader/reader.sol", + "path": "Certified/reader/reader.sol", "sha256": "bff96eb4b5b33ebc37c3dd379d4d55388525e9787dd991afa41cc0b809b89a7e" } ], diff --git a/Certified/w4/Proofs.lean b/Certified/w4/Proofs.lean index 93ea22d3..95899ba8 100644 --- a/Certified/w4/Proofs.lean +++ b/Certified/w4/Proofs.lean @@ -1,3 +1,3 @@ --- Generated by solar-tv/milestone/certify.py; do not edit. +-- Generated by solar's tools/certify/certify.py; do not edit. import w4.Proofs.Stages import w4.Proofs.Assembly diff --git a/Certified/w4/Proofs/Assembly.lean b/Certified/w4/Proofs/Assembly.lean index 7eec049c..bbb4c8a2 100644 --- a/Certified/w4/Proofs/Assembly.lean +++ b/Certified/w4/Proofs/Assembly.lean @@ -1,4 +1,4 @@ --- Generated by solar-tv/milestone/certify.py; do not edit. +-- Generated by solar's tools/certify/certify.py; do not edit. import W1Proofs.Items import w4.gen.Main.Evm4 import w4.gen.Main.Bytecode diff --git a/Certified/w4/Proofs/Runs/Evm1.lean b/Certified/w4/Proofs/Runs/Evm1.lean index 48c70b19..8e249712 100644 --- a/Certified/w4/Proofs/Runs/Evm1.lean +++ b/Certified/w4/Proofs/Runs/Evm1.lean @@ -1,4 +1,4 @@ --- Generated by solar-tv/milestone/certify.py; do not edit. +-- Generated by solar's tools/certify/certify.py; do not edit. import W1Proofs.Tactic import W1Proofs.Axioms import w4.gen.Main.Evm1 diff --git a/Certified/w4/Proofs/Runs/Evm2.lean b/Certified/w4/Proofs/Runs/Evm2.lean index 67918531..da59e059 100644 --- a/Certified/w4/Proofs/Runs/Evm2.lean +++ b/Certified/w4/Proofs/Runs/Evm2.lean @@ -1,4 +1,4 @@ --- Generated by solar-tv/milestone/certify.py; do not edit. +-- Generated by solar's tools/certify/certify.py; do not edit. import W1Proofs.Tactic import W1Proofs.Axioms import w4.gen.Main.Evm2 diff --git a/Certified/w4/Proofs/Runs/Evm3.lean b/Certified/w4/Proofs/Runs/Evm3.lean index 52f1c048..17a01a5f 100644 --- a/Certified/w4/Proofs/Runs/Evm3.lean +++ b/Certified/w4/Proofs/Runs/Evm3.lean @@ -1,4 +1,4 @@ --- Generated by solar-tv/milestone/certify.py; do not edit. +-- Generated by solar's tools/certify/certify.py; do not edit. import W1Proofs.Tactic import W1Proofs.Axioms import w4.gen.Main.Evm3 diff --git a/Certified/w4/Proofs/Runs/Evm4.lean b/Certified/w4/Proofs/Runs/Evm4.lean index c18f6ed3..9b5a46e6 100644 --- a/Certified/w4/Proofs/Runs/Evm4.lean +++ b/Certified/w4/Proofs/Runs/Evm4.lean @@ -1,4 +1,4 @@ --- Generated by solar-tv/milestone/certify.py; do not edit. +-- Generated by solar's tools/certify/certify.py; do not edit. import W1Proofs.Tactic import W1Proofs.Axioms import w4.gen.Main.Evm4 diff --git a/Certified/w4/Proofs/Runs/Sched.lean b/Certified/w4/Proofs/Runs/Sched.lean index f1631f4e..1ea10de8 100644 --- a/Certified/w4/Proofs/Runs/Sched.lean +++ b/Certified/w4/Proofs/Runs/Sched.lean @@ -1,4 +1,4 @@ --- Generated by solar-tv/milestone/certify.py; do not edit. +-- Generated by solar's tools/certify/certify.py; do not edit. import W1Proofs.Tactic import W1Proofs.Axioms import w4.gen.Main.Sched diff --git a/Certified/w4/Proofs/Runs/Stage0.lean b/Certified/w4/Proofs/Runs/Stage0.lean index 77a270e1..a41a3be8 100644 --- a/Certified/w4/Proofs/Runs/Stage0.lean +++ b/Certified/w4/Proofs/Runs/Stage0.lean @@ -1,4 +1,4 @@ --- Generated by solar-tv/milestone/certify.py; do not edit. +-- Generated by solar's tools/certify/certify.py; do not edit. import W1Proofs.Tactic import W1Proofs.Axioms import w4.gen.Main.Stage0 diff --git a/Certified/w4/Proofs/Stages.lean b/Certified/w4/Proofs/Stages.lean index 66a10a06..d8c9fd6a 100644 --- a/Certified/w4/Proofs/Stages.lean +++ b/Certified/w4/Proofs/Stages.lean @@ -1,4 +1,4 @@ --- Generated by solar-tv/milestone/certify.py; do not edit. +-- Generated by solar's tools/certify/certify.py; do not edit. import w4.Proofs.Runs.Stage0 import w4.Proofs.Runs.Sched import w4.Proofs.Runs.Evm1 diff --git a/Certified/w4/gen/Main/Manifest.lean b/Certified/w4/gen/Main/Manifest.lean index f7a39202..8f30a6c7 100644 --- a/Certified/w4/gen/Main/Manifest.lean +++ b/Certified/w4/gen/Main/Manifest.lean @@ -8,17 +8,17 @@ stage's file, its definition, the pass whose output it is, and the SHA-256 of th namespace SolarTV.Export.Main.Manifest def sources : List (String × String) := - [("solar-tv/milestone/w4/w4.sol", "942f34d659aeb6e6809054e007c8201ad58d6ddb4ac748444eb9442dc317f02d")] + [("Certified/w4/w4.sol", "942f34d659aeb6e6809054e007c8201ad58d6ddb4ac748444eb9442dc317f02d")] -def compiler : String := "0.8.38+commit.7817979b.solar.0.3.0-dev" +def compiler : String := "0.8.38+commit.ebdc3376.solar.0.3.0-dev" def arguments : List String := - ["solar-tv/milestone/w4/w4.sol", + ["Certified/w4/w4.sol", "-Ogas", "--evm-version", "osaka", "--emit=bin-runtime", - "-Zemit-lean-stages=solar-tv/milestone/w4/gen"] + "-Zemit-lean-stages=Certified/w4/gen"] def evmVersion : String := "osaka" diff --git a/Certified/w4/gen/Main/Schedule.json b/Certified/w4/gen/Main/Schedule.json new file mode 100644 index 00000000..c8a5f4e5 --- /dev/null +++ b/Certified/w4/gen/Main/Schedule.json @@ -0,0 +1,15 @@ +{ + "functions": [ + {"function": 1, "entry": null, "returns": false, "rebuilt": false, "unsupported": null, "blocks": [ + {"block": 0, "start": [0, 0], "layout": [], "floating": true, "continues": null}, + {"block": 1, "start": [1, 0], "layout": [], "floating": true, "continues": null}, + {"block": 2, "start": [2, 0], "layout": [], "floating": true, "continues": null}, + {"block": 3, "start": [3, 0], "layout": [], "floating": true, "continues": null} + ]}, + {"function": 0, "entry": 4, "returns": false, "rebuilt": false, "unsupported": null, "blocks": [ + {"block": 0, "start": [4, 0], "layout": [], "floating": true, "continues": null}, + {"block": 1, "start": [6, 0], "layout": [], "floating": true, "continues": null}, + {"block": 2, "start": [5, 0], "layout": [], "floating": true, "continues": null} + ]} + ] +} diff --git a/Certified/w4/gen/Main/manifest.json b/Certified/w4/gen/Main/manifest.json index dcd74eab..5f6f0461 100644 --- a/Certified/w4/gen/Main/manifest.json +++ b/Certified/w4/gen/Main/manifest.json @@ -1,22 +1,22 @@ { "arguments": [ - "solar-tv/milestone/w4/w4.sol", + "Certified/w4/w4.sol", "-Ogas", "--evm-version", "osaka", "--emit=bin-runtime", - "-Zemit-lean-stages=solar-tv/milestone/w4/gen" + "-Zemit-lean-stages=Certified/w4/gen" ], "bytecode": "346020575f3560e01c806360fe47b103602057602436106020576004355f55005b5f5ffd", "bytecode_sha256": "4ac6a427e10e54ab60dbae0bd734633543eafea6ea38440d53363c8fa50018ee", - "compiler": "0.8.38+commit.7817979b.solar.0.3.0-dev", + "compiler": "0.8.38+commit.ebdc3376.solar.0.3.0-dev", "contract": "Main", "evm_version": "osaka", "optimization": "Gas", - "options": "CompileOpts { input: [\"solar-tv/milestone/w4/w4.sol\"], import_remappings: [], base_path: None, include_paths: [], allow_paths: [], no_import_callback: false, language: Solidity, threads: 4, evm_version: Osaka, stop_after: None, optimization: Gas, optimizer_runs: None, revert_strings: Default, libraries: [], out_dir: None, emit: [BinRuntime], standard_json: false, color: Auto, verbose: false, pretty_json: false, pretty_json_err: false, error_format: Human, error_format_human: Unicode, diagnostic_width: None, no_warnings: false, allow: [], _unstable: [\"emit-lean-stages=solar-tv/milestone/w4/gen\"], unstable: UnstableOpts { ui_testing: false, track_diagnostics: false, parse_yul: false, no_resolve_imports: false, recover_incomplete_input: false, dump: None, ast_stats: false, hir_stats: false, standard_json_stats: false, span_visitor: false, print_max_storage_sizes: false, print_natspec: false, mir_pipeline: None, evm_ir_pipeline: None, print_after_each: false, pass_diff: false, debugify: None, debugify_output: None, solar_tv: None, validate_ir: None, time_passes: false, codegen_all_functions: false, switch_lowering: Auto, switch_max_gas_code_growth: None, switch_max_bit_slice_gas_code_growth: None, tune: None, pack_wide_jump_tables: false, check_analyses: None, prove_analyses: None, validate_passes: None, validate_passes_fault: None, validate_backend: None, validate_backend_fault: None, validate_evm_ir_passes: None, validate_assembly: false, validate_assembly_fault: None, emit_lean_stages: Some(\"solar-tv/milestone/w4/gen\"), forget_gcx: true, help: (), _non_exhaustive: () }, _non_exhaustive: () }", + "options": "CompileOpts { input: [\"Certified/w4/w4.sol\"], import_remappings: [], base_path: None, include_paths: [], allow_paths: [], no_import_callback: false, language: Solidity, threads: 4, evm_version: Osaka, stop_after: None, optimization: Gas, optimizer_runs: None, revert_strings: Default, libraries: [], out_dir: None, emit: [BinRuntime], standard_json: false, color: Auto, verbose: false, pretty_json: false, pretty_json_err: false, error_format: Human, error_format_human: Unicode, diagnostic_width: None, no_warnings: false, allow: [], _unstable: [\"emit-lean-stages=Certified/w4/gen\"], unstable: UnstableOpts { ui_testing: false, track_diagnostics: false, parse_yul: false, no_resolve_imports: false, recover_incomplete_input: false, dump: None, ast_stats: false, hir_stats: false, standard_json_stats: false, span_visitor: false, print_max_storage_sizes: false, print_natspec: false, mir_pipeline: None, evm_ir_pipeline: None, print_after_each: false, pass_diff: false, debugify: None, debugify_output: None, solar_tv: None, validate_ir: None, time_passes: false, codegen_all_functions: false, switch_lowering: Auto, switch_max_gas_code_growth: None, switch_max_bit_slice_gas_code_growth: None, tune: None, pack_wide_jump_tables: false, check_analyses: None, prove_analyses: None, validate_passes: None, validate_passes_fault: None, validate_backend: None, validate_backend_fault: None, validate_evm_ir_passes: None, validate_assembly: false, validate_assembly_fault: None, emit_lean_stages: Some(\"Certified/w4/gen\"), forget_gcx: true, help: (), _non_exhaustive: () }, _non_exhaustive: () }", "sources": [ { - "path": "solar-tv/milestone/w4/w4.sol", + "path": "Certified/w4/w4.sol", "sha256": "942f34d659aeb6e6809054e007c8201ad58d6ddb4ac748444eb9442dc317f02d" } ], diff --git a/Contracts/ArrayMax/Audit.lean b/Contracts/ArrayMax/Audit.lean new file mode 100644 index 00000000..8f620e1b --- /dev/null +++ b/Contracts/ArrayMax/Audit.lean @@ -0,0 +1,22 @@ +import Contracts.ArrayMax.Proofs.ArrayMax.max +import Contracts.ArrayMax.Proofs.ArrayMax.clamp +import Contracts.ArrayMax.Proofs.ArrayMaxEntry.max + +/-! Fails unless every theorem under `Contracts.ArrayMax.max`, `Contracts.ArrayMax.clamp`, `Contracts.ArrayMaxEntry.max` uses no axiom but `propext`, +`Classical.choice` and `Quot.sound`, and prints how many it checked. -/ + +open Lean Elab Command in +#eval show CommandElabM Unit from do + let env ← getEnv + let roots : List Name := [`Contracts.ArrayMax.max, `Contracts.ArrayMax.clamp, `Contracts.ArrayMaxEntry.max] + let allowed : List Name := [`propext, `Classical.choice, `Quot.sound] + let mut n := 0 + for (name, info) in env.constants.toList do + unless roots.any (·.isPrefixOf name) do continue + unless info matches .thmInfo _ do continue + let axs ← Lean.collectAxioms name + for a in axs do + unless allowed.contains a do throwError "{name} uses axiom {a}" + n := n + 1 + if n == 0 then throwError "no theorems found" + IO.println s!"ArrayMax: {n} theorems, axioms within propext, Classical.choice, Quot.sound" diff --git a/Contracts/ArrayMax/Bounded.lean b/Contracts/ArrayMax/Bounded.lean new file mode 100644 index 00000000..61861d06 --- /dev/null +++ b/Contracts/ArrayMax/Bounded.lean @@ -0,0 +1,158 @@ +import Verify.Discharge + +/- +A bounded variant of `vc_search` (Verify.Discharge) for obligations whose hypotheses chain a loop +or path condition through many local Booleans, where the unbounded search times out or exhausts +memory (ArrayMax `max`'s preserved quantified invariants) or `vc_norm` exceeds the recursion +limit (Vault's reentrancy-lock obligations): + +1. definitions of local symbols are substituted away, and every remaining Boolean constant is + split into its two cases, so that Boolean formulas fold to literals before `vc_norm`; +2. quantified hypotheses are instantiated once, at the witnesses of existentials and at the + arguments of matching array reads, and never again; +3. a conditional whose condition has quantifiers (a path condition the context restates) is + proved from the context by `and_intros`, `assumption` and `omega`, and otherwise split; +4. each case clears its quantified hypotheses and is closed by `omega`. + +Every step builds a proof term the kernel checks; a goal it cannot close fails, never passes. +-/ +/- +A bounded variant of `vc_search` (Verify.Discharge) for obligations whose hypotheses chain a loop +or path condition through many local Booleans, where the unbounded search times out or exhausts +memory (ArrayMax `max`'s preserved quantified invariants) or `vc_norm` exceeds the recursion +limit (Vault's reentrancy-lock obligations): + +1. definitions of local symbols are substituted away, and every remaining Boolean constant is + split into its two cases, so that Boolean formulas fold to literals before `vc_norm`; +2. quantified hypotheses are instantiated once, at the witnesses of existentials and at the + arguments of matching array reads, and never again; +3. a conditional whose condition has quantifiers (a path condition the context restates) is + proved from the context by `and_intros`, `assumption` and `omega`, and otherwise split; +4. each case clears its quantified hypotheses and is closed by `omega`. + +Every step builds a proof term the kernel checks; a goal it cannot close fails, never passes. +-/ +open Lean Meta Elab Tactic SolarVerify.Discharge + +namespace Contracts.Bounded + +/-- Like the search's `splitIte`, but proves a quantified condition the context implies +directly in the tactic monad (so a failed attempt is an exception, never a logged error), with +enough depth for a path condition's left-nested conjunction. -/ +def splitIteB : TacticM Unit := withMainContext do + let some c ← findIteCond | throwError "no conditional" + let hcN ← mkFreshUserName `hc + let hcI := mkIdent hcN + if hasQuantifier c then + let s ← saveState + try + let m ← mkFreshExprSyntheticOpaqueMVar c + let main ← getMainGoal + setGoals [m.mvarId!] + evalTactic (← `(tactic| and_intros <;> first | assumption | omega)) + unless (← getGoals).isEmpty do throwError "condition not proved" + let m ← instantiateMVars m + if m.hasMVar then throwError "condition not proved" + let (_, g') ← (← main.assert hcN c m).intro1P + setGoals [g'] + simpCase (← `(tactic| simp only [↓reduceIte, SolarVerify.Discharge.ite_pos $hcI, SolarVerify.Discharge.qite_pos $hcI])) + return + catch _ => s.restore + evalTactic (← `(tactic| by_cases $hcI : $(← Term.exprToSyntax c))) + let gs ← getGoals + let mut out := [] + for (g, pos) in gs.zip [true, false] do + setGoals [g] + if pos then + simpCase (← `(tactic| simp only [↓reduceIte, SolarVerify.Discharge.ite_pos $hcI, SolarVerify.Discharge.qite_pos $hcI])) + else + simpCase (← `(tactic| simp only [↓reduceIte, SolarVerify.Discharge.ite_neg $hcI, SolarVerify.Discharge.qite_neg $hcI])) + out := out ++ (← getGoals) + setGoals out + +/-- Normalizes, splits hypotheses, then splits one conditional or propositional atom per level +(at most `fuel` levels) and closes each case with `omega`, without instantiating again. -/ +partial def boundedLeaf (fuel : Nat) : TacticM Unit := do + if fuel = 0 then throwError "bounded: depth exhausted" + for g in (← getGoals) do + setGoals [g] + evalTactic (← `(tactic| vc_norm)) + if (← getGoals).isEmpty then continue + splitHyps + for g in (← getGoals) do + setGoals [g] + if (← findIteCond).isSome then + splitIteB + boundedLeaf (fuel - 1) + else if let some p ← findPropAtom then + splitProp p + boundedLeaf (fuel - 1) + else + clearQuantified + evalTactic (← `(tactic| omega)) + setGoals [] + +/-- Substitutes definitions, normalizes, splits hypotheses and instantiates once. -/ +def boundedPre : TacticM Unit := do + evalTactic (← `(tactic| intros)) + iffToEq + evalTactic (← `(tactic| subst_vars)) + evalTactic (← `(tactic| vc_norm)) + splitHyps + let gs ← getGoals + let mut out := [] + for g in gs do + setGoals [g] + let _ ← instantiate (← witnesses) {} + out := out ++ (← getGoals) + setGoals out + +/-- Cases on every Boolean local variable (an SMT `Bool` constant), so that the Boolean +formulas over it fold to literals before `vc_norm` runs. -/ +partial def boolCases : TacticM Unit := withMainContext do + for ldecl in (← getLCtx) do + if ldecl.isImplementationDetail then continue + if (← instantiateMVars ldecl.type) == mkConst ``Bool then + let gs ← (← getMainGoal).cases ldecl.fvarId + let mut out := [] + for sg in gs do + setGoals [sg.mvarId] + boolCases + out := out ++ (← getGoals) + setGoals out + return + +/-- `boundedPre` with a case split on every Boolean constant before `vc_norm`. -/ +def boundedPreB : TacticM Unit := do + evalTactic (← `(tactic| intros)) + iffToEq + evalTactic (← `(tactic| subst_vars)) + boolCases + let gs ← getGoals + let mut out := [] + for g in gs do + setGoals [g] + evalTactic (← `(tactic| simp -failIfUnchanged only [Bool.true_and, Bool.and_true, Bool.false_and, Bool.and_false, Bool.not_true, Bool.not_false, Bool.true_or, Bool.or_true, Bool.false_or, Bool.or_false, Bool.false_eq_true, Bool.true_eq_false, false_and, and_false, not_true_eq_false] at *)) + unless (← getGoals).isEmpty do + evalTactic (← `(tactic| vc_norm)) + unless (← getGoals).isEmpty do + splitHyps + let gs' ← getGoals + for g' in gs' do + setGoals [g'] + let _ ← instantiate (← witnesses) {} + out := out ++ (← getGoals) + setGoals out + +end Contracts.Bounded + +open Contracts.Bounded + +/-- The bounded search on a goal `vc_valid_prep` left, without Boolean case splits. -/ +elab "vc_bounded" : tactic => do boundedPre; boundedLeaf 16 + +/-- The bounded search on a goal `vc_valid_prep` left, after splitting every Boolean constant. -/ +elab "vc_bounded_bool" : tactic => do boundedPreB; boundedLeaf 16 + +/-- `vc_valid_prep`, then the bounded search with Boolean case splits. -/ +macro "vc_bounded_valid" : tactic => `(tactic| (vc_valid_prep <;> vc_bounded_bool)) diff --git a/Contracts/ArrayMax/Proofs/ArrayMax/clamp.lean b/Contracts/ArrayMax/Proofs/ArrayMax/clamp.lean new file mode 100644 index 00000000..fe8a6774 --- /dev/null +++ b/Contracts/ArrayMax/Proofs/ArrayMax/clamp.lean @@ -0,0 +1,16 @@ +import Contracts.ArrayMax.Bounded +import Contracts.ArrayMax.Vc.ArrayMax.clamp + +set_option maxHeartbeats 0 +set_option maxRecDepth 100000 + +/-! Kernel proofs of the required obligations of ArrayMax.clamp, as the frozen v1 export states them +(`Vc/ArrayMax/clamp.lean`). -/ + +namespace Contracts.ArrayMax.clamp + +/-- ArrayMax.clamp#1 (obligation): postcondition not satisfied: r <= n. -/ +theorem ob1 : SolarVerifyVc.ArrayMax.clamp.ob1.Valid := by + first | vc_bounded_valid | vc_valid + +end Contracts.ArrayMax.clamp diff --git a/Contracts/ArrayMax/Proofs/ArrayMax/max.lean b/Contracts/ArrayMax/Proofs/ArrayMax/max.lean new file mode 100644 index 00000000..ee70c0dd --- /dev/null +++ b/Contracts/ArrayMax/Proofs/ArrayMax/max.lean @@ -0,0 +1,72 @@ +import Contracts.ArrayMax.Bounded +import Contracts.ArrayMax.Vc.ArrayMax.max + +set_option maxHeartbeats 0 +set_option maxRecDepth 100000 + +/-! Kernel proofs of the required obligations of ArrayMax.max, as the frozen v1 export states them +(`Vc/ArrayMax/max.lean`). -/ + +namespace Contracts.ArrayMax.max + +/-- ArrayMax.max#0 (obligation): loop invariant not satisfied on entry: 1 <= i. -/ +theorem ob0 : SolarVerifyVc.ArrayMax.max.ob0.Valid := by + first | vc_bounded_valid | vc_valid + +/-- ArrayMax.max#1 (obligation): loop invariant not satisfied on entry: i <= xs.length. -/ +theorem ob1 : SolarVerifyVc.ArrayMax.max.ob1.Valid := by + first | vc_bounded_valid | vc_valid + +/-- ArrayMax.max#2 (obligation): loop invariant not satisfied on entry: forall uint256 j :: j < i ==> xs[j] <= m. -/ +theorem ob2 : SolarVerifyVc.ArrayMax.max.ob2.Valid := by + first | vc_bounded_valid | vc_valid + +/-- ArrayMax.max#3 (obligation): loop invariant not satisfied on entry: exists uint256 j :: j < i && xs[j] == m. -/ +theorem ob3 : SolarVerifyVc.ArrayMax.max.ob3.Valid := by + first | vc_bounded_valid | vc_valid + +/-- ArrayMax.max#4 (obligation): loop invariant not satisfied on entry: exists uint256 j :: j < xs.length && xs[j] == m. -/ +theorem ob4 : SolarVerifyVc.ArrayMax.max.ob4.Valid := by + first | vc_bounded_valid | vc_valid + +/-- ArrayMax.max#5 (obligation): loop invariant not satisfied on entry: xs.length > 0. -/ +theorem ob5 : SolarVerifyVc.ArrayMax.max.ob5.Valid := by + first | vc_bounded_valid | vc_valid + +/-- ArrayMax.max#6 (obligation): loop invariant not preserved by the loop body: 1 <= i. -/ +theorem ob6 : SolarVerifyVc.ArrayMax.max.ob6.Valid := by + first | vc_bounded_valid | vc_valid + +/-- ArrayMax.max#7 (obligation): loop invariant not preserved by the loop body: i <= xs.length. -/ +theorem ob7 : SolarVerifyVc.ArrayMax.max.ob7.Valid := by + first | vc_bounded_valid | vc_valid + +/-- ArrayMax.max#8 (obligation): loop invariant not preserved by the loop body: forall uint256 j :: j < i ==> xs[j] <= m. -/ +theorem ob8 : SolarVerifyVc.ArrayMax.max.ob8.Valid := by + first | vc_bounded_valid | vc_valid + +/-- ArrayMax.max#9 (obligation): loop invariant not preserved by the loop body: exists uint256 j :: j < i && xs[j] == m. -/ +theorem ob9 : SolarVerifyVc.ArrayMax.max.ob9.Valid := by + first | vc_bounded_valid | vc_valid + +/-- ArrayMax.max#10 (obligation): loop invariant not preserved by the loop body: exists uint256 j :: j < xs.length && xs[j] == m. -/ +theorem ob10 : SolarVerifyVc.ArrayMax.max.ob10.Valid := by + first | vc_bounded_valid | vc_valid + +/-- ArrayMax.max#11 (obligation): loop invariant not preserved by the loop body: xs.length > 0. -/ +theorem ob11 : SolarVerifyVc.ArrayMax.max.ob11.Valid := by + first | vc_bounded_valid | vc_valid + +/-- ArrayMax.max#12 (obligation): loop does not terminate: decreases clause not decreased: (xs.length) - i. -/ +theorem ob12 : SolarVerifyVc.ArrayMax.max.ob12.Valid := by + first | vc_bounded_valid | vc_valid + +/-- ArrayMax.max#14 (obligation): postcondition not satisfied: forall uint256 j :: j < xs.length ==> xs[j] <= m. -/ +theorem ob14 : SolarVerifyVc.ArrayMax.max.ob14.Valid := by + first | vc_bounded_valid | vc_valid + +/-- ArrayMax.max#15 (obligation): postcondition not satisfied: exists uint256 j :: j < xs.length && xs[j] == m. -/ +theorem ob15 : SolarVerifyVc.ArrayMax.max.ob15.Valid := by + first | vc_bounded_valid | vc_valid + +end Contracts.ArrayMax.max diff --git a/Contracts/ArrayMax/Proofs/ArrayMaxEntry/max.lean b/Contracts/ArrayMax/Proofs/ArrayMaxEntry/max.lean new file mode 100644 index 00000000..635cffab --- /dev/null +++ b/Contracts/ArrayMax/Proofs/ArrayMaxEntry/max.lean @@ -0,0 +1,24 @@ +import Contracts.ArrayMax.Bounded +import Contracts.ArrayMax.Vc.ArrayMaxEntry.max + +set_option maxHeartbeats 0 +set_option maxRecDepth 100000 + +/-! Kernel proofs of the required obligations of ArrayMaxEntry.max, as the frozen v1 export states them +(`Vc/ArrayMaxEntry/max.lean`). -/ + +namespace Contracts.ArrayMaxEntry.max + +/-- ArrayMaxEntry.max#0 (obligation): precondition of 'max' not satisfied: xs.length > 0. -/ +theorem ob0 : SolarVerifyVc.ArrayMaxEntry.max.ob0.Valid := by + first | vc_bounded_valid | vc_valid + +/-- ArrayMaxEntry.max#2 (obligation): postcondition not satisfied: forall uint256 j :: j < xs.length ==> xs[j] <= result. -/ +theorem ob2 : SolarVerifyVc.ArrayMaxEntry.max.ob2.Valid := by + first | vc_bounded_valid | vc_valid + +/-- ArrayMaxEntry.max#3 (obligation): postcondition not satisfied: exists uint256 j :: j < xs.length && xs[j] == result. -/ +theorem ob3 : SolarVerifyVc.ArrayMaxEntry.max.ob3.Valid := by + first | vc_bounded_valid | vc_valid + +end Contracts.ArrayMaxEntry.max diff --git a/Contracts/ArrayMax/README.md b/Contracts/ArrayMax/README.md new file mode 100644 index 00000000..78e4ac47 --- /dev/null +++ b/Contracts/ArrayMax/README.md @@ -0,0 +1,29 @@ +# ArrayMax: solar-verify's obligations in the Lean kernel + +`Vc/` holds the frozen v1 export of `crates/verify/examples/ArrayMax.sol` (paradigmxyz/solar +7f4e94e, `solar-verify --emit-lean`, z3 4.13.4, cvc5 1.3.1). Each module is the exporter's output +with one change: its first line `import SolarVerify` reads `import Verify.Obligation`, where the +same library now lives (the `VerifyDischarge` library). `Vc/frozen.sha256` is the lock of the unchanged export, which +`Vc/manifest.json` and the modules match before that rewrite. + +The loop of `ArrayMax.max` carries no written invariant: solar-verify infers it, and the inferred +clauses reach Lean only as the ordinary loop obligations (on entry, preserved, and the +postconditions they imply), which are proved here like any other. + +`Bounded.lean` is the search that closes the obligations the default `vc_valid` cannot +(`max`'s preserved quantified invariants, and Vault's reentrancy-lock obligations); it builds +proof terms only, and every theorem's axioms are checked to be `propext`, `Classical.choice` and +`Quot.sound`. + +## Inferred invariant and memory writes + +solar-verify's loop-invariant inference was later found to be unsound for loops around internal +calls that write a memory array the caller passed; solar now refuses those loops. ArrayMax is +outside that case: `max` only reads `xs`, calls nothing, and neither `ArrayMaxEntry.max` nor +`clamp` writes an array, so the inferred clauses checked here are unaffected. They are, in any +case, not trusted: each is re-proved here as an ordinary obligation. + +## Building + +`lake build ContractsArrayMaxVault` builds the exports, the proofs and `Audit.lean`, which fails +unless every theorem uses no axiom but `propext`, `Classical.choice` and `Quot.sound`. diff --git a/Contracts/ArrayMax/Vc/ArrayMax/clamp.lean b/Contracts/ArrayMax/Vc/ArrayMax/clamp.lean new file mode 100644 index 00000000..e83ea593 --- /dev/null +++ b/Contracts/ArrayMax/Vc/ArrayMax/clamp.lean @@ -0,0 +1,74 @@ +-- Generated by solar-verify --emit-lean (format 1); do not edit. +import Verify.Obligation + +set_option maxRecDepth 100000 + +namespace SolarVerifyVc.ArrayMax.clamp +open SolarVerify.Smt SolarVerify.Vc + +/-- Script 0 of ArrayMax.clamp: the solver's assertion stack. -/ +def script0 : Script where + decls := [ + ⟨"|this@1|", [], .int⟩, + ⟨"|msg.sender@2|", [], .int⟩, + ⟨"|msg.value@3|", [], .int⟩, + ⟨"|block.timestamp@4|", [], .int⟩, + ⟨"|block.number@5|", [], .int⟩, + ⟨"|block.chainid@6|", [], .int⟩, + ⟨"|tx.origin@7|", [], .int⟩, + ⟨"|tx.gasprice@8|", [], .int⟩, + ⟨"|msg.sig@9|", [], .int⟩, + ⟨"|msg.data@10|", [], .int⟩, + ⟨"|block.basefee@11|", [], .int⟩, + ⟨"|block.blobbasefee@12|", [], .int⟩, + ⟨"|block.coinbase@13|", [], .int⟩, + ⟨"|block.prevrandao@14|", [], .int⟩, + ⟨"|block.difficulty@15|", [], .int⟩, + ⟨"|block.gaslimit@16|", [], .int⟩, + ⟨"|x@17|", [], .int⟩, + ⟨"|n@18|", [], .int⟩, + ⟨"|g@19|", [], .bool⟩, + ⟨"|g@20|", [], .bool⟩, + ⟨"|g@21|", [], .bool⟩, + ⟨"|r@22|", [], .int⟩ + ] + asserts := [ + .app .and [.app .le [.int 0, .fn 0 []], .app .le [.fn 0 [], .int 1461501637330902918203684832716283019655932542975]], + .app .and [.app .le [.int 0, .fn 1 []], .app .le [.fn 1 [], .int 1461501637330902918203684832716283019655932542975]], + .app .not [.app .eq [.fn 1 [], .int 0]], + .app .and [.app .le [.int 0, .fn 2 []], .app .le [.fn 2 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .and [.app .le [.int 0, .fn 3 []], .app .le [.fn 3 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .and [.app .le [.int 0, .fn 4 []], .app .le [.fn 4 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .and [.app .le [.int 0, .fn 5 []], .app .le [.fn 5 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .and [.app .le [.int 0, .fn 6 []], .app .le [.fn 6 [], .int 1461501637330902918203684832716283019655932542975]], + .app .and [.app .le [.int 0, .fn 7 []], .app .le [.fn 7 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .and [.app .le [.int 0, .fn 8 []], .app .le [.fn 8 [], .int 4294967295]], + .app .and [.app .le [.int 0, .fn 10 []], .app .le [.fn 10 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .and [.app .le [.int 0, .fn 11 []], .app .le [.fn 11 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .and [.app .le [.int 0, .fn 12 []], .app .le [.fn 12 [], .int 1461501637330902918203684832716283019655932542975]], + .app .and [.app .le [.int 0, .fn 13 []], .app .le [.fn 13 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .and [.app .le [.int 0, .fn 14 []], .app .le [.fn 14 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .and [.app .le [.int 0, .fn 15 []], .app .le [.fn 15 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .and [.app .le [.int 0, .fn 16 []], .app .le [.fn 16 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .and [.app .le [.int 0, .fn 17 []], .app .le [.fn 17 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .eq [.fn 18 [], .app .and [.bool true, .app .gt [.fn 16 [], .fn 17 []]]], + .app .eq [.fn 19 [], .app .and [.bool true, .app .not [.app .gt [.fn 16 [], .fn 17 []]]]], + .app .eq [.fn 20 [], .app .or [.fn 18 [], .fn 19 []]], + .app .eq [.fn 21 [], .app .ite [.app .gt [.fn 16 [], .fn 17 []], .fn 17 [], .fn 16 []]] + ] + +/-- ArrayMax.clamp#0: a query only a warning reads (sat). -/ +def ob0 : Obligation where + script := script0 + upto := 22 + guard := .fn 20 [] + goal := .bool false + +/-- ArrayMax.clamp#1: postcondition not satisfied: `r <= n` (unsat). -/ +def ob1 : Obligation where + script := script0 + upto := 22 + guard := .fn 20 [] + goal := .app .le [.fn 21 [], .fn 17 []] + +end SolarVerifyVc.ArrayMax.clamp diff --git a/Contracts/ArrayMax/Vc/ArrayMax/max.lean b/Contracts/ArrayMax/Vc/ArrayMax/max.lean new file mode 100644 index 00000000..d903dbab --- /dev/null +++ b/Contracts/ArrayMax/Vc/ArrayMax/max.lean @@ -0,0 +1,210 @@ +-- Generated by solar-verify --emit-lean (format 1); do not edit. +import Verify.Obligation + +set_option maxRecDepth 100000 + +namespace SolarVerifyVc.ArrayMax.max +open SolarVerify.Smt SolarVerify.Vc + +/-- Script 0 of ArrayMax.max: the solver's assertion stack. -/ +def script0 : Script where + decls := [ + ⟨"|this@1|", [], .int⟩, + ⟨"|msg.sender@2|", [], .int⟩, + ⟨"|msg.value@3|", [], .int⟩, + ⟨"|block.timestamp@4|", [], .int⟩, + ⟨"|block.number@5|", [], .int⟩, + ⟨"|block.chainid@6|", [], .int⟩, + ⟨"|tx.origin@7|", [], .int⟩, + ⟨"|tx.gasprice@8|", [], .int⟩, + ⟨"|msg.sig@9|", [], .int⟩, + ⟨"|msg.data@10|", [], .int⟩, + ⟨"|block.basefee@11|", [], .int⟩, + ⟨"|block.blobbasefee@12|", [], .int⟩, + ⟨"|block.coinbase@13|", [], .int⟩, + ⟨"|block.prevrandao@14|", [], .int⟩, + ⟨"|block.difficulty@15|", [], .int⟩, + ⟨"|block.gaslimit@16|", [], .int⟩, + ⟨"|xs@17|", [], (.array .int .int)⟩, + ⟨"|xs.length@18|", [], .int⟩, + ⟨"|g@19|", [], .bool⟩, + ⟨"|g@20|", [], .bool⟩, + ⟨"|m@21|", [], .int⟩, + ⟨"|i@28|", [], .int⟩, + ⟨"|m@29|", [], .int⟩, + ⟨"|g@30|", [], .bool⟩, + ⟨"|g@31|", [], .bool⟩, + ⟨"|g@33|", [], .bool⟩, + ⟨"|g@35|", [], .bool⟩, + ⟨"|g@37|", [], .bool⟩, + ⟨"|g@38|", [], .bool⟩, + ⟨"|g@39|", [], .bool⟩, + ⟨"|g@40|", [], .bool⟩, + ⟨"|g@41|", [], .bool⟩, + ⟨"|g@42|", [], .bool⟩, + ⟨"|m@43|", [], .int⟩, + ⟨"|g@44|", [], .bool⟩, + ⟨"|g@45|", [], .bool⟩, + ⟨"|m@46|", [], .int⟩, + ⟨"|arith@47|", [], .int⟩, + ⟨"|g@48|", [], .bool⟩, + ⟨"|g@52|", [], .bool⟩ + ] + asserts := [ + .app .and [.app .le [.int 0, .fn 0 []], .app .le [.fn 0 [], .int 1461501637330902918203684832716283019655932542975]], + .app .and [.app .le [.int 0, .fn 1 []], .app .le [.fn 1 [], .int 1461501637330902918203684832716283019655932542975]], + .app .not [.app .eq [.fn 1 [], .int 0]], + .app .and [.app .le [.int 0, .fn 2 []], .app .le [.fn 2 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .and [.app .le [.int 0, .fn 3 []], .app .le [.fn 3 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .and [.app .le [.int 0, .fn 4 []], .app .le [.fn 4 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .and [.app .le [.int 0, .fn 5 []], .app .le [.fn 5 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .and [.app .le [.int 0, .fn 6 []], .app .le [.fn 6 [], .int 1461501637330902918203684832716283019655932542975]], + .app .and [.app .le [.int 0, .fn 7 []], .app .le [.fn 7 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .and [.app .le [.int 0, .fn 8 []], .app .le [.fn 8 [], .int 4294967295]], + .app .and [.app .le [.int 0, .fn 10 []], .app .le [.fn 10 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .and [.app .le [.int 0, .fn 11 []], .app .le [.fn 11 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .and [.app .le [.int 0, .fn 12 []], .app .le [.fn 12 [], .int 1461501637330902918203684832716283019655932542975]], + .app .and [.app .le [.int 0, .fn 13 []], .app .le [.fn 13 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .and [.app .le [.int 0, .fn 14 []], .app .le [.fn 14 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .and [.app .le [.int 0, .fn 15 []], .app .le [.fn 15 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .and [.app .le [.int 0, .fn 17 []], .app .le [.fn 17 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .eq [.fn 18 [], .app .and [.bool true, .app .gt [.fn 17 [], .int 0]]], + .app .eq [.fn 19 [], .app .and [.fn 18 [], .app .and [.app .le [.int 0, .int 0], .app .lt [.int 0, .fn 17 []]]]], + .app .and [.app .le [.int 0, .app .select [.fn 16 [], .int 0]], .app .le [.app .select [.fn 16 [], .int 0], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .eq [.fn 20 [], .app .select [.fn 16 [], .int 0]], + .app .and [.app .le [.int 0, .fn 21 []], .app .le [.fn 21 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .and [.app .le [.int 0, .fn 22 []], .app .le [.fn 22 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .eq [.fn 23 [], .app .and [.fn 19 [], .app .le [.int 1, .fn 21 []]]], + .app .eq [.fn 24 [], .app .and [.fn 23 [], .app .le [.fn 21 [], .fn 17 []]]], + .app .eq [.fn 25 [], .app .and [.fn 24 [], .«forall» [.int] (.app .implies [.app .and [.app .and [.app .le [.int 0, .var 0], .app .le [.var 0, .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]]], .app .implies [.app .lt [.var 0, .fn 21 []], .app .le [.app .select [.fn 16 [], .var 0], .fn 22 []]]])]], + .app .eq [.fn 26 [], .app .and [.fn 25 [], .«exists» [.int] (.app .and [.app .and [.app .and [.app .le [.int 0, .var 0], .app .le [.var 0, .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]]], .app .and [.app .lt [.var 0, .fn 21 []], .app .eq [.app .select [.fn 16 [], .var 0], .fn 22 []]]])]], + .app .eq [.fn 27 [], .app .and [.fn 26 [], .«exists» [.int] (.app .and [.app .and [.app .and [.app .le [.int 0, .var 0], .app .le [.var 0, .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]]], .app .and [.app .lt [.var 0, .fn 17 []], .app .eq [.app .select [.fn 16 [], .var 0], .fn 22 []]]])]], + .app .eq [.fn 28 [], .app .and [.fn 27 [], .app .gt [.fn 17 [], .int 0]]], + .app .eq [.fn 29 [], .app .and [.fn 28 [], .app .lt [.fn 21 [], .fn 17 []]]], + .app .eq [.fn 30 [], .app .and [.fn 29 [], .app .and [.app .le [.int 0, .fn 21 []], .app .lt [.fn 21 [], .fn 17 []]]]], + .app .and [.app .le [.int 0, .app .select [.fn 16 [], .fn 21 []]], .app .le [.app .select [.fn 16 [], .fn 21 []], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .eq [.fn 31 [], .app .and [.fn 30 [], .app .gt [.app .select [.fn 16 [], .fn 21 []], .fn 22 []]]], + .app .eq [.fn 32 [], .app .and [.fn 31 [], .app .and [.app .le [.int 0, .fn 21 []], .app .lt [.fn 21 [], .fn 17 []]]]], + .app .and [.app .le [.int 0, .app .select [.fn 16 [], .fn 21 []]], .app .le [.app .select [.fn 16 [], .fn 21 []], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .eq [.fn 33 [], .app .select [.fn 16 [], .fn 21 []]], + .app .eq [.fn 34 [], .app .and [.fn 30 [], .app .not [.app .gt [.app .select [.fn 16 [], .fn 21 []], .fn 22 []]]]], + .app .eq [.fn 35 [], .app .or [.fn 32 [], .fn 34 []]], + .app .eq [.fn 36 [], .app .ite [.fn 32 [], .fn 33 [], .fn 22 []]], + .app .eq [.fn 37 [], .app .add [.fn 21 [], .int 1]], + .app .eq [.fn 38 [], .app .and [.fn 35 [], .app .and [.app .le [.int 0, .fn 37 []], .app .le [.fn 37 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]]]], + .app .eq [.fn 39 [], .app .and [.fn 28 [], .app .not [.app .lt [.fn 21 [], .fn 17 []]]]] + ] + +/-- ArrayMax.max#0: loop invariant not satisfied on entry: `1 <= i` (unsat). -/ +def ob0 : Obligation where + script := script0 + upto := 21 + guard := .fn 19 [] + goal := .app .le [.int 1, .int 1] + +/-- ArrayMax.max#1: loop invariant not satisfied on entry: `i <= xs.length` (unsat). -/ +def ob1 : Obligation where + script := script0 + upto := 21 + guard := .fn 19 [] + goal := .app .le [.int 1, .fn 17 []] + +/-- ArrayMax.max#2: loop invariant not satisfied on entry: `forall uint256 j :: j < i ==> xs[j] <= m` (unsat). -/ +def ob2 : Obligation where + script := script0 + upto := 21 + guard := .fn 19 [] + goal := .«forall» [.int] (.app .implies [.app .and [.app .and [.app .le [.int 0, .var 0], .app .le [.var 0, .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]]], .app .implies [.app .lt [.var 0, .int 1], .app .le [.app .select [.fn 16 [], .var 0], .fn 20 []]]]) + +/-- ArrayMax.max#3: loop invariant not satisfied on entry: `exists uint256 j :: j < i && xs[j] == m` (unsat). -/ +def ob3 : Obligation where + script := script0 + upto := 21 + guard := .fn 19 [] + goal := .«exists» [.int] (.app .and [.app .and [.app .and [.app .le [.int 0, .var 0], .app .le [.var 0, .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]]], .app .and [.app .lt [.var 0, .int 1], .app .eq [.app .select [.fn 16 [], .var 0], .fn 20 []]]]) + +/-- ArrayMax.max#4: loop invariant not satisfied on entry: `exists uint256 j :: j < xs.length && xs[j] == m` (unsat). -/ +def ob4 : Obligation where + script := script0 + upto := 21 + guard := .fn 19 [] + goal := .«exists» [.int] (.app .and [.app .and [.app .and [.app .le [.int 0, .var 0], .app .le [.var 0, .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]]], .app .and [.app .lt [.var 0, .fn 17 []], .app .eq [.app .select [.fn 16 [], .var 0], .fn 20 []]]]) + +/-- ArrayMax.max#5: loop invariant not satisfied on entry: `xs.length > 0` (unsat). -/ +def ob5 : Obligation where + script := script0 + upto := 21 + guard := .fn 19 [] + goal := .app .gt [.fn 17 [], .int 0] + +/-- ArrayMax.max#6: loop invariant not preserved by the loop body: `1 <= i` (unsat). -/ +def ob6 : Obligation where + script := script0 + upto := 41 + guard := .fn 38 [] + goal := .app .le [.int 1, .fn 37 []] + +/-- ArrayMax.max#7: loop invariant not preserved by the loop body: `i <= xs.length` (unsat). -/ +def ob7 : Obligation where + script := script0 + upto := 41 + guard := .fn 38 [] + goal := .app .le [.fn 37 [], .fn 17 []] + +/-- ArrayMax.max#8: loop invariant not preserved by the loop body: `forall uint256 j :: j < i ==> xs[j] <= m` (unsat). -/ +def ob8 : Obligation where + script := script0 + upto := 41 + guard := .fn 38 [] + goal := .«forall» [.int] (.app .implies [.app .and [.app .and [.app .le [.int 0, .var 0], .app .le [.var 0, .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]]], .app .implies [.app .lt [.var 0, .fn 37 []], .app .le [.app .select [.fn 16 [], .var 0], .fn 36 []]]]) + +/-- ArrayMax.max#9: loop invariant not preserved by the loop body: `exists uint256 j :: j < i && xs[j] == m` (unsat). -/ +def ob9 : Obligation where + script := script0 + upto := 41 + guard := .fn 38 [] + goal := .«exists» [.int] (.app .and [.app .and [.app .and [.app .le [.int 0, .var 0], .app .le [.var 0, .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]]], .app .and [.app .lt [.var 0, .fn 37 []], .app .eq [.app .select [.fn 16 [], .var 0], .fn 36 []]]]) + +/-- ArrayMax.max#10: loop invariant not preserved by the loop body: `exists uint256 j :: j < xs.length && xs[j] == m` (unsat). -/ +def ob10 : Obligation where + script := script0 + upto := 41 + guard := .fn 38 [] + goal := .«exists» [.int] (.app .and [.app .and [.app .and [.app .le [.int 0, .var 0], .app .le [.var 0, .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]]], .app .and [.app .lt [.var 0, .fn 17 []], .app .eq [.app .select [.fn 16 [], .var 0], .fn 36 []]]]) + +/-- ArrayMax.max#11: loop invariant not preserved by the loop body: `xs.length > 0` (unsat). -/ +def ob11 : Obligation where + script := script0 + upto := 41 + guard := .fn 38 [] + goal := .app .gt [.fn 17 [], .int 0] + +/-- ArrayMax.max#12: loop does not terminate: decreases clause not decreased: `(xs.length) - i` (unsat). -/ +def ob12 : Obligation where + script := script0 + upto := 41 + guard := .fn 38 [] + goal := .app .and [.app .le [.int 0, .app .sub [.fn 17 [], .fn 21 []]], .app .lt [.app .sub [.fn 17 [], .fn 37 []], .app .sub [.fn 17 [], .fn 21 []]]] + +/-- ArrayMax.max#13: a query only a warning reads (sat). -/ +def ob13 : Obligation where + script := script0 + upto := 42 + guard := .fn 39 [] + goal := .bool false + +/-- ArrayMax.max#14: postcondition not satisfied: `forall uint256 j :: j < xs.length ==> xs[j] <= m` (unsat). -/ +def ob14 : Obligation where + script := script0 + upto := 42 + guard := .fn 39 [] + goal := .«forall» [.int] (.app .implies [.app .and [.app .and [.app .le [.int 0, .var 0], .app .le [.var 0, .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]]], .app .implies [.app .lt [.var 0, .fn 17 []], .app .le [.app .select [.fn 16 [], .var 0], .fn 22 []]]]) + +/-- ArrayMax.max#15: postcondition not satisfied: `exists uint256 j :: j < xs.length && xs[j] == m` (unsat). -/ +def ob15 : Obligation where + script := script0 + upto := 42 + guard := .fn 39 [] + goal := .«exists» [.int] (.app .and [.app .and [.app .and [.app .le [.int 0, .var 0], .app .le [.var 0, .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]]], .app .and [.app .lt [.var 0, .fn 17 []], .app .eq [.app .select [.fn 16 [], .var 0], .fn 22 []]]]) + +end SolarVerifyVc.ArrayMax.max diff --git a/Contracts/ArrayMax/Vc/ArrayMaxEntry/constructor.lean b/Contracts/ArrayMax/Vc/ArrayMaxEntry/constructor.lean new file mode 100644 index 00000000..501038db --- /dev/null +++ b/Contracts/ArrayMax/Vc/ArrayMaxEntry/constructor.lean @@ -0,0 +1,60 @@ +-- Generated by solar-verify --emit-lean (format 1); do not edit. +import Verify.Obligation + +set_option maxRecDepth 100000 + +namespace SolarVerifyVc.ArrayMaxEntry.constructor +open SolarVerify.Smt SolarVerify.Vc + +/-- Script 0 of ArrayMaxEntry.constructor: the solver's assertion stack. -/ +def script0 : Script where + decls := [ + ⟨"|this@1|", [], .int⟩, + ⟨"|msg.sender@2|", [], .int⟩, + ⟨"|msg.value@3|", [], .int⟩, + ⟨"|block.timestamp@4|", [], .int⟩, + ⟨"|block.number@5|", [], .int⟩, + ⟨"|block.chainid@6|", [], .int⟩, + ⟨"|tx.origin@7|", [], .int⟩, + ⟨"|tx.gasprice@8|", [], .int⟩, + ⟨"|msg.sig@9|", [], .int⟩, + ⟨"|msg.data@10|", [], .int⟩, + ⟨"|block.basefee@11|", [], .int⟩, + ⟨"|block.blobbasefee@12|", [], .int⟩, + ⟨"|block.coinbase@13|", [], .int⟩, + ⟨"|block.prevrandao@14|", [], .int⟩, + ⟨"|block.difficulty@15|", [], .int⟩, + ⟨"|block.gaslimit@16|", [], .int⟩, + ⟨"|__balance@17|", [], (.array .int .int)⟩, + ⟨"|__code_epoch@18|", [], .int⟩, + ⟨"|g@19|", [], .bool⟩ + ] + asserts := [ + .app .and [.app .le [.int 0, .fn 0 []], .app .le [.fn 0 [], .int 1461501637330902918203684832716283019655932542975]], + .app .and [.app .le [.int 0, .fn 1 []], .app .le [.fn 1 [], .int 1461501637330902918203684832716283019655932542975]], + .app .not [.app .eq [.fn 1 [], .int 0]], + .app .and [.app .le [.int 0, .fn 2 []], .app .le [.fn 2 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .and [.app .le [.int 0, .fn 3 []], .app .le [.fn 3 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .and [.app .le [.int 0, .fn 4 []], .app .le [.fn 4 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .and [.app .le [.int 0, .fn 5 []], .app .le [.fn 5 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .and [.app .le [.int 0, .fn 6 []], .app .le [.fn 6 [], .int 1461501637330902918203684832716283019655932542975]], + .app .and [.app .le [.int 0, .fn 7 []], .app .le [.fn 7 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .and [.app .le [.int 0, .fn 8 []], .app .le [.fn 8 [], .int 4294967295]], + .app .and [.app .le [.int 0, .fn 10 []], .app .le [.fn 10 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .and [.app .le [.int 0, .fn 11 []], .app .le [.fn 11 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .and [.app .le [.int 0, .fn 12 []], .app .le [.fn 12 [], .int 1461501637330902918203684832716283019655932542975]], + .app .and [.app .le [.int 0, .fn 13 []], .app .le [.fn 13 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .and [.app .le [.int 0, .fn 14 []], .app .le [.fn 14 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .and [.app .le [.int 0, .fn 15 []], .app .le [.fn 15 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .and [.app .le [.int 0, .fn 17 []], .app .le [.fn 17 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .eq [.fn 18 [], .app .and [.bool true, .app .eq [.fn 2 [], .int 0]]] + ] + +/-- ArrayMaxEntry.constructor#0: a query only a warning reads (sat). -/ +def ob0 : Obligation where + script := script0 + upto := 18 + guard := .fn 18 [] + goal := .bool false + +end SolarVerifyVc.ArrayMaxEntry.constructor diff --git a/Contracts/ArrayMax/Vc/ArrayMaxEntry/max.lean b/Contracts/ArrayMax/Vc/ArrayMaxEntry/max.lean new file mode 100644 index 00000000..9ab295ed --- /dev/null +++ b/Contracts/ArrayMax/Vc/ArrayMaxEntry/max.lean @@ -0,0 +1,92 @@ +-- Generated by solar-verify --emit-lean (format 1); do not edit. +import Verify.Obligation + +set_option maxRecDepth 100000 + +namespace SolarVerifyVc.ArrayMaxEntry.max +open SolarVerify.Smt SolarVerify.Vc + +/-- Script 0 of ArrayMaxEntry.max: the solver's assertion stack. -/ +def script0 : Script where + decls := [ + ⟨"|this@1|", [], .int⟩, + ⟨"|msg.sender@2|", [], .int⟩, + ⟨"|msg.value@3|", [], .int⟩, + ⟨"|block.timestamp@4|", [], .int⟩, + ⟨"|block.number@5|", [], .int⟩, + ⟨"|block.chainid@6|", [], .int⟩, + ⟨"|tx.origin@7|", [], .int⟩, + ⟨"|tx.gasprice@8|", [], .int⟩, + ⟨"|msg.sig@9|", [], .int⟩, + ⟨"|msg.data@10|", [], .int⟩, + ⟨"|block.basefee@11|", [], .int⟩, + ⟨"|block.blobbasefee@12|", [], .int⟩, + ⟨"|block.coinbase@13|", [], .int⟩, + ⟨"|block.prevrandao@14|", [], .int⟩, + ⟨"|block.difficulty@15|", [], .int⟩, + ⟨"|block.gaslimit@16|", [], .int⟩, + ⟨"|__balance@17|", [], (.array .int .int)⟩, + ⟨"|__code_epoch@18|", [], .int⟩, + ⟨"|xs@19|", [], (.array .int .int)⟩, + ⟨"|xs.length@20|", [], .int⟩, + ⟨"|g@21|", [], .bool⟩, + ⟨"|g@22|", [], .bool⟩, + ⟨"|m@23|", [], .int⟩, + ⟨"|g@25|", [], .bool⟩, + ⟨"|g@27|", [], .bool⟩ + ] + asserts := [ + .app .and [.app .le [.int 0, .fn 0 []], .app .le [.fn 0 [], .int 1461501637330902918203684832716283019655932542975]], + .app .and [.app .le [.int 0, .fn 1 []], .app .le [.fn 1 [], .int 1461501637330902918203684832716283019655932542975]], + .app .not [.app .eq [.fn 1 [], .int 0]], + .app .and [.app .le [.int 0, .fn 2 []], .app .le [.fn 2 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .and [.app .le [.int 0, .fn 3 []], .app .le [.fn 3 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .and [.app .le [.int 0, .fn 4 []], .app .le [.fn 4 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .and [.app .le [.int 0, .fn 5 []], .app .le [.fn 5 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .and [.app .le [.int 0, .fn 6 []], .app .le [.fn 6 [], .int 1461501637330902918203684832716283019655932542975]], + .app .and [.app .le [.int 0, .fn 7 []], .app .le [.fn 7 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .and [.app .le [.int 0, .fn 8 []], .app .le [.fn 8 [], .int 4294967295]], + .app .and [.app .le [.int 0, .fn 10 []], .app .le [.fn 10 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .and [.app .le [.int 0, .fn 11 []], .app .le [.fn 11 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .and [.app .le [.int 0, .fn 12 []], .app .le [.fn 12 [], .int 1461501637330902918203684832716283019655932542975]], + .app .and [.app .le [.int 0, .fn 13 []], .app .le [.fn 13 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .and [.app .le [.int 0, .fn 14 []], .app .le [.fn 14 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .and [.app .le [.int 0, .fn 15 []], .app .le [.fn 15 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .and [.app .le [.int 0, .fn 17 []], .app .le [.fn 17 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .and [.app .le [.int 0, .fn 19 []], .app .le [.fn 19 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .eq [.fn 20 [], .app .and [.bool true, .app .eq [.fn 2 [], .int 0]]], + .app .eq [.fn 21 [], .app .and [.fn 20 [], .app .gt [.fn 19 [], .int 0]]], + .app .and [.app .le [.int 0, .fn 22 []], .app .le [.fn 22 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .eq [.fn 23 [], .app .and [.fn 21 [], .«forall» [.int] (.app .implies [.app .and [.app .and [.app .le [.int 0, .var 0], .app .le [.var 0, .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]]], .app .implies [.app .lt [.var 0, .fn 19 []], .app .le [.app .select [.fn 18 [], .var 0], .fn 22 []]]])]], + .app .eq [.fn 24 [], .app .and [.fn 23 [], .«exists» [.int] (.app .and [.app .and [.app .and [.app .le [.int 0, .var 0], .app .le [.var 0, .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]]], .app .and [.app .lt [.var 0, .fn 19 []], .app .eq [.app .select [.fn 18 [], .var 0], .fn 22 []]]])]] + ] + +/-- ArrayMaxEntry.max#0: precondition of `max` not satisfied: `xs.length > 0` (unsat). -/ +def ob0 : Obligation where + script := script0 + upto := 20 + guard := .fn 21 [] + goal := .app .gt [.fn 19 [], .int 0] + +/-- ArrayMaxEntry.max#1: a query only a warning reads (sat). -/ +def ob1 : Obligation where + script := script0 + upto := 23 + guard := .fn 24 [] + goal := .bool false + +/-- ArrayMaxEntry.max#2: postcondition not satisfied: `forall uint256 j :: j < xs.length ==> xs[j] <= result` (unsat). -/ +def ob2 : Obligation where + script := script0 + upto := 23 + guard := .fn 24 [] + goal := .«forall» [.int] (.app .implies [.app .and [.app .and [.app .le [.int 0, .var 0], .app .le [.var 0, .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]]], .app .implies [.app .lt [.var 0, .fn 19 []], .app .le [.app .select [.fn 18 [], .var 0], .fn 22 []]]]) + +/-- ArrayMaxEntry.max#3: postcondition not satisfied: `exists uint256 j :: j < xs.length && xs[j] == result` (unsat). -/ +def ob3 : Obligation where + script := script0 + upto := 23 + guard := .fn 24 [] + goal := .«exists» [.int] (.app .and [.app .and [.app .and [.app .le [.int 0, .var 0], .app .le [.var 0, .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]]], .app .and [.app .lt [.var 0, .fn 19 []], .app .eq [.app .select [.fn 18 [], .var 0], .fn 22 []]]]) + +end SolarVerifyVc.ArrayMaxEntry.max diff --git a/Contracts/ArrayMax/Vc/frozen.sha256 b/Contracts/ArrayMax/Vc/frozen.sha256 new file mode 100644 index 00000000..62894797 --- /dev/null +++ b/Contracts/ArrayMax/Vc/frozen.sha256 @@ -0,0 +1,5 @@ +fd6ba812db32525b609d720b646fa1db1c6f847553ffe5689aa569c0a0213241 manifest.json +1a02fe322248251cb404d8f56ad9110bbf4ead96cf56ad1117976351eeca0f5a ArrayMax/clamp.lean +a39b2942dcd59cf63faa1ced3aa86bb2834f362bfa894d7be9878f0ba66a44c6 ArrayMax/max.lean +fdda1a5f2c6049ddb1b7136571217dc2d743845728edbd4bbc4cfe2256ef5bd9 ArrayMaxEntry/constructor.lean +9bd919a6e290d34c0723dd1529e9bd64004112cd5c1ba5c91d13425f080329ed ArrayMaxEntry/max.lean diff --git a/Contracts/ArrayMax/Vc/manifest.json b/Contracts/ArrayMax/Vc/manifest.json new file mode 100644 index 00000000..03459c9e --- /dev/null +++ b/Contracts/ArrayMax/Vc/manifest.json @@ -0,0 +1,760 @@ +{ + "arguments": [ + "--emit-lean", + "vc-exports/ArrayMax", + "crates/verify/examples/ArrayMax.sol" + ], + "compiler": "0.8.38+commit.7f4e94e0.solar.0.3.0-dev", + "errors": [], + "format": "solar-verify-lean", + "lean": { + "library": "SolarVerify", + "smt_sha256": "2c92f3bcd927369da89250662bd5a6174d3c06d0c3c38f5021509fe8810036e3", + "toolchain": "leanprover/lean4:v4.35.0", + "vc_sha256": "7275fa354f077a4826dd9fe56124cbffee2337d7a21975b477534fc5f45d7cfe" + }, + "options": { + "dry_run": false, + "only": null, + "strict": false, + "timeout_ms": 10000 + }, + "solvers": { + "bitwuzla": null, + "cvc5": "This is cvc5 version 1.3.1 [git ea1b484 on branch HEAD]", + "z3": "Z3 version 4.13.4 - 64 bit" + }, + "sources": [ + { + "path": "/home/hand/wt-inferred/crates/verify/examples/ArrayMax.sol", + "sha256": "904535ac694498a9823f530ca158ee0c762fd1adcc56f3e7b73ca0e457e61f4a" + } + ], + "units": [ + { + "module": "ArrayMax/max.lean", + "name": "ArrayMax.max", + "namespace": "SolarVerifyVc.ArrayMax.max", + "obligations": [ + { + "answer": "unsat", + "asserts": 21, + "commands": 42, + "goal": "(<= 1 1)", + "guard": "|g@20|", + "id": "ArrayMax.max#0", + "kind": "loop invariant not satisfied on entry", + "lean": "SolarVerifyVc.ArrayMax.max.ob0", + "required": true, + "role": "obligation", + "script": 0, + "site": { + "column": 9, + "file": "crates/verify/examples/ArrayMax.sol", + "line": 10 + }, + "smt_sha256": "5295b5100b304c78178c05e0648edf7b8c5c65328262f7ee8a78c53d8182ee89", + "solver": "z3", + "spec": { + "column": 9, + "file": "crates/verify/examples/ArrayMax.sol", + "line": 10, + "text": "1 <= i" + } + }, + { + "answer": "unsat", + "asserts": 21, + "commands": 42, + "goal": "(<= 1 |xs.length@18|)", + "guard": "|g@20|", + "id": "ArrayMax.max#1", + "kind": "loop invariant not satisfied on entry", + "lean": "SolarVerifyVc.ArrayMax.max.ob1", + "required": true, + "role": "obligation", + "script": 0, + "site": { + "column": 9, + "file": "crates/verify/examples/ArrayMax.sol", + "line": 10 + }, + "smt_sha256": "347c5f72952324b53f4727ba7bf3fb662d77ca67db931b9655ec59d710bb22c4", + "solver": "z3", + "spec": { + "column": 9, + "file": "crates/verify/examples/ArrayMax.sol", + "line": 10, + "text": "i <= xs.length" + } + }, + { + "answer": "unsat", + "asserts": 21, + "commands": 42, + "goal": "(forall ((|j!25| Int)) (=> (and (and (<= 0 |j!25|) (<= |j!25| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) (=> (< |j!25| 1) (<= (select |xs@17| |j!25|) |m@21|))))", + "guard": "|g@20|", + "id": "ArrayMax.max#2", + "kind": "loop invariant not satisfied on entry", + "lean": "SolarVerifyVc.ArrayMax.max.ob2", + "required": true, + "role": "obligation", + "script": 0, + "site": { + "column": 9, + "file": "crates/verify/examples/ArrayMax.sol", + "line": 10 + }, + "smt_sha256": "f980a79aecb59738706917debadad336afdd06f91c4b5507757b75995f9fd2b9", + "solver": "z3", + "spec": { + "column": 9, + "file": "crates/verify/examples/ArrayMax.sol", + "line": 10, + "text": "forall uint256 j :: j < i ==> xs[j] <= m" + } + }, + { + "answer": "unsat", + "asserts": 21, + "commands": 42, + "goal": "(exists ((|j!26| Int)) (and (and (and (<= 0 |j!26|) (<= |j!26| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) (and (< |j!26| 1) (= (select |xs@17| |j!26|) |m@21|))))", + "guard": "|g@20|", + "id": "ArrayMax.max#3", + "kind": "loop invariant not satisfied on entry", + "lean": "SolarVerifyVc.ArrayMax.max.ob3", + "required": true, + "role": "obligation", + "script": 0, + "site": { + "column": 9, + "file": "crates/verify/examples/ArrayMax.sol", + "line": 10 + }, + "smt_sha256": "5dbc71e2ea2e9f356ecb6b576ba70861bf6170313124b302aec223cc7503b697", + "solver": "z3", + "spec": { + "column": 9, + "file": "crates/verify/examples/ArrayMax.sol", + "line": 10, + "text": "exists uint256 j :: j < i && xs[j] == m" + } + }, + { + "answer": "unsat", + "asserts": 21, + "commands": 42, + "goal": "(exists ((|j!27| Int)) (and (and (and (<= 0 |j!27|) (<= |j!27| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) (and (< |j!27| |xs.length@18|) (= (select |xs@17| |j!27|) |m@21|))))", + "guard": "|g@20|", + "id": "ArrayMax.max#4", + "kind": "loop invariant not satisfied on entry", + "lean": "SolarVerifyVc.ArrayMax.max.ob4", + "required": true, + "role": "obligation", + "script": 0, + "site": { + "column": 9, + "file": "crates/verify/examples/ArrayMax.sol", + "line": 10 + }, + "smt_sha256": "55ecfb69494a22d6e58ad91840bcbb0897fdf19bb2ad70583faf832f8056b227", + "solver": "z3", + "spec": { + "column": 9, + "file": "crates/verify/examples/ArrayMax.sol", + "line": 10, + "text": "exists uint256 j :: j < xs.length && xs[j] == m" + } + }, + { + "answer": "unsat", + "asserts": 21, + "commands": 42, + "goal": "(> |xs.length@18| 0)", + "guard": "|g@20|", + "id": "ArrayMax.max#5", + "kind": "loop invariant not satisfied on entry", + "lean": "SolarVerifyVc.ArrayMax.max.ob5", + "required": true, + "role": "obligation", + "script": 0, + "site": { + "column": 9, + "file": "crates/verify/examples/ArrayMax.sol", + "line": 10 + }, + "smt_sha256": "4dfac29473863b79f8e4b029a64e650a5062964c2a069706eaa080479282ff0e", + "solver": "z3", + "spec": { + "column": 9, + "file": "crates/verify/examples/ArrayMax.sol", + "line": 10, + "text": "xs.length > 0" + } + }, + { + "answer": "unsat", + "asserts": 41, + "commands": 80, + "goal": "(<= 1 |arith@47|)", + "guard": "|g@48|", + "id": "ArrayMax.max#6", + "kind": "loop invariant not preserved by the loop body", + "lean": "SolarVerifyVc.ArrayMax.max.ob6", + "required": true, + "role": "obligation", + "script": 0, + "site": { + "column": 9, + "file": "crates/verify/examples/ArrayMax.sol", + "line": 10 + }, + "smt_sha256": "b515578b67f66dd4eaa1bc5a770b54e58b64ce5a77460f54f931a02729f6ab19", + "solver": "z3", + "spec": { + "column": 9, + "file": "crates/verify/examples/ArrayMax.sol", + "line": 10, + "text": "1 <= i" + } + }, + { + "answer": "unsat", + "asserts": 41, + "commands": 80, + "goal": "(<= |arith@47| |xs.length@18|)", + "guard": "|g@48|", + "id": "ArrayMax.max#7", + "kind": "loop invariant not preserved by the loop body", + "lean": "SolarVerifyVc.ArrayMax.max.ob7", + "required": true, + "role": "obligation", + "script": 0, + "site": { + "column": 9, + "file": "crates/verify/examples/ArrayMax.sol", + "line": 10 + }, + "smt_sha256": "bf57c3c10ee62b1215acc86c6d35917fafe7b6d43f4e08e00d0e103e9d2af6ca", + "solver": "z3", + "spec": { + "column": 9, + "file": "crates/verify/examples/ArrayMax.sol", + "line": 10, + "text": "i <= xs.length" + } + }, + { + "answer": "unsat", + "asserts": 41, + "commands": 80, + "goal": "(forall ((|j!49| Int)) (=> (and (and (<= 0 |j!49|) (<= |j!49| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) (=> (< |j!49| |arith@47|) (<= (select |xs@17| |j!49|) |m@46|))))", + "guard": "|g@48|", + "id": "ArrayMax.max#8", + "kind": "loop invariant not preserved by the loop body", + "lean": "SolarVerifyVc.ArrayMax.max.ob8", + "required": true, + "role": "obligation", + "script": 0, + "site": { + "column": 9, + "file": "crates/verify/examples/ArrayMax.sol", + "line": 10 + }, + "smt_sha256": "f25bff351a6ea08f2bcc9d638abb5bf7189a4968ac5e2a62576f42f2639ffd05", + "solver": "z3", + "spec": { + "column": 9, + "file": "crates/verify/examples/ArrayMax.sol", + "line": 10, + "text": "forall uint256 j :: j < i ==> xs[j] <= m" + } + }, + { + "answer": "unsat", + "asserts": 41, + "commands": 80, + "goal": "(exists ((|j!50| Int)) (and (and (and (<= 0 |j!50|) (<= |j!50| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) (and (< |j!50| |arith@47|) (= (select |xs@17| |j!50|) |m@46|))))", + "guard": "|g@48|", + "id": "ArrayMax.max#9", + "kind": "loop invariant not preserved by the loop body", + "lean": "SolarVerifyVc.ArrayMax.max.ob9", + "required": true, + "role": "obligation", + "script": 0, + "site": { + "column": 9, + "file": "crates/verify/examples/ArrayMax.sol", + "line": 10 + }, + "smt_sha256": "b0fa429989bc9d610ac25c80224ea993b198f49fa116f7ddefde114a96eb7a01", + "solver": "z3", + "spec": { + "column": 9, + "file": "crates/verify/examples/ArrayMax.sol", + "line": 10, + "text": "exists uint256 j :: j < i && xs[j] == m" + } + }, + { + "answer": "unsat", + "asserts": 41, + "commands": 80, + "goal": "(exists ((|j!51| Int)) (and (and (and (<= 0 |j!51|) (<= |j!51| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) (and (< |j!51| |xs.length@18|) (= (select |xs@17| |j!51|) |m@46|))))", + "guard": "|g@48|", + "id": "ArrayMax.max#10", + "kind": "loop invariant not preserved by the loop body", + "lean": "SolarVerifyVc.ArrayMax.max.ob10", + "required": true, + "role": "obligation", + "script": 0, + "site": { + "column": 9, + "file": "crates/verify/examples/ArrayMax.sol", + "line": 10 + }, + "smt_sha256": "dba88be31a4526edfb6ef423e6b08ecef7db4ca61f4b6abfcfc62407e049d851", + "solver": "z3", + "spec": { + "column": 9, + "file": "crates/verify/examples/ArrayMax.sol", + "line": 10, + "text": "exists uint256 j :: j < xs.length && xs[j] == m" + } + }, + { + "answer": "unsat", + "asserts": 41, + "commands": 80, + "goal": "(> |xs.length@18| 0)", + "guard": "|g@48|", + "id": "ArrayMax.max#11", + "kind": "loop invariant not preserved by the loop body", + "lean": "SolarVerifyVc.ArrayMax.max.ob11", + "required": true, + "role": "obligation", + "script": 0, + "site": { + "column": 9, + "file": "crates/verify/examples/ArrayMax.sol", + "line": 10 + }, + "smt_sha256": "934a80355bad5cc493fce7387db616006574e4727549114faa462f45b85f57c4", + "solver": "z3", + "spec": { + "column": 9, + "file": "crates/verify/examples/ArrayMax.sol", + "line": 10, + "text": "xs.length > 0" + } + }, + { + "answer": "unsat", + "asserts": 41, + "commands": 80, + "goal": "(and (<= 0 (- |xs.length@18| |i@28|)) (< (- |xs.length@18| |arith@47|) (- |xs.length@18| |i@28|)))", + "guard": "|g@48|", + "id": "ArrayMax.max#12", + "kind": "loop does not terminate: decreases clause not decreased", + "lean": "SolarVerifyVc.ArrayMax.max.ob12", + "required": true, + "role": "obligation", + "script": 0, + "site": { + "column": 9, + "file": "crates/verify/examples/ArrayMax.sol", + "line": 10 + }, + "smt_sha256": "ab98ca88f80753c5ac3991a7b6b4189cc5fe5b02ee4d7203111d9ec183c0ded7", + "solver": "z3", + "spec": { + "column": 9, + "file": "crates/verify/examples/ArrayMax.sol", + "line": 10, + "text": "(xs.length) - i" + } + }, + { + "answer": "sat", + "asserts": 42, + "commands": 82, + "goal": "false", + "guard": "|g@52|", + "id": "ArrayMax.max#13", + "lean": "SolarVerifyVc.ArrayMax.max.ob13", + "required": false, + "role": "advisory", + "script": 0, + "smt_sha256": "f92d705bb601763d2dfb970f85c5c278b5c349e4bbe00aa2d4fa9b125314817d", + "solver": "z3" + }, + { + "answer": "unsat", + "asserts": 42, + "commands": 82, + "goal": "(forall ((|j!53| Int)) (=> (and (and (<= 0 |j!53|) (<= |j!53| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) (=> (< |j!53| |xs.length@18|) (<= (select |xs@17| |j!53|) |m@29|))))", + "guard": "|g@52|", + "id": "ArrayMax.max#14", + "kind": "postcondition not satisfied", + "lean": "SolarVerifyVc.ArrayMax.max.ob14", + "required": true, + "role": "obligation", + "script": 0, + "site": { + "column": 10, + "file": "crates/verify/examples/ArrayMax.sol", + "line": 6 + }, + "smt_sha256": "9eb45f23e4334f8efc8813e249422b90ce287a408a64ac239401e574fc219fd8", + "solver": "z3", + "spec": { + "column": 10, + "file": "crates/verify/examples/ArrayMax.sol", + "line": 6, + "text": "forall uint256 j :: j < xs.length ==> xs[j] <= m" + } + }, + { + "answer": "unsat", + "asserts": 42, + "commands": 82, + "goal": "(exists ((|j!54| Int)) (and (and (and (<= 0 |j!54|) (<= |j!54| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) (and (< |j!54| |xs.length@18|) (= (select |xs@17| |j!54|) |m@29|))))", + "guard": "|g@52|", + "id": "ArrayMax.max#15", + "kind": "postcondition not satisfied", + "lean": "SolarVerifyVc.ArrayMax.max.ob15", + "required": true, + "role": "obligation", + "script": 0, + "site": { + "column": 10, + "file": "crates/verify/examples/ArrayMax.sol", + "line": 7 + }, + "smt_sha256": "e0e3e9b245cc79d0a181a12470b923c5f05bfbe4af657301137ae1344b42b2d4", + "solver": "z3", + "spec": { + "column": 10, + "file": "crates/verify/examples/ArrayMax.sol", + "line": 7, + "text": "exists uint256 j :: j < xs.length && xs[j] == m" + } + } + ], + "scripts": [ + { + "commands": 82, + "decls": [ + "|this@1|", + "|msg.sender@2|", + "|msg.value@3|", + "|block.timestamp@4|", + "|block.number@5|", + "|block.chainid@6|", + "|tx.origin@7|", + "|tx.gasprice@8|", + "|msg.sig@9|", + "|msg.data@10|", + "|block.basefee@11|", + "|block.blobbasefee@12|", + "|block.coinbase@13|", + "|block.prevrandao@14|", + "|block.difficulty@15|", + "|block.gaslimit@16|", + "|xs@17|", + "|xs.length@18|", + "|g@19|", + "|g@20|", + "|m@21|", + "|i@28|", + "|m@29|", + "|g@30|", + "|g@31|", + "|g@33|", + "|g@35|", + "|g@37|", + "|g@38|", + "|g@39|", + "|g@40|", + "|g@41|", + "|g@42|", + "|m@43|", + "|g@44|", + "|g@45|", + "|m@46|", + "|arith@47|", + "|g@48|", + "|g@52|" + ], + "lean": "SolarVerifyVc.ArrayMax.max.script0", + "smt": "ArrayMax/max.script0.smt2" + } + ], + "status": "verified" + }, + { + "module": "ArrayMax/clamp.lean", + "name": "ArrayMax.clamp", + "namespace": "SolarVerifyVc.ArrayMax.clamp", + "obligations": [ + { + "answer": "sat", + "asserts": 22, + "commands": 44, + "goal": "false", + "guard": "|g@21|", + "id": "ArrayMax.clamp#0", + "lean": "SolarVerifyVc.ArrayMax.clamp.ob0", + "required": false, + "role": "advisory", + "script": 0, + "smt_sha256": "c669e10e759850f1b0ed3843c8440755652c2b706652835d7415a7dfef329df3", + "solver": "z3" + }, + { + "answer": "unsat", + "asserts": 22, + "commands": 44, + "goal": "(<= |r@22| |n@18|)", + "guard": "|g@21|", + "id": "ArrayMax.clamp#1", + "kind": "postcondition not satisfied", + "lean": "SolarVerifyVc.ArrayMax.clamp.ob1", + "required": true, + "role": "obligation", + "script": 0, + "site": { + "column": 10, + "file": "crates/verify/examples/ArrayMax.sol", + "line": 17 + }, + "smt_sha256": "ae925b0907b4ef1737b19d4fc649c22775148b4351b0413901526e9c10bd82a7", + "solver": "z3", + "spec": { + "column": 10, + "file": "crates/verify/examples/ArrayMax.sol", + "line": 17, + "text": "r <= n" + } + } + ], + "scripts": [ + { + "commands": 44, + "decls": [ + "|this@1|", + "|msg.sender@2|", + "|msg.value@3|", + "|block.timestamp@4|", + "|block.number@5|", + "|block.chainid@6|", + "|tx.origin@7|", + "|tx.gasprice@8|", + "|msg.sig@9|", + "|msg.data@10|", + "|block.basefee@11|", + "|block.blobbasefee@12|", + "|block.coinbase@13|", + "|block.prevrandao@14|", + "|block.difficulty@15|", + "|block.gaslimit@16|", + "|x@17|", + "|n@18|", + "|g@19|", + "|g@20|", + "|g@21|", + "|r@22|" + ], + "lean": "SolarVerifyVc.ArrayMax.clamp.script0", + "smt": "ArrayMax/clamp.script0.smt2" + } + ], + "status": "verified" + }, + { + "module": "ArrayMaxEntry/max.lean", + "name": "ArrayMaxEntry.max", + "namespace": "SolarVerifyVc.ArrayMaxEntry.max", + "obligations": [ + { + "answer": "unsat", + "asserts": 20, + "commands": 42, + "goal": "(> |xs.length@20| 0)", + "guard": "|g@22|", + "id": "ArrayMaxEntry.max#0", + "kind": "precondition of `max` not satisfied", + "lean": "SolarVerifyVc.ArrayMaxEntry.max.ob0", + "required": true, + "role": "obligation", + "script": 0, + "site": { + "column": 16, + "file": "crates/verify/examples/ArrayMax.sol", + "line": 30 + }, + "smt_sha256": "250434d86bc1b5c4e45f2e3538f7c1e5123fa49df127e0943ff25a45ebd9e13f", + "solver": "z3", + "spec": { + "column": 10, + "file": "crates/verify/examples/ArrayMax.sol", + "line": 5, + "text": "xs.length > 0" + } + }, + { + "answer": "sat", + "asserts": 23, + "commands": 48, + "goal": "false", + "guard": "|g@27|", + "id": "ArrayMaxEntry.max#1", + "lean": "SolarVerifyVc.ArrayMaxEntry.max.ob1", + "required": false, + "role": "advisory", + "script": 0, + "smt_sha256": "6a103618ebb3edca8d5011cb95b77f711994fef7c719df636741f80fa7f2e54e", + "solver": "z3" + }, + { + "answer": "unsat", + "asserts": 23, + "commands": 48, + "goal": "(forall ((|j!28| Int)) (=> (and (and (<= 0 |j!28|) (<= |j!28| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) (=> (< |j!28| |xs.length@20|) (<= (select |xs@19| |j!28|) |m@23|))))", + "guard": "|g@27|", + "id": "ArrayMaxEntry.max#2", + "kind": "postcondition not satisfied", + "lean": "SolarVerifyVc.ArrayMaxEntry.max.ob2", + "required": true, + "role": "obligation", + "script": 0, + "site": { + "column": 10, + "file": "crates/verify/examples/ArrayMax.sol", + "line": 26 + }, + "smt_sha256": "d1712d8397bf64d098f81b53f58d74d79369f8df7c7e83f1df197cf66c13530b", + "solver": "z3", + "spec": { + "column": 10, + "file": "crates/verify/examples/ArrayMax.sol", + "line": 26, + "text": "forall uint256 j :: j < xs.length ==> xs[j] <= result" + } + }, + { + "answer": "unsat", + "asserts": 23, + "commands": 48, + "goal": "(exists ((|j!29| Int)) (and (and (and (<= 0 |j!29|) (<= |j!29| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) (and (< |j!29| |xs.length@20|) (= (select |xs@19| |j!29|) |m@23|))))", + "guard": "|g@27|", + "id": "ArrayMaxEntry.max#3", + "kind": "postcondition not satisfied", + "lean": "SolarVerifyVc.ArrayMaxEntry.max.ob3", + "required": true, + "role": "obligation", + "script": 0, + "site": { + "column": 10, + "file": "crates/verify/examples/ArrayMax.sol", + "line": 27 + }, + "smt_sha256": "48dc434e3f17562a86578ff2efe8db9146ebef7af86cb3190c125e5c4e88f5e4", + "solver": "z3", + "spec": { + "column": 10, + "file": "crates/verify/examples/ArrayMax.sol", + "line": 27, + "text": "exists uint256 j :: j < xs.length && xs[j] == result" + } + } + ], + "scripts": [ + { + "commands": 48, + "decls": [ + "|this@1|", + "|msg.sender@2|", + "|msg.value@3|", + "|block.timestamp@4|", + "|block.number@5|", + "|block.chainid@6|", + "|tx.origin@7|", + "|tx.gasprice@8|", + "|msg.sig@9|", + "|msg.data@10|", + "|block.basefee@11|", + "|block.blobbasefee@12|", + "|block.coinbase@13|", + "|block.prevrandao@14|", + "|block.difficulty@15|", + "|block.gaslimit@16|", + "|__balance@17|", + "|__code_epoch@18|", + "|xs@19|", + "|xs.length@20|", + "|g@21|", + "|g@22|", + "|m@23|", + "|g@25|", + "|g@27|" + ], + "lean": "SolarVerifyVc.ArrayMaxEntry.max.script0", + "smt": "ArrayMaxEntry/max.script0.smt2" + } + ], + "status": "verified" + }, + { + "module": "ArrayMaxEntry/constructor.lean", + "name": "ArrayMaxEntry.constructor", + "namespace": "SolarVerifyVc.ArrayMaxEntry.constructor", + "obligations": [ + { + "answer": "sat", + "asserts": 18, + "commands": 37, + "goal": "false", + "guard": "|g@19|", + "id": "ArrayMaxEntry.constructor#0", + "lean": "SolarVerifyVc.ArrayMaxEntry.constructor.ob0", + "required": false, + "role": "advisory", + "script": 0, + "smt_sha256": "47045d9c3bc9bc2bb3756918d7c08545edc1433497ba6f34db2b2e3a5ba0fa43", + "solver": "z3" + } + ], + "scripts": [ + { + "commands": 37, + "decls": [ + "|this@1|", + "|msg.sender@2|", + "|msg.value@3|", + "|block.timestamp@4|", + "|block.number@5|", + "|block.chainid@6|", + "|tx.origin@7|", + "|tx.gasprice@8|", + "|msg.sig@9|", + "|msg.data@10|", + "|block.basefee@11|", + "|block.blobbasefee@12|", + "|block.coinbase@13|", + "|block.prevrandao@14|", + "|block.difficulty@15|", + "|block.gaslimit@16|", + "|__balance@17|", + "|__code_epoch@18|", + "|g@19|" + ], + "lean": "SolarVerifyVc.ArrayMaxEntry.constructor.script0", + "smt": "ArrayMaxEntry/constructor.script0.smt2" + } + ], + "status": "verified" + } + ], + "version": 1 +} diff --git a/Contracts/C4/Spec/Axioms.lean b/Contracts/C4/Spec/Axioms.lean new file mode 100644 index 00000000..522b56ee --- /dev/null +++ b/Contracts/C4/Spec/Axioms.lean @@ -0,0 +1,22 @@ +import Contracts.C4.Spec.Bytecode +import Verify.Spec.GhostFree + +/-! The axioms of the spec semantics' theorems: `propext`, `Classical.choice` and `Quot.sound` at +most, and no `sorry`, `native_decide` (`Lean.ofReduceBool`) or `bv_decide`. -/ + +#print axioms SolidCore.Spec.Ghost.sound +#print axioms SolidCore.Spec.Ghost.complete +#print axioms SolidCore.Spec.Ghost.spec_of_erased +#print axioms SolidCore.Spec.Ghost.spec_of_erased_real +#print axioms SolidCore.Spec.Ghost.ghostTotal_of_straight +#print axioms SolidCore.Spec.eval_ghostEquiv +#print axioms SolidCore.Spec.Bundle.sat_ghostEquiv +#print axioms SolidCore.Spec.Holds.of_stage +#print axioms SolidCore.Spec.spec_of_verdict +#print axioms SolidCore.Spec.Export.C4.Main_wf +#print axioms SolidCore.Spec.Solar.C4.post_of_postAt +#print axioms SolidCore.Spec.Solar.C4.holds_source +#print axioms SolidCore.Spec.Solar.C4.holds_bytecode +#print axioms SolidCore.Spec.Solar.C4.holds_bytecode_at +#print axioms SolidCore.Spec.Solar.C4.certified +#print axioms SolidCore.Spec.Solar.C4.wrong_fails diff --git a/Contracts/C4/Spec/Bytecode.lean b/Contracts/C4/Spec/Bytecode.lean new file mode 100644 index 00000000..6d13dd17 --- /dev/null +++ b/Contracts/C4/Spec/Bytecode.lean @@ -0,0 +1,260 @@ +import Contracts.C4.Spec.Export +import Contracts.C4.Spec.ExportWrong +import Verify.Spec.TrustedBase +import Verify.C4 +import SolidCore.Refinement.Corpus.C4 +import SolidCore.Refinement.Spec + +/-! +# c4: solar-verify's spec, proved of SolidCore and of solar's bytecode + +c4 (`scripts/refinement/corpus/c4.sol`) with specs written for solar-verify +(`scripts/refinement/spec/c4.sol`): + + contract Main { + uint8 v; + uint8 w = 7; + /// @custom:ensures result == old(v) + x + /// @custom:ensures v == old(v) + x + /// @custom:ensures w == (old(w) ^ x) + /// @custom:succeeds-if v + x < 256 + function add(uint8 x) external returns (uint8) { v += x; w ^= x; return v; } } + +`solar-verify --emit-lean` writes those specs as `Export.C4.Main`, whose meaning is +`SolidCore.Spec.Holds`: every call of `add` with a clean `uint8` argument finishes; when it succeeds +it returns a clean `uint8` equal to the old `v` plus `x`, `v` (the low byte of slot 0) is the old `v` +plus `x`, and `w` (the next byte) is the old `w` xor `x`; and when the old `v` plus `x` is below 256 +it succeeds. + +All of it is proved in Lean, with no trusted base: solar-verify's verdict, the one trusted item +of `spec_of_verdict`, is not used, since SolidCore's run of `add` is known exactly +(`Verify.C4.postAt`, by symbolic evaluation of SolidCore's interpreter from any storage that +writes slot 0). `post_of_postAt` reads that run through the spec's meaning. + +* `holds_source`: the spec of SolidCore's checked `Main`, from any storage that writes slot 0. +* `holds_bytecode`: the spec of solar's runtime bytecode on EthLib, from the deployed storage, + through the corpus's refinement (`Corpus.C4.refines_full`, solar 9688f215). +* `holds_bytecode_at`: from any storage that writes slot 0, given the stage from SolidCore to + the bytecode that solar-tv's c4 milestone certifies (`Solar.C4.certified_at`, whose + milestone proofs are outside this module's imports). +* `certified`: `holds_bytecode` bound to the export's manifest. +* `wrong_fails`: the negative test. With `result == old(v) + x + 1` + (`scripts/refinement/spec/c4_wrong.sol`, which solar-verify also rejects) the spec does not hold + of the bytecode, by a real mismatch: `add(0)` from the deployed storage returns 0. +-/ + +namespace SolidCore.Spec.Solar.C4 + +open SolidCore.Refinement SolidCore.Refinement.Abi SolidCore.Spec + +/-- The call context of SolidCore's and EthLib's interface (`Refinement.Statement`): sender +`0x2000`, the contract at `0x1000`, block timestamp 1. -/ +def ctxOf (call : Call) : Ctx := + { sender := 0x2000, value := call.callvalue, timestamp := 1, self := 0x1000 } + +/-- c4 has no ghost state. -/ +def step : GhostStep := fun _ g => g + +theorem bytesWord_map (l : List UInt8) : + bytesWord (l.map (·.toNat)) = EthLib.Base.bytesToNat l := by + simp [bytesWord, EthLib.Base.bytesToNat, List.foldl_map] + +theorem bytesWord_word {v : Nat} (h : v < 2 ^ 256) : bytesWord (Verify.word v) = v := by + rw [Verify.word, bytesWord_map, EthLib.Base.bytesToNat_natToBytes_of_lt] + simpa using h + +theorem length_word (v : Nat) : (Verify.word v).length = 32 := by + simp [Verify.word, EthLib.Base.natToBytes_length] + +theorem words_word {v : Nat} (h : v < 2 ^ 256) : words (Verify.word v) = [v] := by + simp only [words, length_word, Nat.reduceDiv, List.range_one, List.map_cons, List.map_nil, + Nat.mul_zero, List.drop_zero] + rw [List.take_of_length_le (by rw [length_word]), bytesWord_word h] + +/-- The argument bytes of one word are the word's bytes. -/ +theorem argBytes_one (a : Nat) : Dirty.argBytes [a] = Verify.word a := by + simp [Dirty.argBytes, Verify.word] + +/-- A call of the scope is `add` on one word `a` from a storage `σ`. -/ +theorem scopeAt_call {call : Call} (h : Verify.C4.scopeAt call) : + ∃ σ a, a < 2 ^ 256 ∧ call = Call.mk (Abi.calldata Bytecode.C4.Main.addSelector [a]) 0 σ := by + obtain ⟨σ, _, fn, hfn, args, hlen, hargs, rfl⟩ := h + simp only [Corpus.C4.fns, List.mem_singleton] at hfn + subst hfn + rcases args with _ | ⟨a, _ | _⟩ <;> simp at hlen + exact ⟨σ, a, hargs a (by simp), rfl⟩ + +/-- The argument words after the selector of such a call. -/ +theorem words_args (a : Nat) (ha : a < 2 ^ 256) : + words (((Abi.calldata Bytecode.C4.Main.addSelector [a]).data.toList.map (·.toNat)).drop 4) = + [a] := by + rw [Dirty.bytes_calldata, Wide.drop_selector, argBytes_one, words_word ha] + +/-- **SolidCore's run of `add`, read through the spec.** A call of the scope from a pre-state +meeting `Pre` that finishes as `Verify.C4.postAt` says finishes meeting `Post`. -/ +theorem post_of_postAt {call : Call} (hs : Verify.C4.scopeAt call) {fs : FnSpec} + (hfs : fs ∈ Export.C4.Main.spec.specs) {args : List Int} {pre : State} + (hpre : Pre Export.C4.Main fs (ctxOf call) pre call args) {obs : Observable} + (hpost : Verify.C4.postAt call obs) : + Post Export.C4.Main fs (ctxOf call) pre (step call pre.ghost) obs args := by + simp only [Export.C4.Main, List.mem_singleton] at hfs + subst hfs + obtain ⟨σ, a, ha, rfl⟩ := scopeAt_call hs + obtain ⟨⟨_, _, hdec⟩, hst, -, -, -⟩ := hpre + rw [words_args a ha] at hdec + simp only [decodeWords, Ty.ofWord, Nat.reducePow] at hdec + by_cases hx : a < 256 + swap + · simp [hx] at hdec + have hargs : args = [(a : Int)] := by + simp [hx, bind, pure] at hdec + exact hdec.symm + subst hargs + replace hx : a < 2 ^ 8 := hx + have haw : Verify.argWords 1 (Call.mk (Abi.calldata Bytecode.C4.Main.addSelector [a]) 0 σ) = + [a] := + Verify.argWords_calldata _ [a] (by simpa using ha) 0 σ + simp only [Verify.C4.postAt, haw, List.getD_cons_zero, hx, ite_true] at hpost + obtain ⟨hpost, -⟩ := hpost + have hs0lt : slotValue σ 0 < 2 ^ 256 := SolidCore.Refinement.Evm.Wide.slotValue_lt σ 0 + have hpre0 : pre.storage 0 = slotValue σ 0 := by rw [hst] + generalize slotValue σ 0 = s0 at hpost hs0lt hpre0 + by_cases hfit : s0 % 2 ^ 8 + a < 2 ^ 8 + · simp only [hfit, ite_true] at hpost + obtain ⟨hsucc, hout, hstore⟩ := hpost + have h0 := hstore 0 + simp only [Nat.zero_mod, ite_true] at h0 + have hy : s0 / 2 ^ 8 % 2 ^ 8 ^^^ a < 2 ^ 8 := Nat.xor_lt_two_pow (by omega) hx + refine ⟨fun _ => ⟨[((s0 % 2 ^ 8 + a : Nat) : Int)], ?_, ?_, ?_⟩, fun _ _ => hsucc⟩ + · rw [hout, words_word (by omega)] + simp [decodeWords, Ty.ofWord, show s0 % 256 + a < 256 by omega] + · simp [Bundle.satAll, Bundle.sat, eval, slotOf, mkEnv, Env.cur, BinOp.apply, + Ty.ofBits, toWord, hpre0, h0] + have e1 : ((s0 : Int) / 256 % 256 % + 115792089237316195423570985008687907853269984665640564039457584007913129639936).toNat = + s0 / 2 ^ 8 % 2 ^ 8 := by omega + have e2 : ((a : Int) % + 115792089237316195423570985008687907853269984665640564039457584007913129639936).toNat = + a := by omega + simp only [e1, e2] + generalize s0 / 2 ^ 8 % 2 ^ 8 ^^^ a = y at hy ⊢ + constructor <;> omega + · simp [Bundle.satAll, Export.C4.Main] + · simp only [hfit, ite_false] at hpost + refine ⟨fun h => by simp [hpost.1] at h, fun _ hsi => ?_⟩ + simp [Bundle.satAll, Bundle.sat, eval, slotOf, mkEnv, Env.cur, BinOp.apply, + Ty.ofBits, toWord, hpre0] at hsi + omega + +/-! ## The spec of SolidCore and of the bytecode -/ + +/-- **The spec of SolidCore's checked `Main`**, on every call of `add` from any storage that writes +slot 0. -/ +theorem holds_source : ∃ c, Corpus.C4.contract? = .ok c ∧ + Holds (solidCore Corpus.C4.fuel) c Verify.C4.scopeAt Export.C4.Main ctxOf step := by + obtain ⟨c, hc, hsat⟩ := Verify.C4.satisfiesAt + refine ⟨c, hc, fun fs hfs call hs args pre hpre => ?_⟩ + obtain ⟨obs, hrun, hpost⟩ := hsat call hs trivial + exact ⟨obs, hrun, post_of_postAt hs hfs hpre hpost⟩ + +/-- SolidCore's run of `add` from any storage, carried to the bytecode on the deployed storage by +the corpus refinement. -/ +theorem satisfies_bytecode : + Satisfies ethLib Corpus.C4.code Verify.C4.scope Verify.C4.pre Verify.C4.postAt := by + obtain ⟨c, hc, hsat⟩ := Verify.C4.satisfiesAt + obtain ⟨c', s, hc', hs', href⟩ := Corpus.C4.refines_full + rw [hc] at hc' + cases hc' + have hs : s = Verify.C4.deployed := by + rw [(Verify.C4.shape_of hc).2.1] at hs' + exact (Option.some.inj hs').symm + subst hs + exact bytecode_of_refines (fun call h hp => hsat call (Verify.C4.scopeAt_of_scope h) hp) href + +/-- **The spec of solar's runtime bytecode on EthLib**, on every call of `add` (any argument word, +no value) from the deployed storage. -/ +theorem holds_bytecode : + Holds ethLib Corpus.C4.code Verify.C4.scope Export.C4.Main ctxOf step := by + intro fs hfs call hs args pre hpre + obtain ⟨obs, hrun, hpost⟩ := satisfies_bytecode call hs trivial + exact ⟨obs, hrun, post_of_postAt (Verify.C4.scopeAt_of_scope hs) hfs hpre hpost⟩ + +/-- **The spec of the bytecode from any storage that writes slot 0**, given the stage from +SolidCore to the bytecode on that scope, which solar-tv's c4 milestone certifies +(`SolidCore.Refinement.Solar.C4.certified_at`). -/ +theorem holds_bytecode_at {c : SolidCore.Solidity.TypeCheck.CheckedContract} (hc : Corpus.C4.contract? = .ok c) + (stage : Stage (solidCore Corpus.C4.fuel) ethLib c Corpus.C4.code Verify.C4.scopeAt) : + Holds ethLib Corpus.C4.code Verify.C4.scopeAt Export.C4.Main ctxOf step := by + obtain ⟨c', hc', h⟩ := holds_source + rw [hc] at hc' + cases hc' + exact h.of_stage stage + +/-- **c4's solar-verify spec, certified on solar's bytecode**, bound to the export's manifest: +the annotated source's sha256, the compiler that built the bytecode, the bytecode's sha256 (that +of `Bytecode.C4.Main.runtimeNat`'s 107 bytes, which `scripts/refinement/spec/check.sh` checks +outside the kernel, as solar's certify.sh does), the spec's well-formedness, and the spec. -/ +theorem certified : + Export.C4.manifest.sourceSha256 = + "f6a3a1d0280a07e6f5697b57489f426936b41078de11390f18fe62a313a495c9" ∧ + Export.C4.manifest.compiler = "solar 0.3.0-dev+commit.9688f215" ∧ + Bytecode.C4.solarRev = "9688f21581717743806cb7bf3afae2ac3c156a08" ∧ + Export.C4.manifest.bytecodeSha256 = + "8a21bc207d9dd8be48d921a717eda3ecb7e5bfcb5397850bc3d64a29037fac47" ∧ + Export.C4.Main.WF = true ∧ + Holds ethLib Corpus.C4.code Verify.C4.scope Export.C4.Main ctxOf step := + ⟨rfl, rfl, rfl, rfl, Export.C4.Main_wf, holds_bytecode⟩ + +/-! ## The negative test -/ + +/-- The call `add(0)` from the deployed storage. -/ +def call0 : Call := Call.mk (Abi.calldata Bytecode.C4.Main.addSelector [0]) 0 Verify.C4.deployed + +theorem selectorOf_calldata (sel : Nat) (hsel : sel < 2 ^ 32) (args : List Nat) : + selectorOf (Call.mk (Abi.calldata sel args) 0 []) = sel := by + simp only [selectorOf, Dirty.bytes_calldata] + rw [List.take_append_of_le_length (by simp [EthLib.Base.natToBytes_length]), + List.take_of_length_le (by simp [EthLib.Base.natToBytes_length]), bytesWord_map, + EthLib.Base.bytesToNat_natToBytes_of_lt (by simpa using hsel)] + +/-- **The wrong spec fails, by a mismatch.** `result == old(v) + x + 1` does not hold of the +bytecode: `add(0)` from the deployed storage returns 0, and the spec asks for 1. -/ +theorem wrong_fails : + ¬ Holds ethLib Corpus.C4.code Verify.C4.scope Export.C4Wrong.Main ctxOf step := by + intro h + have hs : Verify.C4.scope call0 := + ⟨_, List.mem_singleton_self _, [0], rfl, by simp, rfl⟩ + let pre : State := ⟨slotValue call0.storage, Ghost.zero, 0⟩ + have hfs := List.mem_singleton_self (Export.C4Wrong.Main.spec.specs.head (by simp [Export.C4Wrong.Main])) + have hdec : decodeWords [.uint 8] + (words ((call0.calldata.data.toList.map (·.toNat)).drop 4)) = some [0] := by + rw [call0, words_args 0 (by decide)] + simp [decodeWords, Ty.ofWord, bind, pure] + have hpre : Pre Export.C4Wrong.Main (Export.C4Wrong.Main.spec.specs.head (by simp [Export.C4Wrong.Main])) + (ctxOf call0) pre call0 [0] := by + refine ⟨⟨?_, ?_, ?_⟩, rfl, by simp [pre, ctxOf], ?_, ?_⟩ + · simp [call0, Abi.calldata, EthLib.Base.natToBytes_length, ByteArray.size] + · show selectorOf call0 = Bytecode.C4.Main.addSelector + have := selectorOf_calldata Bytecode.C4.Main.addSelector (by decide) [0] + exact this + · simpa [Export.C4Wrong.Main] using hdec + · simp [Bundle.satAll, Export.C4Wrong.Main] + · simp [Bundle.satAll, Export.C4Wrong.Main] + obtain ⟨obs, hrun, hpost⟩ := h _ (by simpa [Export.C4Wrong.Main] using hfs) call0 hs [0] pre hpre + obtain ⟨obs', hrun', hpost'⟩ := satisfies_bytecode call0 hs trivial + rw [hrun] at hrun' + cases hrun' + have haw : Verify.argWords 1 call0 = [0] := + Verify.argWords_calldata _ [0] (by simp) 0 Verify.C4.deployed + simp only [Verify.C4.postAt, haw] at hpost' + simp [call0, Verify.C4.deployed, slotValue] at hpost' + obtain ⟨⟨hsucc, hout, -⟩, -⟩ := hpost' + obtain ⟨rets, hrets, hens, -⟩ := hpost.1 hsucc + rw [hout, words_word (by decide)] at hrets + simp [decodeWords, Ty.ofWord, bind, pure, Export.C4Wrong.Main, List.head] at hrets + subst hrets + have := hens _ (by simp [Export.C4Wrong.Main, List.head]; exact Or.inl rfl) + simp [Bundle.sat, Export.C4Wrong.Main, eval, slotOf, mkEnv, Env.cur, BinOp.apply, Ty.ofBits, + toWord, pre, call0, Verify.C4.deployed, slotValue] at this + +end SolidCore.Spec.Solar.C4 diff --git a/Contracts/C4/Spec/Export.lean b/Contracts/C4/Spec/Export.lean new file mode 100644 index 00000000..7392ec3d --- /dev/null +++ b/Contracts/C4/Spec/Export.lean @@ -0,0 +1,51 @@ +import Verify.Spec.Contract + +/-! +Specs of `scripts/refinement/spec/c4.sol`, exported by solar-verify 0.3.0 with `--emit-lean-spec`. +Generated: do not edit. +-/ + +namespace SolidCore.Spec.Export.C4 + +open SolidCore.Spec + +/-- What the specs were exported from and are about. -/ +def manifest : Manifest := + { source := "scripts/refinement/spec/c4.sol", + sourceSha256 := "f6a3a1d0280a07e6f5697b57489f426936b41078de11390f18fe62a313a495c9", + compiler := "solar 0.3.0-dev+commit.9688f215", + options := [], + bytecodeSha256 := "8a21bc207d9dd8be48d921a717eda3ecb7e5bfcb5397850bc3d64a29037fac47" } + +/-- The specs of `Main`. -/ +def Main : Bundle where + fuel := 0 + spec := + { name := "Main", + fns := [ + ], + invariants := [ + ], + ghosts := [], + specs := [ + { name := "Main.add", + selector := 0x02067e6a, + params := [(.uint 8)], + rets := [(.uint 8)], + payable := false, + requires := [], + ensures := [ + (.bin .eq (.ret 0) (.bin .add (.old (.load (.slot 0) (.lit 0) 1 (.uint 8))) (.arg 0))), + (.bin .eq (.load (.slot 0) (.lit 0) 1 (.uint 8)) (.bin .add (.old (.load (.slot 0) (.lit 0) 1 (.uint 8))) (.arg 0))), + (.bin .eq (.load (.slot 0) (.lit 1) 1 (.uint 8)) (.bin .bxor (.old (.load (.slot 0) (.lit 1) 1 (.uint 8))) (.arg 0)))], + succeedsIf := [ + (.bin .lt (.bin .add (.load (.slot 0) (.lit 0) 1 (.uint 8)) (.arg 0)) (.lit 256))] }] } + +/-- Every spec function call resolves and nests within the fuel. -/ +theorem Main_wf : Main.WF = true := by decide +kernel + +/-- Trusted-base items these specs' proofs rely on beyond the verdict +(`SolidCore.Spec.Assumptions`). -/ +def trusted : List String := [] + +end SolidCore.Spec.Export.C4 diff --git a/Contracts/C4/Spec/ExportWrong.lean b/Contracts/C4/Spec/ExportWrong.lean new file mode 100644 index 00000000..f9d6984e --- /dev/null +++ b/Contracts/C4/Spec/ExportWrong.lean @@ -0,0 +1,51 @@ +import Verify.Spec.Contract + +/-! +Specs of `scripts/refinement/spec/c4_wrong.sol`, exported by solar-verify 0.3.0 with `--emit-lean-spec`. +Generated: do not edit. +-/ + +namespace SolidCore.Spec.Export.C4Wrong + +open SolidCore.Spec + +/-- What the specs were exported from and are about. -/ +def manifest : Manifest := + { source := "scripts/refinement/spec/c4_wrong.sol", + sourceSha256 := "2420cff959eb9497ee90798a5be2ea0bad65e9b79b10890c64815f4e4113875f", + compiler := "solar 0.3.0-dev+commit.9688f215", + options := [], + bytecodeSha256 := "8a21bc207d9dd8be48d921a717eda3ecb7e5bfcb5397850bc3d64a29037fac47" } + +/-- The specs of `Main`. -/ +def Main : Bundle where + fuel := 0 + spec := + { name := "Main", + fns := [ + ], + invariants := [ + ], + ghosts := [], + specs := [ + { name := "Main.add", + selector := 0x02067e6a, + params := [(.uint 8)], + rets := [(.uint 8)], + payable := false, + requires := [], + ensures := [ + (.bin .eq (.ret 0) (.bin .add (.bin .add (.old (.load (.slot 0) (.lit 0) 1 (.uint 8))) (.arg 0)) (.lit 1))), + (.bin .eq (.load (.slot 0) (.lit 0) 1 (.uint 8)) (.bin .add (.old (.load (.slot 0) (.lit 0) 1 (.uint 8))) (.arg 0))), + (.bin .eq (.load (.slot 0) (.lit 1) 1 (.uint 8)) (.bin .bxor (.old (.load (.slot 0) (.lit 1) 1 (.uint 8))) (.arg 0)))], + succeedsIf := [ + (.bin .lt (.bin .add (.load (.slot 0) (.lit 0) 1 (.uint 8)) (.arg 0)) (.lit 256))] }] } + +/-- Every spec function call resolves and nests within the fuel. -/ +theorem Main_wf : Main.WF = true := by decide +kernel + +/-- Trusted-base items these specs' proofs rely on beyond the verdict +(`SolidCore.Spec.Assumptions`). -/ +def trusted : List String := [] + +end SolidCore.Spec.Export.C4Wrong diff --git a/Contracts/Counter/EndToEnd.lean b/Contracts/Counter/EndToEnd.lean new file mode 100644 index 00000000..420da4b4 --- /dev/null +++ b/Contracts/Counter/EndToEnd.lean @@ -0,0 +1,99 @@ +import Contracts.Counter.Verdict +import Contracts.Counter.VC.Inc +import Contracts.Counter.VC.Get +import Contracts.Counter.VC.Mutants + +/-! +# The counter milestone: solar-verify's spec of `inc` holds of the deployed bytecode + +One theorem from solar-verify's checked obligation to solar's runtime bytecode, for +`inc(uint256 d)` of the counter milestone (`scripts/refinement/counter/counter.sol`; its annotated +copy `scripts/verify/CounterMilestone.sol` adds `@custom:ensures x == old(x) + d`): + +* `SolidCore.Verify.VC.Counter.inc_triple`: SolidCore's checked counter meets `incPost` on every + call of `inc` (any argument word, no value, any storage). It is read off solar-verify's + exported obligation, which `checkScript` accepts by the kernel (`inc_check`), and bound to + SolidCore's run of `inc` (`inc_binding`). +* `Counter.Verdict.bytecode_of_triple`: the stage from SolidCore's checked counter to solar's + bytecode (`Counter.Verdict.agree`, through solar-tv's backend stages and the assembly stage) + carries it to the bytecode under EthLib. +* `Counter.Final.bound`, `Counter.Final.frameLocal`: the bytecode is the exporter's (its hex and + SHA-256, checked by the kernel), and it runs in one frame: no instruction calls out, creates or + reads outside its frame. + +`incPost` says the call succeeds exactly when `x + d` does not overflow, and then sets slot 0 to +`x + d` and leaves every other slot as it was. It is not met trivially: `Counter.Final.inc_succeeds` +and `inc_overflow_fails` run the bytecode both ways, and solar-verify's checked script rejects +a source mutant and a spec mutant (`CounterMutants.lean`). + +The trusted base is empty here: the counter hashes nothing and calls nothing, and the theorem +takes no hypothesis. `get_spec_bytecode` does the same for `get`, from a direct proof (no NatSpec, no VC). What they do not cover: deployment (the constructor), +gas limits other than EthLib's default (`Target.run`), and calls with value (not in +`stageScope`; the bytecode rejects them, as `Counter.Final`'s `scopeEvery` shows). +-/ + +namespace SolidCore.Refinement.Solar.Counter.EndToEnd + +open SolidCore.Refinement SolidCore.Refinement.Final + +/-- Every call of `inc` in solar-verify's binding scope is in the stage's scope. -/ +theorem inc_in_scope {call : Call} + (h : SolidCore.Verify.VC.stageScope SolidCore.Verify.VC.Counter.fnInc [] call) : + scopeEvery call := by + obtain ⟨σ, -, fn, hfn, args, hl, hargs, rfl⟩ := h + simp only [List.mem_singleton] at hfn + subst hfn + match args, hl with + | [a], _ => + have ha : a < 2 ^ 256 := hargs a (List.mem_singleton_self a) + refine ⟨Nat.two_pow_pos 256, Or.inl ⟨BitVec.ofNat 256 a, ?_⟩⟩ + simp only [Evm.Wide.callOf, List.map, BitVec.toNat_ofNat, Nat.mod_eq_of_lt ha] + rfl + +/-- **The counter's `inc`: solar-verify's spec holds of the deployed bytecode.** The bytecode is +the exporter's and runs in one frame, and on every call of `inc(uint256)` with any argument +word, no value and any storage, EthLib runs it to an observable meeting `incPost`. -/ +theorem inc_spec_bytecode : + Bound Final.manifest code ∧ FrameLocal code = true ∧ + ∀ call, SolidCore.Verify.VC.stageScope SolidCore.Verify.VC.Counter.fnInc [] call → + ∃ obs, Target.run code call = some obs ∧ SolidCore.Verify.VC.Counter.incPost call obs := by + obtain ⟨c, hc⟩ := contract_ok + exact ⟨Final.bound, Final.frameLocal, fun call h => + Verdict.bytecode_of_triple hc (fun _ h => inc_in_scope h) + (SolidCore.Verify.VC.Counter.inc_triple (by exact hc)) call h trivial⟩ + +/-- info: 'SolidCore.Refinement.Solar.Counter.EndToEnd.inc_spec_bytecode' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms inc_spec_bytecode + +/-- Every call of §get§ in the binding scope is in the stage's scope. -/ +theorem get_in_scope {call : Call} + (h : SolidCore.Verify.VC.stageScope SolidCore.Verify.VC.Counter.fnGet [] call) : + scopeEvery call := by + obtain ⟨σ, -, fn, hfn, args, hl, -, rfl⟩ := h + simp only [List.mem_singleton] at hfn + subst hfn + match args, hl with + | [], _ => + refine ⟨Nat.two_pow_pos 256, Or.inr (Or.inl ?_)⟩ + simp only [Evm.Wide.callOf, List.map] + rfl + +/-- **The counter's §get§ on the deployed bytecode.** On every call of §get()§ with no value and +any storage, EthLib runs the bytecode to a success that returns slot 0 as a word and changes no +slot. §get§ has no NatSpec clause, so solar-verify emits no obligation for it: §get_triple§ is +proved directly of SolidCore's run, with no VC behind it. -/ +theorem get_spec_bytecode : + Bound Final.manifest code ∧ FrameLocal code = true ∧ + ∀ call, SolidCore.Verify.VC.stageScope SolidCore.Verify.VC.Counter.fnGet [] call → + ∃ obs, Target.run code call = some obs ∧ SolidCore.Verify.VC.Counter.getPost call obs := by + obtain ⟨c, hc⟩ := contract_ok + exact ⟨Final.bound, Final.frameLocal, fun call h => + Verdict.bytecode_of_triple hc (fun _ h => get_in_scope h) + (SolidCore.Verify.VC.Counter.get_triple (by exact hc)) call h trivial⟩ + +/-- info: 'SolidCore.Refinement.Solar.Counter.EndToEnd.get_spec_bytecode' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms get_spec_bytecode + +end SolidCore.Refinement.Solar.Counter.EndToEnd diff --git a/Contracts/Counter/Final.lean b/Contracts/Counter/Final.lean new file mode 100644 index 00000000..bc528b53 --- /dev/null +++ b/Contracts/Counter/Final.lean @@ -0,0 +1,248 @@ +import Verify.Final +import SolidCore.Refinement.Solar.Counter.Every + +/-! +# The counter milestone's certificate + +The first instance of `Final.Certificate`: solar's runtime bytecode for + + contract Counter { uint256 x; function inc(uint256 d) external { x += d; } + function get() external view returns (uint256) { return x; } } + +(solar-tv/milestone/counter, `-Ogas --evm-version osaka`), bound to the manifest the exporter +wrote with its stages (`manifest`, `bound`: the hex and the SHA-256 of the bytecode, checked by +the kernel), meets its specification (`spec`: `inc(d)` ensures `x == old(x) + d` and returns +nothing, `get()` ensures `x == old(x)` and returns `x`; neither is payable) and agrees with +SolidCore's checked contract on every call of the specification, with any value and from any +storage (`certificate`). Every stage is a theorem: the source stage and the assembly stage of +`Every.lean` and solar-tv's backend stages, composed by `certifiedEvery`. + +The non-vacuity lemmas show the specification is not met trivially: the bytecode succeeds on +`inc(1)` from the empty storage and stores 1 (`inc_succeeds`), reverts on the overflow +(`inc_overflow_fails`), and the postcondition rejects a state that did not change +(`ensures_rejects`). +-/ + +namespace SolidCore.Refinement.Solar.Counter.Final + +open SolidCore.Refinement SolidCore.Refinement.Final SolidCore.Refinement.Abi +open SolidCore.Refinement.Evm.Wide SolidCore.Refinement.Wide SolidCore.Refinement.Evm +open EthLib.Base + +/-! ## The specification -/ + +/-- `inc(uint256 d)`: `x == old(x) + d`, no return data. -/ +def incSpec : FnSpec Nat where + name := "inc" + sel := incSelector + params := [.uint 256] + requires _ _ := True + ensures args x x' out := x' = x + args.headD 0 ∧ out = [] + payable := false + +/-- `get()`: `x == old(x)`, returns `x`. -/ +def getSpec : FnSpec Nat where + name := "get" + sel := getSelector + params := [] + requires _ _ := True + ensures _ x x' out := x' = x ∧ out = Verify.word x + payable := false + +/-- Counter's specification: the abstract state is `x`, slot 0. -/ +def spec : ContractSpec Nat where + abs s := s 0 + invariant _ := True + fns := [incSpec, getSpec] + +/-! ## From the observable on every call -/ + +theorem inc_call (a v : Nat) (ha : a < 2 ^ 256) (σ : List (Nat × Nat)) : + incSpec.call [a] v σ = + { callOf incSelector [BitVec.ofNat 256 a] with callvalue := v, storage := σ } := by + simp only [FnSpec.call, incSpec, callOf, List.map_cons, List.map_nil, BitVec.toNat_ofNat, + Nat.mod_eq_of_lt ha] + +theorem get_call (v : Nat) (σ : List (Nat × Nat)) : + getSpec.call [] v σ = { callAt getSelector [] σ with callvalue := v } := rfl + +theorem scope_inc (a v : Nat) (ha : a < 2 ^ 256) (hv : v < 2 ^ 256) (σ : List (Nat × Nat)) : + scopeEvery (incSpec.call [a] v σ) := by + rw [inc_call a v ha] + exact ⟨hv, Or.inl ⟨_, rfl⟩⟩ + +theorem scope_get (v : Nat) (hv : v < 2 ^ 256) (σ : List (Nat × Nat)) : + scopeEvery (getSpec.call [] v σ) := + ⟨hv, Or.inr (Or.inl rfl)⟩ + +theorem rejected_outcome {f : FnSpec Nat} {args : List Nat} {call : Call} : + spec.Outcome f args call (Abi.rejected call.storage) := + ⟨fun h => absurd h (by simp [Abi.rejected]), fun _ => ⟨rfl, rfl⟩⟩ + +theorem typed_inc {args : List Nat} (h : incSpec.Typed args) : ∃ a, a < 2 ^ 256 ∧ args = [a] := by + unfold FnSpec.Typed incSpec at h + cases h with + | cons ha hrest => + cases hrest + exact ⟨_, by simpa [Param.clean] using ha, rfl⟩ + +theorem typed_get {args : List Nat} (h : getSpec.Typed args) : args = [] := by + unfold FnSpec.Typed getSpec at h + cases h + rfl + +/-- The specification holds of every program that shows `expectedEvery` on every call of +`scopeEvery`. -/ +theorem holds_of_every {S : Sem} {p : S.Prog} + (h : ∀ call, scopeEvery call → S.run p call = some (expectedEvery call)) : + Holds S p spec := by + intro f hf args ht v hv σ _ _ obs hrun + simp only [spec, List.mem_cons, List.not_mem_nil, or_false] at hf + rcases hf with rfl | rfl + · obtain ⟨a, ha, rfl⟩ := typed_inc ht + rw [h _ (scope_inc a v ha hv σ)] at hrun + cases hrun + by_cases h0 : v = 0 + · subst h0 + rw [inc_call a 0 ha] + have hcall : { callOf incSelector [BitVec.ofNat 256 a] with callvalue := 0, storage := σ } = + { callOf incSelector [BitVec.ofNat 256 a] with storage := σ } := rfl + rw [hcall, expectedEvery_inc] + unfold expectedAt + have hd : (BitVec.ofNat 256 a).toNat = a := by rw [BitVec.toNat_ofNat, Nat.mod_eq_of_lt ha] + split_ifs with hof + · refine ⟨fun _ => ⟨?_, trivial, fun _ => rfl⟩, fun h => absurd h (by simp)⟩ + simp [spec, incSpec, ContractSpec.pre, hd, callOf] + · exact ⟨fun h => absurd h (by simp), fun _ => ⟨rfl, rfl⟩⟩ + · rw [expectedEvery_value _ h0] + exact rejected_outcome + · obtain rfl := typed_get ht + rw [h _ (scope_get v hv σ)] at hrun + cases hrun + by_cases h0 : v = 0 + · subst h0 + rw [get_call, show ({ callAt getSelector [] σ with callvalue := 0 } : Call) = + callAt getSelector [] σ from rfl, expectedEvery_get] + exact ⟨fun _ => ⟨⟨rfl, rfl⟩, trivial, fun _ => rfl⟩, fun h => absurd h (by simp [getAt])⟩ + · rw [expectedEvery_value _ h0] + exact rejected_outcome + +theorem calls_every {call : Call} (h : spec.Calls call) : scopeEvery call := by + obtain ⟨f, hf, args, ht, v, hv, σ, rfl⟩ := h + simp only [spec, List.mem_cons, List.not_mem_nil, or_false] at hf + rcases hf with rfl | rfl + · obtain ⟨a, ha, rfl⟩ := typed_inc ht + exact scope_inc a v ha hv σ + · obtain rfl := typed_get ht + exact scope_get v hv σ + +/-- EthLib runs solar's bytecode to `expectedEvery` on every call of `scopeEvery`. -/ +theorem target_every (call : Call) (h : scopeEvery call) : + Target.run code call = some (expectedEvery call) := by + obtain ⟨-, -, -, hsat⟩ := certifiedEvery + obtain ⟨obs, hrun, hpost⟩ := hsat call h trivial + change Target.run code call = some obs at hrun + rw [hrun, show obs = expectedEvery call from hpost] + +/-! ## The manifest -/ + +/-- The manifest the exporter wrote with Counter's stages. -/ +def manifest : Manifest where + contract := "Counter" + sourceSha256 := (SolarTV.Export.Counter.Manifest.sources.headD ("", "")).2 + compilerCommit := SolarTV.Export.Counter.Manifest.compiler + options := SolarTV.Export.Counter.Manifest.arguments + runtimeHex := SolarTV.Export.Counter.Manifest.bytecodeHex + runtimeSha256 := SolarTV.Export.Counter.Manifest.bytecodeSha256 + +theorem hex_bound : hexOf (code.data.toList.map (·.toNat)) = manifest.runtimeHex := by + decide +kernel + +theorem sha_bound : + hexOf ((EthLib.Cryptography.Hash.Sha256.hash code).data.toList.map (·.toNat)) = + manifest.runtimeSha256 := by + decide +kernel + +theorem bound : Bound manifest code := ⟨hex_bound, sha_bound⟩ + +theorem frameLocal : FrameLocal code = true := by decide +kernel + +/-! ## The certificate -/ + +/-- **Counter's certificate.** solar's bytecode, bound to its manifest and running in one frame, +agrees with SolidCore's checked Counter on every call of `inc` and `get`, with any value and +from any storage, and meets Counter's specification, which SolidCore's Counter meets too. -/ +noncomputable def certificate : Certificate spec manifest := + let c := Classical.choose contract_ok + have hc : contract? = .ok c := Classical.choose_spec contract_ok + { code + fuel + source := c + bound + frameLocal + sourceHolds := holds_of_every fun call h => source_run_every hc call h + refines := fun call h => + ⟨_, source_run_every hc call (calls_every h), target_every call (calls_every h)⟩ + holds := holds_of_every target_every } + +/-- The certificate's two theorems, as one statement. -/ +theorem certified : + Bound manifest code ∧ FrameLocal code = true ∧ + ∃ c, contract? = .ok c ∧ Agree (solidCore fuel) ethLib c code spec.Calls ∧ + Holds (solidCore fuel) c spec ∧ Holds ethLib code spec := by + obtain ⟨c, hc⟩ := contract_ok + exact ⟨bound, frameLocal, c, hc, + fun call h => ⟨_, source_run_every hc call (calls_every h), target_every call (calls_every h)⟩, + holds_of_every fun call h => source_run_every hc call h, holds_of_every target_every⟩ + +/-- The invariants and the specification across every sequence of calls, each from the storage +the one before left. -/ +theorem certified_trace {carry : Carry} + (exact : ∀ call obs, Target.run code call = some obs → Carries carry call obs) + (σ : List (Nat × Nat)) (steps : List (Step Nat)) + (hsteps : ∀ s ∈ steps, s.f ∈ spec.fns ∧ s.f.Typed s.args ∧ s.value < 2 ^ 256) : + Trace spec (Target.run code) carry σ steps := + (holds_of_every target_every).trace (S := ethLib) exact σ steps trivial hsteps + +/-! ## Non-vacuity -/ + +/-- The bytecode succeeds on `inc(1)` with no value from the empty storage and stores 1. -/ +theorem inc_succeeds : ∃ obs, Target.run code (incSpec.call [1] 0 []) = some obs ∧ + obs.success = true ∧ obs.storage 0 = 1 := by + refine ⟨_, target_every _ (scope_inc 1 0 (by decide) (by decide) []), ?_⟩ + rw [inc_call 1 0 (by decide)] + rw [show ({ callOf incSelector [BitVec.ofNat 256 1] with callvalue := 0, storage := [] } : Call) = + { callOf incSelector [BitVec.ofNat 256 1] with storage := [] } from rfl, expectedEvery_inc] + simp [expectedAt, slotValue] + +/-- The bytecode fails on `inc(1)` from a storage whose `x` is `2 ^ 256 - 1`. -/ +theorem inc_overflow_fails : ∃ obs, Target.run code (incSpec.call [1] 0 [(0, 2 ^ 256 - 1)]) = some obs ∧ + obs.success = false := by + refine ⟨_, target_every _ (scope_inc 1 0 (by decide) (by decide) _), ?_⟩ + rw [inc_call 1 0 (by decide)] + have hcall : ({ callOf incSelector [BitVec.ofNat 256 1] with callvalue := 0, storage := [(0, 2 ^ 256 - 1)] } : Call) = + { callOf incSelector [BitVec.ofNat 256 1] with storage := [(0, 2 ^ 256 - 1)] } := rfl + rw [hcall, expectedEvery_inc] + simp [expectedAt, slotValue] + +/-- The postcondition of `inc(1)` rejects a state that did not change. -/ +theorem ensures_rejects : ¬ incSpec.ensures [1] 0 0 [] := by + simp [incSpec] + +/-- info: 'SolidCore.Refinement.Solar.Counter.Final.certified' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms certified + +/-- info: 'SolidCore.Refinement.Solar.Counter.Final.certified_trace' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms certified_trace + +/-- info: 'SolidCore.Refinement.Solar.Counter.Final.inc_succeeds' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms inc_succeeds + +/-- info: 'SolidCore.Refinement.Solar.Counter.Final.inc_overflow_fails' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms inc_overflow_fails + +end SolidCore.Refinement.Solar.Counter.Final diff --git a/Contracts/Counter/Headline.lean b/Contracts/Counter/Headline.lean new file mode 100644 index 00000000..2c9a1f35 --- /dev/null +++ b/Contracts/Counter/Headline.lean @@ -0,0 +1,276 @@ +import Contracts.Counter.Verdict +import Contracts.Counter.Spec.Export +import Contracts.Counter.Spec.ExportWrong +import Contracts.Counter.EndToEnd + +/-! +# Counter: solar-verify's spec holds of solar's deployed bytecode + +The counter milestone (`scripts/refinement/counter/counter.sol`, solar-tv/milestone/counter, +`-Ogas --evm-version osaka`) annotated for solar-verify in `scripts/verify/CounterMilestone.sol` +(the same text plus one NatSpec line, which `scripts/verify/check.sh` checks): + + contract Counter { + uint256 x; + /// @custom:ensures x == old(x) + d + function inc(uint256 d) external { x += d; } + function get() external view returns (uint256) { return x; } } + +`solar-verify --emit-lean-spec` writes that spec as `Export.Counter.Counter` (a +`SolidCore.Spec.Bundle`; `get` has no spec, so the exporter leaves it out). Its meaning is +`SolidCore.Spec.Holds`: every call of `inc` with a clean word argument finishes, and when it +succeeds slot 0 holds the old slot 0 plus the argument. There is no succeeds-if, so no claim +that it succeeds. + +* `holds_source`: the spec of SolidCore's checked `Counter` on every call of `scopeEvery` (any + value, any storage; inc's and get's ABI encodings, short call data, unknown selectors, short + arguments), from SolidCore's run of each (`source_run_every`). +* `verdict`: solar-verify's verdict (`SolidCore.Spec.Verdict`, the one trusted item of + `spec_of_verdict`) under Counter's trusted base `Verdict.hyps` (`Hyps.plain`: no hashing, no + external call, no assembly, no assume, no trusted function), proved in Lean rather than + trusted. +* `EndToEnd.inc_spec_bytecode`, `EndToEnd.get_spec_bytecode`: `inc`'s clause read off + solar-verify's own checked obligation through the source bridge + (`SolidCore.Verify.VC.Counter.inc_triple`, whose binding ties solar-verify's encoding of the new + `x` and of the success guard to SolidCore's run), and `get`'s triple, each carried to the + bytecode by the certified stage; the headline includes both. +* **`spec_holds_of_bytecode`**: the headline. solar's runtime bytecode, bound to the exporter's + manifest by its hex and SHA-256 and to the spec export by the same SHA-256, runs in one frame, + agrees with SolidCore's checked `Counter` on every call of the scope, and meets solar-verify's + spec under EthLib, through the composition `Verdict.bytecode_spec_of_verdict` of the certified + stages (source, backend, assembly) with the verdict. +* `wrong_fails`: the negative. The spec mutant `x == old(x) + d + 1` + (`scripts/verify/mutant/CounterSpecMut.sol`, which solar-verify also rejects) does not hold of + the bytecode, by a mismatch: `inc(1)` from the empty storage stores 1. + +Trusted base left: Lean's kernel; EthLib's EVM (`Target.run`, at its default gas limit, one +frame) as the meaning of the bytecode; that `Export.Counter` is what solar-verify exports for the +annotated source (checked by `scripts/verify/check.sh` outside the kernel). Not covered: +deployment, other gas limits, and call data with bytes past the ABI encoding. +-/ + +namespace SolidCore.Refinement.Solar.Counter.Headline + +open SolidCore.Refinement SolidCore.Refinement.Abi SolidCore.Refinement.Evm +open SolidCore.Refinement.Evm.Wide SolidCore.Refinement.Final + +/-- The exported spec. -/ +abbrev spec : SolidCore.Spec.Bundle := SolidCore.Spec.Export.Counter.Counter + +/-- The call context of SolidCore's and EthLib's interface (`Refinement.Statement`): sender +`0x2000`, the contract at `0x1000`, block timestamp 1. -/ +def ctxOf (call : Call) : SolidCore.Spec.Ctx := + { sender := 0x2000, value := call.callvalue, timestamp := 1, self := 0x1000 } + +/-- Counter has no ghost state. -/ +def step : SolidCore.Spec.GhostStep := fun _ g => g + +/-! ## Reading call data the way the spec does -/ + +theorem bytesWord_map (l : List UInt8) : + SolidCore.Spec.bytesWord (l.map (·.toNat)) = EthLib.Base.bytesToNat l := by + simp [SolidCore.Spec.bytesWord, EthLib.Base.bytesToNat, List.foldl_map] + +theorem spec_selectorOf_append (s : Nat) (hs : s < 2 ^ 32) (data : ByteArray) (v : Nat) + (σ : List (Nat × Nat)) : + SolidCore.Spec.selectorOf { calldata := selectorOf s ++ data, callvalue := v, storage := σ } = s := by + simp only [SolidCore.Spec.selectorOf, selectorOf, ByteArray.data_append, Array.toList_append, + List.map_append, List.toList_toArray] + rw [List.take_append_of_le_length (by simp [EthLib.Base.natToBytes_length]), + List.take_of_length_le (by simp [EthLib.Base.natToBytes_length]), bytesWord_map, + EthLib.Base.bytesToNat_natToBytes_of_lt (by simpa using hs)] + +theorem bytesWord_word {v : Nat} (h : v < 2 ^ 256) : SolidCore.Spec.bytesWord (Verify.word v) = v := by + rw [Verify.word, bytesWord_map, EthLib.Base.bytesToNat_natToBytes_of_lt] + simpa using h + +theorem length_word (v : Nat) : (Verify.word v).length = 32 := by + simp [Verify.word, EthLib.Base.natToBytes_length] + +theorem words_word {v : Nat} (h : v < 2 ^ 256) : SolidCore.Spec.words (Verify.word v) = [v] := by + simp only [SolidCore.Spec.words, length_word, Nat.reduceDiv, List.range_one, List.map_cons, + List.map_nil, Nat.mul_zero, List.drop_zero] + rw [List.take_of_length_le (by rw [length_word]), bytesWord_word h] + +theorem argBytes_one (a : Nat) : Dirty.argBytes [a] = Verify.word a := by + simp [Dirty.argBytes, Verify.word] + +/-- The argument words after the selector of inc's ABI call data. -/ +theorem words_inc (d : U256) : + SolidCore.Spec.words + ((((callOf incSelector [d]).calldata).data.toList.map (·.toNat)).drop 4) = [d.toNat] := by + simp only [callOf, List.map_cons, List.map_nil] + rw [Dirty.bytes_calldata, Wide.drop_selector, argBytes_one, words_word d.isLt] + +/-- Fewer than 32 bytes after the selector: no argument word. -/ +theorem words_short (s : Nat) (data : ByteArray) (h : data.size < 32) : + SolidCore.Spec.words (((selectorOf s ++ data).data.toList.map (·.toNat)).drop 4) = [] := by + simp only [SolidCore.Spec.words, selectorOf, ByteArray.data_append, Array.toList_append, + List.map_append, List.toList_toArray] + rw [List.drop_append_of_le_length (by simp [EthLib.Base.natToBytes_length])] + simp [EthLib.Base.natToBytes_length, ByteArray.size] at h ⊢ + omega + +theorem rejected_success (σ : List (Nat × Nat)) : (Abi.rejected σ).success = false := rfl + +/-! ## The spec of SolidCore's checked counter -/ + +/-- The one function the spec has: `inc`. -/ +theorem mem_specs {fs : SolidCore.Spec.FnSpec} (h : fs ∈ spec.spec.specs) : + fs = spec.spec.specs.head (by simp [spec, SolidCore.Spec.Export.Counter.Counter]) := by + simpa [spec, SolidCore.Spec.Export.Counter.Counter] using h + +/-- **What Counter does, read through the spec.** On every call of the scope, the observable +`expectedEvery` meets `inc`'s postcondition from any pre-state meeting its precondition. -/ +theorem post_every {call : Call} (hs : scopeEvery call) {fs : SolidCore.Spec.FnSpec} + (hfs : fs ∈ spec.spec.specs) {args : List Int} {pre : SolidCore.Spec.State} + (hpre : SolidCore.Spec.Pre spec fs (ctxOf call) pre call args) : + SolidCore.Spec.Post spec fs (ctxOf call) pre (step call pre.ghost) (expectedEvery call) args := by + rw [mem_specs hfs] at hpre ⊢ + refine ⟨fun hsucc => ?_, fun hne => absurd rfl hne⟩ + obtain ⟨⟨h4, hsel, hdec⟩, hst, -, -, -⟩ := hpre + rcases call with ⟨cd, v, σ⟩ + obtain ⟨hv, hcl⟩ := hs + dsimp only at hv hcl hsucc hsel hdec h4 hst ⊢ + by_cases h0 : v = 0 + swap + · rw [expectedEvery_value _ h0] at hsucc + exact absurd hsucc (by simp [rejected_success]) + subst h0 + rcases hcl with ⟨d, rfl⟩ | rfl | hshort | ⟨s, data, hs, rfl, hsel'⟩ + · -- inc's ABI call data: the run adds the argument to slot 0. + have hcall : ({ calldata := (callOf incSelector [d]).calldata, callvalue := 0, storage := σ } : Call) = + { callOf incSelector [d] with storage := σ } := rfl + rw [hcall, expectedEvery_inc] at hsucc ⊢ + rw [words_inc] at hdec + simp only [SolidCore.Spec.Export.Counter.Counter, List.head, SolidCore.Spec.decodeWords, + SolidCore.Spec.Ty.ofWord, d.isLt, ite_true, bind, pure, Option.bind, Option.some.injEq] at hdec + subst hdec + unfold expectedAt at hsucc ⊢ + split_ifs at hsucc ⊢ with hof + · refine ⟨[], by simp [SolidCore.Spec.Export.Counter.Counter, SolidCore.Spec.decodeWords], ?_, ?_⟩ + · have hpre0 : pre.storage 0 = slotValue σ 0 := by rw [hst] + have hlt : slotValue σ 0 < 2 ^ 256 := SolidCore.Refinement.Evm.Wide.slotValue_lt σ 0 + simp [SolidCore.Spec.Bundle.satAll, SolidCore.Spec.Bundle.sat, SolidCore.Spec.eval, + SolidCore.Spec.slotOf, SolidCore.Spec.mkEnv, SolidCore.Spec.Env.cur, + SolidCore.Spec.BinOp.apply, SolidCore.Spec.Ty.ofBits, SolidCore.Spec.toWord, + SolidCore.Spec.Export.Counter.Counter, hpre0] + omega + · simp [SolidCore.Spec.Bundle.satAll, SolidCore.Spec.Export.Counter.Counter] + · simp at hsucc + · -- get's call data: not inc's selector. + have : SolidCore.Spec.selectorOf + ({ calldata := (callOf getSelector []).calldata, callvalue := 0, storage := σ } : Call) = + getSelector := by + rw [calldata_get] + exact spec_selectorOf_append _ (by decide) _ _ _ + rw [this] at hsel + simp [SolidCore.Spec.Export.Counter.Counter, getSelector] at hsel + · exact absurd h4 (by omega) + · rw [spec_selectorOf_append s hs data 0 σ] at hsel + simp only [SolidCore.Spec.Export.Counter.Counter, List.head] at hsel + rcases hsel' with ⟨hne, -⟩ | ⟨-, hshort⟩ + · exact absurd hsel (by simpa [incSelector] using hne) + · rw [words_short s data hshort] at hdec + simp [SolidCore.Spec.Export.Counter.Counter, SolidCore.Spec.decodeWords] at hdec + +/-- **solar-verify's spec, of SolidCore's checked `Counter`**, on every call of the scope. -/ +theorem holds_source {c : SolidCore.Solidity.TypeCheck.CheckedContract} (hc : contract? = .ok c) : + SolidCore.Spec.Holds (solidCore fuel) c scopeEvery spec ctxOf step := + fun _ hfs call hs _ _ hpre => ⟨_, source_run_every hc call hs, post_every hs hfs hpre⟩ + +/-- **solar-verify's verdict on Counter, proved.** The one trusted item of +`SolidCore.Spec.spec_of_verdict`, under Counter's trusted base, is a theorem here. -/ +theorem verdict {c : SolidCore.Solidity.TypeCheck.CheckedContract} (hc : contract? = .ok c) + (deployed : Nat → Nat) : + SolidCore.Spec.Verdict (solidCore fuel) c scopeEvery spec ctxOf step + ((Verdict.hyps c deployed).toAssumptions scopeEvery spec ctxOf step) := + fun fs hfs => (holds_source hc fs hfs).mono fun _ h => h.1 + +/-! ## The headline -/ + +/-- The spec export names the bytecode the certificate binds. -/ +theorem export_bound : + SolidCore.Spec.Export.Counter.manifest.bytecodeSha256 = Final.manifest.runtimeSha256 := by + decide +kernel + +/-- **solar-verify's spec of `Counter` holds of solar's deployed bytecode.** solar's runtime +bytecode for the counter milestone is bound to the exporter's manifest (hex and SHA-256, by the +kernel) and to the spec export (the same SHA-256), runs in one frame, agrees with SolidCore's +checked `Counter` on every call of `scopeEvery`, and meets solar-verify's exported spec under +EthLib on every call of `scopeEvery`: any value, any storage, inc's and get's ABI encodings, +short call data, unknown selectors and short arguments. The spec's well-formedness is checked +by the kernel; the verdict and the trusted base are discharged (`verdict`, +`Instances.counter_on`). With it, the source bridge's two end-to-end theorems +(`EndToEnd.inc_spec_bytecode`: solar-verify's checked obligation for `inc`, bound to SolidCore's +run by `inc_triple`; `EndToEnd.get_spec_bytecode`: `get` returns slot 0 and writes nothing), on +the ABI calls of each with no value and any storage. -/ +theorem spec_holds_of_bytecode : + SolidCore.Spec.Export.Counter.manifest.bytecodeSha256 = Final.manifest.runtimeSha256 ∧ + Bound Final.manifest code ∧ FrameLocal code = true ∧ + ∃ c, contract? = .ok c ∧ Agree (solidCore fuel) ethLib c code scopeEvery ∧ + SolidCore.Spec.Holds ethLib code scopeEvery spec ctxOf step ∧ + (∀ call, SolidCore.Verify.VC.stageScope SolidCore.Verify.VC.Counter.fnInc [] call → + ∃ obs, Target.run code call = some obs ∧ SolidCore.Verify.VC.Counter.incPost call obs) ∧ + (∀ call, SolidCore.Verify.VC.stageScope SolidCore.Verify.VC.Counter.fnGet [] call → + ∃ obs, Target.run code call = some obs ∧ SolidCore.Verify.VC.Counter.getPost call obs) := by + obtain ⟨c, hc⟩ := contract_ok + obtain ⟨hb, hf, ha, hh⟩ := Verdict.bytecode_spec_of_verdict hc (b := spec) (ctxOf := ctxOf) + (step := step) (fun _ => 0) SolidCore.Spec.Export.Counter.Counter_wf + (SolidCore.Spec.opaqueInRange_of_none (by decide)) (verdict hc fun _ => 0) + exact ⟨export_bound, hb, hf, c, hc, ha, hh, EndToEnd.inc_spec_bytecode.2.2, + EndToEnd.get_spec_bytecode.2.2⟩ + +/-! ## The negative -/ + +/-- **The spec mutant fails, by a mismatch.** `x == old(x) + d + 1` does not hold of the +bytecode: `inc(1)` from the empty storage succeeds and stores 1, and the mutant asks for 2. -/ +theorem wrong_fails : + ¬ SolidCore.Spec.Holds ethLib code scopeEvery SolidCore.Spec.Export.CounterSpecMut.Counter + ctxOf step := by + intro h + let call : Call := { callOf incSelector [1#256] with storage := [] } + have hs : scopeEvery call := ⟨by decide, Or.inl ⟨1#256, rfl⟩⟩ + let pre : SolidCore.Spec.State := ⟨slotValue [], SolidCore.Spec.Ghost.zero, 0⟩ + have hne : SolidCore.Spec.Export.CounterSpecMut.Counter.spec.specs ≠ [] := by + simp [SolidCore.Spec.Export.CounterSpecMut.Counter] + have hfs := List.head_mem hne + have hpre : SolidCore.Spec.Pre SolidCore.Spec.Export.CounterSpecMut.Counter + (SolidCore.Spec.Export.CounterSpecMut.Counter.spec.specs.head hne) (ctxOf call) pre call [1] := by + refine ⟨⟨?_, ?_, ?_⟩, rfl, by simp [pre, ctxOf], ?_, ?_⟩ + · have := size_callOf 1#256 + simp only [call] at this ⊢ + omega + · show SolidCore.Spec.selectorOf call = _ + have := spec_selectorOf_append incSelector (by decide) (wordsBytes [1#256]) 0 [] + rw [← calldata_inc] at this + simpa [SolidCore.Spec.Export.CounterSpecMut.Counter, incSelector] using this + · show SolidCore.Spec.decodeWords _ (SolidCore.Spec.words + (((callOf incSelector [1#256]).calldata.data.toList.map (·.toNat)).drop 4)) = _ + rw [words_inc] + simp [SolidCore.Spec.Export.CounterSpecMut.Counter, SolidCore.Spec.decodeWords, + SolidCore.Spec.Ty.ofWord, bind, pure] + · simp [SolidCore.Spec.Bundle.satAll, SolidCore.Spec.Export.CounterSpecMut.Counter] + · simp [SolidCore.Spec.Bundle.satAll, SolidCore.Spec.Export.CounterSpecMut.Counter] + obtain ⟨obs, hrun, hpost⟩ := h _ hfs call hs [1] pre hpre + rw [Final.target_every call hs] at hrun + cases hrun + have hcall : call = { callOf incSelector [1#256] with storage := [] } := rfl + rw [hcall, expectedEvery_inc] at hpost + have hok : (expectedAt [] 1#256).success = true := by simp [expectedAt, slotValue] + obtain ⟨rets, -, hens, -⟩ := hpost.1 hok + have := hens _ (List.mem_singleton_self _) + simp [SolidCore.Spec.Bundle.sat, SolidCore.Spec.Export.CounterSpecMut.Counter, + SolidCore.Spec.eval, SolidCore.Spec.slotOf, SolidCore.Spec.mkEnv, SolidCore.Spec.Env.cur, + SolidCore.Spec.BinOp.apply, SolidCore.Spec.Ty.ofBits, SolidCore.Spec.toWord, pre, + expectedAt, slotValue] at this + +/-- info: 'SolidCore.Refinement.Solar.Counter.Headline.spec_holds_of_bytecode' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms spec_holds_of_bytecode + +/-- info: 'SolidCore.Refinement.Solar.Counter.Headline.wrong_fails' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms wrong_fails + +end SolidCore.Refinement.Solar.Counter.Headline diff --git a/Contracts/Counter/Spec/Export.lean b/Contracts/Counter/Spec/Export.lean new file mode 100644 index 00000000..7d42da6c --- /dev/null +++ b/Contracts/Counter/Spec/Export.lean @@ -0,0 +1,48 @@ +import Verify.Spec.Contract + +/-! +Specs of `scripts/verify/CounterMilestone.sol`, exported by solar-verify 0.3.0 with `--emit-lean-spec`. +Generated: do not edit. +-/ + +namespace SolidCore.Spec.Export.Counter + +open SolidCore.Spec + +/-- What the specs were exported from and are about. -/ +def manifest : Manifest := + { source := "scripts/verify/CounterMilestone.sol", + sourceSha256 := "6ed83fe1a6c41fb109c6a880ed372b37ca1d895b9bde4bb5f202461289706da9", + compiler := "0.8.38+commit.1134e61f.solar.0.3.0-dev", + options := [], + bytecodeSha256 := "daed21b0c790bb2c08bcf999c9ebc6fea950c213ea0a799418552aa14c18f6ec" } + +/-- The specs of `Counter`. -/ +def Counter : Bundle where + fuel := 0 + spec := + { name := "Counter", + fns := [ + ], + invariants := [ + ], + ghosts := [], + specs := [ + { name := "Counter.inc", + selector := 0x812600df, + params := [(.uint 256)], + rets := [], + payable := false, + requires := [], + ensures := [ + (.bin .eq (.load (.slot 0) (.lit 0) 32 (.uint 256)) (.bin .add (.old (.load (.slot 0) (.lit 0) 32 (.uint 256))) (.arg 0)))], + succeedsIf := [] }] } + +/-- Every spec function call resolves and nests within the fuel. -/ +theorem Counter_wf : Counter.WF = true := by decide +kernel + +/-- Trusted-base items these specs' proofs rely on beyond the verdict +(`SolidCore.Spec.Assumptions`). -/ +def trusted : List String := [] + +end SolidCore.Spec.Export.Counter diff --git a/Contracts/Counter/Spec/ExportWrong.lean b/Contracts/Counter/Spec/ExportWrong.lean new file mode 100644 index 00000000..0988b34e --- /dev/null +++ b/Contracts/Counter/Spec/ExportWrong.lean @@ -0,0 +1,48 @@ +import Verify.Spec.Contract + +/-! +Specs of `scripts/verify/mutant/CounterSpecMut.sol`, exported by solar-verify 0.3.0 with `--emit-lean-spec`. +Generated: do not edit. +-/ + +namespace SolidCore.Spec.Export.CounterSpecMut + +open SolidCore.Spec + +/-- What the specs were exported from and are about. -/ +def manifest : Manifest := + { source := "scripts/verify/mutant/CounterSpecMut.sol", + sourceSha256 := "afaec6975bea758e12835d06dafce1c218409d260471a7a039df235b1e91b224", + compiler := "0.8.38+commit.1134e61f.solar.0.3.0-dev", + options := [], + bytecodeSha256 := "daed21b0c790bb2c08bcf999c9ebc6fea950c213ea0a799418552aa14c18f6ec" } + +/-- The specs of `Counter`. -/ +def Counter : Bundle where + fuel := 0 + spec := + { name := "Counter", + fns := [ + ], + invariants := [ + ], + ghosts := [], + specs := [ + { name := "Counter.inc", + selector := 0x812600df, + params := [(.uint 256)], + rets := [], + payable := false, + requires := [], + ensures := [ + (.bin .eq (.load (.slot 0) (.lit 0) 32 (.uint 256)) (.bin .add (.bin .add (.old (.load (.slot 0) (.lit 0) 32 (.uint 256))) (.arg 0)) (.lit 1)))], + succeedsIf := [] }] } + +/-- Every spec function call resolves and nests within the fuel. -/ +theorem Counter_wf : Counter.WF = true := by decide +kernel + +/-- Trusted-base items these specs' proofs rely on beyond the verdict +(`SolidCore.Spec.Assumptions`). -/ +def trusted : List String := [] + +end SolidCore.Spec.Export.CounterSpecMut diff --git a/Contracts/Counter/VC/Bind.lean b/Contracts/Counter/VC/Bind.lean new file mode 100644 index 00000000..16f15956 --- /dev/null +++ b/Contracts/Counter/VC/Bind.lean @@ -0,0 +1,17 @@ +import Contracts.Counter.VC.Export +import Contracts.Counter.VC.ExportMilestone + +/-! +# The exported scripts are solar-verify's transcripts + +Each exported `script` prints back to its `transcript`, the bytes solar-verify wrote with +`--dump-smt` in the same run. The check runs Lean's evaluator: the kernel's evaluation of the +printer on a transcript of 20 KB, with its 78-digit numerals, does not fit in this build's memory. +-/ + +namespace SolidCore.Verify.VC + +#guard printScript Export.Counter.script == Export.Counter.transcript +#guard printScript Export.CounterMilestone.script == Export.CounterMilestone.transcript + +end SolidCore.Verify.VC diff --git a/Contracts/Counter/VC/Export.lean b/Contracts/Counter/VC/Export.lean new file mode 100644 index 00000000..4c5aa64c --- /dev/null +++ b/Contracts/Counter/VC/Export.lean @@ -0,0 +1,331 @@ +-- Generated by solar-verify --dump-lean. Do not edit. + +import Verify.VC.Term + +namespace SolidCore.Verify.VC.Export.Counter + +open SolidCore.Verify.VC + +/-- The commands solar-verify sent the solver. -/ +def script : List Cmd := [ + .push, + .raw "; ===== Counter.constructor", + .decl "this@1" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "this@1")]), (.app "<=" [(.ivar "this@1"), (.num 1461501637330902918203684832716283019655932542975)])]), + .decl "msg.sender@2" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "msg.sender@2")]), (.app "<=" [(.ivar "msg.sender@2"), (.num 1461501637330902918203684832716283019655932542975)])]), + .assert (.app "not" [(.app "=" [(.ivar "msg.sender@2"), (.num 0)])]), + .decl "msg.value@3" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "msg.value@3")]), (.app "<=" [(.ivar "msg.value@3"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.timestamp@4" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.timestamp@4")]), (.app "<=" [(.ivar "block.timestamp@4"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.number@5" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.number@5")]), (.app "<=" [(.ivar "block.number@5"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.chainid@6" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.chainid@6")]), (.app "<=" [(.ivar "block.chainid@6"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "tx.origin@7" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "tx.origin@7")]), (.app "<=" [(.ivar "tx.origin@7"), (.num 1461501637330902918203684832716283019655932542975)])]), + .decl "tx.gasprice@8" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "tx.gasprice@8")]), (.app "<=" [(.ivar "tx.gasprice@8"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "msg.sig@9" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "msg.sig@9")]), (.app "<=" [(.ivar "msg.sig@9"), (.num 4294967295)])]), + .decl "msg.data@10" .int, + .decl "block.basefee@11" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.basefee@11")]), (.app "<=" [(.ivar "block.basefee@11"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.blobbasefee@12" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.blobbasefee@12")]), (.app "<=" [(.ivar "block.blobbasefee@12"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.coinbase@13" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.coinbase@13")]), (.app "<=" [(.ivar "block.coinbase@13"), (.num 1461501637330902918203684832716283019655932542975)])]), + .decl "block.prevrandao@14" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.prevrandao@14")]), (.app "<=" [(.ivar "block.prevrandao@14"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.difficulty@15" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.difficulty@15")]), (.app "<=" [(.ivar "block.difficulty@15"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.gaslimit@16" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.gaslimit@16")]), (.app "<=" [(.ivar "block.gaslimit@16"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "__balance@17" .arr, + .elem "__balance@17" 0 115792089237316195423570985008687907853269984665640564039457584007913129639935, + .decl "__code_epoch@18" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "__code_epoch@18")]), (.app "<=" [(.ivar "__code_epoch@18"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "_limit@19" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "_limit@19")]), (.app "<=" [(.ivar "_limit@19"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "g@20" .bool, + .assert (.app "=" [(.bvar "g@20"), (.app "and" [.tt, (.app "=" [(.ivar "msg.value@3"), (.num 0)])])]), + .push, + .assert (.bvar "g@20"), + .assert (.app "not" [.ff]), + .checkSat, + .pop, + .push, + .assert (.bvar "g@20"), + .assert (.app "not" [(.app "and" [(.app "=" [(.ivar "_limit@19"), (.ivar "_limit@19")]), (.app "=" [(.num 0), (.num 0)])])]), + .checkSat, + .pop, + .push, + .assert (.bvar "g@20"), + .assert (.app "not" [(.app "<=" [(.num 0), (.ivar "_limit@19")])]), + .checkSat, + .pop, + .pop, + .push, + .raw "; ===== Counter.increment", + .decl "this@1" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "this@1")]), (.app "<=" [(.ivar "this@1"), (.num 1461501637330902918203684832716283019655932542975)])]), + .decl "msg.sender@2" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "msg.sender@2")]), (.app "<=" [(.ivar "msg.sender@2"), (.num 1461501637330902918203684832716283019655932542975)])]), + .assert (.app "not" [(.app "=" [(.ivar "msg.sender@2"), (.num 0)])]), + .decl "msg.value@3" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "msg.value@3")]), (.app "<=" [(.ivar "msg.value@3"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.timestamp@4" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.timestamp@4")]), (.app "<=" [(.ivar "block.timestamp@4"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.number@5" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.number@5")]), (.app "<=" [(.ivar "block.number@5"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.chainid@6" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.chainid@6")]), (.app "<=" [(.ivar "block.chainid@6"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "tx.origin@7" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "tx.origin@7")]), (.app "<=" [(.ivar "tx.origin@7"), (.num 1461501637330902918203684832716283019655932542975)])]), + .decl "tx.gasprice@8" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "tx.gasprice@8")]), (.app "<=" [(.ivar "tx.gasprice@8"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "msg.sig@9" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "msg.sig@9")]), (.app "<=" [(.ivar "msg.sig@9"), (.num 4294967295)])]), + .decl "msg.data@10" .int, + .decl "block.basefee@11" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.basefee@11")]), (.app "<=" [(.ivar "block.basefee@11"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.blobbasefee@12" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.blobbasefee@12")]), (.app "<=" [(.ivar "block.blobbasefee@12"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.coinbase@13" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.coinbase@13")]), (.app "<=" [(.ivar "block.coinbase@13"), (.num 1461501637330902918203684832716283019655932542975)])]), + .decl "block.prevrandao@14" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.prevrandao@14")]), (.app "<=" [(.ivar "block.prevrandao@14"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.difficulty@15" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.difficulty@15")]), (.app "<=" [(.ivar "block.difficulty@15"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.gaslimit@16" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.gaslimit@16")]), (.app "<=" [(.ivar "block.gaslimit@16"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "count@17" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "count@17")]), (.app "<=" [(.ivar "count@17"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "limit@18" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "limit@18")]), (.app "<=" [(.ivar "limit@18"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "__balance@19" .arr, + .elem "__balance@19" 0 115792089237316195423570985008687907853269984665640564039457584007913129639935, + .decl "__code_epoch@20" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "__code_epoch@20")]), (.app "<=" [(.ivar "__code_epoch@20"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "g@21" .bool, + .assert (.app "=" [(.bvar "g@21"), (.app "and" [.tt, (.app "<=" [(.ivar "count@17"), (.ivar "limit@18")])])]), + .decl "g@22" .bool, + .assert (.app "=" [(.bvar "g@22"), (.app "and" [(.bvar "g@21"), (.app "<" [(.ivar "count@17"), (.ivar "limit@18")])])]), + .decl "g@23" .bool, + .assert (.app "=" [(.bvar "g@23"), (.app "and" [(.bvar "g@22"), (.app "=" [(.ivar "msg.value@3"), (.num 0)])])]), + .decl "arith@24" .int, + .assert (.app "=" [(.ivar "arith@24"), (.app "+" [(.ivar "count@17"), (.num 1)])]), + .decl "g@25" .bool, + .assert (.app "=" [(.bvar "g@25"), (.app "and" [(.bvar "g@23"), (.app "and" [(.app "<=" [(.num 0), (.ivar "arith@24")]), (.app "<=" [(.ivar "arith@24"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])])])]), + .push, + .assert (.bvar "g@25"), + .assert (.app "not" [.ff]), + .checkSat, + .pop, + .push, + .assert (.bvar "g@25"), + .assert (.app "not" [(.app "=" [(.ivar "arith@24"), (.app "+" [(.ivar "count@17"), (.num 1)])])]), + .checkSat, + .pop, + .push, + .assert (.bvar "g@25"), + .assert (.app "not" [(.app "<=" [(.ivar "arith@24"), (.ivar "limit@18")])]), + .checkSat, + .pop, + .pop, + .push, + .raw "; ===== Counter.bump", + .decl "this@1" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "this@1")]), (.app "<=" [(.ivar "this@1"), (.num 1461501637330902918203684832716283019655932542975)])]), + .decl "msg.sender@2" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "msg.sender@2")]), (.app "<=" [(.ivar "msg.sender@2"), (.num 1461501637330902918203684832716283019655932542975)])]), + .assert (.app "not" [(.app "=" [(.ivar "msg.sender@2"), (.num 0)])]), + .decl "msg.value@3" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "msg.value@3")]), (.app "<=" [(.ivar "msg.value@3"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.timestamp@4" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.timestamp@4")]), (.app "<=" [(.ivar "block.timestamp@4"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.number@5" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.number@5")]), (.app "<=" [(.ivar "block.number@5"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.chainid@6" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.chainid@6")]), (.app "<=" [(.ivar "block.chainid@6"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "tx.origin@7" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "tx.origin@7")]), (.app "<=" [(.ivar "tx.origin@7"), (.num 1461501637330902918203684832716283019655932542975)])]), + .decl "tx.gasprice@8" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "tx.gasprice@8")]), (.app "<=" [(.ivar "tx.gasprice@8"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "msg.sig@9" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "msg.sig@9")]), (.app "<=" [(.ivar "msg.sig@9"), (.num 4294967295)])]), + .decl "msg.data@10" .int, + .decl "block.basefee@11" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.basefee@11")]), (.app "<=" [(.ivar "block.basefee@11"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.blobbasefee@12" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.blobbasefee@12")]), (.app "<=" [(.ivar "block.blobbasefee@12"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.coinbase@13" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.coinbase@13")]), (.app "<=" [(.ivar "block.coinbase@13"), (.num 1461501637330902918203684832716283019655932542975)])]), + .decl "block.prevrandao@14" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.prevrandao@14")]), (.app "<=" [(.ivar "block.prevrandao@14"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.difficulty@15" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.difficulty@15")]), (.app "<=" [(.ivar "block.difficulty@15"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.gaslimit@16" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.gaslimit@16")]), (.app "<=" [(.ivar "block.gaslimit@16"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "count@17" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "count@17")]), (.app "<=" [(.ivar "count@17"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "limit@18" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "limit@18")]), (.app "<=" [(.ivar "limit@18"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "__balance@19" .arr, + .elem "__balance@19" 0 115792089237316195423570985008687907853269984665640564039457584007913129639935, + .decl "__code_epoch@20" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "__code_epoch@20")]), (.app "<=" [(.ivar "__code_epoch@20"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "n@21" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "n@21")]), (.app "<=" [(.ivar "n@21"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "g@22" .bool, + .assert (.app "=" [(.bvar "g@22"), (.app "and" [.tt, (.app "<=" [(.ivar "count@17"), (.ivar "limit@18")])])]), + .decl "g@23" .bool, + .assert (.app "=" [(.bvar "g@23"), (.app "and" [(.bvar "g@22"), (.app "=" [(.ivar "msg.value@3"), (.num 0)])])]), + .decl "arith@24" .int, + .assert (.app "=" [(.ivar "arith@24"), (.app "+" [(.ivar "count@17"), (.ivar "n@21")])]), + .decl "g@25" .bool, + .assert (.app "=" [(.bvar "g@25"), (.app "and" [(.bvar "g@23"), (.app "and" [(.app "<=" [(.num 0), (.ivar "arith@24")]), (.app "<=" [(.ivar "arith@24"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])])])]), + .decl "g@26" .bool, + .assert (.app "=" [(.bvar "g@26"), (.app "and" [(.bvar "g@25"), (.app "<=" [(.ivar "arith@24"), (.ivar "limit@18")])])]), + .push, + .assert (.bvar "g@26"), + .assert (.app "not" [(.app "<=" [(.num 0), (.ivar "n@21")])]), + .checkSat, + .pop, + .push, + .assert (.bvar "g@26"), + .assert (.app "not" [(.app "=" [(.ivar "count@17"), (.app "+" [(.ivar "count@17"), (.num 0)])])]), + .checkSat, + .pop, + .decl "count@27" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "count@27")]), (.app "<=" [(.ivar "count@27"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "i@28" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "i@28")]), (.app "<=" [(.ivar "i@28"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "g@29" .bool, + .assert (.app "=" [(.bvar "g@29"), (.app "and" [(.bvar "g@26"), (.app "<=" [(.ivar "i@28"), (.ivar "n@21")])])]), + .decl "g@30" .bool, + .assert (.app "=" [(.bvar "g@30"), (.app "and" [(.bvar "g@29"), (.app "=" [(.ivar "count@27"), (.app "+" [(.ivar "count@17"), (.ivar "i@28")])])])]), + .decl "g@31" .bool, + .assert (.app "=" [(.bvar "g@31"), (.app "and" [(.bvar "g@30"), (.app "<" [(.ivar "i@28"), (.ivar "n@21")])])]), + .decl "arith@32" .int, + .assert (.app "=" [(.ivar "arith@32"), (.app "+" [(.ivar "count@27"), (.num 1)])]), + .decl "g@33" .bool, + .assert (.app "=" [(.bvar "g@33"), (.app "and" [(.bvar "g@31"), (.app "and" [(.app "<=" [(.num 0), (.ivar "arith@32")]), (.app "<=" [(.ivar "arith@32"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])])])]), + .decl "arith@34" .int, + .assert (.app "=" [(.ivar "arith@34"), (.app "+" [(.ivar "i@28"), (.num 1)])]), + .decl "g@35" .bool, + .assert (.app "=" [(.bvar "g@35"), (.app "and" [(.bvar "g@33"), (.app "and" [(.app "<=" [(.num 0), (.ivar "arith@34")]), (.app "<=" [(.ivar "arith@34"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])])])]), + .push, + .assert (.bvar "g@35"), + .assert (.app "not" [(.app "<=" [(.ivar "arith@34"), (.ivar "n@21")])]), + .checkSat, + .pop, + .push, + .assert (.bvar "g@35"), + .assert (.app "not" [(.app "=" [(.ivar "arith@32"), (.app "+" [(.ivar "count@17"), (.ivar "arith@34")])])]), + .checkSat, + .pop, + .push, + .assert (.bvar "g@35"), + .assert (.app "not" [(.app "and" [(.app "<=" [(.num 0), (.app "-" [(.ivar "n@21"), (.ivar "i@28")])]), (.app "<" [(.app "-" [(.ivar "n@21"), (.ivar "arith@34")]), (.app "-" [(.ivar "n@21"), (.ivar "i@28")])])])]), + .checkSat, + .pop, + .decl "g@36" .bool, + .assert (.app "=" [(.bvar "g@36"), (.app "and" [(.bvar "g@30"), (.app "not" [(.app "<" [(.ivar "i@28"), (.ivar "n@21")])])])]), + .push, + .assert (.bvar "g@36"), + .assert (.app "not" [.ff]), + .checkSat, + .pop, + .push, + .assert (.bvar "g@36"), + .assert (.app "not" [(.app "=" [(.ivar "count@27"), (.app "+" [(.ivar "count@17"), (.ivar "n@21")])])]), + .checkSat, + .pop, + .push, + .assert (.bvar "g@36"), + .assert (.app "not" [(.app "<=" [(.ivar "count@27"), (.ivar "limit@18")])]), + .checkSat, + .pop, + .pop, + .push, + .raw "; ===== Counter.max", + .decl "this@1" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "this@1")]), (.app "<=" [(.ivar "this@1"), (.num 1461501637330902918203684832716283019655932542975)])]), + .decl "msg.sender@2" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "msg.sender@2")]), (.app "<=" [(.ivar "msg.sender@2"), (.num 1461501637330902918203684832716283019655932542975)])]), + .assert (.app "not" [(.app "=" [(.ivar "msg.sender@2"), (.num 0)])]), + .decl "msg.value@3" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "msg.value@3")]), (.app "<=" [(.ivar "msg.value@3"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.timestamp@4" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.timestamp@4")]), (.app "<=" [(.ivar "block.timestamp@4"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.number@5" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.number@5")]), (.app "<=" [(.ivar "block.number@5"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.chainid@6" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.chainid@6")]), (.app "<=" [(.ivar "block.chainid@6"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "tx.origin@7" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "tx.origin@7")]), (.app "<=" [(.ivar "tx.origin@7"), (.num 1461501637330902918203684832716283019655932542975)])]), + .decl "tx.gasprice@8" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "tx.gasprice@8")]), (.app "<=" [(.ivar "tx.gasprice@8"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "msg.sig@9" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "msg.sig@9")]), (.app "<=" [(.ivar "msg.sig@9"), (.num 4294967295)])]), + .decl "msg.data@10" .int, + .decl "block.basefee@11" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.basefee@11")]), (.app "<=" [(.ivar "block.basefee@11"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.blobbasefee@12" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.blobbasefee@12")]), (.app "<=" [(.ivar "block.blobbasefee@12"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.coinbase@13" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.coinbase@13")]), (.app "<=" [(.ivar "block.coinbase@13"), (.num 1461501637330902918203684832716283019655932542975)])]), + .decl "block.prevrandao@14" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.prevrandao@14")]), (.app "<=" [(.ivar "block.prevrandao@14"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.difficulty@15" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.difficulty@15")]), (.app "<=" [(.ivar "block.difficulty@15"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.gaslimit@16" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.gaslimit@16")]), (.app "<=" [(.ivar "block.gaslimit@16"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "count@17" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "count@17")]), (.app "<=" [(.ivar "count@17"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "limit@18" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "limit@18")]), (.app "<=" [(.ivar "limit@18"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "__balance@19" .arr, + .elem "__balance@19" 0 115792089237316195423570985008687907853269984665640564039457584007913129639935, + .decl "__code_epoch@20" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "__code_epoch@20")]), (.app "<=" [(.ivar "__code_epoch@20"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "a@21" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "a@21")]), (.app "<=" [(.ivar "a@21"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "b@22" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "b@22")]), (.app "<=" [(.ivar "b@22"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "g@23" .bool, + .assert (.app "=" [(.bvar "g@23"), (.app "and" [.tt, (.app "<=" [(.ivar "count@17"), (.ivar "limit@18")])])]), + .decl "g@24" .bool, + .assert (.app "=" [(.bvar "g@24"), (.app "and" [(.bvar "g@23"), (.app "=" [(.ivar "msg.value@3"), (.num 0)])])]), + .decl "g@25" .bool, + .assert (.app "=" [(.bvar "g@25"), (.app "and" [(.bvar "g@24"), (.app ">=" [(.ivar "a@21"), (.ivar "b@22")])])]), + .decl "g@26" .bool, + .assert (.app "=" [(.bvar "g@26"), (.app "and" [(.bvar "g@24"), (.app "not" [(.app ">=" [(.ivar "a@21"), (.ivar "b@22")])])])]), + .decl "g@27" .bool, + .assert (.app "=" [(.bvar "g@27"), (.app "or" [(.bvar "g@25"), (.bvar "g@26")])]), + .decl "__ret0@28" .int, + .assert (.app "=" [(.ivar "__ret0@28"), (.app "ite" [(.bvar "g@25"), (.ivar "a@21"), (.ivar "b@22")])]), + .push, + .assert (.bvar "g@27"), + .assert (.app "not" [.ff]), + .checkSat, + .pop, + .push, + .assert (.bvar "g@27"), + .assert (.app "not" [(.app "=" [(.ivar "__ret0@28"), (.app "ite" [(.app ">=" [(.ivar "a@21"), (.ivar "b@22")]), (.ivar "a@21"), (.ivar "b@22")])])]), + .checkSat, + .pop, + .push, + .assert (.bvar "g@27"), + .assert (.app "not" [(.app "and" [(.app ">=" [(.ivar "__ret0@28"), (.ivar "a@21")]), (.app ">=" [(.ivar "__ret0@28"), (.ivar "b@22")])])]), + .checkSat, + .pop, + .pop +] + +/-- The transcript, as solar-verify wrote it. -/ +def transcript : String := "(push 1)\n; ===== Counter.constructor\n(declare-const |this@1| Int)\n(assert (and (<= 0 |this@1|) (<= |this@1| 1461501637330902918203684832716283019655932542975)))\n(declare-const |msg.sender@2| Int)\n(assert (and (<= 0 |msg.sender@2|) (<= |msg.sender@2| 1461501637330902918203684832716283019655932542975)))\n(assert (not (= |msg.sender@2| 0)))\n(declare-const |msg.value@3| Int)\n(assert (and (<= 0 |msg.value@3|) (<= |msg.value@3| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.timestamp@4| Int)\n(assert (and (<= 0 |block.timestamp@4|) (<= |block.timestamp@4| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.number@5| Int)\n(assert (and (<= 0 |block.number@5|) (<= |block.number@5| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.chainid@6| Int)\n(assert (and (<= 0 |block.chainid@6|) (<= |block.chainid@6| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |tx.origin@7| Int)\n(assert (and (<= 0 |tx.origin@7|) (<= |tx.origin@7| 1461501637330902918203684832716283019655932542975)))\n(declare-const |tx.gasprice@8| Int)\n(assert (and (<= 0 |tx.gasprice@8|) (<= |tx.gasprice@8| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |msg.sig@9| Int)\n(assert (and (<= 0 |msg.sig@9|) (<= |msg.sig@9| 4294967295)))\n(declare-const |msg.data@10| Int)\n(declare-const |block.basefee@11| Int)\n(assert (and (<= 0 |block.basefee@11|) (<= |block.basefee@11| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.blobbasefee@12| Int)\n(assert (and (<= 0 |block.blobbasefee@12|) (<= |block.blobbasefee@12| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.coinbase@13| Int)\n(assert (and (<= 0 |block.coinbase@13|) (<= |block.coinbase@13| 1461501637330902918203684832716283019655932542975)))\n(declare-const |block.prevrandao@14| Int)\n(assert (and (<= 0 |block.prevrandao@14|) (<= |block.prevrandao@14| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.difficulty@15| Int)\n(assert (and (<= 0 |block.difficulty@15|) (<= |block.difficulty@15| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.gaslimit@16| Int)\n(assert (and (<= 0 |block.gaslimit@16|) (<= |block.gaslimit@16| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |__balance@17| (Array Int Int))\n;@elem |__balance@17| 0 115792089237316195423570985008687907853269984665640564039457584007913129639935\n(declare-const |__code_epoch@18| Int)\n(assert (and (<= 0 |__code_epoch@18|) (<= |__code_epoch@18| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |_limit@19| Int)\n(assert (and (<= 0 |_limit@19|) (<= |_limit@19| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |g@20| Bool)\n(assert (= |g@20| (and true (= |msg.value@3| 0))))\n(push 1)\n(assert |g@20|)\n(assert (not false))\n(check-sat)\n(pop 1)\n(push 1)\n(assert |g@20|)\n(assert (not (and (= |_limit@19| |_limit@19|) (= 0 0))))\n(check-sat)\n(pop 1)\n(push 1)\n(assert |g@20|)\n(assert (not (<= 0 |_limit@19|)))\n(check-sat)\n(pop 1)\n(pop 1)\n(push 1)\n; ===== Counter.increment\n(declare-const |this@1| Int)\n(assert (and (<= 0 |this@1|) (<= |this@1| 1461501637330902918203684832716283019655932542975)))\n(declare-const |msg.sender@2| Int)\n(assert (and (<= 0 |msg.sender@2|) (<= |msg.sender@2| 1461501637330902918203684832716283019655932542975)))\n(assert (not (= |msg.sender@2| 0)))\n(declare-const |msg.value@3| Int)\n(assert (and (<= 0 |msg.value@3|) (<= |msg.value@3| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.timestamp@4| Int)\n(assert (and (<= 0 |block.timestamp@4|) (<= |block.timestamp@4| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.number@5| Int)\n(assert (and (<= 0 |block.number@5|) (<= |block.number@5| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.chainid@6| Int)\n(assert (and (<= 0 |block.chainid@6|) (<= |block.chainid@6| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |tx.origin@7| Int)\n(assert (and (<= 0 |tx.origin@7|) (<= |tx.origin@7| 1461501637330902918203684832716283019655932542975)))\n(declare-const |tx.gasprice@8| Int)\n(assert (and (<= 0 |tx.gasprice@8|) (<= |tx.gasprice@8| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |msg.sig@9| Int)\n(assert (and (<= 0 |msg.sig@9|) (<= |msg.sig@9| 4294967295)))\n(declare-const |msg.data@10| Int)\n(declare-const |block.basefee@11| Int)\n(assert (and (<= 0 |block.basefee@11|) (<= |block.basefee@11| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.blobbasefee@12| Int)\n(assert (and (<= 0 |block.blobbasefee@12|) (<= |block.blobbasefee@12| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.coinbase@13| Int)\n(assert (and (<= 0 |block.coinbase@13|) (<= |block.coinbase@13| 1461501637330902918203684832716283019655932542975)))\n(declare-const |block.prevrandao@14| Int)\n(assert (and (<= 0 |block.prevrandao@14|) (<= |block.prevrandao@14| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.difficulty@15| Int)\n(assert (and (<= 0 |block.difficulty@15|) (<= |block.difficulty@15| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.gaslimit@16| Int)\n(assert (and (<= 0 |block.gaslimit@16|) (<= |block.gaslimit@16| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |count@17| Int)\n(assert (and (<= 0 |count@17|) (<= |count@17| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |limit@18| Int)\n(assert (and (<= 0 |limit@18|) (<= |limit@18| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |__balance@19| (Array Int Int))\n;@elem |__balance@19| 0 115792089237316195423570985008687907853269984665640564039457584007913129639935\n(declare-const |__code_epoch@20| Int)\n(assert (and (<= 0 |__code_epoch@20|) (<= |__code_epoch@20| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |g@21| Bool)\n(assert (= |g@21| (and true (<= |count@17| |limit@18|))))\n(declare-const |g@22| Bool)\n(assert (= |g@22| (and |g@21| (< |count@17| |limit@18|))))\n(declare-const |g@23| Bool)\n(assert (= |g@23| (and |g@22| (= |msg.value@3| 0))))\n(declare-const |arith@24| Int)\n(assert (= |arith@24| (+ |count@17| 1)))\n(declare-const |g@25| Bool)\n(assert (= |g@25| (and |g@23| (and (<= 0 |arith@24|) (<= |arith@24| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))))\n(push 1)\n(assert |g@25|)\n(assert (not false))\n(check-sat)\n(pop 1)\n(push 1)\n(assert |g@25|)\n(assert (not (= |arith@24| (+ |count@17| 1))))\n(check-sat)\n(pop 1)\n(push 1)\n(assert |g@25|)\n(assert (not (<= |arith@24| |limit@18|)))\n(check-sat)\n(pop 1)\n(pop 1)\n(push 1)\n; ===== Counter.bump\n(declare-const |this@1| Int)\n(assert (and (<= 0 |this@1|) (<= |this@1| 1461501637330902918203684832716283019655932542975)))\n(declare-const |msg.sender@2| Int)\n(assert (and (<= 0 |msg.sender@2|) (<= |msg.sender@2| 1461501637330902918203684832716283019655932542975)))\n(assert (not (= |msg.sender@2| 0)))\n(declare-const |msg.value@3| Int)\n(assert (and (<= 0 |msg.value@3|) (<= |msg.value@3| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.timestamp@4| Int)\n(assert (and (<= 0 |block.timestamp@4|) (<= |block.timestamp@4| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.number@5| Int)\n(assert (and (<= 0 |block.number@5|) (<= |block.number@5| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.chainid@6| Int)\n(assert (and (<= 0 |block.chainid@6|) (<= |block.chainid@6| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |tx.origin@7| Int)\n(assert (and (<= 0 |tx.origin@7|) (<= |tx.origin@7| 1461501637330902918203684832716283019655932542975)))\n(declare-const |tx.gasprice@8| Int)\n(assert (and (<= 0 |tx.gasprice@8|) (<= |tx.gasprice@8| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |msg.sig@9| Int)\n(assert (and (<= 0 |msg.sig@9|) (<= |msg.sig@9| 4294967295)))\n(declare-const |msg.data@10| Int)\n(declare-const |block.basefee@11| Int)\n(assert (and (<= 0 |block.basefee@11|) (<= |block.basefee@11| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.blobbasefee@12| Int)\n(assert (and (<= 0 |block.blobbasefee@12|) (<= |block.blobbasefee@12| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.coinbase@13| Int)\n(assert (and (<= 0 |block.coinbase@13|) (<= |block.coinbase@13| 1461501637330902918203684832716283019655932542975)))\n(declare-const |block.prevrandao@14| Int)\n(assert (and (<= 0 |block.prevrandao@14|) (<= |block.prevrandao@14| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.difficulty@15| Int)\n(assert (and (<= 0 |block.difficulty@15|) (<= |block.difficulty@15| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.gaslimit@16| Int)\n(assert (and (<= 0 |block.gaslimit@16|) (<= |block.gaslimit@16| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |count@17| Int)\n(assert (and (<= 0 |count@17|) (<= |count@17| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |limit@18| Int)\n(assert (and (<= 0 |limit@18|) (<= |limit@18| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |__balance@19| (Array Int Int))\n;@elem |__balance@19| 0 115792089237316195423570985008687907853269984665640564039457584007913129639935\n(declare-const |__code_epoch@20| Int)\n(assert (and (<= 0 |__code_epoch@20|) (<= |__code_epoch@20| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |n@21| Int)\n(assert (and (<= 0 |n@21|) (<= |n@21| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |g@22| Bool)\n(assert (= |g@22| (and true (<= |count@17| |limit@18|))))\n(declare-const |g@23| Bool)\n(assert (= |g@23| (and |g@22| (= |msg.value@3| 0))))\n(declare-const |arith@24| Int)\n(assert (= |arith@24| (+ |count@17| |n@21|)))\n(declare-const |g@25| Bool)\n(assert (= |g@25| (and |g@23| (and (<= 0 |arith@24|) (<= |arith@24| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))))\n(declare-const |g@26| Bool)\n(assert (= |g@26| (and |g@25| (<= |arith@24| |limit@18|))))\n(push 1)\n(assert |g@26|)\n(assert (not (<= 0 |n@21|)))\n(check-sat)\n(pop 1)\n(push 1)\n(assert |g@26|)\n(assert (not (= |count@17| (+ |count@17| 0))))\n(check-sat)\n(pop 1)\n(declare-const |count@27| Int)\n(assert (and (<= 0 |count@27|) (<= |count@27| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |i@28| Int)\n(assert (and (<= 0 |i@28|) (<= |i@28| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |g@29| Bool)\n(assert (= |g@29| (and |g@26| (<= |i@28| |n@21|))))\n(declare-const |g@30| Bool)\n(assert (= |g@30| (and |g@29| (= |count@27| (+ |count@17| |i@28|)))))\n(declare-const |g@31| Bool)\n(assert (= |g@31| (and |g@30| (< |i@28| |n@21|))))\n(declare-const |arith@32| Int)\n(assert (= |arith@32| (+ |count@27| 1)))\n(declare-const |g@33| Bool)\n(assert (= |g@33| (and |g@31| (and (<= 0 |arith@32|) (<= |arith@32| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))))\n(declare-const |arith@34| Int)\n(assert (= |arith@34| (+ |i@28| 1)))\n(declare-const |g@35| Bool)\n(assert (= |g@35| (and |g@33| (and (<= 0 |arith@34|) (<= |arith@34| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))))\n(push 1)\n(assert |g@35|)\n(assert (not (<= |arith@34| |n@21|)))\n(check-sat)\n(pop 1)\n(push 1)\n(assert |g@35|)\n(assert (not (= |arith@32| (+ |count@17| |arith@34|))))\n(check-sat)\n(pop 1)\n(push 1)\n(assert |g@35|)\n(assert (not (and (<= 0 (- |n@21| |i@28|)) (< (- |n@21| |arith@34|) (- |n@21| |i@28|)))))\n(check-sat)\n(pop 1)\n(declare-const |g@36| Bool)\n(assert (= |g@36| (and |g@30| (not (< |i@28| |n@21|)))))\n(push 1)\n(assert |g@36|)\n(assert (not false))\n(check-sat)\n(pop 1)\n(push 1)\n(assert |g@36|)\n(assert (not (= |count@27| (+ |count@17| |n@21|))))\n(check-sat)\n(pop 1)\n(push 1)\n(assert |g@36|)\n(assert (not (<= |count@27| |limit@18|)))\n(check-sat)\n(pop 1)\n(pop 1)\n(push 1)\n; ===== Counter.max\n(declare-const |this@1| Int)\n(assert (and (<= 0 |this@1|) (<= |this@1| 1461501637330902918203684832716283019655932542975)))\n(declare-const |msg.sender@2| Int)\n(assert (and (<= 0 |msg.sender@2|) (<= |msg.sender@2| 1461501637330902918203684832716283019655932542975)))\n(assert (not (= |msg.sender@2| 0)))\n(declare-const |msg.value@3| Int)\n(assert (and (<= 0 |msg.value@3|) (<= |msg.value@3| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.timestamp@4| Int)\n(assert (and (<= 0 |block.timestamp@4|) (<= |block.timestamp@4| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.number@5| Int)\n(assert (and (<= 0 |block.number@5|) (<= |block.number@5| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.chainid@6| Int)\n(assert (and (<= 0 |block.chainid@6|) (<= |block.chainid@6| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |tx.origin@7| Int)\n(assert (and (<= 0 |tx.origin@7|) (<= |tx.origin@7| 1461501637330902918203684832716283019655932542975)))\n(declare-const |tx.gasprice@8| Int)\n(assert (and (<= 0 |tx.gasprice@8|) (<= |tx.gasprice@8| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |msg.sig@9| Int)\n(assert (and (<= 0 |msg.sig@9|) (<= |msg.sig@9| 4294967295)))\n(declare-const |msg.data@10| Int)\n(declare-const |block.basefee@11| Int)\n(assert (and (<= 0 |block.basefee@11|) (<= |block.basefee@11| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.blobbasefee@12| Int)\n(assert (and (<= 0 |block.blobbasefee@12|) (<= |block.blobbasefee@12| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.coinbase@13| Int)\n(assert (and (<= 0 |block.coinbase@13|) (<= |block.coinbase@13| 1461501637330902918203684832716283019655932542975)))\n(declare-const |block.prevrandao@14| Int)\n(assert (and (<= 0 |block.prevrandao@14|) (<= |block.prevrandao@14| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.difficulty@15| Int)\n(assert (and (<= 0 |block.difficulty@15|) (<= |block.difficulty@15| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.gaslimit@16| Int)\n(assert (and (<= 0 |block.gaslimit@16|) (<= |block.gaslimit@16| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |count@17| Int)\n(assert (and (<= 0 |count@17|) (<= |count@17| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |limit@18| Int)\n(assert (and (<= 0 |limit@18|) (<= |limit@18| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |__balance@19| (Array Int Int))\n;@elem |__balance@19| 0 115792089237316195423570985008687907853269984665640564039457584007913129639935\n(declare-const |__code_epoch@20| Int)\n(assert (and (<= 0 |__code_epoch@20|) (<= |__code_epoch@20| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |a@21| Int)\n(assert (and (<= 0 |a@21|) (<= |a@21| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |b@22| Int)\n(assert (and (<= 0 |b@22|) (<= |b@22| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |g@23| Bool)\n(assert (= |g@23| (and true (<= |count@17| |limit@18|))))\n(declare-const |g@24| Bool)\n(assert (= |g@24| (and |g@23| (= |msg.value@3| 0))))\n(declare-const |g@25| Bool)\n(assert (= |g@25| (and |g@24| (>= |a@21| |b@22|))))\n(declare-const |g@26| Bool)\n(assert (= |g@26| (and |g@24| (not (>= |a@21| |b@22|)))))\n(declare-const |g@27| Bool)\n(assert (= |g@27| (or |g@25| |g@26|)))\n(declare-const |__ret0@28| Int)\n(assert (= |__ret0@28| (ite |g@25| |a@21| |b@22|)))\n(push 1)\n(assert |g@27|)\n(assert (not false))\n(check-sat)\n(pop 1)\n(push 1)\n(assert |g@27|)\n(assert (not (= |__ret0@28| (ite (>= |a@21| |b@22|) |a@21| |b@22|))))\n(check-sat)\n(pop 1)\n(push 1)\n(assert |g@27|)\n(assert (not (and (>= |__ret0@28| |a@21|) (>= |__ret0@28| |b@22|))))\n(check-sat)\n(pop 1)\n(pop 1)\n" + +end SolidCore.Verify.VC.Export.Counter diff --git a/Contracts/Counter/VC/ExportMilestone.lean b/Contracts/Counter/VC/ExportMilestone.lean new file mode 100644 index 00000000..25bc07c5 --- /dev/null +++ b/Contracts/Counter/VC/ExportMilestone.lean @@ -0,0 +1,169 @@ +-- Generated by solar-verify --dump-lean. Do not edit. + +import Verify.VC.Term + +namespace SolidCore.Verify.VC.Export.CounterMilestone + +open SolidCore.Verify.VC + +/-- The commands solar-verify sent the solver. -/ +def script : List Cmd := [ + .push, + .raw "; ===== Counter.inc", + .decl "this@1" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "this@1")]), (.app "<=" [(.ivar "this@1"), (.num 1461501637330902918203684832716283019655932542975)])]), + .decl "msg.sender@2" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "msg.sender@2")]), (.app "<=" [(.ivar "msg.sender@2"), (.num 1461501637330902918203684832716283019655932542975)])]), + .assert (.app "not" [(.app "=" [(.ivar "msg.sender@2"), (.num 0)])]), + .decl "msg.value@3" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "msg.value@3")]), (.app "<=" [(.ivar "msg.value@3"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.timestamp@4" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.timestamp@4")]), (.app "<=" [(.ivar "block.timestamp@4"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.number@5" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.number@5")]), (.app "<=" [(.ivar "block.number@5"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.chainid@6" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.chainid@6")]), (.app "<=" [(.ivar "block.chainid@6"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "tx.origin@7" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "tx.origin@7")]), (.app "<=" [(.ivar "tx.origin@7"), (.num 1461501637330902918203684832716283019655932542975)])]), + .decl "tx.gasprice@8" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "tx.gasprice@8")]), (.app "<=" [(.ivar "tx.gasprice@8"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "msg.sig@9" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "msg.sig@9")]), (.app "<=" [(.ivar "msg.sig@9"), (.num 4294967295)])]), + .decl "msg.data@10" .int, + .decl "block.basefee@11" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.basefee@11")]), (.app "<=" [(.ivar "block.basefee@11"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.blobbasefee@12" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.blobbasefee@12")]), (.app "<=" [(.ivar "block.blobbasefee@12"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.coinbase@13" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.coinbase@13")]), (.app "<=" [(.ivar "block.coinbase@13"), (.num 1461501637330902918203684832716283019655932542975)])]), + .decl "block.prevrandao@14" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.prevrandao@14")]), (.app "<=" [(.ivar "block.prevrandao@14"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.difficulty@15" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.difficulty@15")]), (.app "<=" [(.ivar "block.difficulty@15"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.gaslimit@16" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.gaslimit@16")]), (.app "<=" [(.ivar "block.gaslimit@16"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "x@17" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "x@17")]), (.app "<=" [(.ivar "x@17"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "__balance@18" .arr, + .elem "__balance@18" 0 115792089237316195423570985008687907853269984665640564039457584007913129639935, + .decl "__code_epoch@19" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "__code_epoch@19")]), (.app "<=" [(.ivar "__code_epoch@19"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "d@20" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "d@20")]), (.app "<=" [(.ivar "d@20"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "g@21" .bool, + .assert (.app "=" [(.bvar "g@21"), (.app "and" [.tt, (.app "=" [(.ivar "msg.value@3"), (.num 0)])])]), + .decl "arith@22" .int, + .assert (.app "=" [(.ivar "arith@22"), (.app "+" [(.ivar "x@17"), (.ivar "d@20")])]), + .decl "g@23" .bool, + .assert (.app "=" [(.bvar "g@23"), (.app "and" [(.bvar "g@21"), (.app "and" [(.app "<=" [(.num 0), (.ivar "arith@22")]), (.app "<=" [(.ivar "arith@22"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])])])]), + .push, + .assert (.bvar "g@23"), + .assert (.app "not" [.ff]), + .checkSat, + .pop, + .push, + .assert (.bvar "g@23"), + .assert (.app "not" [(.app "=" [(.ivar "arith@22"), (.app "+" [(.ivar "x@17"), (.ivar "d@20")])])]), + .checkSat, + .pop, + .pop, + .push, + .raw "; ===== Counter.get", + .decl "this@1" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "this@1")]), (.app "<=" [(.ivar "this@1"), (.num 1461501637330902918203684832716283019655932542975)])]), + .decl "msg.sender@2" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "msg.sender@2")]), (.app "<=" [(.ivar "msg.sender@2"), (.num 1461501637330902918203684832716283019655932542975)])]), + .assert (.app "not" [(.app "=" [(.ivar "msg.sender@2"), (.num 0)])]), + .decl "msg.value@3" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "msg.value@3")]), (.app "<=" [(.ivar "msg.value@3"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.timestamp@4" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.timestamp@4")]), (.app "<=" [(.ivar "block.timestamp@4"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.number@5" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.number@5")]), (.app "<=" [(.ivar "block.number@5"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.chainid@6" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.chainid@6")]), (.app "<=" [(.ivar "block.chainid@6"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "tx.origin@7" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "tx.origin@7")]), (.app "<=" [(.ivar "tx.origin@7"), (.num 1461501637330902918203684832716283019655932542975)])]), + .decl "tx.gasprice@8" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "tx.gasprice@8")]), (.app "<=" [(.ivar "tx.gasprice@8"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "msg.sig@9" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "msg.sig@9")]), (.app "<=" [(.ivar "msg.sig@9"), (.num 4294967295)])]), + .decl "msg.data@10" .int, + .decl "block.basefee@11" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.basefee@11")]), (.app "<=" [(.ivar "block.basefee@11"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.blobbasefee@12" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.blobbasefee@12")]), (.app "<=" [(.ivar "block.blobbasefee@12"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.coinbase@13" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.coinbase@13")]), (.app "<=" [(.ivar "block.coinbase@13"), (.num 1461501637330902918203684832716283019655932542975)])]), + .decl "block.prevrandao@14" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.prevrandao@14")]), (.app "<=" [(.ivar "block.prevrandao@14"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.difficulty@15" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.difficulty@15")]), (.app "<=" [(.ivar "block.difficulty@15"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.gaslimit@16" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.gaslimit@16")]), (.app "<=" [(.ivar "block.gaslimit@16"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "x@17" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "x@17")]), (.app "<=" [(.ivar "x@17"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "__balance@18" .arr, + .elem "__balance@18" 0 115792089237316195423570985008687907853269984665640564039457584007913129639935, + .decl "__code_epoch@19" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "__code_epoch@19")]), (.app "<=" [(.ivar "__code_epoch@19"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "g@20" .bool, + .assert (.app "=" [(.bvar "g@20"), (.app "and" [.tt, (.app "=" [(.ivar "msg.value@3"), (.num 0)])])]), + .push, + .assert (.bvar "g@20"), + .assert (.app "not" [.ff]), + .checkSat, + .pop, + .pop, + .push, + .raw "; ===== Counter.constructor", + .decl "this@1" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "this@1")]), (.app "<=" [(.ivar "this@1"), (.num 1461501637330902918203684832716283019655932542975)])]), + .decl "msg.sender@2" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "msg.sender@2")]), (.app "<=" [(.ivar "msg.sender@2"), (.num 1461501637330902918203684832716283019655932542975)])]), + .assert (.app "not" [(.app "=" [(.ivar "msg.sender@2"), (.num 0)])]), + .decl "msg.value@3" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "msg.value@3")]), (.app "<=" [(.ivar "msg.value@3"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.timestamp@4" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.timestamp@4")]), (.app "<=" [(.ivar "block.timestamp@4"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.number@5" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.number@5")]), (.app "<=" [(.ivar "block.number@5"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.chainid@6" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.chainid@6")]), (.app "<=" [(.ivar "block.chainid@6"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "tx.origin@7" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "tx.origin@7")]), (.app "<=" [(.ivar "tx.origin@7"), (.num 1461501637330902918203684832716283019655932542975)])]), + .decl "tx.gasprice@8" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "tx.gasprice@8")]), (.app "<=" [(.ivar "tx.gasprice@8"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "msg.sig@9" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "msg.sig@9")]), (.app "<=" [(.ivar "msg.sig@9"), (.num 4294967295)])]), + .decl "msg.data@10" .int, + .decl "block.basefee@11" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.basefee@11")]), (.app "<=" [(.ivar "block.basefee@11"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.blobbasefee@12" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.blobbasefee@12")]), (.app "<=" [(.ivar "block.blobbasefee@12"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.coinbase@13" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.coinbase@13")]), (.app "<=" [(.ivar "block.coinbase@13"), (.num 1461501637330902918203684832716283019655932542975)])]), + .decl "block.prevrandao@14" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.prevrandao@14")]), (.app "<=" [(.ivar "block.prevrandao@14"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.difficulty@15" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.difficulty@15")]), (.app "<=" [(.ivar "block.difficulty@15"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.gaslimit@16" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.gaslimit@16")]), (.app "<=" [(.ivar "block.gaslimit@16"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "__balance@17" .arr, + .elem "__balance@17" 0 115792089237316195423570985008687907853269984665640564039457584007913129639935, + .decl "__code_epoch@18" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "__code_epoch@18")]), (.app "<=" [(.ivar "__code_epoch@18"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "g@19" .bool, + .assert (.app "=" [(.bvar "g@19"), (.app "and" [.tt, (.app "=" [(.ivar "msg.value@3"), (.num 0)])])]), + .push, + .assert (.bvar "g@19"), + .assert (.app "not" [.ff]), + .checkSat, + .pop, + .pop +] + +/-- The transcript, as solar-verify wrote it. -/ +def transcript : String := "(push 1)\n; ===== Counter.inc\n(declare-const |this@1| Int)\n(assert (and (<= 0 |this@1|) (<= |this@1| 1461501637330902918203684832716283019655932542975)))\n(declare-const |msg.sender@2| Int)\n(assert (and (<= 0 |msg.sender@2|) (<= |msg.sender@2| 1461501637330902918203684832716283019655932542975)))\n(assert (not (= |msg.sender@2| 0)))\n(declare-const |msg.value@3| Int)\n(assert (and (<= 0 |msg.value@3|) (<= |msg.value@3| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.timestamp@4| Int)\n(assert (and (<= 0 |block.timestamp@4|) (<= |block.timestamp@4| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.number@5| Int)\n(assert (and (<= 0 |block.number@5|) (<= |block.number@5| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.chainid@6| Int)\n(assert (and (<= 0 |block.chainid@6|) (<= |block.chainid@6| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |tx.origin@7| Int)\n(assert (and (<= 0 |tx.origin@7|) (<= |tx.origin@7| 1461501637330902918203684832716283019655932542975)))\n(declare-const |tx.gasprice@8| Int)\n(assert (and (<= 0 |tx.gasprice@8|) (<= |tx.gasprice@8| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |msg.sig@9| Int)\n(assert (and (<= 0 |msg.sig@9|) (<= |msg.sig@9| 4294967295)))\n(declare-const |msg.data@10| Int)\n(declare-const |block.basefee@11| Int)\n(assert (and (<= 0 |block.basefee@11|) (<= |block.basefee@11| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.blobbasefee@12| Int)\n(assert (and (<= 0 |block.blobbasefee@12|) (<= |block.blobbasefee@12| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.coinbase@13| Int)\n(assert (and (<= 0 |block.coinbase@13|) (<= |block.coinbase@13| 1461501637330902918203684832716283019655932542975)))\n(declare-const |block.prevrandao@14| Int)\n(assert (and (<= 0 |block.prevrandao@14|) (<= |block.prevrandao@14| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.difficulty@15| Int)\n(assert (and (<= 0 |block.difficulty@15|) (<= |block.difficulty@15| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.gaslimit@16| Int)\n(assert (and (<= 0 |block.gaslimit@16|) (<= |block.gaslimit@16| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |x@17| Int)\n(assert (and (<= 0 |x@17|) (<= |x@17| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |__balance@18| (Array Int Int))\n;@elem |__balance@18| 0 115792089237316195423570985008687907853269984665640564039457584007913129639935\n(declare-const |__code_epoch@19| Int)\n(assert (and (<= 0 |__code_epoch@19|) (<= |__code_epoch@19| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |d@20| Int)\n(assert (and (<= 0 |d@20|) (<= |d@20| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |g@21| Bool)\n(assert (= |g@21| (and true (= |msg.value@3| 0))))\n(declare-const |arith@22| Int)\n(assert (= |arith@22| (+ |x@17| |d@20|)))\n(declare-const |g@23| Bool)\n(assert (= |g@23| (and |g@21| (and (<= 0 |arith@22|) (<= |arith@22| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))))\n(push 1)\n(assert |g@23|)\n(assert (not false))\n(check-sat)\n(pop 1)\n(push 1)\n(assert |g@23|)\n(assert (not (= |arith@22| (+ |x@17| |d@20|))))\n(check-sat)\n(pop 1)\n(pop 1)\n(push 1)\n; ===== Counter.get\n(declare-const |this@1| Int)\n(assert (and (<= 0 |this@1|) (<= |this@1| 1461501637330902918203684832716283019655932542975)))\n(declare-const |msg.sender@2| Int)\n(assert (and (<= 0 |msg.sender@2|) (<= |msg.sender@2| 1461501637330902918203684832716283019655932542975)))\n(assert (not (= |msg.sender@2| 0)))\n(declare-const |msg.value@3| Int)\n(assert (and (<= 0 |msg.value@3|) (<= |msg.value@3| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.timestamp@4| Int)\n(assert (and (<= 0 |block.timestamp@4|) (<= |block.timestamp@4| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.number@5| Int)\n(assert (and (<= 0 |block.number@5|) (<= |block.number@5| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.chainid@6| Int)\n(assert (and (<= 0 |block.chainid@6|) (<= |block.chainid@6| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |tx.origin@7| Int)\n(assert (and (<= 0 |tx.origin@7|) (<= |tx.origin@7| 1461501637330902918203684832716283019655932542975)))\n(declare-const |tx.gasprice@8| Int)\n(assert (and (<= 0 |tx.gasprice@8|) (<= |tx.gasprice@8| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |msg.sig@9| Int)\n(assert (and (<= 0 |msg.sig@9|) (<= |msg.sig@9| 4294967295)))\n(declare-const |msg.data@10| Int)\n(declare-const |block.basefee@11| Int)\n(assert (and (<= 0 |block.basefee@11|) (<= |block.basefee@11| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.blobbasefee@12| Int)\n(assert (and (<= 0 |block.blobbasefee@12|) (<= |block.blobbasefee@12| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.coinbase@13| Int)\n(assert (and (<= 0 |block.coinbase@13|) (<= |block.coinbase@13| 1461501637330902918203684832716283019655932542975)))\n(declare-const |block.prevrandao@14| Int)\n(assert (and (<= 0 |block.prevrandao@14|) (<= |block.prevrandao@14| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.difficulty@15| Int)\n(assert (and (<= 0 |block.difficulty@15|) (<= |block.difficulty@15| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.gaslimit@16| Int)\n(assert (and (<= 0 |block.gaslimit@16|) (<= |block.gaslimit@16| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |x@17| Int)\n(assert (and (<= 0 |x@17|) (<= |x@17| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |__balance@18| (Array Int Int))\n;@elem |__balance@18| 0 115792089237316195423570985008687907853269984665640564039457584007913129639935\n(declare-const |__code_epoch@19| Int)\n(assert (and (<= 0 |__code_epoch@19|) (<= |__code_epoch@19| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |g@20| Bool)\n(assert (= |g@20| (and true (= |msg.value@3| 0))))\n(push 1)\n(assert |g@20|)\n(assert (not false))\n(check-sat)\n(pop 1)\n(pop 1)\n(push 1)\n; ===== Counter.constructor\n(declare-const |this@1| Int)\n(assert (and (<= 0 |this@1|) (<= |this@1| 1461501637330902918203684832716283019655932542975)))\n(declare-const |msg.sender@2| Int)\n(assert (and (<= 0 |msg.sender@2|) (<= |msg.sender@2| 1461501637330902918203684832716283019655932542975)))\n(assert (not (= |msg.sender@2| 0)))\n(declare-const |msg.value@3| Int)\n(assert (and (<= 0 |msg.value@3|) (<= |msg.value@3| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.timestamp@4| Int)\n(assert (and (<= 0 |block.timestamp@4|) (<= |block.timestamp@4| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.number@5| Int)\n(assert (and (<= 0 |block.number@5|) (<= |block.number@5| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.chainid@6| Int)\n(assert (and (<= 0 |block.chainid@6|) (<= |block.chainid@6| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |tx.origin@7| Int)\n(assert (and (<= 0 |tx.origin@7|) (<= |tx.origin@7| 1461501637330902918203684832716283019655932542975)))\n(declare-const |tx.gasprice@8| Int)\n(assert (and (<= 0 |tx.gasprice@8|) (<= |tx.gasprice@8| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |msg.sig@9| Int)\n(assert (and (<= 0 |msg.sig@9|) (<= |msg.sig@9| 4294967295)))\n(declare-const |msg.data@10| Int)\n(declare-const |block.basefee@11| Int)\n(assert (and (<= 0 |block.basefee@11|) (<= |block.basefee@11| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.blobbasefee@12| Int)\n(assert (and (<= 0 |block.blobbasefee@12|) (<= |block.blobbasefee@12| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.coinbase@13| Int)\n(assert (and (<= 0 |block.coinbase@13|) (<= |block.coinbase@13| 1461501637330902918203684832716283019655932542975)))\n(declare-const |block.prevrandao@14| Int)\n(assert (and (<= 0 |block.prevrandao@14|) (<= |block.prevrandao@14| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.difficulty@15| Int)\n(assert (and (<= 0 |block.difficulty@15|) (<= |block.difficulty@15| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.gaslimit@16| Int)\n(assert (and (<= 0 |block.gaslimit@16|) (<= |block.gaslimit@16| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |__balance@17| (Array Int Int))\n;@elem |__balance@17| 0 115792089237316195423570985008687907853269984665640564039457584007913129639935\n(declare-const |__code_epoch@18| Int)\n(assert (and (<= 0 |__code_epoch@18|) (<= |__code_epoch@18| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |g@19| Bool)\n(assert (= |g@19| (and true (= |msg.value@3| 0))))\n(push 1)\n(assert |g@19|)\n(assert (not false))\n(check-sat)\n(pop 1)\n(pop 1)\n" + +end SolidCore.Verify.VC.Export.CounterMilestone diff --git a/Contracts/Counter/VC/Generic.lean b/Contracts/Counter/VC/Generic.lean new file mode 100644 index 00000000..52ca1096 --- /dev/null +++ b/Contracts/Counter/VC/Generic.lean @@ -0,0 +1,65 @@ +import Contracts.Counter.VC.Inc +import Verify.VC.Obligations + +/-! +# `Counter.inc` through the generic theorem + +`inc_triple` again, now as an instance of `triple_of_binds`: the only proof about `inc` is the +binding `inc_binds`, which speaks of the erased tree `incTree` and solar-verify's obligation alone +(no SolidCore run, no fuel, no ABI); `triple_of_binds` supplies the rest for every function the +generic source stage erases. The obligation `incHyps ⟹ incGoal` is the one `inc_check` finds in +solar-verify's script, and it is valid by solar-verify's own encoding (`inc_obs_valid`), so the +theorem takes no verdict. +-/ + +namespace SolidCore.Verify.VC.Counter + +open SolidCore.Verify SolidCore.Verify.VC SolidCore.Refinement SolidCore.Refinement.Abi +open SolidCore.Refinement.Generic SolidCore.Solidity + +/-- `inc`'s postcondition of its argument words, its storage and its observable. -/ +def incP (args : List Nat) (s : Storage) (o : SolarTV.Observable) : Prop := + let d := args.getD 0 0 + (o.success = true ↔ s 0 + d < 2 ^ 256) ∧ + (o.success = true → o.storage 0 = s 0 + d ∧ ∀ k, k % 2 ^ 256 ≠ 0 → o.storage k = s k) + +/-- solar-verify's obligation for `inc`'s clause holds everywhere. -/ +theorem inc_obs_valid : ObsValid [(incHyps, incGoal)] := by + intro o ho σ _ + simp only [List.mem_singleton] at ho + subst ho + simp [incGoal, incEff, Ob.add, Ob.eq, Ob.x, Ob.d, Tm.Holds, Tm.eval, Tm.evalList, applyOp, + Value.toProp, Value.eq] + +/-- The binding of `inc`'s erased tree to solar-verify's obligation. -/ +theorem inc_binds : + Binds fnInc incTree [(incHyps, incGoal)] (fun args s => incEnv (args.getD 0 0) s) incP := by + intro args s hl hargs hs _ + obtain ⟨d, rfl⟩ : ∃ d, args = [d] := by + match args, hl with + | [d], _ => exact ⟨d, rfl⟩ + have hd : d < 2 ^ 256 := hargs d (List.mem_singleton_self d) + obtain ⟨hiff, hok⟩ := inc_binding s hs d hd + have hguard := incHyps_iff d s hd (hs 0) + simp only [incP, Res.obs, List.getD_cons_zero] + refine ⟨hiff.trans hguard, fun hsucc => ?_⟩ + obtain ⟨h0, hk⟩ := hok hsucc + rw [incEff_eval] at h0 + exact ⟨by omega, hk⟩ + +/-- `inc_triple`, from the generic theorem and the binding. -/ +theorem inc_triple_of_binds {c : TypeCheck.CheckedContract} (hc : contract? = .ok c) : + Triple fuel c (stageScope fnInc []) (fun _ => True) incPost := by + have hshape := incShape_eq + simp only [incShape?, hc, Option.some.injEq, Prod.mk.injEq] at hshape + obtain ⟨hdep, hmap⟩ := hshape + obtain ⟨dd, hdd⟩ := Wide.deployedAt_of hdep + simp only [Option.map_eq_some_iff, Prod.mk.injEq] at hmap + obtain ⟨f, hf, hlen, hT⟩ := hmap + exact triple_of_binds (fn := fnInc) hdd (by decide) hf hlen hT inc_obs_valid inc_binds + +/-- info: 'SolidCore.Verify.VC.Counter.inc_triple_of_binds' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms inc_triple_of_binds + +end SolidCore.Verify.VC.Counter diff --git a/Contracts/Counter/VC/Get.lean b/Contracts/Counter/VC/Get.lean new file mode 100644 index 00000000..1c0dc58f --- /dev/null +++ b/Contracts/Counter/VC/Get.lean @@ -0,0 +1,79 @@ +import Contracts.Counter.VC.Inc + +/-! +# The certified counter milestone's `get` + +`get` carries no NatSpec clause, so solar-verify emits no obligation for it and there is nothing of +solar-verify's to bind: `get_triple` is a direct proof against SolidCore, with the shape of +`inc_triple` so that final composition consumes both the same way. + +* `getShape_eq` (kernel): `Counter` deploys with no storage and no logs, and the generic source stage + erases `get()` to `getTree`, one success leaf that returns slot 0's 32 bytes and writes nothing. +* `get_triple`: on the stage's scope (any storage, no value), `get` succeeds, returns slot 0 as a + big-endian word and leaves every slot unchanged. +-/ + +namespace SolidCore.Verify.VC.Counter + +open SolidCore.Verify SolidCore.Verify.VC SolidCore.Refinement SolidCore.Refinement.Abi +open SolidCore.Refinement.Generic SolidCore.Solidity SolidCore.Solidity.Source + +/-- `get()` as the stage's ABI sees it. -/ +def fnGet : Fn := ⟨getSel, []⟩ + +/-- The erasure of `get`: return slot 0's word, write nothing. -/ +def getTree : Tree := .halt true (wordOBytes (.init 0)) [] [] + +/-- Whether `Counter` deploys with no storage and no logs, and how SolidCore dispatches `get` and the +generic source stage erases it. -/ +def getShape? : Option (Bool × Option (Nat × Option Tree)) := + match contract? with + | .ok c => some (Wide.deployedAt fuel c [], + (c.core.findFunctionBySelector? getSel).map fun f => (f.params.length, eraseFn (envOf c.core) fuel f)) + | .error _ => none + +kernel_rfl getShape_eq getShape? (some (true, some (0, some getTree))) using selector_eq mkIdx_eq + +/-- The 32 bytes of the word `w`, big-endian. -/ +def wordBytes (w : Nat) : List Nat := (List.range 32).map fun i => w / 256 ^ (31 - i) % 256 + +/-- `get`'s postcondition: it succeeds, returns slot 0 as a big-endian word and changes no slot. -/ +def getPost (call : Call) (obs : SolarTV.Observable) : Prop := + let s := initStorage call + obs.success = true ∧ obs.output = wordBytes (s 0) ∧ ∀ k, obs.storage k = s k + +/-- `Counter.get` on the stage's scope: it succeeds, returns slot 0 and leaves the storage, through +`implementsTree`. -/ +theorem get_triple {c : TypeCheck.CheckedContract} (hc : contract? = .ok c) : + Triple fuel c (stageScope fnGet []) (fun _ => True) getPost := by + have hshape := getShape_eq + simp only [getShape?, hc, Option.some.injEq, Prod.mk.injEq] at hshape + obtain ⟨hdep, hmap⟩ := hshape + obtain ⟨dd, hdd⟩ := Wide.deployedAt_of hdep + simp only [Option.map_eq_some_iff, Prod.mk.injEq] at hmap + obtain ⟨f, hf, hlen, hT⟩ := hmap + have himpl := implements_tree (fn := fnGet) hdd (by decide) hf hlen hT rfl + apply triple_of_wp himpl + rintro _ ⟨σ, -, fn', hfn', args, hl, hargs, rfl⟩ - + simp only [List.mem_singleton] at hfn' + subst hfn' + obtain rfl : args = [] := List.eq_nil_of_length_eq_zero hl + have hw : argWords 0 ({ calldata := Abi.calldata fnGet.sel [], callvalue := 0, storage := σ } : Call) = + [] := argWords_calldata _ [] hargs 0 σ + rw [vc_eq, treeModel_run, show fnGet.params.length = 0 from rfl, hw] + set s := initStorage ({ calldata := Abi.calldata fnGet.sel [], callvalue := 0, storage := σ } : Call) + with hs_def + have hs : ∀ k, s k < 2 ^ 256 := fun k => Generic.slotValue_lt σ k + simp only [getPost, ← hs_def] + refine ⟨rfl, ?_, fun k => rfl⟩ + simp only [getTree, Tree.eval, resOutcome, observe, ite_true, wordOBytes, wordBytes, List.map_map] + congr 1 + funext i + have h0 := hs 0 + simp only [Function.comp_apply, OByte.eval, WExpr.eval, valOf, Generic.wordSize, Nat.mod_eq_of_lt h0] + +/-- info: 'SolidCore.Verify.VC.Counter.get_triple' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms get_triple + +end SolidCore.Verify.VC.Counter diff --git a/Contracts/Counter/VC/Inc.lean b/Contracts/Counter/VC/Inc.lean new file mode 100644 index 00000000..dce409ea --- /dev/null +++ b/Contracts/Counter/VC/Inc.lean @@ -0,0 +1,279 @@ +import Verify.VC +import Verify.VC.KernelIdx +import Contracts.Counter.VC.ExportMilestone +import SolidCore.Refinement.Solar.Counter.Source +import SolidCore.Refinement.KernelRfl + +/-! +# solar-verify's `Counter.inc`, bound to the certified counter milestone + +The contract is the one the certified translation covers: SolidCore's checked `Counter` from +`scripts/refinement/counter/counter.sol` (`contract` below is +`SolidCore.Refinement.Solar.Counter.contract?`'s body, so a proof of either equation is one of the +other). solar-verify reads `scripts/verify/CounterMilestone.sol`, the same text with one NatSpec line, +`ensures x == old(x) + d` (`check`.sh checks that stripping the `///` lines gives counter.sol back). + +What is proved: +* `incShape_eq` (kernel): `Counter` deploys with no storage and no logs, and the generic source stage + erases `inc(uint256)` to `incTree`. +* `inc_check` (kernel): solar-verify's script has an obligation that `checkOb` normalizes to + `incHyps ⟹ incGoal`, written here by hand: its facts are the guard of `inc`'s success path + (no value, `x + d` in range) and its goal states solar-verify's encoding `incEff` of the new `x`. +* `inc_binding`: a call of `inc` on `d` from storage `s` succeeds exactly when `incHyps` hold at the + assignment `incEnv d s` it binds (`x` is slot 0, `d` the argument, `msg.value` 0), and then + writes slot 0 with the value of `incEff` there and nothing else. +* `inc_triple`: on the stage's scope (any storage, any argument word, no value), `inc` succeeds + exactly when `x + d < 2 ^ 256`, and then slot 0 holds `x + d` and every other slot is unchanged. + +The goal of solar-verify's obligation for this clause, after its definition `arith = x + d` is +inlined, is `x + d = x + d`: valid by solar-verify's own encoding of the effect, so a verdict adds +nothing to it, and `inc_triple` takes no `Valid` premise. What ties solar-verify to SolidCore is the +binding: the effect solar-verify encodes is the one SolidCore runs, and the guard it assumes is +exactly SolidCore's success condition. The negatives (`CounterMutants`) show the check failing for +a one-line source mutant and a one-line spec mutant. +-/ + +namespace SolidCore.Verify.VC.Counter + +open SolidCore.Verify SolidCore.Verify.VC SolidCore.Refinement SolidCore.Refinement.Abi +open SolidCore.Refinement.Generic SolidCore.Solidity SolidCore.Solidity.Source + +/-- The interpreter fuel of SolidCore's runs. -/ +def fuel : Nat := 4096 + +/-- SolidCore's checked `Counter`: `SolidCore.Refinement.Solar.Counter.contract?`'s body. -/ +def contract? : Except TypeCheck.TypeError TypeCheck.CheckedContract := + TypeCheck.CheckedInput.contract SolidCore.Refinement.Source.Counter.importedSourceUnit "Counter" + +/-- The selector of `inc(uint256)`. -/ +abbrev incSel : Nat := 0x812600df + +/-- The selector of `get()`. -/ +abbrev getSel : Nat := 0x6d4ce63c + +/-- The selector of `inc(uint256)`, by Keccak-256 of its signature. -/ +def selInc : SolidCore.Solidity.Shared.Word := SolidCore.Solidity.Source.ABI.selectorFromSignature "inc(uint256)" + +kernel_rfl selInc_eq selInc incSel + +/-- The selector of `get()`, by Keccak-256 of its signature. -/ +def selGet : SolidCore.Solidity.Shared.Word := SolidCore.Solidity.Source.ABI.selectorFromSignature "get()" + +kernel_rfl selGet_eq selGet getSel + +/-- `ABI.selectorFromSignature`, with `Counter`'s selectors by table. -/ +def selectorTable (s : String) : SolidCore.Solidity.Shared.Word := + if s = "inc(uint256)" then incSel + else if s = "get()" then getSel + else SolidCore.Solidity.Source.ABI.selectorFromSignature s + +theorem selector_eq : SolidCore.Solidity.Source.ABI.selectorFromSignature = selectorTable := by + funext s + unfold selectorTable + by_cases h0 : s = "inc(uint256)" + · rw [ite_eq_left h0, h0] + exact selInc_eq + rw [ite_eq_right h0] + by_cases h1 : s = "get()" + · rw [ite_eq_left h1, h1] + exact selGet_eq + rw [ite_eq_right h1] + +/-- `inc(uint256)` as the stage's ABI sees it. -/ +def fnInc : Fn := ⟨incSel, [.uint 256]⟩ + +/-- The revert data of `Panic(0x11)`, byte by byte. -/ +def panic11 : List OByte := + [78, 72, 123, 113].map .lit ++ (List.replicate 31 (OByte.lit 0)) ++ [.lit 17] + +/-- The erasure of `inc`: panic when `x + d` wraps, else write it to slot 0. -/ +def incTree : Tree := + .ite (.bin .lt (.bin .add (.init 0) (.arg 0)) (.init 0)) (.halt false panic11 [] []) + (.halt true [] [(.lit 0, .bin .add (.init 0) (.arg 0))] []) + +/-- Whether `Counter` deploys with no storage and no logs, and how SolidCore dispatches `inc` and the +generic source stage erases it. -/ +def incShape? : Option (Bool × Option (Nat × Option Tree)) := + match contract? with + | .ok c => some (Wide.deployedAt fuel c [], + (c.core.findFunctionBySelector? incSel).map fun f => (f.params.length, eraseFn (envOf c.core) fuel f)) + | .error _ => none + +kernel_rfl incShape_eq incShape? (some (true, some (1, some incTree))) using selector_eq mkIdx_eq + +/-! ## The Lean obligation -/ + +namespace Ob + +def x : Tm := .ivar "x" +def d : Tm := .ivar "d" +def mv : Tm := .ivar "msg.value" +def ms : Tm := .ivar "msg.sender" +def le0 (t : Tm) : Tm := .app "<=" [.num 0, t] +def leW (t : Tm) : Tm := .app "<=" [t, .num (2 ^ 256 - 1)] +def add (a b : Tm) : Tm := .app "+" [a, b] +def eq (a b : Tm) : Tm := .app "=" [a, b] + +end Ob + +open Ob in +/-- solar-verify's encoding of `x` after `inc`. -/ +def incEff : Tm := add x d + +open Ob in +/-- The guard of `inc`'s success path, and the ranges of the words it reads. -/ +def incHyps : List Tm := + [eq mv (.num 0), le0 incEff, leW incEff, le0 d, leW d, le0 x, leW x, le0 mv, leW mv, + .app "not" [eq ms (.num 0)], le0 ms, .app "<=" [ms, .num (2 ^ 160 - 1)]] + +open Ob in +/-- `inc`'s ensures clause as solar-verify states it, of its own encoding of the new `x`. -/ +def incGoal : Tm := eq incEff (add x d) + +/-- solar-verify's script for the annotated counter has an obligation that `checkOb` normalizes to +`incHyps ⟹ incGoal`. -/ +theorem inc_check : checkScript Export.CounterMilestone.script [(incHyps, incGoal)] = true := by + decide +kernel + +/-! ## The binding -/ + +/-- The assignment of solar-verify's names that a call of `inc` on `d` from storage `s` binds. -/ +def incEnv (d : Nat) (s : Storage) : Env := + ⟨fun y => if y = "x" then s 0 else if y = "d" then d else if y = "msg.sender" then callerWord else 0, + fun _ => False, fun _ => fun _ => 0⟩ + +section +variable (d : Nat) (s : Storage) +@[simp] theorem incEnv_x : (incEnv d s).i "x" = s 0 := rfl +@[simp] theorem incEnv_d : (incEnv d s).i "d" = d := rfl +@[simp] theorem incEnv_mv : (incEnv d s).i "msg.value" = 0 := rfl +@[simp] theorem incEnv_ms : (incEnv d s).i "msg.sender" = 8192 := rfl +end + +theorem incEff_eval (d : Nat) (s : Storage) : (incEff.eval (incEnv d s)).toInt = (s 0 : Int) + d := by + simp [incEff, Ob.add, Ob.x, Ob.d, Tm.eval, Tm.evalList, applyOp, Value.toInt] + +theorem incHyps_iff (d : Nat) (s : Storage) (hd : d < 2 ^ 256) (hs : s 0 < 2 ^ 256) : + (∀ t ∈ incHyps, t.Holds (incEnv d s)) ↔ s 0 + d < 2 ^ 256 := by + simp only [incHyps, List.mem_cons, List.mem_nil_iff, or_false, forall_eq_or_imp, forall_eq] + simp [Tm.Holds, Tm.eval, Tm.evalList, applyOp, Value.toProp, Value.toInt, Value.eq, incEff, Ob.add, + Ob.x, Ob.d, Ob.mv, Ob.ms, Ob.le0, Ob.leW, Ob.eq] + omega + +theorem incAdd_eval (s : Storage) (hs : ∀ k, s k < 2 ^ 256) (d : Nat) (hd : d < 2 ^ 256) : + (WExpr.bin .add (.init 0) (.arg 0)).eval (valOf [d] s) = (s 0 + d) % 2 ^ 256 := by + simp [WExpr.eval, BinOp.eval, valOf, Generic.wordSize, Nat.mod_eq_of_lt hd, Nat.mod_eq_of_lt (hs 0)] + +theorem incCond_eval (s : Storage) (hs : ∀ k, s k < 2 ^ 256) (d : Nat) (hd : d < 2 ^ 256) : + (WExpr.bin .lt (.bin .add (.init 0) (.arg 0)) (.init 0)).eval (valOf [d] s) = + if s 0 + d < 2 ^ 256 then 0 else 1 := by + have h := incAdd_eval s hs d hd + simp only [WExpr.eval] at h ⊢ + rw [h] + have h0 := hs 0 + simp only [BinOp.eval, valOf, Generic.wordSize, Nat.mod_eq_of_lt h0] + by_cases hov : s 0 + d < 2 ^ 256 + · rw [Nat.mod_eq_of_lt hov, if_neg (by omega), if_pos hov] + · have : (s 0 + d) % 2 ^ 256 = s 0 + d - 2 ^ 256 := by omega + rw [this, if_pos (by omega), if_neg hov] + +/-- The binding: a call of `inc` succeeds exactly when solar-verify's guard holds at the assignment +it binds, and then writes slot 0 with solar-verify's encoding of the new `x` and leaves every other +slot. -/ +theorem inc_binding (s : Storage) (hs : ∀ k, s k < 2 ^ 256) (d : Nat) (hd : d < 2 ^ 256) : + let R := incTree.eval (valOf [d] s) + (R.success = true ↔ ∀ t ∈ incHyps, t.Holds (incEnv d s)) ∧ + (R.success = true → ((R.store 0 : Nat) : Int) = (incEff.eval (incEnv d s)).toInt ∧ + ∀ k, k % 2 ^ 256 ≠ 0 → R.store k = s k) := by + intro R + rw [incHyps_iff d s hd (hs 0), incEff_eval] + have hc := incCond_eval s hs d hd + have ha := incAdd_eval s hs d hd + by_cases hov : s 0 + d < 2 ^ 256 + · have hsucc : R.success = true := by + simp only [R, incTree, Tree.eval, hc, if_pos hov, ite_true] + have hst : R.store = Writes.store (valOf [d] s) [(.lit 0, .bin .add (.init 0) (.arg 0))] := by + simp only [R, incTree, Tree.eval, hc, if_pos hov, ite_true] + refine ⟨by simp only [hsucc, true_iff]; omega, fun _ => ⟨?_, fun k hk => ?_⟩⟩ + · rw [hst] + simp only [Writes.store, ha] + split + · rw [Nat.mod_eq_of_lt hov]; push_cast; rfl + · rename_i h; exact absurd (by simp [WExpr.eval]) h + · rw [hst] + simp only [Writes.store] + split + · rename_i h; simp [WExpr.eval, Generic.wordSize] at h; omega + · rfl + · have hR : R.success = false := by + simp only [R, incTree, Tree.eval, hc, if_neg hov]; rfl + simp only [hR, Bool.false_eq_true, false_iff, false_implies, and_true] + omega + +/-- `inc`'s postcondition: it succeeds exactly when `x + d` does not wrap, and then slot 0 holds +`x + d` and every other slot is unchanged. -/ +def incPost (call : Call) (obs : SolarTV.Observable) : Prop := + let d := (argWords 1 call).getD 0 0 + let s := initStorage call + (obs.success = true ↔ s 0 + d < 2 ^ 256) ∧ + (obs.success = true → obs.storage 0 = s 0 + d ∧ ∀ k, k % 2 ^ 256 ≠ 0 → obs.storage k = s k) + +theorem vc_eq (model : List Nat → SolM (List Nat)) (args : Call → List Nat) + (post : Call → SolarTV.Observable → Prop) (call : Call) : + vc model args post call = + post call (observe (initStorage call) (model (args call) (initStorage call))) := by + unfold vc + rw [wp_eq] + rcases h : model (args call) (initStorage call) with e | ⟨out, s'⟩ <;> simp only [h] <;> rfl + +/-- `Counter.inc` on the stage's scope: it succeeds exactly when `x + d` does not wrap, and then slot 0 +holds `x + d` and every other slot is unchanged, through `implementsTree` and the binding to +solar-verify's encoding. -/ +theorem inc_triple {c : TypeCheck.CheckedContract} (hc : contract? = .ok c) : + Triple fuel c (stageScope fnInc []) (fun _ => True) incPost := by + have hshape := incShape_eq + simp only [incShape?, hc, Option.some.injEq, Prod.mk.injEq] at hshape + obtain ⟨hdep, hmap⟩ := hshape + obtain ⟨dd, hdd⟩ := Wide.deployedAt_of hdep + simp only [Option.map_eq_some_iff, Prod.mk.injEq] at hmap + obtain ⟨f, hf, hlen, hT⟩ := hmap + have himpl := implements_tree (fn := fnInc) hdd (by decide) hf hlen hT rfl + apply triple_of_wp himpl + rintro _ ⟨σ, -, fn', hfn', args, hl, hargs, rfl⟩ - + simp only [List.mem_singleton] at hfn' + subst hfn' + obtain ⟨d, rfl⟩ : ∃ d, args = [d] := by + match args, hl with + | [d], _ => exact ⟨d, rfl⟩ + have hd : d < 2 ^ 256 := hargs d (List.mem_singleton_self d) + have hw : argWords 1 ({ calldata := Abi.calldata fnInc.sel [d], callvalue := 0, storage := σ } : Call) = + [d] := argWords_calldata _ [d] hargs 0 σ + rw [vc_eq, treeModel_run, show fnInc.params.length = 1 from rfl, hw] + set s := initStorage ({ calldata := Abi.calldata fnInc.sel [d], callvalue := 0, storage := σ } : Call) + with hs_def + have hs : ∀ k, s k < 2 ^ 256 := fun k => Generic.slotValue_lt σ k + obtain ⟨hiff, hok⟩ := inc_binding s hs d hd + have hguard := incHyps_iff d s hd (hs 0) + simp only [incPost, hw, List.getD_cons_zero, ← hs_def] + unfold resOutcome + split + · next hsucc => + obtain ⟨h0, hk⟩ := hok hsucc + rw [incEff_eval] at h0 + simp only [observe, true_iff] + refine ⟨hguard.mp (hiff.mp hsucc), fun _ => ⟨?_, hk⟩⟩ + omega + · next hfail => + simp only [observe, Bool.false_eq_true, false_iff, false_implies, and_true] + intro hlt + exact hfail (hiff.mpr (hguard.mpr hlt)) + +/-- info: 'SolidCore.Verify.VC.Counter.inc_triple' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms inc_triple + +/-- info: 'SolidCore.Verify.VC.Counter.inc_check' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms inc_check + +end SolidCore.Verify.VC.Counter diff --git a/Contracts/Counter/VC/Mutant/SpecMut.lean b/Contracts/Counter/VC/Mutant/SpecMut.lean new file mode 100644 index 00000000..3c3d3de3 --- /dev/null +++ b/Contracts/Counter/VC/Mutant/SpecMut.lean @@ -0,0 +1,169 @@ +-- Generated by solar-verify --dump-lean. Do not edit. + +import Verify.VC.Term + +namespace SolidCore.Verify.VC.Export.Mutant.CounterSpecMut + +open SolidCore.Verify.VC + +/-- The commands solar-verify sent the solver. -/ +def script : List Cmd := [ + .push, + .raw "; ===== Counter.inc", + .decl "this@1" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "this@1")]), (.app "<=" [(.ivar "this@1"), (.num 1461501637330902918203684832716283019655932542975)])]), + .decl "msg.sender@2" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "msg.sender@2")]), (.app "<=" [(.ivar "msg.sender@2"), (.num 1461501637330902918203684832716283019655932542975)])]), + .assert (.app "not" [(.app "=" [(.ivar "msg.sender@2"), (.num 0)])]), + .decl "msg.value@3" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "msg.value@3")]), (.app "<=" [(.ivar "msg.value@3"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.timestamp@4" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.timestamp@4")]), (.app "<=" [(.ivar "block.timestamp@4"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.number@5" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.number@5")]), (.app "<=" [(.ivar "block.number@5"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.chainid@6" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.chainid@6")]), (.app "<=" [(.ivar "block.chainid@6"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "tx.origin@7" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "tx.origin@7")]), (.app "<=" [(.ivar "tx.origin@7"), (.num 1461501637330902918203684832716283019655932542975)])]), + .decl "tx.gasprice@8" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "tx.gasprice@8")]), (.app "<=" [(.ivar "tx.gasprice@8"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "msg.sig@9" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "msg.sig@9")]), (.app "<=" [(.ivar "msg.sig@9"), (.num 4294967295)])]), + .decl "msg.data@10" .int, + .decl "block.basefee@11" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.basefee@11")]), (.app "<=" [(.ivar "block.basefee@11"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.blobbasefee@12" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.blobbasefee@12")]), (.app "<=" [(.ivar "block.blobbasefee@12"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.coinbase@13" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.coinbase@13")]), (.app "<=" [(.ivar "block.coinbase@13"), (.num 1461501637330902918203684832716283019655932542975)])]), + .decl "block.prevrandao@14" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.prevrandao@14")]), (.app "<=" [(.ivar "block.prevrandao@14"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.difficulty@15" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.difficulty@15")]), (.app "<=" [(.ivar "block.difficulty@15"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.gaslimit@16" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.gaslimit@16")]), (.app "<=" [(.ivar "block.gaslimit@16"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "x@17" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "x@17")]), (.app "<=" [(.ivar "x@17"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "__balance@18" .arr, + .elem "__balance@18" 0 115792089237316195423570985008687907853269984665640564039457584007913129639935, + .decl "__code_epoch@19" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "__code_epoch@19")]), (.app "<=" [(.ivar "__code_epoch@19"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "d@20" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "d@20")]), (.app "<=" [(.ivar "d@20"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "g@21" .bool, + .assert (.app "=" [(.bvar "g@21"), (.app "and" [.tt, (.app "=" [(.ivar "msg.value@3"), (.num 0)])])]), + .decl "arith@22" .int, + .assert (.app "=" [(.ivar "arith@22"), (.app "+" [(.ivar "x@17"), (.ivar "d@20")])]), + .decl "g@23" .bool, + .assert (.app "=" [(.bvar "g@23"), (.app "and" [(.bvar "g@21"), (.app "and" [(.app "<=" [(.num 0), (.ivar "arith@22")]), (.app "<=" [(.ivar "arith@22"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])])])]), + .push, + .assert (.bvar "g@23"), + .assert (.app "not" [.ff]), + .checkSat, + .pop, + .push, + .assert (.bvar "g@23"), + .assert (.app "not" [(.app "=" [(.ivar "arith@22"), (.app "+" [(.app "+" [(.ivar "x@17"), (.ivar "d@20")]), (.num 1)])])]), + .checkSat, + .pop, + .pop, + .push, + .raw "; ===== Counter.get", + .decl "this@1" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "this@1")]), (.app "<=" [(.ivar "this@1"), (.num 1461501637330902918203684832716283019655932542975)])]), + .decl "msg.sender@2" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "msg.sender@2")]), (.app "<=" [(.ivar "msg.sender@2"), (.num 1461501637330902918203684832716283019655932542975)])]), + .assert (.app "not" [(.app "=" [(.ivar "msg.sender@2"), (.num 0)])]), + .decl "msg.value@3" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "msg.value@3")]), (.app "<=" [(.ivar "msg.value@3"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.timestamp@4" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.timestamp@4")]), (.app "<=" [(.ivar "block.timestamp@4"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.number@5" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.number@5")]), (.app "<=" [(.ivar "block.number@5"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.chainid@6" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.chainid@6")]), (.app "<=" [(.ivar "block.chainid@6"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "tx.origin@7" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "tx.origin@7")]), (.app "<=" [(.ivar "tx.origin@7"), (.num 1461501637330902918203684832716283019655932542975)])]), + .decl "tx.gasprice@8" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "tx.gasprice@8")]), (.app "<=" [(.ivar "tx.gasprice@8"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "msg.sig@9" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "msg.sig@9")]), (.app "<=" [(.ivar "msg.sig@9"), (.num 4294967295)])]), + .decl "msg.data@10" .int, + .decl "block.basefee@11" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.basefee@11")]), (.app "<=" [(.ivar "block.basefee@11"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.blobbasefee@12" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.blobbasefee@12")]), (.app "<=" [(.ivar "block.blobbasefee@12"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.coinbase@13" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.coinbase@13")]), (.app "<=" [(.ivar "block.coinbase@13"), (.num 1461501637330902918203684832716283019655932542975)])]), + .decl "block.prevrandao@14" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.prevrandao@14")]), (.app "<=" [(.ivar "block.prevrandao@14"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.difficulty@15" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.difficulty@15")]), (.app "<=" [(.ivar "block.difficulty@15"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.gaslimit@16" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.gaslimit@16")]), (.app "<=" [(.ivar "block.gaslimit@16"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "x@17" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "x@17")]), (.app "<=" [(.ivar "x@17"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "__balance@18" .arr, + .elem "__balance@18" 0 115792089237316195423570985008687907853269984665640564039457584007913129639935, + .decl "__code_epoch@19" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "__code_epoch@19")]), (.app "<=" [(.ivar "__code_epoch@19"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "g@20" .bool, + .assert (.app "=" [(.bvar "g@20"), (.app "and" [.tt, (.app "=" [(.ivar "msg.value@3"), (.num 0)])])]), + .push, + .assert (.bvar "g@20"), + .assert (.app "not" [.ff]), + .checkSat, + .pop, + .pop, + .push, + .raw "; ===== Counter.constructor", + .decl "this@1" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "this@1")]), (.app "<=" [(.ivar "this@1"), (.num 1461501637330902918203684832716283019655932542975)])]), + .decl "msg.sender@2" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "msg.sender@2")]), (.app "<=" [(.ivar "msg.sender@2"), (.num 1461501637330902918203684832716283019655932542975)])]), + .assert (.app "not" [(.app "=" [(.ivar "msg.sender@2"), (.num 0)])]), + .decl "msg.value@3" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "msg.value@3")]), (.app "<=" [(.ivar "msg.value@3"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.timestamp@4" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.timestamp@4")]), (.app "<=" [(.ivar "block.timestamp@4"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.number@5" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.number@5")]), (.app "<=" [(.ivar "block.number@5"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.chainid@6" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.chainid@6")]), (.app "<=" [(.ivar "block.chainid@6"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "tx.origin@7" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "tx.origin@7")]), (.app "<=" [(.ivar "tx.origin@7"), (.num 1461501637330902918203684832716283019655932542975)])]), + .decl "tx.gasprice@8" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "tx.gasprice@8")]), (.app "<=" [(.ivar "tx.gasprice@8"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "msg.sig@9" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "msg.sig@9")]), (.app "<=" [(.ivar "msg.sig@9"), (.num 4294967295)])]), + .decl "msg.data@10" .int, + .decl "block.basefee@11" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.basefee@11")]), (.app "<=" [(.ivar "block.basefee@11"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.blobbasefee@12" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.blobbasefee@12")]), (.app "<=" [(.ivar "block.blobbasefee@12"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.coinbase@13" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.coinbase@13")]), (.app "<=" [(.ivar "block.coinbase@13"), (.num 1461501637330902918203684832716283019655932542975)])]), + .decl "block.prevrandao@14" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.prevrandao@14")]), (.app "<=" [(.ivar "block.prevrandao@14"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.difficulty@15" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.difficulty@15")]), (.app "<=" [(.ivar "block.difficulty@15"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.gaslimit@16" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.gaslimit@16")]), (.app "<=" [(.ivar "block.gaslimit@16"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "__balance@17" .arr, + .elem "__balance@17" 0 115792089237316195423570985008687907853269984665640564039457584007913129639935, + .decl "__code_epoch@18" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "__code_epoch@18")]), (.app "<=" [(.ivar "__code_epoch@18"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "g@19" .bool, + .assert (.app "=" [(.bvar "g@19"), (.app "and" [.tt, (.app "=" [(.ivar "msg.value@3"), (.num 0)])])]), + .push, + .assert (.bvar "g@19"), + .assert (.app "not" [.ff]), + .checkSat, + .pop, + .pop +] + +/-- The transcript, as solar-verify wrote it. -/ +def transcript : String := "(push 1)\n; ===== Counter.inc\n(declare-const |this@1| Int)\n(assert (and (<= 0 |this@1|) (<= |this@1| 1461501637330902918203684832716283019655932542975)))\n(declare-const |msg.sender@2| Int)\n(assert (and (<= 0 |msg.sender@2|) (<= |msg.sender@2| 1461501637330902918203684832716283019655932542975)))\n(assert (not (= |msg.sender@2| 0)))\n(declare-const |msg.value@3| Int)\n(assert (and (<= 0 |msg.value@3|) (<= |msg.value@3| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.timestamp@4| Int)\n(assert (and (<= 0 |block.timestamp@4|) (<= |block.timestamp@4| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.number@5| Int)\n(assert (and (<= 0 |block.number@5|) (<= |block.number@5| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.chainid@6| Int)\n(assert (and (<= 0 |block.chainid@6|) (<= |block.chainid@6| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |tx.origin@7| Int)\n(assert (and (<= 0 |tx.origin@7|) (<= |tx.origin@7| 1461501637330902918203684832716283019655932542975)))\n(declare-const |tx.gasprice@8| Int)\n(assert (and (<= 0 |tx.gasprice@8|) (<= |tx.gasprice@8| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |msg.sig@9| Int)\n(assert (and (<= 0 |msg.sig@9|) (<= |msg.sig@9| 4294967295)))\n(declare-const |msg.data@10| Int)\n(declare-const |block.basefee@11| Int)\n(assert (and (<= 0 |block.basefee@11|) (<= |block.basefee@11| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.blobbasefee@12| Int)\n(assert (and (<= 0 |block.blobbasefee@12|) (<= |block.blobbasefee@12| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.coinbase@13| Int)\n(assert (and (<= 0 |block.coinbase@13|) (<= |block.coinbase@13| 1461501637330902918203684832716283019655932542975)))\n(declare-const |block.prevrandao@14| Int)\n(assert (and (<= 0 |block.prevrandao@14|) (<= |block.prevrandao@14| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.difficulty@15| Int)\n(assert (and (<= 0 |block.difficulty@15|) (<= |block.difficulty@15| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.gaslimit@16| Int)\n(assert (and (<= 0 |block.gaslimit@16|) (<= |block.gaslimit@16| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |x@17| Int)\n(assert (and (<= 0 |x@17|) (<= |x@17| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |__balance@18| (Array Int Int))\n;@elem |__balance@18| 0 115792089237316195423570985008687907853269984665640564039457584007913129639935\n(declare-const |__code_epoch@19| Int)\n(assert (and (<= 0 |__code_epoch@19|) (<= |__code_epoch@19| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |d@20| Int)\n(assert (and (<= 0 |d@20|) (<= |d@20| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |g@21| Bool)\n(assert (= |g@21| (and true (= |msg.value@3| 0))))\n(declare-const |arith@22| Int)\n(assert (= |arith@22| (+ |x@17| |d@20|)))\n(declare-const |g@23| Bool)\n(assert (= |g@23| (and |g@21| (and (<= 0 |arith@22|) (<= |arith@22| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))))\n(push 1)\n(assert |g@23|)\n(assert (not false))\n(check-sat)\n(pop 1)\n(push 1)\n(assert |g@23|)\n(assert (not (= |arith@22| (+ (+ |x@17| |d@20|) 1))))\n(check-sat)\n(pop 1)\n(pop 1)\n(push 1)\n; ===== Counter.get\n(declare-const |this@1| Int)\n(assert (and (<= 0 |this@1|) (<= |this@1| 1461501637330902918203684832716283019655932542975)))\n(declare-const |msg.sender@2| Int)\n(assert (and (<= 0 |msg.sender@2|) (<= |msg.sender@2| 1461501637330902918203684832716283019655932542975)))\n(assert (not (= |msg.sender@2| 0)))\n(declare-const |msg.value@3| Int)\n(assert (and (<= 0 |msg.value@3|) (<= |msg.value@3| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.timestamp@4| Int)\n(assert (and (<= 0 |block.timestamp@4|) (<= |block.timestamp@4| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.number@5| Int)\n(assert (and (<= 0 |block.number@5|) (<= |block.number@5| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.chainid@6| Int)\n(assert (and (<= 0 |block.chainid@6|) (<= |block.chainid@6| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |tx.origin@7| Int)\n(assert (and (<= 0 |tx.origin@7|) (<= |tx.origin@7| 1461501637330902918203684832716283019655932542975)))\n(declare-const |tx.gasprice@8| Int)\n(assert (and (<= 0 |tx.gasprice@8|) (<= |tx.gasprice@8| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |msg.sig@9| Int)\n(assert (and (<= 0 |msg.sig@9|) (<= |msg.sig@9| 4294967295)))\n(declare-const |msg.data@10| Int)\n(declare-const |block.basefee@11| Int)\n(assert (and (<= 0 |block.basefee@11|) (<= |block.basefee@11| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.blobbasefee@12| Int)\n(assert (and (<= 0 |block.blobbasefee@12|) (<= |block.blobbasefee@12| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.coinbase@13| Int)\n(assert (and (<= 0 |block.coinbase@13|) (<= |block.coinbase@13| 1461501637330902918203684832716283019655932542975)))\n(declare-const |block.prevrandao@14| Int)\n(assert (and (<= 0 |block.prevrandao@14|) (<= |block.prevrandao@14| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.difficulty@15| Int)\n(assert (and (<= 0 |block.difficulty@15|) (<= |block.difficulty@15| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.gaslimit@16| Int)\n(assert (and (<= 0 |block.gaslimit@16|) (<= |block.gaslimit@16| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |x@17| Int)\n(assert (and (<= 0 |x@17|) (<= |x@17| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |__balance@18| (Array Int Int))\n;@elem |__balance@18| 0 115792089237316195423570985008687907853269984665640564039457584007913129639935\n(declare-const |__code_epoch@19| Int)\n(assert (and (<= 0 |__code_epoch@19|) (<= |__code_epoch@19| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |g@20| Bool)\n(assert (= |g@20| (and true (= |msg.value@3| 0))))\n(push 1)\n(assert |g@20|)\n(assert (not false))\n(check-sat)\n(pop 1)\n(pop 1)\n(push 1)\n; ===== Counter.constructor\n(declare-const |this@1| Int)\n(assert (and (<= 0 |this@1|) (<= |this@1| 1461501637330902918203684832716283019655932542975)))\n(declare-const |msg.sender@2| Int)\n(assert (and (<= 0 |msg.sender@2|) (<= |msg.sender@2| 1461501637330902918203684832716283019655932542975)))\n(assert (not (= |msg.sender@2| 0)))\n(declare-const |msg.value@3| Int)\n(assert (and (<= 0 |msg.value@3|) (<= |msg.value@3| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.timestamp@4| Int)\n(assert (and (<= 0 |block.timestamp@4|) (<= |block.timestamp@4| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.number@5| Int)\n(assert (and (<= 0 |block.number@5|) (<= |block.number@5| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.chainid@6| Int)\n(assert (and (<= 0 |block.chainid@6|) (<= |block.chainid@6| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |tx.origin@7| Int)\n(assert (and (<= 0 |tx.origin@7|) (<= |tx.origin@7| 1461501637330902918203684832716283019655932542975)))\n(declare-const |tx.gasprice@8| Int)\n(assert (and (<= 0 |tx.gasprice@8|) (<= |tx.gasprice@8| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |msg.sig@9| Int)\n(assert (and (<= 0 |msg.sig@9|) (<= |msg.sig@9| 4294967295)))\n(declare-const |msg.data@10| Int)\n(declare-const |block.basefee@11| Int)\n(assert (and (<= 0 |block.basefee@11|) (<= |block.basefee@11| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.blobbasefee@12| Int)\n(assert (and (<= 0 |block.blobbasefee@12|) (<= |block.blobbasefee@12| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.coinbase@13| Int)\n(assert (and (<= 0 |block.coinbase@13|) (<= |block.coinbase@13| 1461501637330902918203684832716283019655932542975)))\n(declare-const |block.prevrandao@14| Int)\n(assert (and (<= 0 |block.prevrandao@14|) (<= |block.prevrandao@14| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.difficulty@15| Int)\n(assert (and (<= 0 |block.difficulty@15|) (<= |block.difficulty@15| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.gaslimit@16| Int)\n(assert (and (<= 0 |block.gaslimit@16|) (<= |block.gaslimit@16| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |__balance@17| (Array Int Int))\n;@elem |__balance@17| 0 115792089237316195423570985008687907853269984665640564039457584007913129639935\n(declare-const |__code_epoch@18| Int)\n(assert (and (<= 0 |__code_epoch@18|) (<= |__code_epoch@18| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |g@19| Bool)\n(assert (= |g@19| (and true (= |msg.value@3| 0))))\n(push 1)\n(assert |g@19|)\n(assert (not false))\n(check-sat)\n(pop 1)\n(pop 1)\n" + +end SolidCore.Verify.VC.Export.Mutant.CounterSpecMut diff --git a/Contracts/Counter/VC/Mutant/SrcMut.lean b/Contracts/Counter/VC/Mutant/SrcMut.lean new file mode 100644 index 00000000..d044b751 --- /dev/null +++ b/Contracts/Counter/VC/Mutant/SrcMut.lean @@ -0,0 +1,173 @@ +-- Generated by solar-verify --dump-lean. Do not edit. + +import Verify.VC.Term + +namespace SolidCore.Verify.VC.Export.Mutant.CounterSrcMut + +open SolidCore.Verify.VC + +/-- The commands solar-verify sent the solver. -/ +def script : List Cmd := [ + .push, + .raw "; ===== Counter.inc", + .decl "this@1" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "this@1")]), (.app "<=" [(.ivar "this@1"), (.num 1461501637330902918203684832716283019655932542975)])]), + .decl "msg.sender@2" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "msg.sender@2")]), (.app "<=" [(.ivar "msg.sender@2"), (.num 1461501637330902918203684832716283019655932542975)])]), + .assert (.app "not" [(.app "=" [(.ivar "msg.sender@2"), (.num 0)])]), + .decl "msg.value@3" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "msg.value@3")]), (.app "<=" [(.ivar "msg.value@3"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.timestamp@4" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.timestamp@4")]), (.app "<=" [(.ivar "block.timestamp@4"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.number@5" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.number@5")]), (.app "<=" [(.ivar "block.number@5"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.chainid@6" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.chainid@6")]), (.app "<=" [(.ivar "block.chainid@6"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "tx.origin@7" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "tx.origin@7")]), (.app "<=" [(.ivar "tx.origin@7"), (.num 1461501637330902918203684832716283019655932542975)])]), + .decl "tx.gasprice@8" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "tx.gasprice@8")]), (.app "<=" [(.ivar "tx.gasprice@8"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "msg.sig@9" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "msg.sig@9")]), (.app "<=" [(.ivar "msg.sig@9"), (.num 4294967295)])]), + .decl "msg.data@10" .int, + .decl "block.basefee@11" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.basefee@11")]), (.app "<=" [(.ivar "block.basefee@11"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.blobbasefee@12" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.blobbasefee@12")]), (.app "<=" [(.ivar "block.blobbasefee@12"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.coinbase@13" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.coinbase@13")]), (.app "<=" [(.ivar "block.coinbase@13"), (.num 1461501637330902918203684832716283019655932542975)])]), + .decl "block.prevrandao@14" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.prevrandao@14")]), (.app "<=" [(.ivar "block.prevrandao@14"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.difficulty@15" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.difficulty@15")]), (.app "<=" [(.ivar "block.difficulty@15"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.gaslimit@16" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.gaslimit@16")]), (.app "<=" [(.ivar "block.gaslimit@16"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "x@17" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "x@17")]), (.app "<=" [(.ivar "x@17"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "__balance@18" .arr, + .elem "__balance@18" 0 115792089237316195423570985008687907853269984665640564039457584007913129639935, + .decl "__code_epoch@19" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "__code_epoch@19")]), (.app "<=" [(.ivar "__code_epoch@19"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "d@20" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "d@20")]), (.app "<=" [(.ivar "d@20"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "g@21" .bool, + .assert (.app "=" [(.bvar "g@21"), (.app "and" [.tt, (.app "=" [(.ivar "msg.value@3"), (.num 0)])])]), + .decl "arith@22" .int, + .assert (.app "=" [(.ivar "arith@22"), (.app "+" [(.ivar "d@20"), (.num 1)])]), + .decl "g@23" .bool, + .assert (.app "=" [(.bvar "g@23"), (.app "and" [(.bvar "g@21"), (.app "and" [(.app "<=" [(.num 0), (.ivar "arith@22")]), (.app "<=" [(.ivar "arith@22"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])])])]), + .decl "arith@24" .int, + .assert (.app "=" [(.ivar "arith@24"), (.app "+" [(.ivar "x@17"), (.ivar "arith@22")])]), + .decl "g@25" .bool, + .assert (.app "=" [(.bvar "g@25"), (.app "and" [(.bvar "g@23"), (.app "and" [(.app "<=" [(.num 0), (.ivar "arith@24")]), (.app "<=" [(.ivar "arith@24"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])])])]), + .push, + .assert (.bvar "g@25"), + .assert (.app "not" [.ff]), + .checkSat, + .pop, + .push, + .assert (.bvar "g@25"), + .assert (.app "not" [(.app "=" [(.ivar "arith@24"), (.app "+" [(.ivar "x@17"), (.ivar "d@20")])])]), + .checkSat, + .pop, + .pop, + .push, + .raw "; ===== Counter.get", + .decl "this@1" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "this@1")]), (.app "<=" [(.ivar "this@1"), (.num 1461501637330902918203684832716283019655932542975)])]), + .decl "msg.sender@2" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "msg.sender@2")]), (.app "<=" [(.ivar "msg.sender@2"), (.num 1461501637330902918203684832716283019655932542975)])]), + .assert (.app "not" [(.app "=" [(.ivar "msg.sender@2"), (.num 0)])]), + .decl "msg.value@3" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "msg.value@3")]), (.app "<=" [(.ivar "msg.value@3"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.timestamp@4" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.timestamp@4")]), (.app "<=" [(.ivar "block.timestamp@4"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.number@5" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.number@5")]), (.app "<=" [(.ivar "block.number@5"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.chainid@6" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.chainid@6")]), (.app "<=" [(.ivar "block.chainid@6"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "tx.origin@7" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "tx.origin@7")]), (.app "<=" [(.ivar "tx.origin@7"), (.num 1461501637330902918203684832716283019655932542975)])]), + .decl "tx.gasprice@8" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "tx.gasprice@8")]), (.app "<=" [(.ivar "tx.gasprice@8"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "msg.sig@9" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "msg.sig@9")]), (.app "<=" [(.ivar "msg.sig@9"), (.num 4294967295)])]), + .decl "msg.data@10" .int, + .decl "block.basefee@11" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.basefee@11")]), (.app "<=" [(.ivar "block.basefee@11"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.blobbasefee@12" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.blobbasefee@12")]), (.app "<=" [(.ivar "block.blobbasefee@12"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.coinbase@13" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.coinbase@13")]), (.app "<=" [(.ivar "block.coinbase@13"), (.num 1461501637330902918203684832716283019655932542975)])]), + .decl "block.prevrandao@14" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.prevrandao@14")]), (.app "<=" [(.ivar "block.prevrandao@14"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.difficulty@15" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.difficulty@15")]), (.app "<=" [(.ivar "block.difficulty@15"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.gaslimit@16" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.gaslimit@16")]), (.app "<=" [(.ivar "block.gaslimit@16"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "x@17" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "x@17")]), (.app "<=" [(.ivar "x@17"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "__balance@18" .arr, + .elem "__balance@18" 0 115792089237316195423570985008687907853269984665640564039457584007913129639935, + .decl "__code_epoch@19" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "__code_epoch@19")]), (.app "<=" [(.ivar "__code_epoch@19"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "g@20" .bool, + .assert (.app "=" [(.bvar "g@20"), (.app "and" [.tt, (.app "=" [(.ivar "msg.value@3"), (.num 0)])])]), + .push, + .assert (.bvar "g@20"), + .assert (.app "not" [.ff]), + .checkSat, + .pop, + .pop, + .push, + .raw "; ===== Counter.constructor", + .decl "this@1" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "this@1")]), (.app "<=" [(.ivar "this@1"), (.num 1461501637330902918203684832716283019655932542975)])]), + .decl "msg.sender@2" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "msg.sender@2")]), (.app "<=" [(.ivar "msg.sender@2"), (.num 1461501637330902918203684832716283019655932542975)])]), + .assert (.app "not" [(.app "=" [(.ivar "msg.sender@2"), (.num 0)])]), + .decl "msg.value@3" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "msg.value@3")]), (.app "<=" [(.ivar "msg.value@3"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.timestamp@4" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.timestamp@4")]), (.app "<=" [(.ivar "block.timestamp@4"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.number@5" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.number@5")]), (.app "<=" [(.ivar "block.number@5"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.chainid@6" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.chainid@6")]), (.app "<=" [(.ivar "block.chainid@6"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "tx.origin@7" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "tx.origin@7")]), (.app "<=" [(.ivar "tx.origin@7"), (.num 1461501637330902918203684832716283019655932542975)])]), + .decl "tx.gasprice@8" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "tx.gasprice@8")]), (.app "<=" [(.ivar "tx.gasprice@8"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "msg.sig@9" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "msg.sig@9")]), (.app "<=" [(.ivar "msg.sig@9"), (.num 4294967295)])]), + .decl "msg.data@10" .int, + .decl "block.basefee@11" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.basefee@11")]), (.app "<=" [(.ivar "block.basefee@11"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.blobbasefee@12" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.blobbasefee@12")]), (.app "<=" [(.ivar "block.blobbasefee@12"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.coinbase@13" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.coinbase@13")]), (.app "<=" [(.ivar "block.coinbase@13"), (.num 1461501637330902918203684832716283019655932542975)])]), + .decl "block.prevrandao@14" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.prevrandao@14")]), (.app "<=" [(.ivar "block.prevrandao@14"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.difficulty@15" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.difficulty@15")]), (.app "<=" [(.ivar "block.difficulty@15"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.gaslimit@16" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.gaslimit@16")]), (.app "<=" [(.ivar "block.gaslimit@16"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "__balance@17" .arr, + .elem "__balance@17" 0 115792089237316195423570985008687907853269984665640564039457584007913129639935, + .decl "__code_epoch@18" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "__code_epoch@18")]), (.app "<=" [(.ivar "__code_epoch@18"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "g@19" .bool, + .assert (.app "=" [(.bvar "g@19"), (.app "and" [.tt, (.app "=" [(.ivar "msg.value@3"), (.num 0)])])]), + .push, + .assert (.bvar "g@19"), + .assert (.app "not" [.ff]), + .checkSat, + .pop, + .pop +] + +/-- The transcript, as solar-verify wrote it. -/ +def transcript : String := "(push 1)\n; ===== Counter.inc\n(declare-const |this@1| Int)\n(assert (and (<= 0 |this@1|) (<= |this@1| 1461501637330902918203684832716283019655932542975)))\n(declare-const |msg.sender@2| Int)\n(assert (and (<= 0 |msg.sender@2|) (<= |msg.sender@2| 1461501637330902918203684832716283019655932542975)))\n(assert (not (= |msg.sender@2| 0)))\n(declare-const |msg.value@3| Int)\n(assert (and (<= 0 |msg.value@3|) (<= |msg.value@3| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.timestamp@4| Int)\n(assert (and (<= 0 |block.timestamp@4|) (<= |block.timestamp@4| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.number@5| Int)\n(assert (and (<= 0 |block.number@5|) (<= |block.number@5| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.chainid@6| Int)\n(assert (and (<= 0 |block.chainid@6|) (<= |block.chainid@6| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |tx.origin@7| Int)\n(assert (and (<= 0 |tx.origin@7|) (<= |tx.origin@7| 1461501637330902918203684832716283019655932542975)))\n(declare-const |tx.gasprice@8| Int)\n(assert (and (<= 0 |tx.gasprice@8|) (<= |tx.gasprice@8| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |msg.sig@9| Int)\n(assert (and (<= 0 |msg.sig@9|) (<= |msg.sig@9| 4294967295)))\n(declare-const |msg.data@10| Int)\n(declare-const |block.basefee@11| Int)\n(assert (and (<= 0 |block.basefee@11|) (<= |block.basefee@11| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.blobbasefee@12| Int)\n(assert (and (<= 0 |block.blobbasefee@12|) (<= |block.blobbasefee@12| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.coinbase@13| Int)\n(assert (and (<= 0 |block.coinbase@13|) (<= |block.coinbase@13| 1461501637330902918203684832716283019655932542975)))\n(declare-const |block.prevrandao@14| Int)\n(assert (and (<= 0 |block.prevrandao@14|) (<= |block.prevrandao@14| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.difficulty@15| Int)\n(assert (and (<= 0 |block.difficulty@15|) (<= |block.difficulty@15| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.gaslimit@16| Int)\n(assert (and (<= 0 |block.gaslimit@16|) (<= |block.gaslimit@16| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |x@17| Int)\n(assert (and (<= 0 |x@17|) (<= |x@17| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |__balance@18| (Array Int Int))\n;@elem |__balance@18| 0 115792089237316195423570985008687907853269984665640564039457584007913129639935\n(declare-const |__code_epoch@19| Int)\n(assert (and (<= 0 |__code_epoch@19|) (<= |__code_epoch@19| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |d@20| Int)\n(assert (and (<= 0 |d@20|) (<= |d@20| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |g@21| Bool)\n(assert (= |g@21| (and true (= |msg.value@3| 0))))\n(declare-const |arith@22| Int)\n(assert (= |arith@22| (+ |d@20| 1)))\n(declare-const |g@23| Bool)\n(assert (= |g@23| (and |g@21| (and (<= 0 |arith@22|) (<= |arith@22| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))))\n(declare-const |arith@24| Int)\n(assert (= |arith@24| (+ |x@17| |arith@22|)))\n(declare-const |g@25| Bool)\n(assert (= |g@25| (and |g@23| (and (<= 0 |arith@24|) (<= |arith@24| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))))\n(push 1)\n(assert |g@25|)\n(assert (not false))\n(check-sat)\n(pop 1)\n(push 1)\n(assert |g@25|)\n(assert (not (= |arith@24| (+ |x@17| |d@20|))))\n(check-sat)\n(pop 1)\n(pop 1)\n(push 1)\n; ===== Counter.get\n(declare-const |this@1| Int)\n(assert (and (<= 0 |this@1|) (<= |this@1| 1461501637330902918203684832716283019655932542975)))\n(declare-const |msg.sender@2| Int)\n(assert (and (<= 0 |msg.sender@2|) (<= |msg.sender@2| 1461501637330902918203684832716283019655932542975)))\n(assert (not (= |msg.sender@2| 0)))\n(declare-const |msg.value@3| Int)\n(assert (and (<= 0 |msg.value@3|) (<= |msg.value@3| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.timestamp@4| Int)\n(assert (and (<= 0 |block.timestamp@4|) (<= |block.timestamp@4| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.number@5| Int)\n(assert (and (<= 0 |block.number@5|) (<= |block.number@5| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.chainid@6| Int)\n(assert (and (<= 0 |block.chainid@6|) (<= |block.chainid@6| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |tx.origin@7| Int)\n(assert (and (<= 0 |tx.origin@7|) (<= |tx.origin@7| 1461501637330902918203684832716283019655932542975)))\n(declare-const |tx.gasprice@8| Int)\n(assert (and (<= 0 |tx.gasprice@8|) (<= |tx.gasprice@8| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |msg.sig@9| Int)\n(assert (and (<= 0 |msg.sig@9|) (<= |msg.sig@9| 4294967295)))\n(declare-const |msg.data@10| Int)\n(declare-const |block.basefee@11| Int)\n(assert (and (<= 0 |block.basefee@11|) (<= |block.basefee@11| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.blobbasefee@12| Int)\n(assert (and (<= 0 |block.blobbasefee@12|) (<= |block.blobbasefee@12| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.coinbase@13| Int)\n(assert (and (<= 0 |block.coinbase@13|) (<= |block.coinbase@13| 1461501637330902918203684832716283019655932542975)))\n(declare-const |block.prevrandao@14| Int)\n(assert (and (<= 0 |block.prevrandao@14|) (<= |block.prevrandao@14| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.difficulty@15| Int)\n(assert (and (<= 0 |block.difficulty@15|) (<= |block.difficulty@15| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.gaslimit@16| Int)\n(assert (and (<= 0 |block.gaslimit@16|) (<= |block.gaslimit@16| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |x@17| Int)\n(assert (and (<= 0 |x@17|) (<= |x@17| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |__balance@18| (Array Int Int))\n;@elem |__balance@18| 0 115792089237316195423570985008687907853269984665640564039457584007913129639935\n(declare-const |__code_epoch@19| Int)\n(assert (and (<= 0 |__code_epoch@19|) (<= |__code_epoch@19| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |g@20| Bool)\n(assert (= |g@20| (and true (= |msg.value@3| 0))))\n(push 1)\n(assert |g@20|)\n(assert (not false))\n(check-sat)\n(pop 1)\n(pop 1)\n(push 1)\n; ===== Counter.constructor\n(declare-const |this@1| Int)\n(assert (and (<= 0 |this@1|) (<= |this@1| 1461501637330902918203684832716283019655932542975)))\n(declare-const |msg.sender@2| Int)\n(assert (and (<= 0 |msg.sender@2|) (<= |msg.sender@2| 1461501637330902918203684832716283019655932542975)))\n(assert (not (= |msg.sender@2| 0)))\n(declare-const |msg.value@3| Int)\n(assert (and (<= 0 |msg.value@3|) (<= |msg.value@3| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.timestamp@4| Int)\n(assert (and (<= 0 |block.timestamp@4|) (<= |block.timestamp@4| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.number@5| Int)\n(assert (and (<= 0 |block.number@5|) (<= |block.number@5| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.chainid@6| Int)\n(assert (and (<= 0 |block.chainid@6|) (<= |block.chainid@6| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |tx.origin@7| Int)\n(assert (and (<= 0 |tx.origin@7|) (<= |tx.origin@7| 1461501637330902918203684832716283019655932542975)))\n(declare-const |tx.gasprice@8| Int)\n(assert (and (<= 0 |tx.gasprice@8|) (<= |tx.gasprice@8| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |msg.sig@9| Int)\n(assert (and (<= 0 |msg.sig@9|) (<= |msg.sig@9| 4294967295)))\n(declare-const |msg.data@10| Int)\n(declare-const |block.basefee@11| Int)\n(assert (and (<= 0 |block.basefee@11|) (<= |block.basefee@11| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.blobbasefee@12| Int)\n(assert (and (<= 0 |block.blobbasefee@12|) (<= |block.blobbasefee@12| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.coinbase@13| Int)\n(assert (and (<= 0 |block.coinbase@13|) (<= |block.coinbase@13| 1461501637330902918203684832716283019655932542975)))\n(declare-const |block.prevrandao@14| Int)\n(assert (and (<= 0 |block.prevrandao@14|) (<= |block.prevrandao@14| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.difficulty@15| Int)\n(assert (and (<= 0 |block.difficulty@15|) (<= |block.difficulty@15| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.gaslimit@16| Int)\n(assert (and (<= 0 |block.gaslimit@16|) (<= |block.gaslimit@16| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |__balance@17| (Array Int Int))\n;@elem |__balance@17| 0 115792089237316195423570985008687907853269984665640564039457584007913129639935\n(declare-const |__code_epoch@18| Int)\n(assert (and (<= 0 |__code_epoch@18|) (<= |__code_epoch@18| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |g@19| Bool)\n(assert (= |g@19| (and true (= |msg.value@3| 0))))\n(push 1)\n(assert |g@19|)\n(assert (not false))\n(check-sat)\n(pop 1)\n(pop 1)\n" + +end SolidCore.Verify.VC.Export.Mutant.CounterSrcMut diff --git a/Contracts/Counter/VC/Mutants.lean b/Contracts/Counter/VC/Mutants.lean new file mode 100644 index 00000000..14e16398 --- /dev/null +++ b/Contracts/Counter/VC/Mutants.lean @@ -0,0 +1,28 @@ +import Contracts.Counter.VC.Inc +import Contracts.Counter.VC.Mutant.SrcMut +import Contracts.Counter.VC.Mutant.SpecMut + +/-! +# Mutants that break `Counter.inc`'s binding + +Two copies of `scripts/verify/CounterMilestone.sol`, each changed in one line and exported by the same +solar-verify (`scripts/verify/mutant/MANIFEST`): +* `CounterSrcMut` changes the source to `x += d + 1`. solar-verify's encoding of the new `x` changes with + it, so none of its obligations is `incHyps ⟹ incGoal`, whose effect term `incEff` is the one + `inc_binding` ties to what SolidCore runs on the real source. +* `CounterSpecMut` changes the spec to `x == old(x) + d + 1`. Its obligation's goal is not `incGoal`. + +`checkScript` rejects both, so neither script is bound to SolidCore's `Counter`. +-/ + +namespace SolidCore.Verify.VC.Counter + +open SolidCore.Verify.VC + +theorem srcMut_rejected : checkScript Export.Mutant.CounterSrcMut.script [(incHyps, incGoal)] = false := by + decide +kernel + +theorem specMut_rejected : checkScript Export.Mutant.CounterSpecMut.script [(incHyps, incGoal)] = false := by + decide +kernel + +end SolidCore.Verify.VC.Counter diff --git a/Contracts/Counter/Verdict.lean b/Contracts/Counter/Verdict.lean new file mode 100644 index 00000000..fbf4baa0 --- /dev/null +++ b/Contracts/Counter/Verdict.lean @@ -0,0 +1,81 @@ +import Contracts.Counter.Final +import Verify.Spec.TrustedBase.Instances + +/-! +# The counter milestone's bytecode meets solar-verify's spec, given its verdict + +This is where the certified translation and solar-verify meet for the counter milestone +(solar-tv/milestone/counter, the source `scripts/refinement/counter/counter.sol`). The stage from +SolidCore's checked contract to solar's bytecode is a theorem (`agree`, from +`Counter.Every`'s source run and `Counter.Final.target_every`, which compose solar-tv's backend +stages); the bytecode is bound to the exporter's manifest (`Counter.Final.bound`: its hex and +SHA-256, checked by the kernel) and runs in one frame (`Counter.Final.frameLocal`). + +`bytecode_spec_of_verdict` takes the rest as hypotheses and nothing else: a spec bundle `b` +(what `solar-verify --emit-lean-spec` exports), its well-formedness and opaque ranges, and +solar-verify's verdict on SolidCore's contract under the trusted base `Hyps.plain` of +`SolidCore.Spec.TrustedBase` (no hashing, no external call, no assembly, no assume, no trusted +function), which `TrustedBase.Instances.counter_on` discharges. The verdict is the only premise +about the spec: the theorem holds for every bundle whose verdict holds, and for a bundle the +bytecode does not meet the conclusion fails, so the verdict fails too. + +What it covers: runtime calls of `scopeEvery` (`inc` and `get` with any value, malformed call +data and unknown selectors, from any storage), under EthLib's run at its default gas limit +(`Target.run`). Not covered: deployment, other gas limits, and calls from other contracts +(the code makes none). +-/ + +namespace SolidCore.Refinement.Solar.Counter.Verdict + +open SolidCore.Refinement SolidCore.Refinement.Final + +/-- The counter's trusted base: nothing to trust beyond the verdict (`Hyps.plain`). -/ +abbrev hyps (c : SolidCore.Solidity.TypeCheck.CheckedContract) (deployed : Nat → Nat) : + SolidCore.Spec.TrustedBase.Hyps (solidCore fuel) c := + SolidCore.Spec.TrustedBase.Hyps.plain (solidCore fuel) c Source.Counter.importedSourceUnit + deployed (fun _ => []) + +/-- SolidCore's checked counter and solar's bytecode show the same observable on every call of +the scope. -/ +theorem agree {c : SolidCore.Solidity.TypeCheck.CheckedContract} (hc : contract? = .ok c) : + Agree (solidCore fuel) ethLib c code scopeEvery := + fun call h => ⟨_, source_run_every hc call h, Final.target_every call h⟩ + +/-- **The counter's bytecode meets every spec solar-verify accepts of its source.** -/ +theorem bytecode_spec_of_verdict {c : SolidCore.Solidity.TypeCheck.CheckedContract} (hc : contract? = .ok c) + {b : SolidCore.Spec.Bundle} {ctxOf : Call → SolidCore.Spec.Ctx} + {step : SolidCore.Spec.GhostStep} (deployed : Nat → Nat) + (hwf : b.WF = true) (hopaque : SolidCore.Spec.OpaqueInRange b) + (verdict : SolidCore.Spec.Verdict (solidCore fuel) c scopeEvery b ctxOf step + ((hyps c deployed).toAssumptions scopeEvery b ctxOf step)) : + Bound Final.manifest code ∧ FrameLocal code = true ∧ + Agree (solidCore fuel) ethLib c code scopeEvery ∧ + SolidCore.Spec.Holds ethLib code scopeEvery b ctxOf step := + ⟨Final.bound, Final.frameLocal, agree hc, + SolidCore.Spec.TrustedBase.Instances.counter_spec_of_verdict deployed hwf hopaque verdict + (agree hc).stage⟩ + +/-- info: 'SolidCore.Refinement.Solar.Counter.Verdict.bytecode_spec_of_verdict' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms bytecode_spec_of_verdict + +/-- **The counter's bytecode meets every total-correctness triple of its source.** A +`SolidCore.Verify.Triple` of SolidCore's checked counter, the shape solar-verify's VCs discharge +to through Loom's `triple_of_wp`, on a scope inside `scopeEvery` carries to solar's bytecode +under EthLib: each call of the scope that meets `pre` finishes on the bytecode with an +observable meeting `post`. Pointwise: the fuel is the triple's own. -/ +theorem bytecode_of_triple {c : SolidCore.Solidity.TypeCheck.CheckedContract} + (hc : contract? = .ok c) {scope pre : Call → Prop} {post : Call → Observable → Prop} + (hs : ∀ call, scope call → scopeEvery call) + (h : SolidCore.Verify.Triple fuel c scope pre post) : + ∀ call, scope call → pre call → ∃ obs, Target.run code call = some obs ∧ post call obs := by + intro call hsc hp + obtain ⟨hsome, hpost⟩ := h call hsc hp + obtain ⟨obs, hobs⟩ := Option.isSome_iff_exists.mp hsome + exact ⟨obs, (agree hc).stage call (hs call hsc) obs hobs, hpost obs hobs⟩ + +/-- info: 'SolidCore.Refinement.Solar.Counter.Verdict.bytecode_of_triple' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms bytecode_of_triple + +end SolidCore.Refinement.Solar.Counter.Verdict diff --git a/Contracts/Counter/Verify.lean b/Contracts/Counter/Verify.lean new file mode 100644 index 00000000..7df25d1f --- /dev/null +++ b/Contracts/Counter/Verify.lean @@ -0,0 +1,180 @@ +import Verify.Final +import Verify.Abi + +/-! +# solar-verify's Counter: its specification and what certifies it + +The contract is `crates/verify/examples/Counter.sol` of solar (branch `alpharush/verify`), +compiled by solar at 3a044a9d (`alpharush/tv-backend-stages`) with `-Ogas --evm-version osaka` +to 496 bytes of runtime bytecode (`manifest`, `code`; `bound` checks the hex and the SHA-256 in +the kernel). Its NatSpec, read as `Final.ContractSpec` over the abstract state `(count, limit)` +that slots 0 and 1 hold: + +* `@custom:invariant count <= limit`; +* `increment()`: requires `count < limit`, ensures `count == old(count) + 1`; +* `bump(uint256 n)`: ensures `count == old(count) + n` (its loop's invariants and variant are + the proof's, not the contract's); +* `max(uint256 a, uint256 b)`: ensures `result == (a >= b ? a : b)`, `result >= a` and + `result >= b`; +* the getters `count()` and `limit()` have no specification but the invariants; +* nothing is payable. + +The constructor's `@custom:ensures limit == _limit && count == 0` is about deployment, which +`Final` does not cover; it is what makes the invariant hold of the first storage. + +`bump(n)` runs its loop `n` times, so its gas grows with `n` and SolidCore needs fuel that grows +with `n`: no fixed gas limit or fuel finishes every call. The statement is therefore +`Final.compose_anyGas`'s, against SolidCore with as much fuel as a call needs (`solidCoreAny`) +and at every gas: every result of the bytecode is SolidCore's or a failure that changes nothing, +and the specification holds at every gas. `certified_of_stages` gives it from the stages, each a +hypothesis named after its obligation. None of them is proved yet: the generic source stage, +solar-tv's backend stages and the assembly stage handle loop-free programs only. + +The specification is not met trivially (`satisfiable`: every function has a state that meets the +invariant and its precondition; `ensures_rejects`: each postcondition rejects some result), and +the code runs in one frame (`frameLocal`), so no other contract can run during a call. +-/ + +namespace SolidCore.Refinement.Solar.VerifyCounter + +open SolidCore.Refinement SolidCore.Refinement.Final + +/-- The abstract state: `count` (slot 0) and `limit` (slot 1). -/ +structure State where + count : Nat + limit : Nat + +/-- The storage layout. -/ +def layout (s : Nat → Nat) : State := ⟨s 0, s 1⟩ + +/-- The ABI return data of one word. -/ +def returns (out : List Nat) (r : Nat) : Prop := out = SolidCore.Verify.word r + +def countSpec : FnSpec State where + name := "count" + sel := 0x06661abd + params := [] + requires _ _ := True + ensures _ _ _ _ := True + payable := false + +def limitSpec : FnSpec State where + name := "limit" + sel := 0xa4d66daf + params := [] + requires _ _ := True + ensures _ _ _ _ := True + payable := false + +/-- `@custom:requires count < limit`, `@custom:ensures count == old(count) + 1`. -/ +def incrementSpec : FnSpec State where + name := "increment" + sel := 0xd09de08a + params := [] + requires _ s := s.count < s.limit + ensures _ s s' _ := s'.count = s.count + 1 + payable := false + +/-- `@custom:ensures count == old(count) + n`. -/ +def bumpSpec : FnSpec State where + name := "bump" + sel := 0xb20eb4c4 + params := [.uint 256] + requires _ _ := True + ensures args s s' _ := s'.count = s.count + args.headD 0 + payable := false + +/-- `@custom:ensures result == (a >= b ? a : b)`, `result >= a && result >= b`. -/ +def maxSpec : FnSpec State where + name := "max" + sel := 0x6d5433e6 + params := [.uint 256, .uint 256] + requires _ _ := True + ensures args _ _ out := + let a := args.getD 0 0 + let b := args.getD 1 0 + ∃ r, returns out r ∧ r = (if a ≥ b then a else b) ∧ r ≥ a ∧ r ≥ b + payable := false + +/-- Counter's specification. -/ +def spec : ContractSpec State where + abs := layout + invariant s := s.count ≤ s.limit + fns := [countSpec, limitSpec, incrementSpec, bumpSpec, maxSpec] + +/-! ## The bytecode and its manifest -/ + +def manifest : Manifest where + contract := "Counter" + sourceSha256 := "f1c87a334b8db31fc8f80541febeaf8617318d20b685634f44e26c74146ad326" + compilerCommit := "0.8.38+commit.3a044a9d.solar.0.3.0-dev" + options := ["-Ogas", "--evm-version", "osaka"] + runtimeHex := + "34603c575f3560e01c806306661abd1460525780636d5433e6146101af578063a4d66daf14605b578063b20eb4c4146073578063d09de08a146065575b5f5ffd5b6011602052634e487b715f526024601cfd5b5f545f5260205ff35b6001545f5260205ff35b5f5460010180156040575f55005b60243610603c576004355f54818101818110604057600154106101d25780816080525f60a0528082820361019a575f5f91925060db565b506080516001840180158583036101675760405780608052600160a05260018301925f191480610182575093505060015b8482105f54808503610111575060aa5760a051815f10828203610152571561010f5750505050608051815f5581810361013e575b005b90506d011100000004000000010000000f939091935b60205260405260605263ed572b275b5f526064601cfd5b6d012100000004000000050000000e610127565b506d012100000004000000040000000c610127565b505090506d0121000000040000000300000008929192610127565b5f6d0102000000040000000a00000012919091610127565b506d010300000004000000070000000b610127565b60443610603c576004356024358082106101cb57505f5260205ff35b5f5260205ff35b636f76657260e01b6004602080526040526060526308c379a061013656" + runtimeSha256 := "d74a847b897f855f93daf2805937efe40aec636c2ec3ca0c2d4ca6d21f214cc1" + +/-- The runtime bytecode as one number, most significant byte first, as the milestones write +it: the kernel computes with it by GMP, where parsing the hex string would cost it minutes. -/ +def runtimeNat : Nat := 0x34603c575f3560e01c806306661abd1460525780636d5433e6146101af578063a4d66daf14605b578063b20eb4c4146073578063d09de08a146065575b5f5ffd5b6011602052634e487b715f526024601cfd5b5f545f5260205ff35b6001545f5260205ff35b5f5460010180156040575f55005b60243610603c576004355f54818101818110604057600154106101d25780816080525f60a0528082820361019a575f5f91925060db565b506080516001840180158583036101675760405780608052600160a05260018301925f191480610182575093505060015b8482105f54808503610111575060aa5760a051815f10828203610152571561010f5750505050608051815f5581810361013e575b005b90506d011100000004000000010000000f939091935b60205260405260605263ed572b275b5f526064601cfd5b6d012100000004000000050000000e610127565b506d012100000004000000040000000c610127565b505090506d0121000000040000000300000008929192610127565b5f6d0102000000040000000a00000012919091610127565b506d010300000004000000070000000b610127565b60443610603c576004356024358082106101cb57505f5260205ff35b5f5260205ff35b636f76657260e01b6004602080526040526060526308c379a061013656 + +/-- The runtime bytecode. `bound` checks it against the manifest's hex and SHA-256. -/ +def code : ByteArray := EthLib.Execution.Evm.Logic.NatCode.ofNat runtimeNat 496 + +theorem size_code : code.size = 496 := by decide +kernel + +theorem bound : Bound manifest code := ⟨by decide +kernel, by decide +kernel⟩ + +/-- No instruction of the code runs other code or reads outside its frame. -/ +theorem frameLocal : FrameLocal code = true := by decide +kernel + +/-! ## The specification is not trivial -/ + +/-- Every function has argument words and a state that meet the invariant and its +precondition. -/ +theorem satisfiable : ∀ f ∈ spec.fns, ∃ args st, f.Typed args ∧ spec.invariant st ∧ f.requires args st := by + intro f hf + simp only [spec, List.mem_cons, List.not_mem_nil, or_false] at hf + rcases hf with rfl | rfl | rfl | rfl | rfl + · exact ⟨[], ⟨0, 0⟩, List.Forall₂.nil, Nat.le_refl _, trivial⟩ + · exact ⟨[], ⟨0, 0⟩, List.Forall₂.nil, Nat.le_refl _, trivial⟩ + · exact ⟨[], ⟨0, 1⟩, List.Forall₂.nil, Nat.zero_le 1, Nat.zero_lt_one⟩ + · exact ⟨[0], ⟨0, 0⟩, List.Forall₂.cons (by decide) List.Forall₂.nil, Nat.le_refl _, trivial⟩ + · exact ⟨[0, 0], ⟨0, 0⟩, List.Forall₂.cons (by decide) (List.Forall₂.cons (by decide) + List.Forall₂.nil), Nat.le_refl _, trivial⟩ + +/-- The postconditions of `increment`, `bump` and `max` each reject some result. -/ +theorem ensures_rejects : + ¬ incrementSpec.ensures [] ⟨0, 1⟩ ⟨0, 1⟩ [] ∧ ¬ bumpSpec.ensures [1] ⟨0, 1⟩ ⟨0, 1⟩ [] ∧ + ¬ maxSpec.ensures [1, 2] ⟨0, 0⟩ ⟨0, 0⟩ (SolidCore.Verify.word 1) := by + refine ⟨by simp [incrementSpec], by simp [bumpSpec], ?_⟩ + rintro ⟨r, hret, hr, -⟩ + have h2 : r = 2 := by simpa using hr + subst h2 + exact absurd hret (by unfold returns; decide +kernel) + +/-! ## The certificate from its stages -/ + +/-- **solar-verify's Counter from its stages.** SolidCore's checked contract `c`, which meets the +specification and finishes every call of it with enough fuel, a stage from SolidCore to a lowered +MIR program, the backend's stage to an EVM IR program, and an assembly stage that gives at every +gas the EVM IR's result or a failure, give at every gas: every result of the bytecode is +SolidCore's or a failure that changes nothing, and the specification holds of the bytecode. -/ +theorem certified_of_stages {mirSem evmirSem : Sem} + {c : SolidCore.Solidity.TypeCheck.CheckedContract} {mir : mirSem.Prog} {evmir : evmirSem.Prog} + (source : Holds solidCoreAny c spec) + (fin : ∀ call, spec.Calls call → (solidCoreAny.run c call).isSome) + (lowering : Stage solidCoreAny mirSem c mir spec.Calls) + (backend : Stage mirSem evmirSem mir evmir spec.Calls) + (assembly : ∀ gas, Within evmirSem (ethLibWith gas) evmir code spec.Calls) (gas : Nat) : + Within solidCoreAny (ethLibWith gas) c code spec.Calls ∧ Holds (ethLibWith gas) code spec := + compose_anyGas source fin lowering backend assembly gas + +/-- info: 'SolidCore.Refinement.Solar.VerifyCounter.bound' depends on axioms: [propext, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms bound + +/-- info: 'SolidCore.Refinement.Solar.VerifyCounter.certified_of_stages' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms certified_of_stages + +end SolidCore.Refinement.Solar.VerifyCounter diff --git a/Contracts/Token/VC/Bind.lean b/Contracts/Token/VC/Bind.lean new file mode 100644 index 00000000..98eeafc7 --- /dev/null +++ b/Contracts/Token/VC/Bind.lean @@ -0,0 +1,15 @@ +import Contracts.Token.VC.Export + +/-! +# The exported scripts are solar-verify's transcripts + +Each exported `script` prints back to its `transcript`, the bytes solar-verify wrote with +`--dump-smt` in the same run. The check runs Lean's evaluator: the kernel's evaluation of the +printer on a transcript of 20 KB, with its 78-digit numerals, does not fit in this build's memory. +-/ + +namespace SolidCore.Verify.VC + +#guard printScript Export.Token.script == Export.Token.transcript + +end SolidCore.Verify.VC diff --git a/Contracts/Token/VC/Burn.lean b/Contracts/Token/VC/Burn.lean new file mode 100644 index 00000000..13b4b0b2 --- /dev/null +++ b/Contracts/Token/VC/Burn.lean @@ -0,0 +1,329 @@ +import Verify.VC +import Contracts.Token.VC.Source +import SolidCore.Refinement.KernelRfl +import Verify.VC.KernelIdx + +/-! +# solar-verify's `Token.burn` against SolidCore + +The kernel's evaluation fixes what SolidCore does with `scripts/verify/Token.sol`: it type checks, +its constructor leaves only `owner` (slot 2) and no logs, `burn(uint256)` dispatches to a function +of one parameter, and the generic source stage erases it to `burnTree` (`burnShape_eq`). As in the +Token source stage, the checker's selectors come from a table each of whose entries the kernel +checks against Keccak-256 once. +-/ + +namespace SolidCore.Verify.VC.Token + +open SolidCore.Refinement SolidCore.Refinement.Abi SolidCore.Refinement.Generic +open SolidCore.Solidity SolidCore.Solidity.Source + +/-- The interpreter fuel of SolidCore's runs. -/ +def fuel : Nat := 4096 + +/-- SolidCore's checked `Token`. -/ +def contract? : Except TypeCheck.TypeError TypeCheck.CheckedContract := + TypeCheck.CheckedInput.contract SolidCore.Verify.VC.Source.Token.importedSourceUnit "Token" + +/-- The selector of `balanceOf(address)`. -/ +abbrev balanceofSel : Nat := 1889567281 + +/-- The selector of `balanceOf(address)`, by Keccak-256 of its signature. -/ +def selBalanceOf : SolidCore.Solidity.Shared.Word := + SolidCore.Solidity.Source.ABI.selectorFromSignature "balanceOf(address)" + +kernel_rfl selBalanceOf_eq selBalanceOf balanceofSel + +/-- The selector of `totalSupply()`. -/ +abbrev totalsupplySel : Nat := 404098525 + +/-- The selector of `totalSupply()`, by Keccak-256 of its signature. -/ +def selTotalSupply : SolidCore.Solidity.Shared.Word := + SolidCore.Solidity.Source.ABI.selectorFromSignature "totalSupply()" + +kernel_rfl selTotalSupply_eq selTotalSupply totalsupplySel + +/-- The selector of `owner()`. -/ +abbrev ownerSel : Nat := 2376452955 + +/-- The selector of `owner()`, by Keccak-256 of its signature. -/ +def selOwner : SolidCore.Solidity.Shared.Word := + SolidCore.Solidity.Source.ABI.selectorFromSignature "owner()" + +kernel_rfl selOwner_eq selOwner ownerSel + +/-- The selector of `mint(address,uint256)`. -/ +abbrev mintSel : Nat := 1086394137 + +/-- The selector of `mint(address,uint256)`, by Keccak-256 of its signature. -/ +def selMint : SolidCore.Solidity.Shared.Word := + SolidCore.Solidity.Source.ABI.selectorFromSignature "mint(address,uint256)" + +kernel_rfl selMint_eq selMint mintSel + +/-- The selector of `transfer(address,uint256)`. -/ +abbrev transferSel : Nat := 2835717307 + +/-- The selector of `transfer(address,uint256)`, by Keccak-256 of its signature. -/ +def selTransfer : SolidCore.Solidity.Shared.Word := + SolidCore.Solidity.Source.ABI.selectorFromSignature "transfer(address,uint256)" + +kernel_rfl selTransfer_eq selTransfer transferSel + +/-- The selector of `burn(uint256)`. -/ +abbrev burnSel : Nat := 1117154408 + +/-- The selector of `burn(uint256)`, by Keccak-256 of its signature. -/ +def selBurn : SolidCore.Solidity.Shared.Word := + SolidCore.Solidity.Source.ABI.selectorFromSignature "burn(uint256)" + +kernel_rfl selBurn_eq selBurn burnSel + +/-- `ABI.selectorFromSignature`, with `Token`'s selectors by table. -/ +def selectorTable (s : String) : SolidCore.Solidity.Shared.Word := + if s = "balanceOf(address)" then balanceofSel + else if s = "totalSupply()" then totalsupplySel + else if s = "owner()" then ownerSel + else if s = "mint(address,uint256)" then mintSel + else if s = "transfer(address,uint256)" then transferSel + else if s = "burn(uint256)" then burnSel + else SolidCore.Solidity.Source.ABI.selectorFromSignature s + +theorem selector_eq : SolidCore.Solidity.Source.ABI.selectorFromSignature = selectorTable := by + funext s + unfold selectorTable + by_cases h0 : s = "balanceOf(address)" + · rw [ite_eq_left h0, h0] + exact selBalanceOf_eq + rw [ite_eq_right h0] + by_cases h1 : s = "totalSupply()" + · rw [ite_eq_left h1, h1] + exact selTotalSupply_eq + rw [ite_eq_right h1] + by_cases h2 : s = "owner()" + · rw [ite_eq_left h2, h2] + exact selOwner_eq + rw [ite_eq_right h2] + by_cases h3 : s = "mint(address,uint256)" + · rw [ite_eq_left h3, h3] + exact selMint_eq + rw [ite_eq_right h3] + by_cases h4 : s = "transfer(address,uint256)" + · rw [ite_eq_left h4, h4] + exact selTransfer_eq + rw [ite_eq_right h4] + by_cases h5 : s = "burn(uint256)" + · rw [ite_eq_left h5, h5] + exact selBurn_eq + rw [ite_eq_right h5] + +/-- The revert data of `Panic(0x11)`, byte by byte. -/ +def panic11 : List OByte := + [78, 72, 123, 113].map .lit ++ (List.replicate 31 (OByte.lit 0)) ++ [.lit 17] + +/-- The erasure of `burn`, as the generic source stage computes it. -/ +def burnTree : Tree := + (.ite (.bin .lt (.sinit (.hash (.lit 8192) (.lit 0))) (.arg 0)) (.halt false panic11 [] []) + (.ite (.bin .lt (.sel (.bin .eq (.lit 1) (.hash (.lit 8192) (.lit 0))) + (.bin .sub (.sinit (.hash (.lit 8192) (.lit 0))) (.arg 0)) (.init 1)) (.arg 0)) + (.halt false panic11 [] []) + (.halt true [] [(.lit 1, .bin .sub (.sel (.bin .eq (.lit 1) (.hash (.lit 8192) (.lit 0))) + (.bin .sub (.sinit (.hash (.lit 8192) (.lit 0))) (.arg 0)) (.init 1)) (.arg 0)), + (.hash (.lit 8192) (.lit 0), .bin .sub (.sinit (.hash (.lit 8192) (.lit 0))) (.arg 0))] []))) + +/-- Whether `Token` deploys with `owner` alone in storage and no logs, and how SolidCore dispatches +`burn` and the generic source stage erases it. -/ +def burnShape? : Option (Bool × Option (Nat × Option Tree)) := + match contract? with + | .ok c => some (Wide.deployedAt fuel c [(2, 4096)], + (c.core.findFunctionBySelector? burnSel).map fun f => (f.params.length, eraseFn (envOf c.core) fuel f)) + | .error _ => none + +kernel_rfl burnShape_eq burnShape? (some (true, some (1, some burnTree))) using selector_eq mkIdx_eq + +open SolidCore.Verify SolidCore.Verify.VC SolidCore.Refinement SolidCore.Refinement.Abi +open SolidCore.Refinement.Generic + +/-- `burn` as the stage's ABI sees it. -/ +def fnBurn : Fn := ⟨burnSel, [.uint 256]⟩ + +/-- The slot of `balanceOf[msg.sender]` for the stage's caller `callerWord`. -/ +def senderSlot : Nat := + 55339514551095541597166361489097532198990872027936225909895186517043906691032 + +/-- `balanceOf[msg.sender]`'s slot, by Keccak-256. -/ +def senderSlotOf : Nat := solHash callerWord 0 + +kernel_rfl senderSlot_eq senderSlotOf senderSlot + +theorem hash_eq : solHash 8192 0 = senderSlot := senderSlot_eq + +theorem tree_success (s : Nat → Nat) (hs : ∀ k, s k < 2 ^ 256) (a : Nat) (ha : a < 2 ^ 256) : + let R := burnTree.eval (valOf [a] s) + R.success = true → a ≤ s senderSlot ∧ a ≤ s 1 ∧ + R.store senderSlot = s senderSlot - a ∧ R.store 1 = s 1 - a := by + intro R + have hsm : ∀ k, s k % 2 ^ 256 = s k := fun k => Nat.mod_eq_of_lt (hs k) + have ham : a % 2 ^ 256 = a := Nat.mod_eq_of_lt ha + have hss : senderSlot % 2 ^ 256 = senderSlot := by decide + have hne : (1 = senderSlot) = False := by decide + have hne' : (senderSlot = 1) = False := by decide + have h1 := hs senderSlot + have h2 := hs 1 + have h8 : 8192 % 2 ^ 256 = 8192 := by decide + have h0 : 0 % 2 ^ 256 = 0 := by decide + have h1' : 1 % 2 ^ 256 = 1 := by decide + simp only [R, burnTree, Tree.eval, WExpr.eval, BinOp.eval, valOf, Generic.wordSize, + h8, h0, h1', hash_eq, List.getD_cons_zero, hss, hsm, ham, hne, ite_false, ite_true] + split_ifs <;> simp only [Writes.store, WExpr.eval, BinOp.eval, Generic.wordSize, hash_eq, hss, hsm, + ham, hne, hne', h8, h0, h1', ite_false, ite_true, List.getD_cons_zero, + false_implies, true_implies] <;> first | contradiction | omega + +/-! ## solar-verify's obligation for `burn`, on the Lean side -/ + +namespace Ob + +def amt : Tm := .ivar "amount" +def ms : Tm := .ivar "msg.sender" +def ts : Tm := .ivar "totalSupply" +def sum : Tm := .ivar "sumBalances" +def mv : Tm := .ivar "msg.value" +def bal : Tm := .app "select" [.avar "balanceOf", ms] +def le0 (t : Tm) : Tm := .app "<=" [.num 0, t] +def leW (t : Tm) : Tm := .app "<=" [t, .num (2 ^ 256 - 1)] +def sub (a b : Tm) : Tm := .app "-" [a, b] +def eq (a b : Tm) : Tm := .app "=" [a, b] + +end Ob + +open Ob in +/-- The facts the Lean side of `burn`'s ensures clause rests on: the invariant, no value, the +success path's two range checks, and the words' ranges. -/ +def burnHyps : List Tm := + [eq ts sum, eq mv (.num 0), le0 (sub bal amt), leW (sub bal amt), le0 (sub ts amt), + leW (sub ts amt), le0 bal, leW bal, le0 amt, leW amt, le0 ts, leW ts, le0 sum, leW sum, le0 mv, + leW mv, .app "not" [eq ms (.num 0)], le0 ms, .app "<=" [ms, .num (2 ^ 160 - 1)]] + +open Ob in +/-- solar-verify's encoding of `balanceOf[msg.sender]` after `burn`. -/ +def burnStore : Tm := .app "select" [.app "store" [.avar "balanceOf", ms, sub bal amt], ms] + +open Ob in +/-- `burn`'s ensures clause `balanceOf[msg.sender] == old(balanceOf[msg.sender]) - amount` as +solar-verify states it, of its own encoding of the function's effect. -/ +def burnGoal : Tm := eq burnStore (sub bal amt) + +/-- solar-verify's script for `Token` has an obligation that `checkOb` normalizes to +`burnHyps → burnGoal`. -/ +theorem burn_check : checkScript Export.Token.script [(burnHyps, burnGoal)] = true := by + decide +kernel + +/-- The assignment of solar-verify's names that a call of `burn` on `amount` gives, from the +balance `b` of the caller and the total supply `t`; the ghost `sumBalances` is chosen equal to +`totalSupply`, which the invariant assumes. -/ +def burnEnv (a b t : Nat) : Env := + ⟨fun x => if x = "amount" then a else if x = "msg.sender" then callerWord + else if x = "totalSupply" then t else if x = "sumBalances" then t else 0, + fun _ => False, + fun x => if x = "balanceOf" then fun k => if k = callerWord then b else 0 else fun _ => 0⟩ + +theorem burnHyps_hold {a b t : Nat} (ha : a ≤ b) (ht : a ≤ t) (hb : b < 2 ^ 256) (htt : t < 2 ^ 256) : + ∀ x ∈ burnHyps, x.Holds (burnEnv a b t) := by + have hca : callerWord = 8192 := rfl + simp only [burnHyps, List.mem_cons, List.mem_nil_iff, or_false] + rintro x (rfl | rfl | rfl | rfl | rfl | rfl | rfl | rfl | rfl | rfl | rfl | rfl | rfl | rfl | rfl | + rfl | rfl | rfl | rfl) <;> + simp [Tm.Holds, Tm.eval, Tm.evalList, applyOp, Value.toProp, Value.toInt, Value.toArr, Value.eq, + burnEnv, Ob.amt, Ob.ms, Ob.ts, Ob.sum, Ob.mv, Ob.bal, Ob.le0, Ob.leW, Ob.sub, Ob.eq, hca] <;> + omega + +/-- What solar-verify's encoding of the caller's new balance is at `burnEnv`: the old balance less +the amount. -/ +theorem burnStore_eval (a b t : Nat) : + (burnStore.eval (burnEnv a b t)).toInt = (b : Int) - a := by + have hca : callerWord = 8192 := rfl + simp [burnStore, Tm.eval, Tm.evalList, applyOp, Value.toInt, Value.toArr, burnEnv, Ob.amt, Ob.ms, + Ob.bal, Ob.sub, hca] + +/-- `burn`'s postcondition: on success, the caller's balance and the total supply drop by the +amount. -/ +def burnPost (call : Call) (obs : SolarTV.Observable) : Prop := + obs.success = true → + obs.storage senderSlot = initStorage call senderSlot - (argWords 1 call).getD 0 0 ∧ + obs.storage 1 = initStorage call 1 - (argWords 1 call).getD 0 0 + +theorem vc_eq (model : List Nat → SolM (List Nat)) (args : Call → List Nat) + (post : Call → SolarTV.Observable → Prop) (call : Call) : + vc model args post call = + post call (observe (initStorage call) (model (args call) (initStorage call))) := by + unfold vc + rw [wp_eq] + rcases h : model (args call) (initStorage call) with e | ⟨out, s'⟩ <;> simp only [h] <;> rfl + +/-- solar-verify's verdict on its script for `Token` gives `burn`'s ensures obligation at the +assignment of every successful call: `checkScript_sound`, with the facts discharged from the +success path. -/ +theorem burn_obligation (hv : Valid Export.Token.script) {a b t : Nat} (ha : a ≤ b) (ht : a ≤ t) + (hb : b < 2 ^ 256) (htt : t < 2 ^ 256) : burnGoal.Holds (burnEnv a b t) := + checkScript_sound burn_check hv (burnHyps, burnGoal) (List.mem_singleton_self _) _ + (burnHyps_hold ha ht hb htt) + +/-- `burn` meets its ensures clause on the stage's scope. SolidCore runs every call as the erased +tree (`implements_tree`), whose success path writes the caller's slot with the value of +solar-verify's encoding `burnStore` of the new balance at `burnEnv` (`hagree` below). solar-verify's +goal for this clause selects the stored value back out of its own `store`, which is valid in the +array theory, so the triple rests on that agreement and needs no verdict; `burn_obligation` is the +transfer through `checkScript_sound` that a goal not valid on its own (the invariant, `transfer`'s +frame) needs. -/ +theorem burn_triple {c : SolidCore.Solidity.TypeCheck.CheckedContract} + (hc : contract? = .ok c) : + Triple fuel c (stageScope fnBurn [(2, 4096)]) (fun _ => True) burnPost := by + have hshape := burnShape_eq + simp only [burnShape?, hc, Option.some.injEq, Prod.mk.injEq] at hshape + obtain ⟨hdep, hmap⟩ := hshape + obtain ⟨d, hd⟩ := Wide.deployedAt_of hdep + simp only [Option.map_eq_some_iff, Prod.mk.injEq] at hmap + obtain ⟨f, hf, hlen, hT⟩ := hmap + have himpl := implements_tree (fn := fnBurn) hd (by decide) hf hlen hT rfl + apply triple_of_wp himpl + rintro _ ⟨σ, hcov, fn', hfn', args, hl, hargs, rfl⟩ - + simp only [List.mem_singleton] at hfn' + subst hfn' + obtain ⟨a, rfl⟩ : ∃ a, args = [a] := by + match args, hl with + | [a], _ => exact ⟨a, rfl⟩ + have ha : a < 2 ^ 256 := hargs a (List.mem_singleton_self a) + have hw : argWords 1 ({ calldata := Abi.calldata fnBurn.sel [a], callvalue := 0, storage := σ } : + Call) = [a] := argWords_calldata _ [a] hargs 0 σ + rw [vc_eq, treeModel_run, show fnBurn.params.length = 1 from rfl, hw] + set s := initStorage ({ calldata := Abi.calldata fnBurn.sel [a], callvalue := 0, storage := σ } : + Call) with hs_def + have hs : ∀ k, s k < 2 ^ 256 := fun k => Generic.slotValue_lt σ k + unfold resOutcome + split + · next hok => + intro _ + obtain ⟨hb, ht, h1, h2⟩ := tree_success s hs a ha hok + have hgoal : (burnStore.eval (burnEnv a (s senderSlot) (s 1))).toInt = + ((s senderSlot : Int) - a) := burnStore_eval a _ _ + -- SolidCore's new balance is the value of solar-verify's encoding of it. + have hagree : (((burnTree.eval (valOf [a] s)).store senderSlot : Nat) : Int) = + (burnStore.eval (burnEnv a (s senderSlot) (s 1))).toInt := by + rw [hgoal, h1]; omega + simp only [observe, hw, List.getD_cons_zero] + rw [← hs_def] + refine ⟨?_, ?_⟩ + · omega + · exact h2 + · intro h; simp_all [observe] + + +/-- info: 'SolidCore.Verify.VC.Token.burn_triple' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms burn_triple + +/-- info: 'SolidCore.Verify.VC.Token.burn_obligation' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms burn_obligation + +end SolidCore.Verify.VC.Token diff --git a/Contracts/Token/VC/Export.lean b/Contracts/Token/VC/Export.lean new file mode 100644 index 00000000..df21fb07 --- /dev/null +++ b/Contracts/Token/VC/Export.lean @@ -0,0 +1,354 @@ +-- Generated by solar-verify --dump-lean. Do not edit. + +import Verify.VC.Term + +namespace SolidCore.Verify.VC.Export.Token + +open SolidCore.Verify.VC + +/-- The commands solar-verify sent the solver. -/ +def script : List Cmd := [ + .push, + .raw "; ===== Token.constructor", + .decl "this@1" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "this@1")]), (.app "<=" [(.ivar "this@1"), (.num 1461501637330902918203684832716283019655932542975)])]), + .decl "msg.sender@2" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "msg.sender@2")]), (.app "<=" [(.ivar "msg.sender@2"), (.num 1461501637330902918203684832716283019655932542975)])]), + .assert (.app "not" [(.app "=" [(.ivar "msg.sender@2"), (.num 0)])]), + .decl "msg.value@3" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "msg.value@3")]), (.app "<=" [(.ivar "msg.value@3"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.timestamp@4" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.timestamp@4")]), (.app "<=" [(.ivar "block.timestamp@4"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.number@5" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.number@5")]), (.app "<=" [(.ivar "block.number@5"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.chainid@6" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.chainid@6")]), (.app "<=" [(.ivar "block.chainid@6"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "tx.origin@7" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "tx.origin@7")]), (.app "<=" [(.ivar "tx.origin@7"), (.num 1461501637330902918203684832716283019655932542975)])]), + .decl "tx.gasprice@8" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "tx.gasprice@8")]), (.app "<=" [(.ivar "tx.gasprice@8"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "msg.sig@9" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "msg.sig@9")]), (.app "<=" [(.ivar "msg.sig@9"), (.num 4294967295)])]), + .decl "msg.data@10" .int, + .decl "block.basefee@11" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.basefee@11")]), (.app "<=" [(.ivar "block.basefee@11"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.blobbasefee@12" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.blobbasefee@12")]), (.app "<=" [(.ivar "block.blobbasefee@12"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.coinbase@13" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.coinbase@13")]), (.app "<=" [(.ivar "block.coinbase@13"), (.num 1461501637330902918203684832716283019655932542975)])]), + .decl "block.prevrandao@14" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.prevrandao@14")]), (.app "<=" [(.ivar "block.prevrandao@14"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.difficulty@15" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.difficulty@15")]), (.app "<=" [(.ivar "block.difficulty@15"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.gaslimit@16" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.gaslimit@16")]), (.app "<=" [(.ivar "block.gaslimit@16"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "__balance@17" .arr, + .elem "__balance@17" 0 115792089237316195423570985008687907853269984665640564039457584007913129639935, + .decl "__code_epoch@18" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "__code_epoch@18")]), (.app "<=" [(.ivar "__code_epoch@18"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "g@19" .bool, + .assert (.app "=" [(.bvar "g@19"), (.app "and" [.tt, (.app "=" [(.ivar "msg.value@3"), (.num 0)])])]), + .push, + .assert (.bvar "g@19"), + .assert (.app "not" [.ff]), + .checkSat, + .pop, + .push, + .assert (.bvar "g@19"), + .assert (.app "not" [(.app "=" [(.ivar "msg.sender@2"), (.ivar "msg.sender@2")])]), + .checkSat, + .pop, + .push, + .assert (.bvar "g@19"), + .assert (.app "not" [(.app "=" [(.num 0), (.num 0)])]), + .checkSat, + .pop, + .pop, + .push, + .raw "; ===== Token.mint", + .decl "this@1" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "this@1")]), (.app "<=" [(.ivar "this@1"), (.num 1461501637330902918203684832716283019655932542975)])]), + .decl "msg.sender@2" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "msg.sender@2")]), (.app "<=" [(.ivar "msg.sender@2"), (.num 1461501637330902918203684832716283019655932542975)])]), + .assert (.app "not" [(.app "=" [(.ivar "msg.sender@2"), (.num 0)])]), + .decl "msg.value@3" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "msg.value@3")]), (.app "<=" [(.ivar "msg.value@3"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.timestamp@4" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.timestamp@4")]), (.app "<=" [(.ivar "block.timestamp@4"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.number@5" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.number@5")]), (.app "<=" [(.ivar "block.number@5"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.chainid@6" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.chainid@6")]), (.app "<=" [(.ivar "block.chainid@6"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "tx.origin@7" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "tx.origin@7")]), (.app "<=" [(.ivar "tx.origin@7"), (.num 1461501637330902918203684832716283019655932542975)])]), + .decl "tx.gasprice@8" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "tx.gasprice@8")]), (.app "<=" [(.ivar "tx.gasprice@8"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "msg.sig@9" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "msg.sig@9")]), (.app "<=" [(.ivar "msg.sig@9"), (.num 4294967295)])]), + .decl "msg.data@10" .int, + .decl "block.basefee@11" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.basefee@11")]), (.app "<=" [(.ivar "block.basefee@11"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.blobbasefee@12" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.blobbasefee@12")]), (.app "<=" [(.ivar "block.blobbasefee@12"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.coinbase@13" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.coinbase@13")]), (.app "<=" [(.ivar "block.coinbase@13"), (.num 1461501637330902918203684832716283019655932542975)])]), + .decl "block.prevrandao@14" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.prevrandao@14")]), (.app "<=" [(.ivar "block.prevrandao@14"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.difficulty@15" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.difficulty@15")]), (.app "<=" [(.ivar "block.difficulty@15"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.gaslimit@16" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.gaslimit@16")]), (.app "<=" [(.ivar "block.gaslimit@16"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "sumBalances@17" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "sumBalances@17")]), (.app "<=" [(.ivar "sumBalances@17"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "balanceOf@18" .arr, + .elem "balanceOf@18" 0 115792089237316195423570985008687907853269984665640564039457584007913129639935, + .decl "totalSupply@19" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "totalSupply@19")]), (.app "<=" [(.ivar "totalSupply@19"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "owner@20" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "owner@20")]), (.app "<=" [(.ivar "owner@20"), (.num 1461501637330902918203684832716283019655932542975)])]), + .decl "__balance@21" .arr, + .elem "__balance@21" 0 115792089237316195423570985008687907853269984665640564039457584007913129639935, + .decl "__code_epoch@22" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "__code_epoch@22")]), (.app "<=" [(.ivar "__code_epoch@22"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "to@23" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "to@23")]), (.app "<=" [(.ivar "to@23"), (.num 1461501637330902918203684832716283019655932542975)])]), + .decl "amount@24" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "amount@24")]), (.app "<=" [(.ivar "amount@24"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "g@25" .bool, + .assert (.app "=" [(.bvar "g@25"), (.app "and" [.tt, (.app "=" [(.ivar "totalSupply@19"), (.ivar "sumBalances@17")])])]), + .decl "g@26" .bool, + .assert (.app "=" [(.bvar "g@26"), (.app "and" [(.bvar "g@25"), (.app "=" [(.ivar "msg.value@3"), (.num 0)])])]), + .decl "g@27" .bool, + .assert (.app "=" [(.bvar "g@27"), (.app "and" [(.bvar "g@26"), (.app "=" [(.ivar "msg.sender@2"), (.ivar "owner@20")])])]), + .decl "arith@28" .int, + .assert (.app "=" [(.ivar "arith@28"), (.app "+" [(.ivar "totalSupply@19"), (.ivar "amount@24")])]), + .decl "g@29" .bool, + .assert (.app "=" [(.bvar "g@29"), (.app "and" [(.bvar "g@27"), (.app "and" [(.app "<=" [(.num 0), (.ivar "arith@28")]), (.app "<=" [(.ivar "arith@28"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])])])]), + .decl "sumBalances@30" .int, + .assert (.app "=" [(.ivar "sumBalances@30"), (.app "+" [(.ivar "sumBalances@17"), (.ivar "amount@24")])]), + .assert (.app "and" [(.app "<=" [(.num 0), (.app "select" [(.avar "balanceOf@18"), (.ivar "to@23")])]), (.app "<=" [(.app "select" [(.avar "balanceOf@18"), (.ivar "to@23")]), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "arith@31" .int, + .assert (.app "=" [(.ivar "arith@31"), (.app "+" [(.app "select" [(.avar "balanceOf@18"), (.ivar "to@23")]), (.ivar "amount@24")])]), + .decl "g@32" .bool, + .assert (.app "=" [(.bvar "g@32"), (.app "and" [(.bvar "g@29"), (.app "and" [(.app "<=" [(.num 0), (.ivar "arith@31")]), (.app "<=" [(.ivar "arith@31"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])])])]), + .decl "balanceOf@33" .arr, + .assert (.app "=" [(.avar "balanceOf@33"), (.app "store" [(.avar "balanceOf@18"), (.ivar "to@23"), (.ivar "arith@31")])]), + .push, + .assert (.bvar "g@32"), + .assert (.app "not" [.ff]), + .checkSat, + .pop, + .assert (.app "and" [(.app "<=" [(.num 0), (.app "select" [(.avar "balanceOf@33"), (.ivar "to@23")])]), (.app "<=" [(.app "select" [(.avar "balanceOf@33"), (.ivar "to@23")]), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .assert (.app "and" [(.app "<=" [(.num 0), (.app "select" [(.avar "balanceOf@18"), (.ivar "to@23")])]), (.app "<=" [(.app "select" [(.avar "balanceOf@18"), (.ivar "to@23")]), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .push, + .assert (.bvar "g@32"), + .assert (.app "not" [(.app "=" [(.app "select" [(.avar "balanceOf@33"), (.ivar "to@23")]), (.app "+" [(.app "select" [(.avar "balanceOf@18"), (.ivar "to@23")]), (.ivar "amount@24")])])]), + .checkSat, + .pop, + .push, + .assert (.bvar "g@32"), + .assert (.app "not" [(.app "=" [(.ivar "arith@28"), (.app "+" [(.ivar "totalSupply@19"), (.ivar "amount@24")])])]), + .checkSat, + .pop, + .push, + .assert (.bvar "g@32"), + .assert (.app "not" [(.all "a!34" (.app "=>" [(.app "and" [(.app "and" [(.app "<=" [(.num 0), (.ivar "a!34")]), (.app "<=" [(.ivar "a!34"), (.num 1461501637330902918203684832716283019655932542975)])])]), (.app "=>" [(.app "not" [(.app "=" [(.ivar "a!34"), (.ivar "to@23")])]), (.app "=" [(.app "select" [(.avar "balanceOf@33"), (.ivar "a!34")]), (.app "select" [(.avar "balanceOf@18"), (.ivar "a!34")])])])]))]), + .checkSat, + .pop, + .push, + .assert (.bvar "g@32"), + .assert (.app "not" [(.app "=" [(.ivar "arith@28"), (.ivar "sumBalances@30")])]), + .checkSat, + .pop, + .pop, + .push, + .raw "; ===== Token.transfer", + .decl "this@1" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "this@1")]), (.app "<=" [(.ivar "this@1"), (.num 1461501637330902918203684832716283019655932542975)])]), + .decl "msg.sender@2" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "msg.sender@2")]), (.app "<=" [(.ivar "msg.sender@2"), (.num 1461501637330902918203684832716283019655932542975)])]), + .assert (.app "not" [(.app "=" [(.ivar "msg.sender@2"), (.num 0)])]), + .decl "msg.value@3" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "msg.value@3")]), (.app "<=" [(.ivar "msg.value@3"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.timestamp@4" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.timestamp@4")]), (.app "<=" [(.ivar "block.timestamp@4"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.number@5" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.number@5")]), (.app "<=" [(.ivar "block.number@5"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.chainid@6" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.chainid@6")]), (.app "<=" [(.ivar "block.chainid@6"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "tx.origin@7" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "tx.origin@7")]), (.app "<=" [(.ivar "tx.origin@7"), (.num 1461501637330902918203684832716283019655932542975)])]), + .decl "tx.gasprice@8" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "tx.gasprice@8")]), (.app "<=" [(.ivar "tx.gasprice@8"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "msg.sig@9" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "msg.sig@9")]), (.app "<=" [(.ivar "msg.sig@9"), (.num 4294967295)])]), + .decl "msg.data@10" .int, + .decl "block.basefee@11" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.basefee@11")]), (.app "<=" [(.ivar "block.basefee@11"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.blobbasefee@12" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.blobbasefee@12")]), (.app "<=" [(.ivar "block.blobbasefee@12"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.coinbase@13" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.coinbase@13")]), (.app "<=" [(.ivar "block.coinbase@13"), (.num 1461501637330902918203684832716283019655932542975)])]), + .decl "block.prevrandao@14" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.prevrandao@14")]), (.app "<=" [(.ivar "block.prevrandao@14"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.difficulty@15" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.difficulty@15")]), (.app "<=" [(.ivar "block.difficulty@15"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.gaslimit@16" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.gaslimit@16")]), (.app "<=" [(.ivar "block.gaslimit@16"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "sumBalances@17" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "sumBalances@17")]), (.app "<=" [(.ivar "sumBalances@17"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "balanceOf@18" .arr, + .elem "balanceOf@18" 0 115792089237316195423570985008687907853269984665640564039457584007913129639935, + .decl "totalSupply@19" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "totalSupply@19")]), (.app "<=" [(.ivar "totalSupply@19"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "owner@20" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "owner@20")]), (.app "<=" [(.ivar "owner@20"), (.num 1461501637330902918203684832716283019655932542975)])]), + .decl "__balance@21" .arr, + .elem "__balance@21" 0 115792089237316195423570985008687907853269984665640564039457584007913129639935, + .decl "__code_epoch@22" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "__code_epoch@22")]), (.app "<=" [(.ivar "__code_epoch@22"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "to@23" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "to@23")]), (.app "<=" [(.ivar "to@23"), (.num 1461501637330902918203684832716283019655932542975)])]), + .decl "amount@24" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "amount@24")]), (.app "<=" [(.ivar "amount@24"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "g@25" .bool, + .assert (.app "=" [(.bvar "g@25"), (.app "and" [.tt, (.app "=" [(.ivar "totalSupply@19"), (.ivar "sumBalances@17")])])]), + .decl "g@26" .bool, + .assert (.app "=" [(.bvar "g@26"), (.app "and" [(.bvar "g@25"), (.app "=" [(.ivar "msg.value@3"), (.num 0)])])]), + .assert (.app "and" [(.app "<=" [(.num 0), (.app "select" [(.avar "balanceOf@18"), (.ivar "msg.sender@2")])]), (.app "<=" [(.app "select" [(.avar "balanceOf@18"), (.ivar "msg.sender@2")]), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "bal@27" .int, + .assert (.app "=" [(.ivar "bal@27"), (.app "select" [(.avar "balanceOf@18"), (.ivar "msg.sender@2")])]), + .decl "g@28" .bool, + .assert (.app "=" [(.bvar "g@28"), (.app "and" [(.bvar "g@26"), (.app ">=" [(.ivar "bal@27"), (.ivar "amount@24")])])]), + .decl "arith@29" .int, + .assert (.app "=" [(.ivar "arith@29"), (.app "-" [(.ivar "bal@27"), (.ivar "amount@24")])]), + .decl "g@30" .bool, + .assert (.app "=" [(.bvar "g@30"), (.app "and" [(.bvar "g@28"), (.app "and" [(.app "<=" [(.num 0), (.ivar "arith@29")]), (.app "<=" [(.ivar "arith@29"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])])])]), + .decl "balanceOf@31" .arr, + .assert (.app "=" [(.avar "balanceOf@31"), (.app "store" [(.avar "balanceOf@18"), (.ivar "msg.sender@2"), (.ivar "arith@29")])]), + .assert (.app "and" [(.app "<=" [(.num 0), (.app "select" [(.avar "balanceOf@31"), (.ivar "to@23")])]), (.app "<=" [(.app "select" [(.avar "balanceOf@31"), (.ivar "to@23")]), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "arith@32" .int, + .assert (.app "=" [(.ivar "arith@32"), (.app "+" [(.app "select" [(.avar "balanceOf@31"), (.ivar "to@23")]), (.ivar "amount@24")])]), + .decl "g@33" .bool, + .assert (.app "=" [(.bvar "g@33"), (.app "and" [(.bvar "g@30"), (.app "and" [(.app "<=" [(.num 0), (.ivar "arith@32")]), (.app "<=" [(.ivar "arith@32"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])])])]), + .decl "balanceOf@34" .arr, + .assert (.app "=" [(.avar "balanceOf@34"), (.app "store" [(.avar "balanceOf@31"), (.ivar "to@23"), (.ivar "arith@32")])]), + .push, + .assert (.bvar "g@33"), + .assert (.app "not" [.ff]), + .checkSat, + .pop, + .assert (.app "and" [(.app "<=" [(.num 0), (.app "select" [(.avar "balanceOf@34"), (.ivar "msg.sender@2")])]), (.app "<=" [(.app "select" [(.avar "balanceOf@34"), (.ivar "msg.sender@2")]), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .assert (.app "and" [(.app "<=" [(.num 0), (.app "select" [(.avar "balanceOf@18"), (.ivar "msg.sender@2")])]), (.app "<=" [(.app "select" [(.avar "balanceOf@18"), (.ivar "msg.sender@2")]), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .push, + .assert (.bvar "g@33"), + .assert (.app "not" [(.app "=>" [(.app "not" [(.app "=" [(.ivar "msg.sender@2"), (.ivar "to@23")])]), (.app "=" [(.app "select" [(.avar "balanceOf@34"), (.ivar "msg.sender@2")]), (.app "-" [(.app "select" [(.avar "balanceOf@18"), (.ivar "msg.sender@2")]), (.ivar "amount@24")])])])]), + .checkSat, + .pop, + .assert (.app "and" [(.app "<=" [(.num 0), (.app "select" [(.avar "balanceOf@34"), (.ivar "to@23")])]), (.app "<=" [(.app "select" [(.avar "balanceOf@34"), (.ivar "to@23")]), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .assert (.app "and" [(.app "<=" [(.num 0), (.app "select" [(.avar "balanceOf@18"), (.ivar "to@23")])]), (.app "<=" [(.app "select" [(.avar "balanceOf@18"), (.ivar "to@23")]), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .push, + .assert (.bvar "g@33"), + .assert (.app "not" [(.app "=>" [(.app "not" [(.app "=" [(.ivar "msg.sender@2"), (.ivar "to@23")])]), (.app "=" [(.app "select" [(.avar "balanceOf@34"), (.ivar "to@23")]), (.app "+" [(.app "select" [(.avar "balanceOf@18"), (.ivar "to@23")]), (.ivar "amount@24")])])])]), + .checkSat, + .pop, + .push, + .assert (.bvar "g@33"), + .assert (.app "not" [(.all "a!35" (.app "=>" [(.app "and" [(.app "and" [(.app "<=" [(.num 0), (.ivar "a!35")]), (.app "<=" [(.ivar "a!35"), (.num 1461501637330902918203684832716283019655932542975)])])]), (.app "=>" [(.app "and" [(.app "not" [(.app "=" [(.ivar "a!35"), (.ivar "msg.sender@2")])]), (.app "not" [(.app "=" [(.ivar "a!35"), (.ivar "to@23")])])]), (.app "=" [(.app "select" [(.avar "balanceOf@34"), (.ivar "a!35")]), (.app "select" [(.avar "balanceOf@18"), (.ivar "a!35")])])])]))]), + .checkSat, + .pop, + .push, + .assert (.bvar "g@33"), + .assert (.app "not" [(.app "=" [(.ivar "totalSupply@19"), (.ivar "totalSupply@19")])]), + .checkSat, + .pop, + .pop, + .push, + .raw "; ===== Token.burn", + .decl "this@1" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "this@1")]), (.app "<=" [(.ivar "this@1"), (.num 1461501637330902918203684832716283019655932542975)])]), + .decl "msg.sender@2" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "msg.sender@2")]), (.app "<=" [(.ivar "msg.sender@2"), (.num 1461501637330902918203684832716283019655932542975)])]), + .assert (.app "not" [(.app "=" [(.ivar "msg.sender@2"), (.num 0)])]), + .decl "msg.value@3" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "msg.value@3")]), (.app "<=" [(.ivar "msg.value@3"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.timestamp@4" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.timestamp@4")]), (.app "<=" [(.ivar "block.timestamp@4"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.number@5" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.number@5")]), (.app "<=" [(.ivar "block.number@5"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.chainid@6" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.chainid@6")]), (.app "<=" [(.ivar "block.chainid@6"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "tx.origin@7" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "tx.origin@7")]), (.app "<=" [(.ivar "tx.origin@7"), (.num 1461501637330902918203684832716283019655932542975)])]), + .decl "tx.gasprice@8" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "tx.gasprice@8")]), (.app "<=" [(.ivar "tx.gasprice@8"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "msg.sig@9" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "msg.sig@9")]), (.app "<=" [(.ivar "msg.sig@9"), (.num 4294967295)])]), + .decl "msg.data@10" .int, + .decl "block.basefee@11" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.basefee@11")]), (.app "<=" [(.ivar "block.basefee@11"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.blobbasefee@12" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.blobbasefee@12")]), (.app "<=" [(.ivar "block.blobbasefee@12"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.coinbase@13" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.coinbase@13")]), (.app "<=" [(.ivar "block.coinbase@13"), (.num 1461501637330902918203684832716283019655932542975)])]), + .decl "block.prevrandao@14" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.prevrandao@14")]), (.app "<=" [(.ivar "block.prevrandao@14"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.difficulty@15" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.difficulty@15")]), (.app "<=" [(.ivar "block.difficulty@15"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.gaslimit@16" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.gaslimit@16")]), (.app "<=" [(.ivar "block.gaslimit@16"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "sumBalances@17" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "sumBalances@17")]), (.app "<=" [(.ivar "sumBalances@17"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "balanceOf@18" .arr, + .elem "balanceOf@18" 0 115792089237316195423570985008687907853269984665640564039457584007913129639935, + .decl "totalSupply@19" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "totalSupply@19")]), (.app "<=" [(.ivar "totalSupply@19"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "owner@20" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "owner@20")]), (.app "<=" [(.ivar "owner@20"), (.num 1461501637330902918203684832716283019655932542975)])]), + .decl "__balance@21" .arr, + .elem "__balance@21" 0 115792089237316195423570985008687907853269984665640564039457584007913129639935, + .decl "__code_epoch@22" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "__code_epoch@22")]), (.app "<=" [(.ivar "__code_epoch@22"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "amount@23" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "amount@23")]), (.app "<=" [(.ivar "amount@23"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "g@24" .bool, + .assert (.app "=" [(.bvar "g@24"), (.app "and" [.tt, (.app "=" [(.ivar "totalSupply@19"), (.ivar "sumBalances@17")])])]), + .decl "g@25" .bool, + .assert (.app "=" [(.bvar "g@25"), (.app "and" [(.bvar "g@24"), (.app "=" [(.ivar "msg.value@3"), (.num 0)])])]), + .assert (.app "and" [(.app "<=" [(.num 0), (.app "select" [(.avar "balanceOf@18"), (.ivar "msg.sender@2")])]), (.app "<=" [(.app "select" [(.avar "balanceOf@18"), (.ivar "msg.sender@2")]), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "arith@26" .int, + .assert (.app "=" [(.ivar "arith@26"), (.app "-" [(.app "select" [(.avar "balanceOf@18"), (.ivar "msg.sender@2")]), (.ivar "amount@23")])]), + .decl "g@27" .bool, + .assert (.app "=" [(.bvar "g@27"), (.app "and" [(.bvar "g@25"), (.app "and" [(.app "<=" [(.num 0), (.ivar "arith@26")]), (.app "<=" [(.ivar "arith@26"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])])])]), + .decl "balanceOf@28" .arr, + .assert (.app "=" [(.avar "balanceOf@28"), (.app "store" [(.avar "balanceOf@18"), (.ivar "msg.sender@2"), (.ivar "arith@26")])]), + .decl "sumBalances@29" .int, + .assert (.app "=" [(.ivar "sumBalances@29"), (.app "-" [(.ivar "sumBalances@17"), (.ivar "amount@23")])]), + .decl "arith@30" .int, + .assert (.app "=" [(.ivar "arith@30"), (.app "-" [(.ivar "totalSupply@19"), (.ivar "amount@23")])]), + .decl "g@31" .bool, + .assert (.app "=" [(.bvar "g@31"), (.app "and" [(.bvar "g@27"), (.app "and" [(.app "<=" [(.num 0), (.ivar "arith@30")]), (.app "<=" [(.ivar "arith@30"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])])])]), + .push, + .assert (.bvar "g@31"), + .assert (.app "not" [.ff]), + .checkSat, + .pop, + .assert (.app "and" [(.app "<=" [(.num 0), (.app "select" [(.avar "balanceOf@28"), (.ivar "msg.sender@2")])]), (.app "<=" [(.app "select" [(.avar "balanceOf@28"), (.ivar "msg.sender@2")]), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .assert (.app "and" [(.app "<=" [(.num 0), (.app "select" [(.avar "balanceOf@18"), (.ivar "msg.sender@2")])]), (.app "<=" [(.app "select" [(.avar "balanceOf@18"), (.ivar "msg.sender@2")]), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .push, + .assert (.bvar "g@31"), + .assert (.app "not" [(.app "=" [(.app "select" [(.avar "balanceOf@28"), (.ivar "msg.sender@2")]), (.app "-" [(.app "select" [(.avar "balanceOf@18"), (.ivar "msg.sender@2")]), (.ivar "amount@23")])])]), + .checkSat, + .pop, + .push, + .assert (.bvar "g@31"), + .assert (.app "not" [(.app "=" [(.ivar "arith@30"), (.ivar "sumBalances@29")])]), + .checkSat, + .pop, + .pop +] + +/-- The transcript, as solar-verify wrote it. -/ +def transcript : String := "(push 1)\n; ===== Token.constructor\n(declare-const |this@1| Int)\n(assert (and (<= 0 |this@1|) (<= |this@1| 1461501637330902918203684832716283019655932542975)))\n(declare-const |msg.sender@2| Int)\n(assert (and (<= 0 |msg.sender@2|) (<= |msg.sender@2| 1461501637330902918203684832716283019655932542975)))\n(assert (not (= |msg.sender@2| 0)))\n(declare-const |msg.value@3| Int)\n(assert (and (<= 0 |msg.value@3|) (<= |msg.value@3| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.timestamp@4| Int)\n(assert (and (<= 0 |block.timestamp@4|) (<= |block.timestamp@4| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.number@5| Int)\n(assert (and (<= 0 |block.number@5|) (<= |block.number@5| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.chainid@6| Int)\n(assert (and (<= 0 |block.chainid@6|) (<= |block.chainid@6| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |tx.origin@7| Int)\n(assert (and (<= 0 |tx.origin@7|) (<= |tx.origin@7| 1461501637330902918203684832716283019655932542975)))\n(declare-const |tx.gasprice@8| Int)\n(assert (and (<= 0 |tx.gasprice@8|) (<= |tx.gasprice@8| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |msg.sig@9| Int)\n(assert (and (<= 0 |msg.sig@9|) (<= |msg.sig@9| 4294967295)))\n(declare-const |msg.data@10| Int)\n(declare-const |block.basefee@11| Int)\n(assert (and (<= 0 |block.basefee@11|) (<= |block.basefee@11| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.blobbasefee@12| Int)\n(assert (and (<= 0 |block.blobbasefee@12|) (<= |block.blobbasefee@12| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.coinbase@13| Int)\n(assert (and (<= 0 |block.coinbase@13|) (<= |block.coinbase@13| 1461501637330902918203684832716283019655932542975)))\n(declare-const |block.prevrandao@14| Int)\n(assert (and (<= 0 |block.prevrandao@14|) (<= |block.prevrandao@14| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.difficulty@15| Int)\n(assert (and (<= 0 |block.difficulty@15|) (<= |block.difficulty@15| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.gaslimit@16| Int)\n(assert (and (<= 0 |block.gaslimit@16|) (<= |block.gaslimit@16| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |__balance@17| (Array Int Int))\n;@elem |__balance@17| 0 115792089237316195423570985008687907853269984665640564039457584007913129639935\n(declare-const |__code_epoch@18| Int)\n(assert (and (<= 0 |__code_epoch@18|) (<= |__code_epoch@18| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |g@19| Bool)\n(assert (= |g@19| (and true (= |msg.value@3| 0))))\n(push 1)\n(assert |g@19|)\n(assert (not false))\n(check-sat)\n(pop 1)\n(push 1)\n(assert |g@19|)\n(assert (not (= |msg.sender@2| |msg.sender@2|)))\n(check-sat)\n(pop 1)\n(push 1)\n(assert |g@19|)\n(assert (not (= 0 0)))\n(check-sat)\n(pop 1)\n(pop 1)\n(push 1)\n; ===== Token.mint\n(declare-const |this@1| Int)\n(assert (and (<= 0 |this@1|) (<= |this@1| 1461501637330902918203684832716283019655932542975)))\n(declare-const |msg.sender@2| Int)\n(assert (and (<= 0 |msg.sender@2|) (<= |msg.sender@2| 1461501637330902918203684832716283019655932542975)))\n(assert (not (= |msg.sender@2| 0)))\n(declare-const |msg.value@3| Int)\n(assert (and (<= 0 |msg.value@3|) (<= |msg.value@3| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.timestamp@4| Int)\n(assert (and (<= 0 |block.timestamp@4|) (<= |block.timestamp@4| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.number@5| Int)\n(assert (and (<= 0 |block.number@5|) (<= |block.number@5| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.chainid@6| Int)\n(assert (and (<= 0 |block.chainid@6|) (<= |block.chainid@6| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |tx.origin@7| Int)\n(assert (and (<= 0 |tx.origin@7|) (<= |tx.origin@7| 1461501637330902918203684832716283019655932542975)))\n(declare-const |tx.gasprice@8| Int)\n(assert (and (<= 0 |tx.gasprice@8|) (<= |tx.gasprice@8| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |msg.sig@9| Int)\n(assert (and (<= 0 |msg.sig@9|) (<= |msg.sig@9| 4294967295)))\n(declare-const |msg.data@10| Int)\n(declare-const |block.basefee@11| Int)\n(assert (and (<= 0 |block.basefee@11|) (<= |block.basefee@11| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.blobbasefee@12| Int)\n(assert (and (<= 0 |block.blobbasefee@12|) (<= |block.blobbasefee@12| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.coinbase@13| Int)\n(assert (and (<= 0 |block.coinbase@13|) (<= |block.coinbase@13| 1461501637330902918203684832716283019655932542975)))\n(declare-const |block.prevrandao@14| Int)\n(assert (and (<= 0 |block.prevrandao@14|) (<= |block.prevrandao@14| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.difficulty@15| Int)\n(assert (and (<= 0 |block.difficulty@15|) (<= |block.difficulty@15| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.gaslimit@16| Int)\n(assert (and (<= 0 |block.gaslimit@16|) (<= |block.gaslimit@16| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |sumBalances@17| Int)\n(assert (and (<= 0 |sumBalances@17|) (<= |sumBalances@17| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |balanceOf@18| (Array Int Int))\n;@elem |balanceOf@18| 0 115792089237316195423570985008687907853269984665640564039457584007913129639935\n(declare-const |totalSupply@19| Int)\n(assert (and (<= 0 |totalSupply@19|) (<= |totalSupply@19| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |owner@20| Int)\n(assert (and (<= 0 |owner@20|) (<= |owner@20| 1461501637330902918203684832716283019655932542975)))\n(declare-const |__balance@21| (Array Int Int))\n;@elem |__balance@21| 0 115792089237316195423570985008687907853269984665640564039457584007913129639935\n(declare-const |__code_epoch@22| Int)\n(assert (and (<= 0 |__code_epoch@22|) (<= |__code_epoch@22| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |to@23| Int)\n(assert (and (<= 0 |to@23|) (<= |to@23| 1461501637330902918203684832716283019655932542975)))\n(declare-const |amount@24| Int)\n(assert (and (<= 0 |amount@24|) (<= |amount@24| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |g@25| Bool)\n(assert (= |g@25| (and true (= |totalSupply@19| |sumBalances@17|))))\n(declare-const |g@26| Bool)\n(assert (= |g@26| (and |g@25| (= |msg.value@3| 0))))\n(declare-const |g@27| Bool)\n(assert (= |g@27| (and |g@26| (= |msg.sender@2| |owner@20|))))\n(declare-const |arith@28| Int)\n(assert (= |arith@28| (+ |totalSupply@19| |amount@24|)))\n(declare-const |g@29| Bool)\n(assert (= |g@29| (and |g@27| (and (<= 0 |arith@28|) (<= |arith@28| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))))\n(declare-const |sumBalances@30| Int)\n(assert (= |sumBalances@30| (+ |sumBalances@17| |amount@24|)))\n(assert (and (<= 0 (select |balanceOf@18| |to@23|)) (<= (select |balanceOf@18| |to@23|) 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |arith@31| Int)\n(assert (= |arith@31| (+ (select |balanceOf@18| |to@23|) |amount@24|)))\n(declare-const |g@32| Bool)\n(assert (= |g@32| (and |g@29| (and (<= 0 |arith@31|) (<= |arith@31| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))))\n(declare-const |balanceOf@33| (Array Int Int))\n(assert (= |balanceOf@33| (store |balanceOf@18| |to@23| |arith@31|)))\n(push 1)\n(assert |g@32|)\n(assert (not false))\n(check-sat)\n(pop 1)\n(assert (and (<= 0 (select |balanceOf@33| |to@23|)) (<= (select |balanceOf@33| |to@23|) 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(assert (and (<= 0 (select |balanceOf@18| |to@23|)) (<= (select |balanceOf@18| |to@23|) 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(push 1)\n(assert |g@32|)\n(assert (not (= (select |balanceOf@33| |to@23|) (+ (select |balanceOf@18| |to@23|) |amount@24|))))\n(check-sat)\n(pop 1)\n(push 1)\n(assert |g@32|)\n(assert (not (= |arith@28| (+ |totalSupply@19| |amount@24|))))\n(check-sat)\n(pop 1)\n(push 1)\n(assert |g@32|)\n(assert (not (forall ((|a!34| Int)) (=> (and (and (<= 0 |a!34|) (<= |a!34| 1461501637330902918203684832716283019655932542975))) (=> (not (= |a!34| |to@23|)) (= (select |balanceOf@33| |a!34|) (select |balanceOf@18| |a!34|)))))))\n(check-sat)\n(pop 1)\n(push 1)\n(assert |g@32|)\n(assert (not (= |arith@28| |sumBalances@30|)))\n(check-sat)\n(pop 1)\n(pop 1)\n(push 1)\n; ===== Token.transfer\n(declare-const |this@1| Int)\n(assert (and (<= 0 |this@1|) (<= |this@1| 1461501637330902918203684832716283019655932542975)))\n(declare-const |msg.sender@2| Int)\n(assert (and (<= 0 |msg.sender@2|) (<= |msg.sender@2| 1461501637330902918203684832716283019655932542975)))\n(assert (not (= |msg.sender@2| 0)))\n(declare-const |msg.value@3| Int)\n(assert (and (<= 0 |msg.value@3|) (<= |msg.value@3| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.timestamp@4| Int)\n(assert (and (<= 0 |block.timestamp@4|) (<= |block.timestamp@4| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.number@5| Int)\n(assert (and (<= 0 |block.number@5|) (<= |block.number@5| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.chainid@6| Int)\n(assert (and (<= 0 |block.chainid@6|) (<= |block.chainid@6| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |tx.origin@7| Int)\n(assert (and (<= 0 |tx.origin@7|) (<= |tx.origin@7| 1461501637330902918203684832716283019655932542975)))\n(declare-const |tx.gasprice@8| Int)\n(assert (and (<= 0 |tx.gasprice@8|) (<= |tx.gasprice@8| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |msg.sig@9| Int)\n(assert (and (<= 0 |msg.sig@9|) (<= |msg.sig@9| 4294967295)))\n(declare-const |msg.data@10| Int)\n(declare-const |block.basefee@11| Int)\n(assert (and (<= 0 |block.basefee@11|) (<= |block.basefee@11| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.blobbasefee@12| Int)\n(assert (and (<= 0 |block.blobbasefee@12|) (<= |block.blobbasefee@12| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.coinbase@13| Int)\n(assert (and (<= 0 |block.coinbase@13|) (<= |block.coinbase@13| 1461501637330902918203684832716283019655932542975)))\n(declare-const |block.prevrandao@14| Int)\n(assert (and (<= 0 |block.prevrandao@14|) (<= |block.prevrandao@14| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.difficulty@15| Int)\n(assert (and (<= 0 |block.difficulty@15|) (<= |block.difficulty@15| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.gaslimit@16| Int)\n(assert (and (<= 0 |block.gaslimit@16|) (<= |block.gaslimit@16| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |sumBalances@17| Int)\n(assert (and (<= 0 |sumBalances@17|) (<= |sumBalances@17| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |balanceOf@18| (Array Int Int))\n;@elem |balanceOf@18| 0 115792089237316195423570985008687907853269984665640564039457584007913129639935\n(declare-const |totalSupply@19| Int)\n(assert (and (<= 0 |totalSupply@19|) (<= |totalSupply@19| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |owner@20| Int)\n(assert (and (<= 0 |owner@20|) (<= |owner@20| 1461501637330902918203684832716283019655932542975)))\n(declare-const |__balance@21| (Array Int Int))\n;@elem |__balance@21| 0 115792089237316195423570985008687907853269984665640564039457584007913129639935\n(declare-const |__code_epoch@22| Int)\n(assert (and (<= 0 |__code_epoch@22|) (<= |__code_epoch@22| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |to@23| Int)\n(assert (and (<= 0 |to@23|) (<= |to@23| 1461501637330902918203684832716283019655932542975)))\n(declare-const |amount@24| Int)\n(assert (and (<= 0 |amount@24|) (<= |amount@24| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |g@25| Bool)\n(assert (= |g@25| (and true (= |totalSupply@19| |sumBalances@17|))))\n(declare-const |g@26| Bool)\n(assert (= |g@26| (and |g@25| (= |msg.value@3| 0))))\n(assert (and (<= 0 (select |balanceOf@18| |msg.sender@2|)) (<= (select |balanceOf@18| |msg.sender@2|) 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |bal@27| Int)\n(assert (= |bal@27| (select |balanceOf@18| |msg.sender@2|)))\n(declare-const |g@28| Bool)\n(assert (= |g@28| (and |g@26| (>= |bal@27| |amount@24|))))\n(declare-const |arith@29| Int)\n(assert (= |arith@29| (- |bal@27| |amount@24|)))\n(declare-const |g@30| Bool)\n(assert (= |g@30| (and |g@28| (and (<= 0 |arith@29|) (<= |arith@29| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))))\n(declare-const |balanceOf@31| (Array Int Int))\n(assert (= |balanceOf@31| (store |balanceOf@18| |msg.sender@2| |arith@29|)))\n(assert (and (<= 0 (select |balanceOf@31| |to@23|)) (<= (select |balanceOf@31| |to@23|) 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |arith@32| Int)\n(assert (= |arith@32| (+ (select |balanceOf@31| |to@23|) |amount@24|)))\n(declare-const |g@33| Bool)\n(assert (= |g@33| (and |g@30| (and (<= 0 |arith@32|) (<= |arith@32| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))))\n(declare-const |balanceOf@34| (Array Int Int))\n(assert (= |balanceOf@34| (store |balanceOf@31| |to@23| |arith@32|)))\n(push 1)\n(assert |g@33|)\n(assert (not false))\n(check-sat)\n(pop 1)\n(assert (and (<= 0 (select |balanceOf@34| |msg.sender@2|)) (<= (select |balanceOf@34| |msg.sender@2|) 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(assert (and (<= 0 (select |balanceOf@18| |msg.sender@2|)) (<= (select |balanceOf@18| |msg.sender@2|) 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(push 1)\n(assert |g@33|)\n(assert (not (=> (not (= |msg.sender@2| |to@23|)) (= (select |balanceOf@34| |msg.sender@2|) (- (select |balanceOf@18| |msg.sender@2|) |amount@24|)))))\n(check-sat)\n(pop 1)\n(assert (and (<= 0 (select |balanceOf@34| |to@23|)) (<= (select |balanceOf@34| |to@23|) 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(assert (and (<= 0 (select |balanceOf@18| |to@23|)) (<= (select |balanceOf@18| |to@23|) 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(push 1)\n(assert |g@33|)\n(assert (not (=> (not (= |msg.sender@2| |to@23|)) (= (select |balanceOf@34| |to@23|) (+ (select |balanceOf@18| |to@23|) |amount@24|)))))\n(check-sat)\n(pop 1)\n(push 1)\n(assert |g@33|)\n(assert (not (forall ((|a!35| Int)) (=> (and (and (<= 0 |a!35|) (<= |a!35| 1461501637330902918203684832716283019655932542975))) (=> (and (not (= |a!35| |msg.sender@2|)) (not (= |a!35| |to@23|))) (= (select |balanceOf@34| |a!35|) (select |balanceOf@18| |a!35|)))))))\n(check-sat)\n(pop 1)\n(push 1)\n(assert |g@33|)\n(assert (not (= |totalSupply@19| |totalSupply@19|)))\n(check-sat)\n(pop 1)\n(pop 1)\n(push 1)\n; ===== Token.burn\n(declare-const |this@1| Int)\n(assert (and (<= 0 |this@1|) (<= |this@1| 1461501637330902918203684832716283019655932542975)))\n(declare-const |msg.sender@2| Int)\n(assert (and (<= 0 |msg.sender@2|) (<= |msg.sender@2| 1461501637330902918203684832716283019655932542975)))\n(assert (not (= |msg.sender@2| 0)))\n(declare-const |msg.value@3| Int)\n(assert (and (<= 0 |msg.value@3|) (<= |msg.value@3| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.timestamp@4| Int)\n(assert (and (<= 0 |block.timestamp@4|) (<= |block.timestamp@4| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.number@5| Int)\n(assert (and (<= 0 |block.number@5|) (<= |block.number@5| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.chainid@6| Int)\n(assert (and (<= 0 |block.chainid@6|) (<= |block.chainid@6| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |tx.origin@7| Int)\n(assert (and (<= 0 |tx.origin@7|) (<= |tx.origin@7| 1461501637330902918203684832716283019655932542975)))\n(declare-const |tx.gasprice@8| Int)\n(assert (and (<= 0 |tx.gasprice@8|) (<= |tx.gasprice@8| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |msg.sig@9| Int)\n(assert (and (<= 0 |msg.sig@9|) (<= |msg.sig@9| 4294967295)))\n(declare-const |msg.data@10| Int)\n(declare-const |block.basefee@11| Int)\n(assert (and (<= 0 |block.basefee@11|) (<= |block.basefee@11| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.blobbasefee@12| Int)\n(assert (and (<= 0 |block.blobbasefee@12|) (<= |block.blobbasefee@12| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.coinbase@13| Int)\n(assert (and (<= 0 |block.coinbase@13|) (<= |block.coinbase@13| 1461501637330902918203684832716283019655932542975)))\n(declare-const |block.prevrandao@14| Int)\n(assert (and (<= 0 |block.prevrandao@14|) (<= |block.prevrandao@14| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.difficulty@15| Int)\n(assert (and (<= 0 |block.difficulty@15|) (<= |block.difficulty@15| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.gaslimit@16| Int)\n(assert (and (<= 0 |block.gaslimit@16|) (<= |block.gaslimit@16| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |sumBalances@17| Int)\n(assert (and (<= 0 |sumBalances@17|) (<= |sumBalances@17| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |balanceOf@18| (Array Int Int))\n;@elem |balanceOf@18| 0 115792089237316195423570985008687907853269984665640564039457584007913129639935\n(declare-const |totalSupply@19| Int)\n(assert (and (<= 0 |totalSupply@19|) (<= |totalSupply@19| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |owner@20| Int)\n(assert (and (<= 0 |owner@20|) (<= |owner@20| 1461501637330902918203684832716283019655932542975)))\n(declare-const |__balance@21| (Array Int Int))\n;@elem |__balance@21| 0 115792089237316195423570985008687907853269984665640564039457584007913129639935\n(declare-const |__code_epoch@22| Int)\n(assert (and (<= 0 |__code_epoch@22|) (<= |__code_epoch@22| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |amount@23| Int)\n(assert (and (<= 0 |amount@23|) (<= |amount@23| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |g@24| Bool)\n(assert (= |g@24| (and true (= |totalSupply@19| |sumBalances@17|))))\n(declare-const |g@25| Bool)\n(assert (= |g@25| (and |g@24| (= |msg.value@3| 0))))\n(assert (and (<= 0 (select |balanceOf@18| |msg.sender@2|)) (<= (select |balanceOf@18| |msg.sender@2|) 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |arith@26| Int)\n(assert (= |arith@26| (- (select |balanceOf@18| |msg.sender@2|) |amount@23|)))\n(declare-const |g@27| Bool)\n(assert (= |g@27| (and |g@25| (and (<= 0 |arith@26|) (<= |arith@26| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))))\n(declare-const |balanceOf@28| (Array Int Int))\n(assert (= |balanceOf@28| (store |balanceOf@18| |msg.sender@2| |arith@26|)))\n(declare-const |sumBalances@29| Int)\n(assert (= |sumBalances@29| (- |sumBalances@17| |amount@23|)))\n(declare-const |arith@30| Int)\n(assert (= |arith@30| (- |totalSupply@19| |amount@23|)))\n(declare-const |g@31| Bool)\n(assert (= |g@31| (and |g@27| (and (<= 0 |arith@30|) (<= |arith@30| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))))\n(push 1)\n(assert |g@31|)\n(assert (not false))\n(check-sat)\n(pop 1)\n(assert (and (<= 0 (select |balanceOf@28| |msg.sender@2|)) (<= (select |balanceOf@28| |msg.sender@2|) 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(assert (and (<= 0 (select |balanceOf@18| |msg.sender@2|)) (<= (select |balanceOf@18| |msg.sender@2|) 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(push 1)\n(assert |g@31|)\n(assert (not (= (select |balanceOf@28| |msg.sender@2|) (- (select |balanceOf@18| |msg.sender@2|) |amount@23|))))\n(check-sat)\n(pop 1)\n(push 1)\n(assert |g@31|)\n(assert (not (= |arith@30| |sumBalances@29|)))\n(check-sat)\n(pop 1)\n(pop 1)\n" + +end SolidCore.Verify.VC.Export.Token diff --git a/Contracts/Token/VC/Mutant/SpecMut.lean b/Contracts/Token/VC/Mutant/SpecMut.lean new file mode 100644 index 00000000..84ac5c32 --- /dev/null +++ b/Contracts/Token/VC/Mutant/SpecMut.lean @@ -0,0 +1,354 @@ +-- Generated by solar-verify --dump-lean. Do not edit. + +import Verify.VC.Term + +namespace SolidCore.Verify.VC.Export.Mutant.TokenSpecMut + +open SolidCore.Verify.VC + +/-- The commands solar-verify sent the solver. -/ +def script : List Cmd := [ + .push, + .raw "; ===== Token.constructor", + .decl "this@1" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "this@1")]), (.app "<=" [(.ivar "this@1"), (.num 1461501637330902918203684832716283019655932542975)])]), + .decl "msg.sender@2" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "msg.sender@2")]), (.app "<=" [(.ivar "msg.sender@2"), (.num 1461501637330902918203684832716283019655932542975)])]), + .assert (.app "not" [(.app "=" [(.ivar "msg.sender@2"), (.num 0)])]), + .decl "msg.value@3" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "msg.value@3")]), (.app "<=" [(.ivar "msg.value@3"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.timestamp@4" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.timestamp@4")]), (.app "<=" [(.ivar "block.timestamp@4"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.number@5" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.number@5")]), (.app "<=" [(.ivar "block.number@5"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.chainid@6" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.chainid@6")]), (.app "<=" [(.ivar "block.chainid@6"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "tx.origin@7" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "tx.origin@7")]), (.app "<=" [(.ivar "tx.origin@7"), (.num 1461501637330902918203684832716283019655932542975)])]), + .decl "tx.gasprice@8" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "tx.gasprice@8")]), (.app "<=" [(.ivar "tx.gasprice@8"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "msg.sig@9" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "msg.sig@9")]), (.app "<=" [(.ivar "msg.sig@9"), (.num 4294967295)])]), + .decl "msg.data@10" .int, + .decl "block.basefee@11" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.basefee@11")]), (.app "<=" [(.ivar "block.basefee@11"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.blobbasefee@12" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.blobbasefee@12")]), (.app "<=" [(.ivar "block.blobbasefee@12"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.coinbase@13" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.coinbase@13")]), (.app "<=" [(.ivar "block.coinbase@13"), (.num 1461501637330902918203684832716283019655932542975)])]), + .decl "block.prevrandao@14" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.prevrandao@14")]), (.app "<=" [(.ivar "block.prevrandao@14"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.difficulty@15" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.difficulty@15")]), (.app "<=" [(.ivar "block.difficulty@15"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.gaslimit@16" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.gaslimit@16")]), (.app "<=" [(.ivar "block.gaslimit@16"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "__balance@17" .arr, + .elem "__balance@17" 0 115792089237316195423570985008687907853269984665640564039457584007913129639935, + .decl "__code_epoch@18" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "__code_epoch@18")]), (.app "<=" [(.ivar "__code_epoch@18"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "g@19" .bool, + .assert (.app "=" [(.bvar "g@19"), (.app "and" [.tt, (.app "=" [(.ivar "msg.value@3"), (.num 0)])])]), + .push, + .assert (.bvar "g@19"), + .assert (.app "not" [.ff]), + .checkSat, + .pop, + .push, + .assert (.bvar "g@19"), + .assert (.app "not" [(.app "=" [(.ivar "msg.sender@2"), (.ivar "msg.sender@2")])]), + .checkSat, + .pop, + .push, + .assert (.bvar "g@19"), + .assert (.app "not" [(.app "=" [(.num 0), (.num 0)])]), + .checkSat, + .pop, + .pop, + .push, + .raw "; ===== Token.mint", + .decl "this@1" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "this@1")]), (.app "<=" [(.ivar "this@1"), (.num 1461501637330902918203684832716283019655932542975)])]), + .decl "msg.sender@2" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "msg.sender@2")]), (.app "<=" [(.ivar "msg.sender@2"), (.num 1461501637330902918203684832716283019655932542975)])]), + .assert (.app "not" [(.app "=" [(.ivar "msg.sender@2"), (.num 0)])]), + .decl "msg.value@3" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "msg.value@3")]), (.app "<=" [(.ivar "msg.value@3"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.timestamp@4" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.timestamp@4")]), (.app "<=" [(.ivar "block.timestamp@4"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.number@5" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.number@5")]), (.app "<=" [(.ivar "block.number@5"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.chainid@6" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.chainid@6")]), (.app "<=" [(.ivar "block.chainid@6"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "tx.origin@7" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "tx.origin@7")]), (.app "<=" [(.ivar "tx.origin@7"), (.num 1461501637330902918203684832716283019655932542975)])]), + .decl "tx.gasprice@8" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "tx.gasprice@8")]), (.app "<=" [(.ivar "tx.gasprice@8"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "msg.sig@9" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "msg.sig@9")]), (.app "<=" [(.ivar "msg.sig@9"), (.num 4294967295)])]), + .decl "msg.data@10" .int, + .decl "block.basefee@11" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.basefee@11")]), (.app "<=" [(.ivar "block.basefee@11"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.blobbasefee@12" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.blobbasefee@12")]), (.app "<=" [(.ivar "block.blobbasefee@12"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.coinbase@13" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.coinbase@13")]), (.app "<=" [(.ivar "block.coinbase@13"), (.num 1461501637330902918203684832716283019655932542975)])]), + .decl "block.prevrandao@14" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.prevrandao@14")]), (.app "<=" [(.ivar "block.prevrandao@14"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.difficulty@15" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.difficulty@15")]), (.app "<=" [(.ivar "block.difficulty@15"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.gaslimit@16" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.gaslimit@16")]), (.app "<=" [(.ivar "block.gaslimit@16"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "sumBalances@17" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "sumBalances@17")]), (.app "<=" [(.ivar "sumBalances@17"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "balanceOf@18" .arr, + .elem "balanceOf@18" 0 115792089237316195423570985008687907853269984665640564039457584007913129639935, + .decl "totalSupply@19" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "totalSupply@19")]), (.app "<=" [(.ivar "totalSupply@19"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "owner@20" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "owner@20")]), (.app "<=" [(.ivar "owner@20"), (.num 1461501637330902918203684832716283019655932542975)])]), + .decl "__balance@21" .arr, + .elem "__balance@21" 0 115792089237316195423570985008687907853269984665640564039457584007913129639935, + .decl "__code_epoch@22" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "__code_epoch@22")]), (.app "<=" [(.ivar "__code_epoch@22"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "to@23" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "to@23")]), (.app "<=" [(.ivar "to@23"), (.num 1461501637330902918203684832716283019655932542975)])]), + .decl "amount@24" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "amount@24")]), (.app "<=" [(.ivar "amount@24"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "g@25" .bool, + .assert (.app "=" [(.bvar "g@25"), (.app "and" [.tt, (.app "=" [(.ivar "totalSupply@19"), (.ivar "sumBalances@17")])])]), + .decl "g@26" .bool, + .assert (.app "=" [(.bvar "g@26"), (.app "and" [(.bvar "g@25"), (.app "=" [(.ivar "msg.value@3"), (.num 0)])])]), + .decl "g@27" .bool, + .assert (.app "=" [(.bvar "g@27"), (.app "and" [(.bvar "g@26"), (.app "=" [(.ivar "msg.sender@2"), (.ivar "owner@20")])])]), + .decl "arith@28" .int, + .assert (.app "=" [(.ivar "arith@28"), (.app "+" [(.ivar "totalSupply@19"), (.ivar "amount@24")])]), + .decl "g@29" .bool, + .assert (.app "=" [(.bvar "g@29"), (.app "and" [(.bvar "g@27"), (.app "and" [(.app "<=" [(.num 0), (.ivar "arith@28")]), (.app "<=" [(.ivar "arith@28"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])])])]), + .decl "sumBalances@30" .int, + .assert (.app "=" [(.ivar "sumBalances@30"), (.app "+" [(.ivar "sumBalances@17"), (.ivar "amount@24")])]), + .assert (.app "and" [(.app "<=" [(.num 0), (.app "select" [(.avar "balanceOf@18"), (.ivar "to@23")])]), (.app "<=" [(.app "select" [(.avar "balanceOf@18"), (.ivar "to@23")]), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "arith@31" .int, + .assert (.app "=" [(.ivar "arith@31"), (.app "+" [(.app "select" [(.avar "balanceOf@18"), (.ivar "to@23")]), (.ivar "amount@24")])]), + .decl "g@32" .bool, + .assert (.app "=" [(.bvar "g@32"), (.app "and" [(.bvar "g@29"), (.app "and" [(.app "<=" [(.num 0), (.ivar "arith@31")]), (.app "<=" [(.ivar "arith@31"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])])])]), + .decl "balanceOf@33" .arr, + .assert (.app "=" [(.avar "balanceOf@33"), (.app "store" [(.avar "balanceOf@18"), (.ivar "to@23"), (.ivar "arith@31")])]), + .push, + .assert (.bvar "g@32"), + .assert (.app "not" [.ff]), + .checkSat, + .pop, + .assert (.app "and" [(.app "<=" [(.num 0), (.app "select" [(.avar "balanceOf@33"), (.ivar "to@23")])]), (.app "<=" [(.app "select" [(.avar "balanceOf@33"), (.ivar "to@23")]), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .assert (.app "and" [(.app "<=" [(.num 0), (.app "select" [(.avar "balanceOf@18"), (.ivar "to@23")])]), (.app "<=" [(.app "select" [(.avar "balanceOf@18"), (.ivar "to@23")]), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .push, + .assert (.bvar "g@32"), + .assert (.app "not" [(.app "=" [(.app "select" [(.avar "balanceOf@33"), (.ivar "to@23")]), (.app "+" [(.app "select" [(.avar "balanceOf@18"), (.ivar "to@23")]), (.ivar "amount@24")])])]), + .checkSat, + .pop, + .push, + .assert (.bvar "g@32"), + .assert (.app "not" [(.app "=" [(.ivar "arith@28"), (.app "+" [(.ivar "totalSupply@19"), (.ivar "amount@24")])])]), + .checkSat, + .pop, + .push, + .assert (.bvar "g@32"), + .assert (.app "not" [(.all "a!34" (.app "=>" [(.app "and" [(.app "and" [(.app "<=" [(.num 0), (.ivar "a!34")]), (.app "<=" [(.ivar "a!34"), (.num 1461501637330902918203684832716283019655932542975)])])]), (.app "=>" [(.app "not" [(.app "=" [(.ivar "a!34"), (.ivar "to@23")])]), (.app "=" [(.app "select" [(.avar "balanceOf@33"), (.ivar "a!34")]), (.app "select" [(.avar "balanceOf@18"), (.ivar "a!34")])])])]))]), + .checkSat, + .pop, + .push, + .assert (.bvar "g@32"), + .assert (.app "not" [(.app "=" [(.ivar "arith@28"), (.ivar "sumBalances@30")])]), + .checkSat, + .pop, + .pop, + .push, + .raw "; ===== Token.transfer", + .decl "this@1" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "this@1")]), (.app "<=" [(.ivar "this@1"), (.num 1461501637330902918203684832716283019655932542975)])]), + .decl "msg.sender@2" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "msg.sender@2")]), (.app "<=" [(.ivar "msg.sender@2"), (.num 1461501637330902918203684832716283019655932542975)])]), + .assert (.app "not" [(.app "=" [(.ivar "msg.sender@2"), (.num 0)])]), + .decl "msg.value@3" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "msg.value@3")]), (.app "<=" [(.ivar "msg.value@3"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.timestamp@4" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.timestamp@4")]), (.app "<=" [(.ivar "block.timestamp@4"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.number@5" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.number@5")]), (.app "<=" [(.ivar "block.number@5"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.chainid@6" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.chainid@6")]), (.app "<=" [(.ivar "block.chainid@6"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "tx.origin@7" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "tx.origin@7")]), (.app "<=" [(.ivar "tx.origin@7"), (.num 1461501637330902918203684832716283019655932542975)])]), + .decl "tx.gasprice@8" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "tx.gasprice@8")]), (.app "<=" [(.ivar "tx.gasprice@8"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "msg.sig@9" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "msg.sig@9")]), (.app "<=" [(.ivar "msg.sig@9"), (.num 4294967295)])]), + .decl "msg.data@10" .int, + .decl "block.basefee@11" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.basefee@11")]), (.app "<=" [(.ivar "block.basefee@11"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.blobbasefee@12" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.blobbasefee@12")]), (.app "<=" [(.ivar "block.blobbasefee@12"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.coinbase@13" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.coinbase@13")]), (.app "<=" [(.ivar "block.coinbase@13"), (.num 1461501637330902918203684832716283019655932542975)])]), + .decl "block.prevrandao@14" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.prevrandao@14")]), (.app "<=" [(.ivar "block.prevrandao@14"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.difficulty@15" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.difficulty@15")]), (.app "<=" [(.ivar "block.difficulty@15"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.gaslimit@16" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.gaslimit@16")]), (.app "<=" [(.ivar "block.gaslimit@16"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "sumBalances@17" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "sumBalances@17")]), (.app "<=" [(.ivar "sumBalances@17"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "balanceOf@18" .arr, + .elem "balanceOf@18" 0 115792089237316195423570985008687907853269984665640564039457584007913129639935, + .decl "totalSupply@19" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "totalSupply@19")]), (.app "<=" [(.ivar "totalSupply@19"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "owner@20" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "owner@20")]), (.app "<=" [(.ivar "owner@20"), (.num 1461501637330902918203684832716283019655932542975)])]), + .decl "__balance@21" .arr, + .elem "__balance@21" 0 115792089237316195423570985008687907853269984665640564039457584007913129639935, + .decl "__code_epoch@22" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "__code_epoch@22")]), (.app "<=" [(.ivar "__code_epoch@22"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "to@23" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "to@23")]), (.app "<=" [(.ivar "to@23"), (.num 1461501637330902918203684832716283019655932542975)])]), + .decl "amount@24" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "amount@24")]), (.app "<=" [(.ivar "amount@24"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "g@25" .bool, + .assert (.app "=" [(.bvar "g@25"), (.app "and" [.tt, (.app "=" [(.ivar "totalSupply@19"), (.ivar "sumBalances@17")])])]), + .decl "g@26" .bool, + .assert (.app "=" [(.bvar "g@26"), (.app "and" [(.bvar "g@25"), (.app "=" [(.ivar "msg.value@3"), (.num 0)])])]), + .assert (.app "and" [(.app "<=" [(.num 0), (.app "select" [(.avar "balanceOf@18"), (.ivar "msg.sender@2")])]), (.app "<=" [(.app "select" [(.avar "balanceOf@18"), (.ivar "msg.sender@2")]), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "bal@27" .int, + .assert (.app "=" [(.ivar "bal@27"), (.app "select" [(.avar "balanceOf@18"), (.ivar "msg.sender@2")])]), + .decl "g@28" .bool, + .assert (.app "=" [(.bvar "g@28"), (.app "and" [(.bvar "g@26"), (.app ">=" [(.ivar "bal@27"), (.ivar "amount@24")])])]), + .decl "arith@29" .int, + .assert (.app "=" [(.ivar "arith@29"), (.app "-" [(.ivar "bal@27"), (.ivar "amount@24")])]), + .decl "g@30" .bool, + .assert (.app "=" [(.bvar "g@30"), (.app "and" [(.bvar "g@28"), (.app "and" [(.app "<=" [(.num 0), (.ivar "arith@29")]), (.app "<=" [(.ivar "arith@29"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])])])]), + .decl "balanceOf@31" .arr, + .assert (.app "=" [(.avar "balanceOf@31"), (.app "store" [(.avar "balanceOf@18"), (.ivar "msg.sender@2"), (.ivar "arith@29")])]), + .assert (.app "and" [(.app "<=" [(.num 0), (.app "select" [(.avar "balanceOf@31"), (.ivar "to@23")])]), (.app "<=" [(.app "select" [(.avar "balanceOf@31"), (.ivar "to@23")]), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "arith@32" .int, + .assert (.app "=" [(.ivar "arith@32"), (.app "+" [(.app "select" [(.avar "balanceOf@31"), (.ivar "to@23")]), (.ivar "amount@24")])]), + .decl "g@33" .bool, + .assert (.app "=" [(.bvar "g@33"), (.app "and" [(.bvar "g@30"), (.app "and" [(.app "<=" [(.num 0), (.ivar "arith@32")]), (.app "<=" [(.ivar "arith@32"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])])])]), + .decl "balanceOf@34" .arr, + .assert (.app "=" [(.avar "balanceOf@34"), (.app "store" [(.avar "balanceOf@31"), (.ivar "to@23"), (.ivar "arith@32")])]), + .push, + .assert (.bvar "g@33"), + .assert (.app "not" [.ff]), + .checkSat, + .pop, + .assert (.app "and" [(.app "<=" [(.num 0), (.app "select" [(.avar "balanceOf@34"), (.ivar "msg.sender@2")])]), (.app "<=" [(.app "select" [(.avar "balanceOf@34"), (.ivar "msg.sender@2")]), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .assert (.app "and" [(.app "<=" [(.num 0), (.app "select" [(.avar "balanceOf@18"), (.ivar "msg.sender@2")])]), (.app "<=" [(.app "select" [(.avar "balanceOf@18"), (.ivar "msg.sender@2")]), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .push, + .assert (.bvar "g@33"), + .assert (.app "not" [(.app "=>" [(.app "not" [(.app "=" [(.ivar "msg.sender@2"), (.ivar "to@23")])]), (.app "=" [(.app "select" [(.avar "balanceOf@34"), (.ivar "msg.sender@2")]), (.app "-" [(.app "select" [(.avar "balanceOf@18"), (.ivar "msg.sender@2")]), (.ivar "amount@24")])])])]), + .checkSat, + .pop, + .assert (.app "and" [(.app "<=" [(.num 0), (.app "select" [(.avar "balanceOf@34"), (.ivar "to@23")])]), (.app "<=" [(.app "select" [(.avar "balanceOf@34"), (.ivar "to@23")]), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .assert (.app "and" [(.app "<=" [(.num 0), (.app "select" [(.avar "balanceOf@18"), (.ivar "to@23")])]), (.app "<=" [(.app "select" [(.avar "balanceOf@18"), (.ivar "to@23")]), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .push, + .assert (.bvar "g@33"), + .assert (.app "not" [(.app "=>" [(.app "not" [(.app "=" [(.ivar "msg.sender@2"), (.ivar "to@23")])]), (.app "=" [(.app "select" [(.avar "balanceOf@34"), (.ivar "to@23")]), (.app "+" [(.app "+" [(.app "select" [(.avar "balanceOf@18"), (.ivar "to@23")]), (.ivar "amount@24")]), (.num 1)])])])]), + .checkSat, + .pop, + .push, + .assert (.bvar "g@33"), + .assert (.app "not" [(.all "a!35" (.app "=>" [(.app "and" [(.app "and" [(.app "<=" [(.num 0), (.ivar "a!35")]), (.app "<=" [(.ivar "a!35"), (.num 1461501637330902918203684832716283019655932542975)])])]), (.app "=>" [(.app "and" [(.app "not" [(.app "=" [(.ivar "a!35"), (.ivar "msg.sender@2")])]), (.app "not" [(.app "=" [(.ivar "a!35"), (.ivar "to@23")])])]), (.app "=" [(.app "select" [(.avar "balanceOf@34"), (.ivar "a!35")]), (.app "select" [(.avar "balanceOf@18"), (.ivar "a!35")])])])]))]), + .checkSat, + .pop, + .push, + .assert (.bvar "g@33"), + .assert (.app "not" [(.app "=" [(.ivar "totalSupply@19"), (.ivar "totalSupply@19")])]), + .checkSat, + .pop, + .pop, + .push, + .raw "; ===== Token.burn", + .decl "this@1" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "this@1")]), (.app "<=" [(.ivar "this@1"), (.num 1461501637330902918203684832716283019655932542975)])]), + .decl "msg.sender@2" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "msg.sender@2")]), (.app "<=" [(.ivar "msg.sender@2"), (.num 1461501637330902918203684832716283019655932542975)])]), + .assert (.app "not" [(.app "=" [(.ivar "msg.sender@2"), (.num 0)])]), + .decl "msg.value@3" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "msg.value@3")]), (.app "<=" [(.ivar "msg.value@3"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.timestamp@4" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.timestamp@4")]), (.app "<=" [(.ivar "block.timestamp@4"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.number@5" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.number@5")]), (.app "<=" [(.ivar "block.number@5"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.chainid@6" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.chainid@6")]), (.app "<=" [(.ivar "block.chainid@6"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "tx.origin@7" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "tx.origin@7")]), (.app "<=" [(.ivar "tx.origin@7"), (.num 1461501637330902918203684832716283019655932542975)])]), + .decl "tx.gasprice@8" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "tx.gasprice@8")]), (.app "<=" [(.ivar "tx.gasprice@8"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "msg.sig@9" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "msg.sig@9")]), (.app "<=" [(.ivar "msg.sig@9"), (.num 4294967295)])]), + .decl "msg.data@10" .int, + .decl "block.basefee@11" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.basefee@11")]), (.app "<=" [(.ivar "block.basefee@11"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.blobbasefee@12" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.blobbasefee@12")]), (.app "<=" [(.ivar "block.blobbasefee@12"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.coinbase@13" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.coinbase@13")]), (.app "<=" [(.ivar "block.coinbase@13"), (.num 1461501637330902918203684832716283019655932542975)])]), + .decl "block.prevrandao@14" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.prevrandao@14")]), (.app "<=" [(.ivar "block.prevrandao@14"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.difficulty@15" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.difficulty@15")]), (.app "<=" [(.ivar "block.difficulty@15"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.gaslimit@16" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.gaslimit@16")]), (.app "<=" [(.ivar "block.gaslimit@16"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "sumBalances@17" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "sumBalances@17")]), (.app "<=" [(.ivar "sumBalances@17"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "balanceOf@18" .arr, + .elem "balanceOf@18" 0 115792089237316195423570985008687907853269984665640564039457584007913129639935, + .decl "totalSupply@19" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "totalSupply@19")]), (.app "<=" [(.ivar "totalSupply@19"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "owner@20" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "owner@20")]), (.app "<=" [(.ivar "owner@20"), (.num 1461501637330902918203684832716283019655932542975)])]), + .decl "__balance@21" .arr, + .elem "__balance@21" 0 115792089237316195423570985008687907853269984665640564039457584007913129639935, + .decl "__code_epoch@22" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "__code_epoch@22")]), (.app "<=" [(.ivar "__code_epoch@22"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "amount@23" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "amount@23")]), (.app "<=" [(.ivar "amount@23"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "g@24" .bool, + .assert (.app "=" [(.bvar "g@24"), (.app "and" [.tt, (.app "=" [(.ivar "totalSupply@19"), (.ivar "sumBalances@17")])])]), + .decl "g@25" .bool, + .assert (.app "=" [(.bvar "g@25"), (.app "and" [(.bvar "g@24"), (.app "=" [(.ivar "msg.value@3"), (.num 0)])])]), + .assert (.app "and" [(.app "<=" [(.num 0), (.app "select" [(.avar "balanceOf@18"), (.ivar "msg.sender@2")])]), (.app "<=" [(.app "select" [(.avar "balanceOf@18"), (.ivar "msg.sender@2")]), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "arith@26" .int, + .assert (.app "=" [(.ivar "arith@26"), (.app "-" [(.app "select" [(.avar "balanceOf@18"), (.ivar "msg.sender@2")]), (.ivar "amount@23")])]), + .decl "g@27" .bool, + .assert (.app "=" [(.bvar "g@27"), (.app "and" [(.bvar "g@25"), (.app "and" [(.app "<=" [(.num 0), (.ivar "arith@26")]), (.app "<=" [(.ivar "arith@26"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])])])]), + .decl "balanceOf@28" .arr, + .assert (.app "=" [(.avar "balanceOf@28"), (.app "store" [(.avar "balanceOf@18"), (.ivar "msg.sender@2"), (.ivar "arith@26")])]), + .decl "sumBalances@29" .int, + .assert (.app "=" [(.ivar "sumBalances@29"), (.app "-" [(.ivar "sumBalances@17"), (.ivar "amount@23")])]), + .decl "arith@30" .int, + .assert (.app "=" [(.ivar "arith@30"), (.app "-" [(.ivar "totalSupply@19"), (.ivar "amount@23")])]), + .decl "g@31" .bool, + .assert (.app "=" [(.bvar "g@31"), (.app "and" [(.bvar "g@27"), (.app "and" [(.app "<=" [(.num 0), (.ivar "arith@30")]), (.app "<=" [(.ivar "arith@30"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])])])]), + .push, + .assert (.bvar "g@31"), + .assert (.app "not" [.ff]), + .checkSat, + .pop, + .assert (.app "and" [(.app "<=" [(.num 0), (.app "select" [(.avar "balanceOf@28"), (.ivar "msg.sender@2")])]), (.app "<=" [(.app "select" [(.avar "balanceOf@28"), (.ivar "msg.sender@2")]), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .assert (.app "and" [(.app "<=" [(.num 0), (.app "select" [(.avar "balanceOf@18"), (.ivar "msg.sender@2")])]), (.app "<=" [(.app "select" [(.avar "balanceOf@18"), (.ivar "msg.sender@2")]), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .push, + .assert (.bvar "g@31"), + .assert (.app "not" [(.app "=" [(.app "select" [(.avar "balanceOf@28"), (.ivar "msg.sender@2")]), (.app "-" [(.app "select" [(.avar "balanceOf@18"), (.ivar "msg.sender@2")]), (.ivar "amount@23")])])]), + .checkSat, + .pop, + .push, + .assert (.bvar "g@31"), + .assert (.app "not" [(.app "=" [(.ivar "arith@30"), (.ivar "sumBalances@29")])]), + .checkSat, + .pop, + .pop +] + +/-- The transcript, as solar-verify wrote it. -/ +def transcript : String := "(push 1)\n; ===== Token.constructor\n(declare-const |this@1| Int)\n(assert (and (<= 0 |this@1|) (<= |this@1| 1461501637330902918203684832716283019655932542975)))\n(declare-const |msg.sender@2| Int)\n(assert (and (<= 0 |msg.sender@2|) (<= |msg.sender@2| 1461501637330902918203684832716283019655932542975)))\n(assert (not (= |msg.sender@2| 0)))\n(declare-const |msg.value@3| Int)\n(assert (and (<= 0 |msg.value@3|) (<= |msg.value@3| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.timestamp@4| Int)\n(assert (and (<= 0 |block.timestamp@4|) (<= |block.timestamp@4| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.number@5| Int)\n(assert (and (<= 0 |block.number@5|) (<= |block.number@5| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.chainid@6| Int)\n(assert (and (<= 0 |block.chainid@6|) (<= |block.chainid@6| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |tx.origin@7| Int)\n(assert (and (<= 0 |tx.origin@7|) (<= |tx.origin@7| 1461501637330902918203684832716283019655932542975)))\n(declare-const |tx.gasprice@8| Int)\n(assert (and (<= 0 |tx.gasprice@8|) (<= |tx.gasprice@8| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |msg.sig@9| Int)\n(assert (and (<= 0 |msg.sig@9|) (<= |msg.sig@9| 4294967295)))\n(declare-const |msg.data@10| Int)\n(declare-const |block.basefee@11| Int)\n(assert (and (<= 0 |block.basefee@11|) (<= |block.basefee@11| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.blobbasefee@12| Int)\n(assert (and (<= 0 |block.blobbasefee@12|) (<= |block.blobbasefee@12| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.coinbase@13| Int)\n(assert (and (<= 0 |block.coinbase@13|) (<= |block.coinbase@13| 1461501637330902918203684832716283019655932542975)))\n(declare-const |block.prevrandao@14| Int)\n(assert (and (<= 0 |block.prevrandao@14|) (<= |block.prevrandao@14| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.difficulty@15| Int)\n(assert (and (<= 0 |block.difficulty@15|) (<= |block.difficulty@15| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.gaslimit@16| Int)\n(assert (and (<= 0 |block.gaslimit@16|) (<= |block.gaslimit@16| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |__balance@17| (Array Int Int))\n;@elem |__balance@17| 0 115792089237316195423570985008687907853269984665640564039457584007913129639935\n(declare-const |__code_epoch@18| Int)\n(assert (and (<= 0 |__code_epoch@18|) (<= |__code_epoch@18| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |g@19| Bool)\n(assert (= |g@19| (and true (= |msg.value@3| 0))))\n(push 1)\n(assert |g@19|)\n(assert (not false))\n(check-sat)\n(pop 1)\n(push 1)\n(assert |g@19|)\n(assert (not (= |msg.sender@2| |msg.sender@2|)))\n(check-sat)\n(pop 1)\n(push 1)\n(assert |g@19|)\n(assert (not (= 0 0)))\n(check-sat)\n(pop 1)\n(pop 1)\n(push 1)\n; ===== Token.mint\n(declare-const |this@1| Int)\n(assert (and (<= 0 |this@1|) (<= |this@1| 1461501637330902918203684832716283019655932542975)))\n(declare-const |msg.sender@2| Int)\n(assert (and (<= 0 |msg.sender@2|) (<= |msg.sender@2| 1461501637330902918203684832716283019655932542975)))\n(assert (not (= |msg.sender@2| 0)))\n(declare-const |msg.value@3| Int)\n(assert (and (<= 0 |msg.value@3|) (<= |msg.value@3| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.timestamp@4| Int)\n(assert (and (<= 0 |block.timestamp@4|) (<= |block.timestamp@4| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.number@5| Int)\n(assert (and (<= 0 |block.number@5|) (<= |block.number@5| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.chainid@6| Int)\n(assert (and (<= 0 |block.chainid@6|) (<= |block.chainid@6| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |tx.origin@7| Int)\n(assert (and (<= 0 |tx.origin@7|) (<= |tx.origin@7| 1461501637330902918203684832716283019655932542975)))\n(declare-const |tx.gasprice@8| Int)\n(assert (and (<= 0 |tx.gasprice@8|) (<= |tx.gasprice@8| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |msg.sig@9| Int)\n(assert (and (<= 0 |msg.sig@9|) (<= |msg.sig@9| 4294967295)))\n(declare-const |msg.data@10| Int)\n(declare-const |block.basefee@11| Int)\n(assert (and (<= 0 |block.basefee@11|) (<= |block.basefee@11| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.blobbasefee@12| Int)\n(assert (and (<= 0 |block.blobbasefee@12|) (<= |block.blobbasefee@12| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.coinbase@13| Int)\n(assert (and (<= 0 |block.coinbase@13|) (<= |block.coinbase@13| 1461501637330902918203684832716283019655932542975)))\n(declare-const |block.prevrandao@14| Int)\n(assert (and (<= 0 |block.prevrandao@14|) (<= |block.prevrandao@14| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.difficulty@15| Int)\n(assert (and (<= 0 |block.difficulty@15|) (<= |block.difficulty@15| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.gaslimit@16| Int)\n(assert (and (<= 0 |block.gaslimit@16|) (<= |block.gaslimit@16| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |sumBalances@17| Int)\n(assert (and (<= 0 |sumBalances@17|) (<= |sumBalances@17| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |balanceOf@18| (Array Int Int))\n;@elem |balanceOf@18| 0 115792089237316195423570985008687907853269984665640564039457584007913129639935\n(declare-const |totalSupply@19| Int)\n(assert (and (<= 0 |totalSupply@19|) (<= |totalSupply@19| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |owner@20| Int)\n(assert (and (<= 0 |owner@20|) (<= |owner@20| 1461501637330902918203684832716283019655932542975)))\n(declare-const |__balance@21| (Array Int Int))\n;@elem |__balance@21| 0 115792089237316195423570985008687907853269984665640564039457584007913129639935\n(declare-const |__code_epoch@22| Int)\n(assert (and (<= 0 |__code_epoch@22|) (<= |__code_epoch@22| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |to@23| Int)\n(assert (and (<= 0 |to@23|) (<= |to@23| 1461501637330902918203684832716283019655932542975)))\n(declare-const |amount@24| Int)\n(assert (and (<= 0 |amount@24|) (<= |amount@24| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |g@25| Bool)\n(assert (= |g@25| (and true (= |totalSupply@19| |sumBalances@17|))))\n(declare-const |g@26| Bool)\n(assert (= |g@26| (and |g@25| (= |msg.value@3| 0))))\n(declare-const |g@27| Bool)\n(assert (= |g@27| (and |g@26| (= |msg.sender@2| |owner@20|))))\n(declare-const |arith@28| Int)\n(assert (= |arith@28| (+ |totalSupply@19| |amount@24|)))\n(declare-const |g@29| Bool)\n(assert (= |g@29| (and |g@27| (and (<= 0 |arith@28|) (<= |arith@28| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))))\n(declare-const |sumBalances@30| Int)\n(assert (= |sumBalances@30| (+ |sumBalances@17| |amount@24|)))\n(assert (and (<= 0 (select |balanceOf@18| |to@23|)) (<= (select |balanceOf@18| |to@23|) 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |arith@31| Int)\n(assert (= |arith@31| (+ (select |balanceOf@18| |to@23|) |amount@24|)))\n(declare-const |g@32| Bool)\n(assert (= |g@32| (and |g@29| (and (<= 0 |arith@31|) (<= |arith@31| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))))\n(declare-const |balanceOf@33| (Array Int Int))\n(assert (= |balanceOf@33| (store |balanceOf@18| |to@23| |arith@31|)))\n(push 1)\n(assert |g@32|)\n(assert (not false))\n(check-sat)\n(pop 1)\n(assert (and (<= 0 (select |balanceOf@33| |to@23|)) (<= (select |balanceOf@33| |to@23|) 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(assert (and (<= 0 (select |balanceOf@18| |to@23|)) (<= (select |balanceOf@18| |to@23|) 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(push 1)\n(assert |g@32|)\n(assert (not (= (select |balanceOf@33| |to@23|) (+ (select |balanceOf@18| |to@23|) |amount@24|))))\n(check-sat)\n(pop 1)\n(push 1)\n(assert |g@32|)\n(assert (not (= |arith@28| (+ |totalSupply@19| |amount@24|))))\n(check-sat)\n(pop 1)\n(push 1)\n(assert |g@32|)\n(assert (not (forall ((|a!34| Int)) (=> (and (and (<= 0 |a!34|) (<= |a!34| 1461501637330902918203684832716283019655932542975))) (=> (not (= |a!34| |to@23|)) (= (select |balanceOf@33| |a!34|) (select |balanceOf@18| |a!34|)))))))\n(check-sat)\n(pop 1)\n(push 1)\n(assert |g@32|)\n(assert (not (= |arith@28| |sumBalances@30|)))\n(check-sat)\n(pop 1)\n(pop 1)\n(push 1)\n; ===== Token.transfer\n(declare-const |this@1| Int)\n(assert (and (<= 0 |this@1|) (<= |this@1| 1461501637330902918203684832716283019655932542975)))\n(declare-const |msg.sender@2| Int)\n(assert (and (<= 0 |msg.sender@2|) (<= |msg.sender@2| 1461501637330902918203684832716283019655932542975)))\n(assert (not (= |msg.sender@2| 0)))\n(declare-const |msg.value@3| Int)\n(assert (and (<= 0 |msg.value@3|) (<= |msg.value@3| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.timestamp@4| Int)\n(assert (and (<= 0 |block.timestamp@4|) (<= |block.timestamp@4| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.number@5| Int)\n(assert (and (<= 0 |block.number@5|) (<= |block.number@5| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.chainid@6| Int)\n(assert (and (<= 0 |block.chainid@6|) (<= |block.chainid@6| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |tx.origin@7| Int)\n(assert (and (<= 0 |tx.origin@7|) (<= |tx.origin@7| 1461501637330902918203684832716283019655932542975)))\n(declare-const |tx.gasprice@8| Int)\n(assert (and (<= 0 |tx.gasprice@8|) (<= |tx.gasprice@8| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |msg.sig@9| Int)\n(assert (and (<= 0 |msg.sig@9|) (<= |msg.sig@9| 4294967295)))\n(declare-const |msg.data@10| Int)\n(declare-const |block.basefee@11| Int)\n(assert (and (<= 0 |block.basefee@11|) (<= |block.basefee@11| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.blobbasefee@12| Int)\n(assert (and (<= 0 |block.blobbasefee@12|) (<= |block.blobbasefee@12| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.coinbase@13| Int)\n(assert (and (<= 0 |block.coinbase@13|) (<= |block.coinbase@13| 1461501637330902918203684832716283019655932542975)))\n(declare-const |block.prevrandao@14| Int)\n(assert (and (<= 0 |block.prevrandao@14|) (<= |block.prevrandao@14| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.difficulty@15| Int)\n(assert (and (<= 0 |block.difficulty@15|) (<= |block.difficulty@15| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.gaslimit@16| Int)\n(assert (and (<= 0 |block.gaslimit@16|) (<= |block.gaslimit@16| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |sumBalances@17| Int)\n(assert (and (<= 0 |sumBalances@17|) (<= |sumBalances@17| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |balanceOf@18| (Array Int Int))\n;@elem |balanceOf@18| 0 115792089237316195423570985008687907853269984665640564039457584007913129639935\n(declare-const |totalSupply@19| Int)\n(assert (and (<= 0 |totalSupply@19|) (<= |totalSupply@19| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |owner@20| Int)\n(assert (and (<= 0 |owner@20|) (<= |owner@20| 1461501637330902918203684832716283019655932542975)))\n(declare-const |__balance@21| (Array Int Int))\n;@elem |__balance@21| 0 115792089237316195423570985008687907853269984665640564039457584007913129639935\n(declare-const |__code_epoch@22| Int)\n(assert (and (<= 0 |__code_epoch@22|) (<= |__code_epoch@22| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |to@23| Int)\n(assert (and (<= 0 |to@23|) (<= |to@23| 1461501637330902918203684832716283019655932542975)))\n(declare-const |amount@24| Int)\n(assert (and (<= 0 |amount@24|) (<= |amount@24| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |g@25| Bool)\n(assert (= |g@25| (and true (= |totalSupply@19| |sumBalances@17|))))\n(declare-const |g@26| Bool)\n(assert (= |g@26| (and |g@25| (= |msg.value@3| 0))))\n(assert (and (<= 0 (select |balanceOf@18| |msg.sender@2|)) (<= (select |balanceOf@18| |msg.sender@2|) 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |bal@27| Int)\n(assert (= |bal@27| (select |balanceOf@18| |msg.sender@2|)))\n(declare-const |g@28| Bool)\n(assert (= |g@28| (and |g@26| (>= |bal@27| |amount@24|))))\n(declare-const |arith@29| Int)\n(assert (= |arith@29| (- |bal@27| |amount@24|)))\n(declare-const |g@30| Bool)\n(assert (= |g@30| (and |g@28| (and (<= 0 |arith@29|) (<= |arith@29| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))))\n(declare-const |balanceOf@31| (Array Int Int))\n(assert (= |balanceOf@31| (store |balanceOf@18| |msg.sender@2| |arith@29|)))\n(assert (and (<= 0 (select |balanceOf@31| |to@23|)) (<= (select |balanceOf@31| |to@23|) 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |arith@32| Int)\n(assert (= |arith@32| (+ (select |balanceOf@31| |to@23|) |amount@24|)))\n(declare-const |g@33| Bool)\n(assert (= |g@33| (and |g@30| (and (<= 0 |arith@32|) (<= |arith@32| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))))\n(declare-const |balanceOf@34| (Array Int Int))\n(assert (= |balanceOf@34| (store |balanceOf@31| |to@23| |arith@32|)))\n(push 1)\n(assert |g@33|)\n(assert (not false))\n(check-sat)\n(pop 1)\n(assert (and (<= 0 (select |balanceOf@34| |msg.sender@2|)) (<= (select |balanceOf@34| |msg.sender@2|) 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(assert (and (<= 0 (select |balanceOf@18| |msg.sender@2|)) (<= (select |balanceOf@18| |msg.sender@2|) 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(push 1)\n(assert |g@33|)\n(assert (not (=> (not (= |msg.sender@2| |to@23|)) (= (select |balanceOf@34| |msg.sender@2|) (- (select |balanceOf@18| |msg.sender@2|) |amount@24|)))))\n(check-sat)\n(pop 1)\n(assert (and (<= 0 (select |balanceOf@34| |to@23|)) (<= (select |balanceOf@34| |to@23|) 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(assert (and (<= 0 (select |balanceOf@18| |to@23|)) (<= (select |balanceOf@18| |to@23|) 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(push 1)\n(assert |g@33|)\n(assert (not (=> (not (= |msg.sender@2| |to@23|)) (= (select |balanceOf@34| |to@23|) (+ (+ (select |balanceOf@18| |to@23|) |amount@24|) 1)))))\n(check-sat)\n(pop 1)\n(push 1)\n(assert |g@33|)\n(assert (not (forall ((|a!35| Int)) (=> (and (and (<= 0 |a!35|) (<= |a!35| 1461501637330902918203684832716283019655932542975))) (=> (and (not (= |a!35| |msg.sender@2|)) (not (= |a!35| |to@23|))) (= (select |balanceOf@34| |a!35|) (select |balanceOf@18| |a!35|)))))))\n(check-sat)\n(pop 1)\n(push 1)\n(assert |g@33|)\n(assert (not (= |totalSupply@19| |totalSupply@19|)))\n(check-sat)\n(pop 1)\n(pop 1)\n(push 1)\n; ===== Token.burn\n(declare-const |this@1| Int)\n(assert (and (<= 0 |this@1|) (<= |this@1| 1461501637330902918203684832716283019655932542975)))\n(declare-const |msg.sender@2| Int)\n(assert (and (<= 0 |msg.sender@2|) (<= |msg.sender@2| 1461501637330902918203684832716283019655932542975)))\n(assert (not (= |msg.sender@2| 0)))\n(declare-const |msg.value@3| Int)\n(assert (and (<= 0 |msg.value@3|) (<= |msg.value@3| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.timestamp@4| Int)\n(assert (and (<= 0 |block.timestamp@4|) (<= |block.timestamp@4| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.number@5| Int)\n(assert (and (<= 0 |block.number@5|) (<= |block.number@5| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.chainid@6| Int)\n(assert (and (<= 0 |block.chainid@6|) (<= |block.chainid@6| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |tx.origin@7| Int)\n(assert (and (<= 0 |tx.origin@7|) (<= |tx.origin@7| 1461501637330902918203684832716283019655932542975)))\n(declare-const |tx.gasprice@8| Int)\n(assert (and (<= 0 |tx.gasprice@8|) (<= |tx.gasprice@8| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |msg.sig@9| Int)\n(assert (and (<= 0 |msg.sig@9|) (<= |msg.sig@9| 4294967295)))\n(declare-const |msg.data@10| Int)\n(declare-const |block.basefee@11| Int)\n(assert (and (<= 0 |block.basefee@11|) (<= |block.basefee@11| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.blobbasefee@12| Int)\n(assert (and (<= 0 |block.blobbasefee@12|) (<= |block.blobbasefee@12| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.coinbase@13| Int)\n(assert (and (<= 0 |block.coinbase@13|) (<= |block.coinbase@13| 1461501637330902918203684832716283019655932542975)))\n(declare-const |block.prevrandao@14| Int)\n(assert (and (<= 0 |block.prevrandao@14|) (<= |block.prevrandao@14| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.difficulty@15| Int)\n(assert (and (<= 0 |block.difficulty@15|) (<= |block.difficulty@15| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.gaslimit@16| Int)\n(assert (and (<= 0 |block.gaslimit@16|) (<= |block.gaslimit@16| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |sumBalances@17| Int)\n(assert (and (<= 0 |sumBalances@17|) (<= |sumBalances@17| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |balanceOf@18| (Array Int Int))\n;@elem |balanceOf@18| 0 115792089237316195423570985008687907853269984665640564039457584007913129639935\n(declare-const |totalSupply@19| Int)\n(assert (and (<= 0 |totalSupply@19|) (<= |totalSupply@19| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |owner@20| Int)\n(assert (and (<= 0 |owner@20|) (<= |owner@20| 1461501637330902918203684832716283019655932542975)))\n(declare-const |__balance@21| (Array Int Int))\n;@elem |__balance@21| 0 115792089237316195423570985008687907853269984665640564039457584007913129639935\n(declare-const |__code_epoch@22| Int)\n(assert (and (<= 0 |__code_epoch@22|) (<= |__code_epoch@22| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |amount@23| Int)\n(assert (and (<= 0 |amount@23|) (<= |amount@23| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |g@24| Bool)\n(assert (= |g@24| (and true (= |totalSupply@19| |sumBalances@17|))))\n(declare-const |g@25| Bool)\n(assert (= |g@25| (and |g@24| (= |msg.value@3| 0))))\n(assert (and (<= 0 (select |balanceOf@18| |msg.sender@2|)) (<= (select |balanceOf@18| |msg.sender@2|) 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |arith@26| Int)\n(assert (= |arith@26| (- (select |balanceOf@18| |msg.sender@2|) |amount@23|)))\n(declare-const |g@27| Bool)\n(assert (= |g@27| (and |g@25| (and (<= 0 |arith@26|) (<= |arith@26| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))))\n(declare-const |balanceOf@28| (Array Int Int))\n(assert (= |balanceOf@28| (store |balanceOf@18| |msg.sender@2| |arith@26|)))\n(declare-const |sumBalances@29| Int)\n(assert (= |sumBalances@29| (- |sumBalances@17| |amount@23|)))\n(declare-const |arith@30| Int)\n(assert (= |arith@30| (- |totalSupply@19| |amount@23|)))\n(declare-const |g@31| Bool)\n(assert (= |g@31| (and |g@27| (and (<= 0 |arith@30|) (<= |arith@30| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))))\n(push 1)\n(assert |g@31|)\n(assert (not false))\n(check-sat)\n(pop 1)\n(assert (and (<= 0 (select |balanceOf@28| |msg.sender@2|)) (<= (select |balanceOf@28| |msg.sender@2|) 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(assert (and (<= 0 (select |balanceOf@18| |msg.sender@2|)) (<= (select |balanceOf@18| |msg.sender@2|) 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(push 1)\n(assert |g@31|)\n(assert (not (= (select |balanceOf@28| |msg.sender@2|) (- (select |balanceOf@18| |msg.sender@2|) |amount@23|))))\n(check-sat)\n(pop 1)\n(push 1)\n(assert |g@31|)\n(assert (not (= |arith@30| |sumBalances@29|)))\n(check-sat)\n(pop 1)\n(pop 1)\n" + +end SolidCore.Verify.VC.Export.Mutant.TokenSpecMut diff --git a/Contracts/Token/VC/Mutant/SrcMut.lean b/Contracts/Token/VC/Mutant/SrcMut.lean new file mode 100644 index 00000000..fdbe7367 --- /dev/null +++ b/Contracts/Token/VC/Mutant/SrcMut.lean @@ -0,0 +1,358 @@ +-- Generated by solar-verify --dump-lean. Do not edit. + +import Verify.VC.Term + +namespace SolidCore.Verify.VC.Export.Mutant.TokenSrcMut + +open SolidCore.Verify.VC + +/-- The commands solar-verify sent the solver. -/ +def script : List Cmd := [ + .push, + .raw "; ===== Token.constructor", + .decl "this@1" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "this@1")]), (.app "<=" [(.ivar "this@1"), (.num 1461501637330902918203684832716283019655932542975)])]), + .decl "msg.sender@2" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "msg.sender@2")]), (.app "<=" [(.ivar "msg.sender@2"), (.num 1461501637330902918203684832716283019655932542975)])]), + .assert (.app "not" [(.app "=" [(.ivar "msg.sender@2"), (.num 0)])]), + .decl "msg.value@3" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "msg.value@3")]), (.app "<=" [(.ivar "msg.value@3"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.timestamp@4" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.timestamp@4")]), (.app "<=" [(.ivar "block.timestamp@4"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.number@5" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.number@5")]), (.app "<=" [(.ivar "block.number@5"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.chainid@6" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.chainid@6")]), (.app "<=" [(.ivar "block.chainid@6"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "tx.origin@7" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "tx.origin@7")]), (.app "<=" [(.ivar "tx.origin@7"), (.num 1461501637330902918203684832716283019655932542975)])]), + .decl "tx.gasprice@8" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "tx.gasprice@8")]), (.app "<=" [(.ivar "tx.gasprice@8"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "msg.sig@9" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "msg.sig@9")]), (.app "<=" [(.ivar "msg.sig@9"), (.num 4294967295)])]), + .decl "msg.data@10" .int, + .decl "block.basefee@11" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.basefee@11")]), (.app "<=" [(.ivar "block.basefee@11"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.blobbasefee@12" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.blobbasefee@12")]), (.app "<=" [(.ivar "block.blobbasefee@12"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.coinbase@13" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.coinbase@13")]), (.app "<=" [(.ivar "block.coinbase@13"), (.num 1461501637330902918203684832716283019655932542975)])]), + .decl "block.prevrandao@14" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.prevrandao@14")]), (.app "<=" [(.ivar "block.prevrandao@14"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.difficulty@15" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.difficulty@15")]), (.app "<=" [(.ivar "block.difficulty@15"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.gaslimit@16" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.gaslimit@16")]), (.app "<=" [(.ivar "block.gaslimit@16"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "__balance@17" .arr, + .elem "__balance@17" 0 115792089237316195423570985008687907853269984665640564039457584007913129639935, + .decl "__code_epoch@18" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "__code_epoch@18")]), (.app "<=" [(.ivar "__code_epoch@18"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "g@19" .bool, + .assert (.app "=" [(.bvar "g@19"), (.app "and" [.tt, (.app "=" [(.ivar "msg.value@3"), (.num 0)])])]), + .push, + .assert (.bvar "g@19"), + .assert (.app "not" [.ff]), + .checkSat, + .pop, + .push, + .assert (.bvar "g@19"), + .assert (.app "not" [(.app "=" [(.ivar "msg.sender@2"), (.ivar "msg.sender@2")])]), + .checkSat, + .pop, + .push, + .assert (.bvar "g@19"), + .assert (.app "not" [(.app "=" [(.num 0), (.num 0)])]), + .checkSat, + .pop, + .pop, + .push, + .raw "; ===== Token.mint", + .decl "this@1" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "this@1")]), (.app "<=" [(.ivar "this@1"), (.num 1461501637330902918203684832716283019655932542975)])]), + .decl "msg.sender@2" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "msg.sender@2")]), (.app "<=" [(.ivar "msg.sender@2"), (.num 1461501637330902918203684832716283019655932542975)])]), + .assert (.app "not" [(.app "=" [(.ivar "msg.sender@2"), (.num 0)])]), + .decl "msg.value@3" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "msg.value@3")]), (.app "<=" [(.ivar "msg.value@3"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.timestamp@4" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.timestamp@4")]), (.app "<=" [(.ivar "block.timestamp@4"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.number@5" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.number@5")]), (.app "<=" [(.ivar "block.number@5"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.chainid@6" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.chainid@6")]), (.app "<=" [(.ivar "block.chainid@6"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "tx.origin@7" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "tx.origin@7")]), (.app "<=" [(.ivar "tx.origin@7"), (.num 1461501637330902918203684832716283019655932542975)])]), + .decl "tx.gasprice@8" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "tx.gasprice@8")]), (.app "<=" [(.ivar "tx.gasprice@8"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "msg.sig@9" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "msg.sig@9")]), (.app "<=" [(.ivar "msg.sig@9"), (.num 4294967295)])]), + .decl "msg.data@10" .int, + .decl "block.basefee@11" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.basefee@11")]), (.app "<=" [(.ivar "block.basefee@11"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.blobbasefee@12" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.blobbasefee@12")]), (.app "<=" [(.ivar "block.blobbasefee@12"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.coinbase@13" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.coinbase@13")]), (.app "<=" [(.ivar "block.coinbase@13"), (.num 1461501637330902918203684832716283019655932542975)])]), + .decl "block.prevrandao@14" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.prevrandao@14")]), (.app "<=" [(.ivar "block.prevrandao@14"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.difficulty@15" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.difficulty@15")]), (.app "<=" [(.ivar "block.difficulty@15"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.gaslimit@16" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.gaslimit@16")]), (.app "<=" [(.ivar "block.gaslimit@16"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "sumBalances@17" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "sumBalances@17")]), (.app "<=" [(.ivar "sumBalances@17"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "balanceOf@18" .arr, + .elem "balanceOf@18" 0 115792089237316195423570985008687907853269984665640564039457584007913129639935, + .decl "totalSupply@19" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "totalSupply@19")]), (.app "<=" [(.ivar "totalSupply@19"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "owner@20" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "owner@20")]), (.app "<=" [(.ivar "owner@20"), (.num 1461501637330902918203684832716283019655932542975)])]), + .decl "__balance@21" .arr, + .elem "__balance@21" 0 115792089237316195423570985008687907853269984665640564039457584007913129639935, + .decl "__code_epoch@22" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "__code_epoch@22")]), (.app "<=" [(.ivar "__code_epoch@22"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "to@23" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "to@23")]), (.app "<=" [(.ivar "to@23"), (.num 1461501637330902918203684832716283019655932542975)])]), + .decl "amount@24" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "amount@24")]), (.app "<=" [(.ivar "amount@24"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "g@25" .bool, + .assert (.app "=" [(.bvar "g@25"), (.app "and" [.tt, (.app "=" [(.ivar "totalSupply@19"), (.ivar "sumBalances@17")])])]), + .decl "g@26" .bool, + .assert (.app "=" [(.bvar "g@26"), (.app "and" [(.bvar "g@25"), (.app "=" [(.ivar "msg.value@3"), (.num 0)])])]), + .decl "g@27" .bool, + .assert (.app "=" [(.bvar "g@27"), (.app "and" [(.bvar "g@26"), (.app "=" [(.ivar "msg.sender@2"), (.ivar "owner@20")])])]), + .decl "arith@28" .int, + .assert (.app "=" [(.ivar "arith@28"), (.app "+" [(.ivar "totalSupply@19"), (.ivar "amount@24")])]), + .decl "g@29" .bool, + .assert (.app "=" [(.bvar "g@29"), (.app "and" [(.bvar "g@27"), (.app "and" [(.app "<=" [(.num 0), (.ivar "arith@28")]), (.app "<=" [(.ivar "arith@28"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])])])]), + .decl "sumBalances@30" .int, + .assert (.app "=" [(.ivar "sumBalances@30"), (.app "+" [(.ivar "sumBalances@17"), (.ivar "amount@24")])]), + .assert (.app "and" [(.app "<=" [(.num 0), (.app "select" [(.avar "balanceOf@18"), (.ivar "to@23")])]), (.app "<=" [(.app "select" [(.avar "balanceOf@18"), (.ivar "to@23")]), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "arith@31" .int, + .assert (.app "=" [(.ivar "arith@31"), (.app "+" [(.app "select" [(.avar "balanceOf@18"), (.ivar "to@23")]), (.ivar "amount@24")])]), + .decl "g@32" .bool, + .assert (.app "=" [(.bvar "g@32"), (.app "and" [(.bvar "g@29"), (.app "and" [(.app "<=" [(.num 0), (.ivar "arith@31")]), (.app "<=" [(.ivar "arith@31"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])])])]), + .decl "balanceOf@33" .arr, + .assert (.app "=" [(.avar "balanceOf@33"), (.app "store" [(.avar "balanceOf@18"), (.ivar "to@23"), (.ivar "arith@31")])]), + .push, + .assert (.bvar "g@32"), + .assert (.app "not" [.ff]), + .checkSat, + .pop, + .assert (.app "and" [(.app "<=" [(.num 0), (.app "select" [(.avar "balanceOf@33"), (.ivar "to@23")])]), (.app "<=" [(.app "select" [(.avar "balanceOf@33"), (.ivar "to@23")]), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .assert (.app "and" [(.app "<=" [(.num 0), (.app "select" [(.avar "balanceOf@18"), (.ivar "to@23")])]), (.app "<=" [(.app "select" [(.avar "balanceOf@18"), (.ivar "to@23")]), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .push, + .assert (.bvar "g@32"), + .assert (.app "not" [(.app "=" [(.app "select" [(.avar "balanceOf@33"), (.ivar "to@23")]), (.app "+" [(.app "select" [(.avar "balanceOf@18"), (.ivar "to@23")]), (.ivar "amount@24")])])]), + .checkSat, + .pop, + .push, + .assert (.bvar "g@32"), + .assert (.app "not" [(.app "=" [(.ivar "arith@28"), (.app "+" [(.ivar "totalSupply@19"), (.ivar "amount@24")])])]), + .checkSat, + .pop, + .push, + .assert (.bvar "g@32"), + .assert (.app "not" [(.all "a!34" (.app "=>" [(.app "and" [(.app "and" [(.app "<=" [(.num 0), (.ivar "a!34")]), (.app "<=" [(.ivar "a!34"), (.num 1461501637330902918203684832716283019655932542975)])])]), (.app "=>" [(.app "not" [(.app "=" [(.ivar "a!34"), (.ivar "to@23")])]), (.app "=" [(.app "select" [(.avar "balanceOf@33"), (.ivar "a!34")]), (.app "select" [(.avar "balanceOf@18"), (.ivar "a!34")])])])]))]), + .checkSat, + .pop, + .push, + .assert (.bvar "g@32"), + .assert (.app "not" [(.app "=" [(.ivar "arith@28"), (.ivar "sumBalances@30")])]), + .checkSat, + .pop, + .pop, + .push, + .raw "; ===== Token.transfer", + .decl "this@1" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "this@1")]), (.app "<=" [(.ivar "this@1"), (.num 1461501637330902918203684832716283019655932542975)])]), + .decl "msg.sender@2" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "msg.sender@2")]), (.app "<=" [(.ivar "msg.sender@2"), (.num 1461501637330902918203684832716283019655932542975)])]), + .assert (.app "not" [(.app "=" [(.ivar "msg.sender@2"), (.num 0)])]), + .decl "msg.value@3" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "msg.value@3")]), (.app "<=" [(.ivar "msg.value@3"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.timestamp@4" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.timestamp@4")]), (.app "<=" [(.ivar "block.timestamp@4"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.number@5" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.number@5")]), (.app "<=" [(.ivar "block.number@5"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.chainid@6" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.chainid@6")]), (.app "<=" [(.ivar "block.chainid@6"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "tx.origin@7" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "tx.origin@7")]), (.app "<=" [(.ivar "tx.origin@7"), (.num 1461501637330902918203684832716283019655932542975)])]), + .decl "tx.gasprice@8" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "tx.gasprice@8")]), (.app "<=" [(.ivar "tx.gasprice@8"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "msg.sig@9" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "msg.sig@9")]), (.app "<=" [(.ivar "msg.sig@9"), (.num 4294967295)])]), + .decl "msg.data@10" .int, + .decl "block.basefee@11" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.basefee@11")]), (.app "<=" [(.ivar "block.basefee@11"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.blobbasefee@12" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.blobbasefee@12")]), (.app "<=" [(.ivar "block.blobbasefee@12"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.coinbase@13" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.coinbase@13")]), (.app "<=" [(.ivar "block.coinbase@13"), (.num 1461501637330902918203684832716283019655932542975)])]), + .decl "block.prevrandao@14" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.prevrandao@14")]), (.app "<=" [(.ivar "block.prevrandao@14"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.difficulty@15" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.difficulty@15")]), (.app "<=" [(.ivar "block.difficulty@15"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.gaslimit@16" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.gaslimit@16")]), (.app "<=" [(.ivar "block.gaslimit@16"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "sumBalances@17" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "sumBalances@17")]), (.app "<=" [(.ivar "sumBalances@17"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "balanceOf@18" .arr, + .elem "balanceOf@18" 0 115792089237316195423570985008687907853269984665640564039457584007913129639935, + .decl "totalSupply@19" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "totalSupply@19")]), (.app "<=" [(.ivar "totalSupply@19"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "owner@20" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "owner@20")]), (.app "<=" [(.ivar "owner@20"), (.num 1461501637330902918203684832716283019655932542975)])]), + .decl "__balance@21" .arr, + .elem "__balance@21" 0 115792089237316195423570985008687907853269984665640564039457584007913129639935, + .decl "__code_epoch@22" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "__code_epoch@22")]), (.app "<=" [(.ivar "__code_epoch@22"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "to@23" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "to@23")]), (.app "<=" [(.ivar "to@23"), (.num 1461501637330902918203684832716283019655932542975)])]), + .decl "amount@24" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "amount@24")]), (.app "<=" [(.ivar "amount@24"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "g@25" .bool, + .assert (.app "=" [(.bvar "g@25"), (.app "and" [.tt, (.app "=" [(.ivar "totalSupply@19"), (.ivar "sumBalances@17")])])]), + .decl "g@26" .bool, + .assert (.app "=" [(.bvar "g@26"), (.app "and" [(.bvar "g@25"), (.app "=" [(.ivar "msg.value@3"), (.num 0)])])]), + .assert (.app "and" [(.app "<=" [(.num 0), (.app "select" [(.avar "balanceOf@18"), (.ivar "msg.sender@2")])]), (.app "<=" [(.app "select" [(.avar "balanceOf@18"), (.ivar "msg.sender@2")]), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "bal@27" .int, + .assert (.app "=" [(.ivar "bal@27"), (.app "select" [(.avar "balanceOf@18"), (.ivar "msg.sender@2")])]), + .decl "g@28" .bool, + .assert (.app "=" [(.bvar "g@28"), (.app "and" [(.bvar "g@26"), (.app ">=" [(.ivar "bal@27"), (.ivar "amount@24")])])]), + .decl "arith@29" .int, + .assert (.app "=" [(.ivar "arith@29"), (.app "-" [(.ivar "bal@27"), (.ivar "amount@24")])]), + .decl "g@30" .bool, + .assert (.app "=" [(.bvar "g@30"), (.app "and" [(.bvar "g@28"), (.app "and" [(.app "<=" [(.num 0), (.ivar "arith@29")]), (.app "<=" [(.ivar "arith@29"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])])])]), + .decl "balanceOf@31" .arr, + .assert (.app "=" [(.avar "balanceOf@31"), (.app "store" [(.avar "balanceOf@18"), (.ivar "msg.sender@2"), (.ivar "arith@29")])]), + .assert (.app "and" [(.app "<=" [(.num 0), (.app "select" [(.avar "balanceOf@31"), (.ivar "to@23")])]), (.app "<=" [(.app "select" [(.avar "balanceOf@31"), (.ivar "to@23")]), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "arith@32" .int, + .assert (.app "=" [(.ivar "arith@32"), (.app "+" [(.ivar "amount@24"), (.num 1)])]), + .decl "g@33" .bool, + .assert (.app "=" [(.bvar "g@33"), (.app "and" [(.bvar "g@30"), (.app "and" [(.app "<=" [(.num 0), (.ivar "arith@32")]), (.app "<=" [(.ivar "arith@32"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])])])]), + .decl "arith@34" .int, + .assert (.app "=" [(.ivar "arith@34"), (.app "+" [(.app "select" [(.avar "balanceOf@31"), (.ivar "to@23")]), (.ivar "arith@32")])]), + .decl "g@35" .bool, + .assert (.app "=" [(.bvar "g@35"), (.app "and" [(.bvar "g@33"), (.app "and" [(.app "<=" [(.num 0), (.ivar "arith@34")]), (.app "<=" [(.ivar "arith@34"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])])])]), + .decl "balanceOf@36" .arr, + .assert (.app "=" [(.avar "balanceOf@36"), (.app "store" [(.avar "balanceOf@31"), (.ivar "to@23"), (.ivar "arith@34")])]), + .push, + .assert (.bvar "g@35"), + .assert (.app "not" [.ff]), + .checkSat, + .pop, + .assert (.app "and" [(.app "<=" [(.num 0), (.app "select" [(.avar "balanceOf@36"), (.ivar "msg.sender@2")])]), (.app "<=" [(.app "select" [(.avar "balanceOf@36"), (.ivar "msg.sender@2")]), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .assert (.app "and" [(.app "<=" [(.num 0), (.app "select" [(.avar "balanceOf@18"), (.ivar "msg.sender@2")])]), (.app "<=" [(.app "select" [(.avar "balanceOf@18"), (.ivar "msg.sender@2")]), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .push, + .assert (.bvar "g@35"), + .assert (.app "not" [(.app "=>" [(.app "not" [(.app "=" [(.ivar "msg.sender@2"), (.ivar "to@23")])]), (.app "=" [(.app "select" [(.avar "balanceOf@36"), (.ivar "msg.sender@2")]), (.app "-" [(.app "select" [(.avar "balanceOf@18"), (.ivar "msg.sender@2")]), (.ivar "amount@24")])])])]), + .checkSat, + .pop, + .assert (.app "and" [(.app "<=" [(.num 0), (.app "select" [(.avar "balanceOf@36"), (.ivar "to@23")])]), (.app "<=" [(.app "select" [(.avar "balanceOf@36"), (.ivar "to@23")]), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .assert (.app "and" [(.app "<=" [(.num 0), (.app "select" [(.avar "balanceOf@18"), (.ivar "to@23")])]), (.app "<=" [(.app "select" [(.avar "balanceOf@18"), (.ivar "to@23")]), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .push, + .assert (.bvar "g@35"), + .assert (.app "not" [(.app "=>" [(.app "not" [(.app "=" [(.ivar "msg.sender@2"), (.ivar "to@23")])]), (.app "=" [(.app "select" [(.avar "balanceOf@36"), (.ivar "to@23")]), (.app "+" [(.app "select" [(.avar "balanceOf@18"), (.ivar "to@23")]), (.ivar "amount@24")])])])]), + .checkSat, + .pop, + .push, + .assert (.bvar "g@35"), + .assert (.app "not" [(.all "a!37" (.app "=>" [(.app "and" [(.app "and" [(.app "<=" [(.num 0), (.ivar "a!37")]), (.app "<=" [(.ivar "a!37"), (.num 1461501637330902918203684832716283019655932542975)])])]), (.app "=>" [(.app "and" [(.app "not" [(.app "=" [(.ivar "a!37"), (.ivar "msg.sender@2")])]), (.app "not" [(.app "=" [(.ivar "a!37"), (.ivar "to@23")])])]), (.app "=" [(.app "select" [(.avar "balanceOf@36"), (.ivar "a!37")]), (.app "select" [(.avar "balanceOf@18"), (.ivar "a!37")])])])]))]), + .checkSat, + .pop, + .push, + .assert (.bvar "g@35"), + .assert (.app "not" [(.app "=" [(.ivar "totalSupply@19"), (.ivar "totalSupply@19")])]), + .checkSat, + .pop, + .pop, + .push, + .raw "; ===== Token.burn", + .decl "this@1" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "this@1")]), (.app "<=" [(.ivar "this@1"), (.num 1461501637330902918203684832716283019655932542975)])]), + .decl "msg.sender@2" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "msg.sender@2")]), (.app "<=" [(.ivar "msg.sender@2"), (.num 1461501637330902918203684832716283019655932542975)])]), + .assert (.app "not" [(.app "=" [(.ivar "msg.sender@2"), (.num 0)])]), + .decl "msg.value@3" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "msg.value@3")]), (.app "<=" [(.ivar "msg.value@3"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.timestamp@4" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.timestamp@4")]), (.app "<=" [(.ivar "block.timestamp@4"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.number@5" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.number@5")]), (.app "<=" [(.ivar "block.number@5"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.chainid@6" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.chainid@6")]), (.app "<=" [(.ivar "block.chainid@6"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "tx.origin@7" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "tx.origin@7")]), (.app "<=" [(.ivar "tx.origin@7"), (.num 1461501637330902918203684832716283019655932542975)])]), + .decl "tx.gasprice@8" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "tx.gasprice@8")]), (.app "<=" [(.ivar "tx.gasprice@8"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "msg.sig@9" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "msg.sig@9")]), (.app "<=" [(.ivar "msg.sig@9"), (.num 4294967295)])]), + .decl "msg.data@10" .int, + .decl "block.basefee@11" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.basefee@11")]), (.app "<=" [(.ivar "block.basefee@11"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.blobbasefee@12" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.blobbasefee@12")]), (.app "<=" [(.ivar "block.blobbasefee@12"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.coinbase@13" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.coinbase@13")]), (.app "<=" [(.ivar "block.coinbase@13"), (.num 1461501637330902918203684832716283019655932542975)])]), + .decl "block.prevrandao@14" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.prevrandao@14")]), (.app "<=" [(.ivar "block.prevrandao@14"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.difficulty@15" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.difficulty@15")]), (.app "<=" [(.ivar "block.difficulty@15"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.gaslimit@16" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.gaslimit@16")]), (.app "<=" [(.ivar "block.gaslimit@16"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "sumBalances@17" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "sumBalances@17")]), (.app "<=" [(.ivar "sumBalances@17"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "balanceOf@18" .arr, + .elem "balanceOf@18" 0 115792089237316195423570985008687907853269984665640564039457584007913129639935, + .decl "totalSupply@19" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "totalSupply@19")]), (.app "<=" [(.ivar "totalSupply@19"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "owner@20" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "owner@20")]), (.app "<=" [(.ivar "owner@20"), (.num 1461501637330902918203684832716283019655932542975)])]), + .decl "__balance@21" .arr, + .elem "__balance@21" 0 115792089237316195423570985008687907853269984665640564039457584007913129639935, + .decl "__code_epoch@22" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "__code_epoch@22")]), (.app "<=" [(.ivar "__code_epoch@22"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "amount@23" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "amount@23")]), (.app "<=" [(.ivar "amount@23"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "g@24" .bool, + .assert (.app "=" [(.bvar "g@24"), (.app "and" [.tt, (.app "=" [(.ivar "totalSupply@19"), (.ivar "sumBalances@17")])])]), + .decl "g@25" .bool, + .assert (.app "=" [(.bvar "g@25"), (.app "and" [(.bvar "g@24"), (.app "=" [(.ivar "msg.value@3"), (.num 0)])])]), + .assert (.app "and" [(.app "<=" [(.num 0), (.app "select" [(.avar "balanceOf@18"), (.ivar "msg.sender@2")])]), (.app "<=" [(.app "select" [(.avar "balanceOf@18"), (.ivar "msg.sender@2")]), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "arith@26" .int, + .assert (.app "=" [(.ivar "arith@26"), (.app "-" [(.app "select" [(.avar "balanceOf@18"), (.ivar "msg.sender@2")]), (.ivar "amount@23")])]), + .decl "g@27" .bool, + .assert (.app "=" [(.bvar "g@27"), (.app "and" [(.bvar "g@25"), (.app "and" [(.app "<=" [(.num 0), (.ivar "arith@26")]), (.app "<=" [(.ivar "arith@26"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])])])]), + .decl "balanceOf@28" .arr, + .assert (.app "=" [(.avar "balanceOf@28"), (.app "store" [(.avar "balanceOf@18"), (.ivar "msg.sender@2"), (.ivar "arith@26")])]), + .decl "sumBalances@29" .int, + .assert (.app "=" [(.ivar "sumBalances@29"), (.app "-" [(.ivar "sumBalances@17"), (.ivar "amount@23")])]), + .decl "arith@30" .int, + .assert (.app "=" [(.ivar "arith@30"), (.app "-" [(.ivar "totalSupply@19"), (.ivar "amount@23")])]), + .decl "g@31" .bool, + .assert (.app "=" [(.bvar "g@31"), (.app "and" [(.bvar "g@27"), (.app "and" [(.app "<=" [(.num 0), (.ivar "arith@30")]), (.app "<=" [(.ivar "arith@30"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])])])]), + .push, + .assert (.bvar "g@31"), + .assert (.app "not" [.ff]), + .checkSat, + .pop, + .assert (.app "and" [(.app "<=" [(.num 0), (.app "select" [(.avar "balanceOf@28"), (.ivar "msg.sender@2")])]), (.app "<=" [(.app "select" [(.avar "balanceOf@28"), (.ivar "msg.sender@2")]), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .assert (.app "and" [(.app "<=" [(.num 0), (.app "select" [(.avar "balanceOf@18"), (.ivar "msg.sender@2")])]), (.app "<=" [(.app "select" [(.avar "balanceOf@18"), (.ivar "msg.sender@2")]), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .push, + .assert (.bvar "g@31"), + .assert (.app "not" [(.app "=" [(.app "select" [(.avar "balanceOf@28"), (.ivar "msg.sender@2")]), (.app "-" [(.app "select" [(.avar "balanceOf@18"), (.ivar "msg.sender@2")]), (.ivar "amount@23")])])]), + .checkSat, + .pop, + .push, + .assert (.bvar "g@31"), + .assert (.app "not" [(.app "=" [(.ivar "arith@30"), (.ivar "sumBalances@29")])]), + .checkSat, + .pop, + .pop +] + +/-- The transcript, as solar-verify wrote it. -/ +def transcript : String := "(push 1)\n; ===== Token.constructor\n(declare-const |this@1| Int)\n(assert (and (<= 0 |this@1|) (<= |this@1| 1461501637330902918203684832716283019655932542975)))\n(declare-const |msg.sender@2| Int)\n(assert (and (<= 0 |msg.sender@2|) (<= |msg.sender@2| 1461501637330902918203684832716283019655932542975)))\n(assert (not (= |msg.sender@2| 0)))\n(declare-const |msg.value@3| Int)\n(assert (and (<= 0 |msg.value@3|) (<= |msg.value@3| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.timestamp@4| Int)\n(assert (and (<= 0 |block.timestamp@4|) (<= |block.timestamp@4| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.number@5| Int)\n(assert (and (<= 0 |block.number@5|) (<= |block.number@5| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.chainid@6| Int)\n(assert (and (<= 0 |block.chainid@6|) (<= |block.chainid@6| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |tx.origin@7| Int)\n(assert (and (<= 0 |tx.origin@7|) (<= |tx.origin@7| 1461501637330902918203684832716283019655932542975)))\n(declare-const |tx.gasprice@8| Int)\n(assert (and (<= 0 |tx.gasprice@8|) (<= |tx.gasprice@8| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |msg.sig@9| Int)\n(assert (and (<= 0 |msg.sig@9|) (<= |msg.sig@9| 4294967295)))\n(declare-const |msg.data@10| Int)\n(declare-const |block.basefee@11| Int)\n(assert (and (<= 0 |block.basefee@11|) (<= |block.basefee@11| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.blobbasefee@12| Int)\n(assert (and (<= 0 |block.blobbasefee@12|) (<= |block.blobbasefee@12| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.coinbase@13| Int)\n(assert (and (<= 0 |block.coinbase@13|) (<= |block.coinbase@13| 1461501637330902918203684832716283019655932542975)))\n(declare-const |block.prevrandao@14| Int)\n(assert (and (<= 0 |block.prevrandao@14|) (<= |block.prevrandao@14| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.difficulty@15| Int)\n(assert (and (<= 0 |block.difficulty@15|) (<= |block.difficulty@15| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.gaslimit@16| Int)\n(assert (and (<= 0 |block.gaslimit@16|) (<= |block.gaslimit@16| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |__balance@17| (Array Int Int))\n;@elem |__balance@17| 0 115792089237316195423570985008687907853269984665640564039457584007913129639935\n(declare-const |__code_epoch@18| Int)\n(assert (and (<= 0 |__code_epoch@18|) (<= |__code_epoch@18| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |g@19| Bool)\n(assert (= |g@19| (and true (= |msg.value@3| 0))))\n(push 1)\n(assert |g@19|)\n(assert (not false))\n(check-sat)\n(pop 1)\n(push 1)\n(assert |g@19|)\n(assert (not (= |msg.sender@2| |msg.sender@2|)))\n(check-sat)\n(pop 1)\n(push 1)\n(assert |g@19|)\n(assert (not (= 0 0)))\n(check-sat)\n(pop 1)\n(pop 1)\n(push 1)\n; ===== Token.mint\n(declare-const |this@1| Int)\n(assert (and (<= 0 |this@1|) (<= |this@1| 1461501637330902918203684832716283019655932542975)))\n(declare-const |msg.sender@2| Int)\n(assert (and (<= 0 |msg.sender@2|) (<= |msg.sender@2| 1461501637330902918203684832716283019655932542975)))\n(assert (not (= |msg.sender@2| 0)))\n(declare-const |msg.value@3| Int)\n(assert (and (<= 0 |msg.value@3|) (<= |msg.value@3| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.timestamp@4| Int)\n(assert (and (<= 0 |block.timestamp@4|) (<= |block.timestamp@4| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.number@5| Int)\n(assert (and (<= 0 |block.number@5|) (<= |block.number@5| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.chainid@6| Int)\n(assert (and (<= 0 |block.chainid@6|) (<= |block.chainid@6| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |tx.origin@7| Int)\n(assert (and (<= 0 |tx.origin@7|) (<= |tx.origin@7| 1461501637330902918203684832716283019655932542975)))\n(declare-const |tx.gasprice@8| Int)\n(assert (and (<= 0 |tx.gasprice@8|) (<= |tx.gasprice@8| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |msg.sig@9| Int)\n(assert (and (<= 0 |msg.sig@9|) (<= |msg.sig@9| 4294967295)))\n(declare-const |msg.data@10| Int)\n(declare-const |block.basefee@11| Int)\n(assert (and (<= 0 |block.basefee@11|) (<= |block.basefee@11| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.blobbasefee@12| Int)\n(assert (and (<= 0 |block.blobbasefee@12|) (<= |block.blobbasefee@12| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.coinbase@13| Int)\n(assert (and (<= 0 |block.coinbase@13|) (<= |block.coinbase@13| 1461501637330902918203684832716283019655932542975)))\n(declare-const |block.prevrandao@14| Int)\n(assert (and (<= 0 |block.prevrandao@14|) (<= |block.prevrandao@14| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.difficulty@15| Int)\n(assert (and (<= 0 |block.difficulty@15|) (<= |block.difficulty@15| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.gaslimit@16| Int)\n(assert (and (<= 0 |block.gaslimit@16|) (<= |block.gaslimit@16| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |sumBalances@17| Int)\n(assert (and (<= 0 |sumBalances@17|) (<= |sumBalances@17| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |balanceOf@18| (Array Int Int))\n;@elem |balanceOf@18| 0 115792089237316195423570985008687907853269984665640564039457584007913129639935\n(declare-const |totalSupply@19| Int)\n(assert (and (<= 0 |totalSupply@19|) (<= |totalSupply@19| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |owner@20| Int)\n(assert (and (<= 0 |owner@20|) (<= |owner@20| 1461501637330902918203684832716283019655932542975)))\n(declare-const |__balance@21| (Array Int Int))\n;@elem |__balance@21| 0 115792089237316195423570985008687907853269984665640564039457584007913129639935\n(declare-const |__code_epoch@22| Int)\n(assert (and (<= 0 |__code_epoch@22|) (<= |__code_epoch@22| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |to@23| Int)\n(assert (and (<= 0 |to@23|) (<= |to@23| 1461501637330902918203684832716283019655932542975)))\n(declare-const |amount@24| Int)\n(assert (and (<= 0 |amount@24|) (<= |amount@24| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |g@25| Bool)\n(assert (= |g@25| (and true (= |totalSupply@19| |sumBalances@17|))))\n(declare-const |g@26| Bool)\n(assert (= |g@26| (and |g@25| (= |msg.value@3| 0))))\n(declare-const |g@27| Bool)\n(assert (= |g@27| (and |g@26| (= |msg.sender@2| |owner@20|))))\n(declare-const |arith@28| Int)\n(assert (= |arith@28| (+ |totalSupply@19| |amount@24|)))\n(declare-const |g@29| Bool)\n(assert (= |g@29| (and |g@27| (and (<= 0 |arith@28|) (<= |arith@28| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))))\n(declare-const |sumBalances@30| Int)\n(assert (= |sumBalances@30| (+ |sumBalances@17| |amount@24|)))\n(assert (and (<= 0 (select |balanceOf@18| |to@23|)) (<= (select |balanceOf@18| |to@23|) 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |arith@31| Int)\n(assert (= |arith@31| (+ (select |balanceOf@18| |to@23|) |amount@24|)))\n(declare-const |g@32| Bool)\n(assert (= |g@32| (and |g@29| (and (<= 0 |arith@31|) (<= |arith@31| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))))\n(declare-const |balanceOf@33| (Array Int Int))\n(assert (= |balanceOf@33| (store |balanceOf@18| |to@23| |arith@31|)))\n(push 1)\n(assert |g@32|)\n(assert (not false))\n(check-sat)\n(pop 1)\n(assert (and (<= 0 (select |balanceOf@33| |to@23|)) (<= (select |balanceOf@33| |to@23|) 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(assert (and (<= 0 (select |balanceOf@18| |to@23|)) (<= (select |balanceOf@18| |to@23|) 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(push 1)\n(assert |g@32|)\n(assert (not (= (select |balanceOf@33| |to@23|) (+ (select |balanceOf@18| |to@23|) |amount@24|))))\n(check-sat)\n(pop 1)\n(push 1)\n(assert |g@32|)\n(assert (not (= |arith@28| (+ |totalSupply@19| |amount@24|))))\n(check-sat)\n(pop 1)\n(push 1)\n(assert |g@32|)\n(assert (not (forall ((|a!34| Int)) (=> (and (and (<= 0 |a!34|) (<= |a!34| 1461501637330902918203684832716283019655932542975))) (=> (not (= |a!34| |to@23|)) (= (select |balanceOf@33| |a!34|) (select |balanceOf@18| |a!34|)))))))\n(check-sat)\n(pop 1)\n(push 1)\n(assert |g@32|)\n(assert (not (= |arith@28| |sumBalances@30|)))\n(check-sat)\n(pop 1)\n(pop 1)\n(push 1)\n; ===== Token.transfer\n(declare-const |this@1| Int)\n(assert (and (<= 0 |this@1|) (<= |this@1| 1461501637330902918203684832716283019655932542975)))\n(declare-const |msg.sender@2| Int)\n(assert (and (<= 0 |msg.sender@2|) (<= |msg.sender@2| 1461501637330902918203684832716283019655932542975)))\n(assert (not (= |msg.sender@2| 0)))\n(declare-const |msg.value@3| Int)\n(assert (and (<= 0 |msg.value@3|) (<= |msg.value@3| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.timestamp@4| Int)\n(assert (and (<= 0 |block.timestamp@4|) (<= |block.timestamp@4| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.number@5| Int)\n(assert (and (<= 0 |block.number@5|) (<= |block.number@5| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.chainid@6| Int)\n(assert (and (<= 0 |block.chainid@6|) (<= |block.chainid@6| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |tx.origin@7| Int)\n(assert (and (<= 0 |tx.origin@7|) (<= |tx.origin@7| 1461501637330902918203684832716283019655932542975)))\n(declare-const |tx.gasprice@8| Int)\n(assert (and (<= 0 |tx.gasprice@8|) (<= |tx.gasprice@8| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |msg.sig@9| Int)\n(assert (and (<= 0 |msg.sig@9|) (<= |msg.sig@9| 4294967295)))\n(declare-const |msg.data@10| Int)\n(declare-const |block.basefee@11| Int)\n(assert (and (<= 0 |block.basefee@11|) (<= |block.basefee@11| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.blobbasefee@12| Int)\n(assert (and (<= 0 |block.blobbasefee@12|) (<= |block.blobbasefee@12| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.coinbase@13| Int)\n(assert (and (<= 0 |block.coinbase@13|) (<= |block.coinbase@13| 1461501637330902918203684832716283019655932542975)))\n(declare-const |block.prevrandao@14| Int)\n(assert (and (<= 0 |block.prevrandao@14|) (<= |block.prevrandao@14| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.difficulty@15| Int)\n(assert (and (<= 0 |block.difficulty@15|) (<= |block.difficulty@15| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.gaslimit@16| Int)\n(assert (and (<= 0 |block.gaslimit@16|) (<= |block.gaslimit@16| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |sumBalances@17| Int)\n(assert (and (<= 0 |sumBalances@17|) (<= |sumBalances@17| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |balanceOf@18| (Array Int Int))\n;@elem |balanceOf@18| 0 115792089237316195423570985008687907853269984665640564039457584007913129639935\n(declare-const |totalSupply@19| Int)\n(assert (and (<= 0 |totalSupply@19|) (<= |totalSupply@19| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |owner@20| Int)\n(assert (and (<= 0 |owner@20|) (<= |owner@20| 1461501637330902918203684832716283019655932542975)))\n(declare-const |__balance@21| (Array Int Int))\n;@elem |__balance@21| 0 115792089237316195423570985008687907853269984665640564039457584007913129639935\n(declare-const |__code_epoch@22| Int)\n(assert (and (<= 0 |__code_epoch@22|) (<= |__code_epoch@22| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |to@23| Int)\n(assert (and (<= 0 |to@23|) (<= |to@23| 1461501637330902918203684832716283019655932542975)))\n(declare-const |amount@24| Int)\n(assert (and (<= 0 |amount@24|) (<= |amount@24| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |g@25| Bool)\n(assert (= |g@25| (and true (= |totalSupply@19| |sumBalances@17|))))\n(declare-const |g@26| Bool)\n(assert (= |g@26| (and |g@25| (= |msg.value@3| 0))))\n(assert (and (<= 0 (select |balanceOf@18| |msg.sender@2|)) (<= (select |balanceOf@18| |msg.sender@2|) 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |bal@27| Int)\n(assert (= |bal@27| (select |balanceOf@18| |msg.sender@2|)))\n(declare-const |g@28| Bool)\n(assert (= |g@28| (and |g@26| (>= |bal@27| |amount@24|))))\n(declare-const |arith@29| Int)\n(assert (= |arith@29| (- |bal@27| |amount@24|)))\n(declare-const |g@30| Bool)\n(assert (= |g@30| (and |g@28| (and (<= 0 |arith@29|) (<= |arith@29| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))))\n(declare-const |balanceOf@31| (Array Int Int))\n(assert (= |balanceOf@31| (store |balanceOf@18| |msg.sender@2| |arith@29|)))\n(assert (and (<= 0 (select |balanceOf@31| |to@23|)) (<= (select |balanceOf@31| |to@23|) 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |arith@32| Int)\n(assert (= |arith@32| (+ |amount@24| 1)))\n(declare-const |g@33| Bool)\n(assert (= |g@33| (and |g@30| (and (<= 0 |arith@32|) (<= |arith@32| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))))\n(declare-const |arith@34| Int)\n(assert (= |arith@34| (+ (select |balanceOf@31| |to@23|) |arith@32|)))\n(declare-const |g@35| Bool)\n(assert (= |g@35| (and |g@33| (and (<= 0 |arith@34|) (<= |arith@34| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))))\n(declare-const |balanceOf@36| (Array Int Int))\n(assert (= |balanceOf@36| (store |balanceOf@31| |to@23| |arith@34|)))\n(push 1)\n(assert |g@35|)\n(assert (not false))\n(check-sat)\n(pop 1)\n(assert (and (<= 0 (select |balanceOf@36| |msg.sender@2|)) (<= (select |balanceOf@36| |msg.sender@2|) 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(assert (and (<= 0 (select |balanceOf@18| |msg.sender@2|)) (<= (select |balanceOf@18| |msg.sender@2|) 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(push 1)\n(assert |g@35|)\n(assert (not (=> (not (= |msg.sender@2| |to@23|)) (= (select |balanceOf@36| |msg.sender@2|) (- (select |balanceOf@18| |msg.sender@2|) |amount@24|)))))\n(check-sat)\n(pop 1)\n(assert (and (<= 0 (select |balanceOf@36| |to@23|)) (<= (select |balanceOf@36| |to@23|) 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(assert (and (<= 0 (select |balanceOf@18| |to@23|)) (<= (select |balanceOf@18| |to@23|) 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(push 1)\n(assert |g@35|)\n(assert (not (=> (not (= |msg.sender@2| |to@23|)) (= (select |balanceOf@36| |to@23|) (+ (select |balanceOf@18| |to@23|) |amount@24|)))))\n(check-sat)\n(pop 1)\n(push 1)\n(assert |g@35|)\n(assert (not (forall ((|a!37| Int)) (=> (and (and (<= 0 |a!37|) (<= |a!37| 1461501637330902918203684832716283019655932542975))) (=> (and (not (= |a!37| |msg.sender@2|)) (not (= |a!37| |to@23|))) (= (select |balanceOf@36| |a!37|) (select |balanceOf@18| |a!37|)))))))\n(check-sat)\n(pop 1)\n(push 1)\n(assert |g@35|)\n(assert (not (= |totalSupply@19| |totalSupply@19|)))\n(check-sat)\n(pop 1)\n(pop 1)\n(push 1)\n; ===== Token.burn\n(declare-const |this@1| Int)\n(assert (and (<= 0 |this@1|) (<= |this@1| 1461501637330902918203684832716283019655932542975)))\n(declare-const |msg.sender@2| Int)\n(assert (and (<= 0 |msg.sender@2|) (<= |msg.sender@2| 1461501637330902918203684832716283019655932542975)))\n(assert (not (= |msg.sender@2| 0)))\n(declare-const |msg.value@3| Int)\n(assert (and (<= 0 |msg.value@3|) (<= |msg.value@3| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.timestamp@4| Int)\n(assert (and (<= 0 |block.timestamp@4|) (<= |block.timestamp@4| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.number@5| Int)\n(assert (and (<= 0 |block.number@5|) (<= |block.number@5| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.chainid@6| Int)\n(assert (and (<= 0 |block.chainid@6|) (<= |block.chainid@6| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |tx.origin@7| Int)\n(assert (and (<= 0 |tx.origin@7|) (<= |tx.origin@7| 1461501637330902918203684832716283019655932542975)))\n(declare-const |tx.gasprice@8| Int)\n(assert (and (<= 0 |tx.gasprice@8|) (<= |tx.gasprice@8| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |msg.sig@9| Int)\n(assert (and (<= 0 |msg.sig@9|) (<= |msg.sig@9| 4294967295)))\n(declare-const |msg.data@10| Int)\n(declare-const |block.basefee@11| Int)\n(assert (and (<= 0 |block.basefee@11|) (<= |block.basefee@11| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.blobbasefee@12| Int)\n(assert (and (<= 0 |block.blobbasefee@12|) (<= |block.blobbasefee@12| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.coinbase@13| Int)\n(assert (and (<= 0 |block.coinbase@13|) (<= |block.coinbase@13| 1461501637330902918203684832716283019655932542975)))\n(declare-const |block.prevrandao@14| Int)\n(assert (and (<= 0 |block.prevrandao@14|) (<= |block.prevrandao@14| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.difficulty@15| Int)\n(assert (and (<= 0 |block.difficulty@15|) (<= |block.difficulty@15| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.gaslimit@16| Int)\n(assert (and (<= 0 |block.gaslimit@16|) (<= |block.gaslimit@16| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |sumBalances@17| Int)\n(assert (and (<= 0 |sumBalances@17|) (<= |sumBalances@17| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |balanceOf@18| (Array Int Int))\n;@elem |balanceOf@18| 0 115792089237316195423570985008687907853269984665640564039457584007913129639935\n(declare-const |totalSupply@19| Int)\n(assert (and (<= 0 |totalSupply@19|) (<= |totalSupply@19| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |owner@20| Int)\n(assert (and (<= 0 |owner@20|) (<= |owner@20| 1461501637330902918203684832716283019655932542975)))\n(declare-const |__balance@21| (Array Int Int))\n;@elem |__balance@21| 0 115792089237316195423570985008687907853269984665640564039457584007913129639935\n(declare-const |__code_epoch@22| Int)\n(assert (and (<= 0 |__code_epoch@22|) (<= |__code_epoch@22| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |amount@23| Int)\n(assert (and (<= 0 |amount@23|) (<= |amount@23| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |g@24| Bool)\n(assert (= |g@24| (and true (= |totalSupply@19| |sumBalances@17|))))\n(declare-const |g@25| Bool)\n(assert (= |g@25| (and |g@24| (= |msg.value@3| 0))))\n(assert (and (<= 0 (select |balanceOf@18| |msg.sender@2|)) (<= (select |balanceOf@18| |msg.sender@2|) 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |arith@26| Int)\n(assert (= |arith@26| (- (select |balanceOf@18| |msg.sender@2|) |amount@23|)))\n(declare-const |g@27| Bool)\n(assert (= |g@27| (and |g@25| (and (<= 0 |arith@26|) (<= |arith@26| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))))\n(declare-const |balanceOf@28| (Array Int Int))\n(assert (= |balanceOf@28| (store |balanceOf@18| |msg.sender@2| |arith@26|)))\n(declare-const |sumBalances@29| Int)\n(assert (= |sumBalances@29| (- |sumBalances@17| |amount@23|)))\n(declare-const |arith@30| Int)\n(assert (= |arith@30| (- |totalSupply@19| |amount@23|)))\n(declare-const |g@31| Bool)\n(assert (= |g@31| (and |g@27| (and (<= 0 |arith@30|) (<= |arith@30| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))))\n(push 1)\n(assert |g@31|)\n(assert (not false))\n(check-sat)\n(pop 1)\n(assert (and (<= 0 (select |balanceOf@28| |msg.sender@2|)) (<= (select |balanceOf@28| |msg.sender@2|) 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(assert (and (<= 0 (select |balanceOf@18| |msg.sender@2|)) (<= (select |balanceOf@18| |msg.sender@2|) 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(push 1)\n(assert |g@31|)\n(assert (not (= (select |balanceOf@28| |msg.sender@2|) (- (select |balanceOf@18| |msg.sender@2|) |amount@23|))))\n(check-sat)\n(pop 1)\n(push 1)\n(assert |g@31|)\n(assert (not (= |arith@30| |sumBalances@29|)))\n(check-sat)\n(pop 1)\n(pop 1)\n" + +end SolidCore.Verify.VC.Export.Mutant.TokenSrcMut diff --git a/Contracts/Token/VC/Mutants.lean b/Contracts/Token/VC/Mutants.lean new file mode 100644 index 00000000..f14d8c44 --- /dev/null +++ b/Contracts/Token/VC/Mutants.lean @@ -0,0 +1,43 @@ +import Contracts.Token.VC.Transfer +import Contracts.Token.VC.Mutant.SrcMut +import Contracts.Token.VC.Mutant.SpecMut + +/-! +# Mutants that break `transfer`'s binding + +Two copies of `scripts/verify/Token.sol`, each changed in one line, exported by the same +solar-verify (`scripts/verify/mutant/MANIFEST`): +* `TokenSrcMut` changes the source: `transfer` credits `amount + 1`. solar-verify's encoding of the + call's effect changes with it, so none of its obligations is the Lean obligation of + `transfer`'s clauses, which `trStore_eval` ties to what SolidCore does with the real source. +* `TokenSpecMut` changes the spec: the recipient's clause claims `old + amount + 1`. Its obligation + for that clause is not the one SolidCore's run supports. + +In both, `checkScript` rejects, so no verdict on a mutant yields `transfer_triple`'s clauses. +-/ + +namespace SolidCore.Verify.VC.Token + +open SolidCore.Verify.VC + +theorem srcMut_rejects_to : checkScript Export.Mutant.TokenSrcMut.script [(trHyps, trGoalTo)] = false := by + decide +kernel + +theorem srcMut_rejects_from : + checkScript Export.Mutant.TokenSrcMut.script [(trHyps, trGoalFrom)] = false := by + decide +kernel + +theorem srcMut_rejects_frame : + checkScript Export.Mutant.TokenSrcMut.script [(trHyps, trGoalFrame)] = false := by + decide +kernel + +theorem specMut_rejects_to : + checkScript Export.Mutant.TokenSpecMut.script [(trHyps, trGoalTo)] = false := by + decide +kernel + +/-- The unchanged clauses of the spec mutant still check: the rejection is the changed clause's. -/ +theorem specMut_keeps_from_frame : + checkScript Export.Mutant.TokenSpecMut.script [(trHyps, trGoalFrom), (trHyps, trGoalFrame)] = true := by + decide +kernel + +end SolidCore.Verify.VC.Token diff --git a/Contracts/Token/VC/Source.lean b/Contracts/Token/VC/Source.lean new file mode 100644 index 00000000..8e004dda --- /dev/null +++ b/Contracts/Token/VC/Source.lean @@ -0,0 +1,101 @@ +-- Generated from scripts/verify/Token.sol (solar-verify's crates/verify/examples/Token.sol) with solc 0.8.35 by scripts/solc_ast_to_lean_source.py. Do not edit. + +import SolidCore.Solidity.Checked + +open SolidCore.Solidity + +namespace SolidCore +namespace Verify +namespace VC +namespace Source +namespace Token + +def importedSourceName : String := "scripts/verify/Token.sol" + +def importedContractDecl0 : ContractDecl := +{ kind := ContractKind.contract + name := "Token" + abstract := false + bases := [] + items := [(ContractItem.stateVar + { name := "balanceOf", + ty := Ty.mapping (Ty.address false) (Ty.uint 256), + visibility := some Visibility.public_, + mutability := VarMutability.mutable, + override? := none, + init := none }), (ContractItem.stateVar + { name := "totalSupply", + ty := Ty.uint 256, + visibility := some Visibility.public_, + mutability := VarMutability.mutable, + override? := none, + init := none }), (ContractItem.stateVar + { name := "owner", + ty := Ty.address false, + visibility := some Visibility.public_, + mutability := VarMutability.mutable, + override? := none, + init := none }), ContractItem.modifierDecl + { name := "onlyOwner" + params := [] + virtual := false + override? := none + body := some (Stmt.block [Stmt.expr (Expr.call (Expr.ident "require") [Arg.positional (Expr.binary BinaryOp.eq (Expr.member (Expr.ident "msg") "sender") (Expr.ident "owner")), Arg.positional (Expr.literal (Literal.string "not owner"))]), Stmt.modifierPlaceholder]) }, (ContractItem.function + { kind := FunctionKind.constructor, + name := none, + visibility := some Visibility.public_, + mutability := StateMutability.nonpayable, + params := [], + returns := [], + virtual := false, + override? := none, + modifiers := [], + body := some (Stmt.block [Stmt.expr (Expr.assign (Expr.ident "owner") AssignOp.assign (Expr.member (Expr.ident "msg") "sender"))]) }), (ContractItem.function + { kind := FunctionKind.function, + name := some "mint", + visibility := some Visibility.external_, + mutability := StateMutability.nonpayable, + params := [{ name := some "to", ty := Ty.address false, location := none }, { name := some "amount", ty := Ty.uint 256, location := none }], + returns := [], + virtual := false, + override? := none, + modifiers := [{ target := { segments := ["onlyOwner"] }, args := [], hasArgList := false }], + body := some (Stmt.block [Stmt.expr (Expr.assign (Expr.ident "totalSupply") AssignOp.addAssign (Expr.ident "amount")), Stmt.expr (Expr.assign (Expr.index (Expr.ident "balanceOf") (Expr.ident "to")) AssignOp.addAssign (Expr.ident "amount"))]) }), (ContractItem.function + { kind := FunctionKind.function, + name := some "transfer", + visibility := some Visibility.external_, + mutability := StateMutability.nonpayable, + params := [{ name := some "to", ty := Ty.address false, location := none }, { name := some "amount", ty := Ty.uint 256, location := none }], + returns := [{ name := none, ty := Ty.bool, location := none }], + virtual := false, + override? := none, + modifiers := [], + body := some (Stmt.block [Stmt.varDecl [{ name := some "bal", ty := Ty.uint 256, location := none }] (some (Expr.index (Expr.ident "balanceOf") (Expr.member (Expr.ident "msg") "sender"))), Stmt.expr (Expr.call (Expr.ident "require") [Arg.positional (Expr.binary BinaryOp.ge (Expr.ident "bal") (Expr.ident "amount")), Arg.positional (Expr.literal (Literal.string "insufficient"))]), Stmt.expr (Expr.assign (Expr.index (Expr.ident "balanceOf") (Expr.member (Expr.ident "msg") "sender")) AssignOp.assign (Expr.binary BinaryOp.sub (Expr.ident "bal") (Expr.ident "amount"))), Stmt.expr (Expr.assign (Expr.index (Expr.ident "balanceOf") (Expr.ident "to")) AssignOp.addAssign (Expr.ident "amount")), Stmt.returnValues (some (Expr.literal (Literal.bool true)))]) }), (ContractItem.function + { kind := FunctionKind.function, + name := some "burn", + visibility := some Visibility.external_, + mutability := StateMutability.nonpayable, + params := [{ name := some "amount", ty := Ty.uint 256, location := none }], + returns := [], + virtual := false, + override? := none, + modifiers := [], + body := some (Stmt.block [Stmt.expr (Expr.assign (Expr.index (Expr.ident "balanceOf") (Expr.member (Expr.ident "msg") "sender")) AssignOp.subAssign (Expr.ident "amount")), Stmt.expr (Expr.assign (Expr.ident "totalSupply") AssignOp.subAssign (Expr.ident "amount"))]) })] } + +def importedContract : ContractDecl := + importedContractDecl0 + +def importedContracts : List ContractDecl := + [importedContractDecl0] + +def importedSourceUnit : SourceUnit := + { items := [SourceItem.pragma "solidity" "^0.8.20", SourceItem.contract importedContractDecl0] } + +def importedContractAccepted : Bool := + TypeCheck.Result.isOk (TypeCheck.TypecheckedInput.checkedSourceUnit importedSourceUnit) + +end Token +end Source +end VC +end Verify +end SolidCore diff --git a/Contracts/Token/VC/Transfer.lean b/Contracts/Token/VC/Transfer.lean new file mode 100644 index 00000000..0747fa80 --- /dev/null +++ b/Contracts/Token/VC/Transfer.lean @@ -0,0 +1,683 @@ +import Contracts.Token.VC.Burn + +/-! +# solar-verify's `Token.transfer`, bound to SolidCore + +`transfer`'s three ensures clauses on distinct addresses (the sender's and the recipient's new +balances, and every other balance unchanged) as a `Triple` against SolidCore's `Source.run`, proved +from solar-verify's own obligations: `transfer_triple` takes the verdict `Valid Export.Token.script`, +and its proof reads each clause off the obligation `checkScript_sound` gives, at the assignment +`trEnv` that a call binds. Nothing in the proof re-derives a clause in Lean: the bridge is the +binding lemma `trStore_eval`, which says that SolidCore's storage after the call, read through +`balanceOf`'s layout (`balanceOf[k]` at slot `keccak(k, 0)`), is solar-verify's array term `S2` at +`trEnv`, for every address. + +The binding is explicit: +* widths: `amount` is the call's second word, below `2 ^ 256`; `to` its first, which the erased tree + reverts on above `2 ^ 160 - 1` (any word is in scope, dirty ones included); +* environment: `msg.sender` is the stage's caller `callerWord`, `msg.value` is 0 (the stage's scope); +* storage: `totalSupply` is slot 1, `balanceOf` is the array `k ↦ storage (keccak(k, 0))`; +* ghost: `sumBalances` is not program state, so the assignment sets it to `totalSupply`, which is + what solar-verify's assumed invariant asks; the clauses proved here do not mention it; +* Keccak: `HashInj`, injectivity of the mapping slot on address keys, is a hypothesis of the + theorem, never an axiom. It is what makes `to`, the sender and every third address name distinct + slots. +-/ + +namespace SolidCore.Verify.VC.Token + +open SolidCore.Verify SolidCore.Verify.VC SolidCore.Refinement SolidCore.Refinement.Abi +open SolidCore.Refinement.Generic + +/-- `transfer` as the stage's ABI sees it: two words, any value below `2 ^ 256`. -/ +def fnTransfer : Fn := ⟨transferSel, [.uint 256, .uint 256]⟩ + +/-- The erasure of `transfer`, as the generic source stage computes it. -/ +def transferTree : Tree := + (Tree.ite + (WExpr.bin + (BinOp.gt) + (WExpr.arg 0) + (WExpr.lit 1461501637330902918203684832716283019655932542975)) + (Tree.halt false [] [] []) + (Tree.ite + (WExpr.un + (UnOp.iszero) + (WExpr.bin + (BinOp.lt) + (WExpr.sinit + (WExpr.hash + (WExpr.lit 8192) + (WExpr.lit 0))) + (WExpr.arg 1))) + (Tree.ite + (WExpr.bin + (BinOp.lt) + (WExpr.sinit + (WExpr.hash + (WExpr.lit 8192) + (WExpr.lit 0))) + (WExpr.arg 1)) + (Tree.halt + false + [OByte.lit 78, + OByte.lit 72, + OByte.lit 123, + OByte.lit 113, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0, + OByte.lit 17] + [] + []) + (Tree.ite + (WExpr.bin + (BinOp.lt) + (WExpr.bin + (BinOp.add) + (WExpr.sel + (WExpr.bin + (BinOp.eq) + (WExpr.hash + (WExpr.arg 0) + (WExpr.lit 0)) + (WExpr.hash + (WExpr.lit 8192) + (WExpr.lit 0))) + (WExpr.bin + (BinOp.sub) + (WExpr.sinit + (WExpr.hash + (WExpr.lit 8192) + (WExpr.lit 0))) + (WExpr.arg 1)) + (WExpr.sinit + (WExpr.hash + (WExpr.arg 0) + (WExpr.lit 0)))) + (WExpr.arg 1)) + (WExpr.sel + (WExpr.bin + (BinOp.eq) + (WExpr.hash + (WExpr.arg 0) + (WExpr.lit 0)) + (WExpr.hash + (WExpr.lit 8192) + (WExpr.lit 0))) + (WExpr.bin + (BinOp.sub) + (WExpr.sinit + (WExpr.hash + (WExpr.lit 8192) + (WExpr.lit 0))) + (WExpr.arg 1)) + (WExpr.sinit + (WExpr.hash + (WExpr.arg 0) + (WExpr.lit 0))))) + (Tree.halt + false + [OByte.lit 78, + OByte.lit 72, + OByte.lit 123, + OByte.lit 113, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0, + OByte.lit 17] + [] + []) + (Tree.halt + true + [OByte.byteOf (WExpr.lit 1) 0, + OByte.byteOf (WExpr.lit 1) 1, + OByte.byteOf (WExpr.lit 1) 2, + OByte.byteOf (WExpr.lit 1) 3, + OByte.byteOf (WExpr.lit 1) 4, + OByte.byteOf (WExpr.lit 1) 5, + OByte.byteOf (WExpr.lit 1) 6, + OByte.byteOf (WExpr.lit 1) 7, + OByte.byteOf (WExpr.lit 1) 8, + OByte.byteOf (WExpr.lit 1) 9, + OByte.byteOf (WExpr.lit 1) 10, + OByte.byteOf (WExpr.lit 1) 11, + OByte.byteOf (WExpr.lit 1) 12, + OByte.byteOf (WExpr.lit 1) 13, + OByte.byteOf (WExpr.lit 1) 14, + OByte.byteOf (WExpr.lit 1) 15, + OByte.byteOf (WExpr.lit 1) 16, + OByte.byteOf (WExpr.lit 1) 17, + OByte.byteOf (WExpr.lit 1) 18, + OByte.byteOf (WExpr.lit 1) 19, + OByte.byteOf (WExpr.lit 1) 20, + OByte.byteOf (WExpr.lit 1) 21, + OByte.byteOf (WExpr.lit 1) 22, + OByte.byteOf (WExpr.lit 1) 23, + OByte.byteOf (WExpr.lit 1) 24, + OByte.byteOf (WExpr.lit 1) 25, + OByte.byteOf (WExpr.lit 1) 26, + OByte.byteOf (WExpr.lit 1) 27, + OByte.byteOf (WExpr.lit 1) 28, + OByte.byteOf (WExpr.lit 1) 29, + OByte.byteOf (WExpr.lit 1) 30, + OByte.byteOf (WExpr.lit 1) 31] + [(WExpr.hash + (WExpr.arg 0) + (WExpr.lit 0), + WExpr.bin + (BinOp.add) + (WExpr.sel + (WExpr.bin + (BinOp.eq) + (WExpr.hash + (WExpr.arg 0) + (WExpr.lit 0)) + (WExpr.hash + (WExpr.lit 8192) + (WExpr.lit 0))) + (WExpr.bin + (BinOp.sub) + (WExpr.sinit + (WExpr.hash + (WExpr.lit 8192) + (WExpr.lit 0))) + (WExpr.arg 1)) + (WExpr.sinit + (WExpr.hash + (WExpr.arg 0) + (WExpr.lit 0)))) + (WExpr.arg 1)), + (WExpr.hash + (WExpr.lit 8192) + (WExpr.lit 0), + WExpr.bin + (BinOp.sub) + (WExpr.sinit + (WExpr.hash + (WExpr.lit 8192) + (WExpr.lit 0))) + (WExpr.arg 1))] + []))) + (Tree.halt + false + [OByte.lit 8, + OByte.lit 195, + OByte.lit 121, + OByte.lit 160, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0, + OByte.lit 32, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0, + OByte.lit 12, + OByte.lit 105, + OByte.lit 110, + OByte.lit 115, + OByte.lit 117, + OByte.lit 102, + OByte.lit 102, + OByte.lit 105, + OByte.lit 99, + OByte.lit 105, + OByte.lit 101, + OByte.lit 110, + OByte.lit 116, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0] + [] + []))) + +/-- How SolidCore dispatches `transfer` and the generic source stage erases it. -/ +def transferShape? : Option (Option (Nat × Option Tree)) := + match contract? with + | .ok c => some ((c.core.findFunctionBySelector? transferSel).map fun f => + (f.params.length, eraseFn (envOf c.core) fuel f)) + | .error _ => none + +kernel_rfl transferShape_eq transferShape? (some (some (2, some transferTree))) using selector_eq mkIdx_eq + +/-! ## The Lean obligations -/ + +namespace Ob + +def rcpt : Tm := .ivar "to" +def add (a b : Tm) : Tm := .app "+" [a, b] +def leA (t : Tm) : Tm := .app "<=" [t, .num (2 ^ 160 - 1)] +def sel (a i : Tm) : Tm := .app "select" [a, i] +def sto (a i v : Tm) : Tm := .app "store" [a, i, v] +def B : Tm := .avar "balanceOf" +/-- The balances after the sender's debit. -/ +def S1 : Tm := sto B ms (sub bal amt) +/-- `balanceOf` after the call, as solar-verify encodes it. -/ +def S2 : Tm := sto S1 rcpt (add (sel S1 rcpt) amt) + +end Ob + +open Ob in +/-- The facts every successful `transfer` meets at `trEnv`. -/ +def trHyps : List Tm := + [eq ts sum, eq mv (.num 0), .app ">=" [bal, amt], le0 (sub bal amt), leW (sub bal amt), + le0 (add (sel S1 rcpt) amt), leW (add (sel S1 rcpt) amt), arrFact "k" "balanceOf" (2 ^ 256 - 1), + le0 amt, leW amt, le0 rcpt, leA rcpt, le0 ts, leW ts, le0 sum, leW sum, le0 mv, leW mv, + .app "not" [eq ms (.num 0)], le0 ms, .app "<=" [ms, .num (2 ^ 160 - 1)]] + +open Ob in +/-- The sender's clause: `msg.sender != to ==> balanceOf[msg.sender] == old(…) - amount`. -/ +def trGoalFrom : Tm := .app "=>" [.app "not" [eq ms rcpt], eq (sel S2 ms) (sub bal amt)] + +open Ob in +/-- The recipient's clause: `msg.sender != to ==> balanceOf[rcpt] == old(balanceOf[rcpt]) + amount`. -/ +def trGoalTo : Tm := .app "=>" [.app "not" [eq ms rcpt], eq (sel S2 rcpt) (add (sel B rcpt) amt)] + +open Ob in +/-- The frame: every other address keeps its balance. -/ +def trGoalFrame : Tm := + .all "a" (.app "=>" [.app "and" [.app "and" [le0 (.ivar "a"), leA (.ivar "a")]], + .app "=>" [.app "and" [.app "not" [eq (.ivar "a") ms], .app "not" [eq (.ivar "a") rcpt]], + eq (sel S2 (.ivar "a")) (sel B (.ivar "a"))]]) + +/-- The Lean obligations of `transfer`'s clauses. -/ +def trObs : List (List Tm × Tm) := [(trHyps, trGoalFrom), (trHyps, trGoalTo), (trHyps, trGoalFrame)] + +/-- solar-verify's script for `Token` has obligations that `checkOb` normalizes to each of them. -/ +theorem transfer_check : checkScript Export.Token.script trObs = true := by + decide +kernel + + +/-! ## The binding -/ + +/-- Injectivity of `balanceOf`'s slot on address keys: distinct addresses name distinct slots. A +hypothesis on Keccak-256, stated where it is used, never assumed. -/ +def HashInj : Prop := ∀ x y, x < 2 ^ 160 → y < 2 ^ 160 → solHash x 0 = solHash y 0 → x = y + +/-- `balanceOf` as an array, through its storage layout. -/ +def balArr (s : Storage) : Int → Int := fun k => s (solHash k.toNat 0) + +/-- The assignment of solar-verify's names that a call of `transfer` binds: `to = t`, `amount = a`, +`msg.sender` the stage's caller, `totalSupply` slot 1, `balanceOf` its layout in the storage `s`, +the ghost `sumBalances` set to `totalSupply`, and every other name 0. -/ +def trEnv (t a : Nat) (s : Storage) : Env := + ⟨fun x => if x = "amount" then a else if x = "to" then t else if x = "msg.sender" then callerWord + else if x = "totalSupply" then s 1 else if x = "sumBalances" then s 1 else 0, + fun _ => False, + fun x => if x = "balanceOf" then balArr s else fun _ => 0⟩ + +/-- The recipient's balance after the debit: the sender's own when they are one address. -/ +def midTo (t a : Nat) (s : Storage) : Nat := if t = callerWord then s senderSlot - a else s (solHash t 0) + +theorem S2_eval (t a : Nat) (s : Storage) (j : Int) : + (Ob.S2.eval (trEnv t a s)).toArr j = + if j = t then (if t = callerWord then balArr s callerWord - a else balArr s t) + a + else if j = callerWord then balArr s callerWord - a else balArr s j := by + simp [Ob.S2, Ob.S1, Ob.sto, Ob.sel, Ob.add, Ob.B, Ob.rcpt, Ob.sub, Ob.bal, Ob.amt, Ob.ms, + Tm.eval, Tm.evalList, applyOp, Value.toArr, Value.toInt, trEnv, callerWord] + by_cases h1 : j = t <;> by_cases h2 : t = 8192 <;> by_cases h3 : j = 8192 <;> + simp [h1, h2, h3] <;> omega + +theorem hashT (t : Nat) : solHash t 0 % 2 ^ 256 = solHash t 0 := Nat.mod_eq_of_lt (solHash_lt t 0) + +/-- What a successful run of QtransferQ's erased tree shows: QtoQ is an address, the sender had +the amount, the recipient's credit does not overflow, and the storage changes in exactly the +recipient's and the sender's slots. QHashInjQ decides the tree's test of whether they are one. -/ +theorem tr_success (inj : HashInj) (s : Storage) (hs : ∀ k, s k < 2 ^ 256) (t a : Nat) + (ht : t < 2 ^ 256) (ha : a < 2 ^ 256) : + let R := transferTree.eval (valOf [t, a] s) + R.success = true → t < 2 ^ 160 ∧ a ≤ s senderSlot ∧ midTo t a s + a < 2 ^ 256 ∧ + ∀ n < 2 ^ 256, R.store n = if n = solHash t 0 then midTo t a s + a + else if n = senderSlot then s senderSlot - a else s n := by + intro R hR + have hsm : ∀ k, s k % 2 ^ 256 = s k := fun k => Nat.mod_eq_of_lt (hs k) + have ham : a % 2 ^ 256 = a := Nat.mod_eq_of_lt ha + have htm : t % 2 ^ 256 = t := Nat.mod_eq_of_lt ht + have hss : senderSlot % 2 ^ 256 = senderSlot := by decide + have h8 : 8192 % 2 ^ 256 = 8192 := by decide + have h0 : 0 % 2 ^ 256 = 0 := by decide + have hA : 1461501637330902918203684832716283019655932542975 % 2 ^ 256 = + 1461501637330902918203684832716283019655932542975 := by decide + have h1 := hs senderSlot + have hmid : midTo t a s = if t = 8192 then s senderSlot - a else s (solHash t 0) := rfl + simp only [R, transferTree, Tree.eval] at hR ⊢ + simp only [WExpr.eval, BinOp.eval, UnOp.eval, valOf, Generic.wordSize, List.getD_cons_zero, + List.getD_cons_succ, htm, hA, h8, h0, ham, hss, hsm, hashT, hash_eq] at hR ⊢ + split_ifs at hR ⊢ <;> simp only at hR + · rename_i hgt hlt _ hc hov + have hta : t < 2 ^ 160 := by omega + have ht8 : t = 8192 := inj t 8192 hta (by decide) (hc.trans hash_eq.symm) + subst ht8 + have hsub : (s senderSlot + (2 ^ 256 - a)) % 2 ^ 256 = s senderSlot - a := by omega + rw [hsub, Nat.mod_eq_of_lt (by omega : s senderSlot - a < 2 ^ 256)] at hov + have hm : midTo 8192 a s = s senderSlot - a := by simp [hmid] + refine ⟨hta, by omega, by omega, ?_⟩ + intro n hn + rw [hm, hc] + simp only [Writes.store, WExpr.eval, BinOp.eval, Generic.wordSize, List.getD_cons_zero, + List.getD_cons_succ, h8, h0, ham, hss, hsm, hashT, hash_eq, Nat.mod_eq_of_lt hn, hsub] + by_cases hn' : n = senderSlot + · subst hn'; simp; omega + · simp [hn', Ne.symm hn'] + · rename_i hgt hlt _ hc hov + have hta : t < 2 ^ 160 := by omega + have ht8 : t ≠ 8192 := fun h => hc (h ▸ hash_eq) + have hm : midTo t a s = s (solHash t 0) := by simp [hmid, ht8] + have hst := hs (solHash t 0) + have hno : s (solHash t 0) + a < 2 ^ 256 := by omega + refine ⟨hta, by omega, by omega, ?_⟩ + intro n hn + rw [hm] + simp only [Writes.store, WExpr.eval, BinOp.eval, Generic.wordSize, List.getD_cons_zero, + List.getD_cons_succ, htm, h8, h0, ham, hss, hsm, hashT, hash_eq, Nat.mod_eq_of_lt hn] + by_cases hn1 : n = solHash t 0 + · subst hn1; simp [hc]; omega + · by_cases hn2 : n = senderSlot + · subst hn2; simp [hc, Ne.symm hc]; omega + · simp [hn1, hn2, Ne.symm hn1, Ne.symm hn2] + +theorem balArr_nat (s : Storage) (x : Nat) : balArr s x = s (solHash x 0) := by simp [balArr] + +theorem balArr_caller (s : Storage) : balArr s callerWord = s senderSlot := by + rw [balArr_nat]; exact congrArg (fun n => ((s n : Nat) : Int)) hash_eq + + +section +variable (t a : Nat) (s : Storage) +@[simp] theorem trEnv_amount : (trEnv t a s).i "amount" = a := rfl +@[simp] theorem trEnv_to : (trEnv t a s).i "to" = t := rfl +@[simp] theorem trEnv_sender : (trEnv t a s).i "msg.sender" = 8192 := rfl +@[simp] theorem trEnv_bal : (trEnv t a s).a "balanceOf" = balArr s := rfl +end + +section +variable (t a : Nat) (s : Storage) (n : Int) +@[simp] theorem trEnvA_a : ((trEnv t a s).setI "a" n).i "a" = n := rfl +@[simp] theorem trEnvA_to : ((trEnv t a s).setI "a" n).i "to" = t := rfl +@[simp] theorem trEnvA_sender : ((trEnv t a s).setI "a" n).i "msg.sender" = 8192 := rfl +@[simp] theorem trEnvA_amount : ((trEnv t a s).setI "a" n).i "amount" = a := rfl +@[simp] theorem trEnvA_bal : ((trEnv t a s).setI "a" n).a "balanceOf" = balArr s := rfl + +/-- solar-verify's array term does not read the frame's bound address. -/ +theorem S2_setI : Ob.S2.eval ((trEnv t a s).setI "a" n) = Ob.S2.eval (trEnv t a s) := by + apply Tm.eval_congr + intro y hy + have hna : y ≠ "a" := by + rintro rfl + revert hy + decide + exact ⟨by simp [Env.setI, hna], rfl, rfl⟩ +end + +/-- The binding: after a successful `transfer`, every address's `balanceOf` slot in SolidCore's +storage holds solar-verify's array term `S2` at `trEnv`. -/ +theorem trStore_eval (inj : HashInj) (s : Storage) (hs : ∀ k, s k < 2 ^ 256) (t a : Nat) + (ht : t < 2 ^ 256) (ha : a < 2 ^ 256) + (hR : (transferTree.eval (valOf [t, a] s)).success = true) (x : Nat) (hx : x < 2 ^ 160) : + (((transferTree.eval (valOf [t, a] s)).store (solHash x 0) : Nat) : Int) = + (Ob.S2.eval (trEnv t a s)).toArr x := by + obtain ⟨hta, hle, hov, hst⟩ := tr_success inj s hs t a ht ha hR + rw [hst _ (solHash_lt x 0), S2_eval] + have hc : (callerWord : Int) = 8192 := rfl + have hxt : (solHash x 0 = solHash t 0) ↔ x = t := + ⟨inj x t hx hta, fun h => h ▸ rfl⟩ + have hx8 : (solHash x 0 = senderSlot) ↔ x = 8192 := + ⟨fun h => inj x 8192 hx (by decide) (h.trans hash_eq.symm), fun h => h ▸ hash_eq⟩ + have hmid : midTo t a s = if t = 8192 then s senderSlot - a else s (solHash t 0) := rfl + rw [balArr_caller, balArr_nat, balArr_nat] + by_cases h1 : x = t + · subst h1 + by_cases h2 : x = 8192 + · subst h2; simp [hmid]; omega + · simp [hmid, h2, hc]; omega + · by_cases h2 : x = 8192 + · subst h2 + have : ¬ (8192 : Int) = t := by omega + simp [hxt, h1, hash_eq, this]; omega + · have h1' : ¬ (x : Int) = t := by omega + have h2' : ¬ (x : Int) = 8192 := by omega + simp [hxt, h1, hx8, h2, h1', h2', hc] + +theorem trHyps_hold (s : Storage) (hs : ∀ k, s k < 2 ^ 256) (t a : Nat) (hta : t < 2 ^ 160) + (ha : a < 2 ^ 256) (hle : a ≤ s senderSlot) (hov : midTo t a s + a < 2 ^ 256) : + ∀ x ∈ trHyps, x.Holds (trEnv t a s) := by + have hc : (callerWord : Int) = 8192 := rfl + have h8 : balArr s 8192 = s senderSlot := balArr_caller s + have hmid : midTo t a s = if t = 8192 then s senderSlot - a else s (solHash t 0) := rfl + have h1 := hs senderSlot + have h1' := hs (solHash t 0) + have h2 := hs 1 + simp only [trHyps, List.mem_cons, List.mem_nil_iff, or_false] + rintro x (rfl | rfl | rfl | rfl | rfl | rfl | rfl | rfl | rfl | rfl | rfl | rfl | rfl | rfl | rfl | + rfl | rfl | rfl | rfl | rfl | rfl) <;> + simp [Tm.Holds, Tm.eval, Tm.evalList, applyOp, Value.toProp, Value.toInt, Value.toArr, Value.eq, + trEnv, Ob.amt, Ob.ms, Ob.ts, Ob.sum, Ob.mv, Ob.bal, Ob.le0, Ob.leW, Ob.sub, Ob.eq, Ob.add, + Ob.leA, Ob.sel, Ob.sto, Ob.S1, Ob.B, Ob.rcpt, arrFact, Env.setI, hc, h8, balArr_nat] <;> + first + | omega + | (intro n; have := hs (solHash n.toNat 0); simp only [balArr]; omega) + | (by_cases ht8 : t = 8192 <;> simp [ht8, hmid] at hov ⊢ <;> omega) + +/-- `transfer`'s ensures clauses on distinct addresses, as SolidCore sees them: on success, for +the call's words `t = to` and `a = amount`, the sender's slot drops by `a` and the recipient's +rises by `a` when they differ, and every other address's slot is unchanged. -/ +def trPost (call : Call) (obs : SolarTV.Observable) : Prop := + obs.success = true → + let t := (argWords 2 call).getD 0 0 + let a := (argWords 2 call).getD 1 0 + let s := initStorage call + (t ≠ callerWord → obs.storage (solHash callerWord 0) = s (solHash callerWord 0) - a) ∧ + (t ≠ callerWord → obs.storage (solHash t 0) = s (solHash t 0) + a) ∧ + (∀ x < 2 ^ 160, x ≠ callerWord → x ≠ t → obs.storage (solHash x 0) = s (solHash x 0)) + +/-- The goal of one of `transfer`'s obligations, at `trEnv`, from solar-verify's verdict. -/ +theorem tr_obligation (hv : Valid Export.Token.script) {φ : Tm} (hφ : (trHyps, φ) ∈ trObs) + {s : Storage} (hs : ∀ k, s k < 2 ^ 256) {t a : Nat} (hta : t < 2 ^ 160) (ha : a < 2 ^ 256) + (hle : a ≤ s senderSlot) (hov : midTo t a s + a < 2 ^ 256) : φ.Holds (trEnv t a s) := + checkScript_sound transfer_check hv _ hφ _ (trHyps_hold s hs t a hta ha hle hov) + +/-- `Token.transfer` meets its three ensures clauses on distinct addresses on the stage's scope, +given solar-verify's verdict on its script for `Token` and injectivity of the mapping slot on +address keys. Each clause is read off solar-verify's obligation for it (`tr_obligation`) through +the binding `trStore_eval`. -/ +theorem transfer_triple (hv : Valid Export.Token.script) (inj : HashInj) + {c : SolidCore.Solidity.TypeCheck.CheckedContract} (hc : contract? = .ok c) : + Triple fuel c (stageScope fnTransfer [(2, 4096)]) (fun _ => True) trPost := by + have hdep := burnShape_eq + simp only [burnShape?, hc, Option.some.injEq, Prod.mk.injEq] at hdep + obtain ⟨d, hd⟩ := Wide.deployedAt_of hdep.1 + have hshape := transferShape_eq + simp only [transferShape?, hc, Option.some.injEq, Option.map_eq_some_iff, Prod.mk.injEq] at hshape + obtain ⟨f, hf, hlen, hT⟩ := hshape + have himpl := implements_tree (fn := fnTransfer) hd (by decide) hf hlen hT rfl + apply triple_of_wp himpl + rintro _ ⟨σ, hcov, fn', hfn', args, hl, hargs, rfl⟩ - + simp only [List.mem_singleton] at hfn' + subst hfn' + obtain ⟨t, a, rfl⟩ : ∃ t a, args = [t, a] := by + match args, hl with + | [t, a], _ => exact ⟨t, a, rfl⟩ + have ht : t < 2 ^ 256 := hargs t (by simp) + have ha : a < 2 ^ 256 := hargs a (by simp) + have hw : argWords 2 ({ calldata := Abi.calldata fnTransfer.sel [t, a], callvalue := 0, storage := σ } : Call) = + [t, a] := argWords_calldata _ [t, a] hargs 0 σ + rw [vc_eq, treeModel_run, show fnTransfer.params.length = 2 from rfl, hw] + set s := initStorage ({ calldata := Abi.calldata fnTransfer.sel [t, a], callvalue := 0, storage := σ } : Call) + with hs_def + have hs : ∀ k, s k < 2 ^ 256 := fun k => Generic.slotValue_lt σ k + unfold resOutcome + split + · next hok => + intro _ + obtain ⟨hta, hle, hov, -⟩ := tr_success inj s hs t a ht ha hok + have hb := trStore_eval inj s hs t a ht ha hok + have hcw : (callerWord : Int) = 8192 := rfl + have h8 : balArr s 8192 = (s senderSlot : Int) := balArr_caller s + have hob := fun φ (hφ : (trHyps, φ) ∈ trObs) => tr_obligation hv hφ hs hta ha hle hov + have gFrom := hob trGoalFrom (by simp [trObs]) + have gTo := hob trGoalTo (by simp [trObs]) + have gFrame := hob trGoalFrame (by simp [trObs]) + simp only [trGoalFrom, trGoalTo, trGoalFrame, Tm.Holds, Tm.eval, Tm.evalList, applyOp, + Value.toProp, Value.toInt, Value.toArr, Value.eq, Ob.eq, Ob.sel, Ob.sub, Ob.add, Ob.le0, + Ob.leA, Ob.bal, Ob.B, Ob.ms, Ob.amt, Ob.rcpt, S2_setI] at gFrom gTo gFrame + simp only [observe, hw, List.getD_cons_zero, List.getD_cons_succ] + rw [← hs_def] + have hsl : solHash callerWord 0 = senderSlot := hash_eq + refine ⟨fun hne => ?_, fun hne => ?_, fun x hx hx8 hxt => ?_⟩ + · have e : (((transferTree.eval (valOf [t, a] s)).store senderSlot : Nat) : Int) = + (Ob.S2.eval (trEnv t a s)).toArr 8192 := by + have := hb callerWord (by decide); rwa [hsl] at this + have g := gFrom (by simp; omega) + simp [h8] at g + simp only [Value.toArr] at e g + rw [hsl] + omega + · have e := hb t hta + have g := gTo (by simp; omega) + simp [balArr_nat] at g + simp only [Value.toArr] at e g + omega + · have e := hb x hx + have hx8' : ¬ (x : Int) = 8192 := by intro h; apply hx8; exact_mod_cast h + have hxt' : ¬ (x : Int) = t := by omega + have hxA : (x : Int) ≤ 1461501637330902918203684832716283019655932542975 := by omega + have g := gFrame x + simp [balArr_nat, hx8', hxt', hxA, S2_setI] at g + simp only [Value.toArr] at e g + omega + · intro h; simp_all [observe] + +/-- info: 'SolidCore.Verify.VC.Token.transfer_triple' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms transfer_triple + +end SolidCore.Verify.VC.Token diff --git a/Contracts/Vault/Audit.lean b/Contracts/Vault/Audit.lean new file mode 100644 index 00000000..e89745e1 --- /dev/null +++ b/Contracts/Vault/Audit.lean @@ -0,0 +1,24 @@ +import Contracts.Vault.Proofs.Vault.constructor +import Contracts.Vault.Proofs.Vault.deposit +import Contracts.Vault.Proofs.Vault.withdraw +import Contracts.Vault.Proofs.Vacuous + +/-! Fails unless every theorem under `Contracts.Vault.constructor`, `Contracts.Vault.deposit`, `Contracts.Vault.withdraw`, `Contracts.Vault.Vacuous` uses no axiom but `propext`, +`Classical.choice` and `Quot.sound`, and prints how many it checked. -/ + +open Lean Elab Command in +#eval show CommandElabM Unit from do + let env ← getEnv + let roots : List Name := [`Contracts.Vault.constructor, `Contracts.Vault.deposit, `Contracts.Vault.withdraw, + `Contracts.Vault.Vacuous] + let allowed : List Name := [`propext, `Classical.choice, `Quot.sound] + let mut n := 0 + for (name, info) in env.constants.toList do + unless roots.any (·.isPrefixOf name) do continue + unless info matches .thmInfo _ do continue + let axs ← Lean.collectAxioms name + for a in axs do + unless allowed.contains a do throwError "{name} uses axiom {a}" + n := n + 1 + if n == 0 then throwError "no theorems found" + IO.println s!"Vault: {n} theorems, axioms within propext, Classical.choice, Quot.sound" diff --git a/Contracts/Vault/Proofs/Vacuous.lean b/Contracts/Vault/Proofs/Vacuous.lean new file mode 100644 index 00000000..fbdb05f0 --- /dev/null +++ b/Contracts/Vault/Proofs/Vacuous.lean @@ -0,0 +1,41 @@ +import Contracts.ArrayMax.Bounded +import Contracts.Vault.Vc.Vault.deposit +import Contracts.Vault.Vc.Vault.withdraw + +set_option maxHeartbeats 0 +set_option maxRecDepth 100000 + +/-! Vault's vacuous obligations. Each theorem proves that the obligation's assertions and guard +alone are unsatisfiable: the obligation with its goal replaced by `false` is valid. These +obligations therefore hold whatever their goal says, and their proofs (Proofs/Vault/) are no +evidence about the goal. They are the paths that start with the reentrancy guard `locked` held, +which the contract invariant and the entry point's own check exclude. -/ + +namespace Contracts.Vault.Vacuous + +open SolarVerify.Vc SolarVerify.Smt + +/-- The obligation with goal `false`: valid exactly when its hypotheses refute. -/ +def refute (o : Obligation) : Obligation := { o with goal := .bool false } + +/-- Vault.deposit#6 (side): its hypotheses refute. -/ +theorem deposit_ob6 : (refute SolarVerifyVc.Vault.deposit.ob6).Valid := by + unfold refute; first | vc_bounded_valid | vc_valid + +/-- Vault.deposit#7: its hypotheses refute (its goal is already `false`). -/ +theorem deposit_ob7 : (refute SolarVerifyVc.Vault.deposit.ob7).Valid := by + unfold refute; first | vc_bounded_valid | vc_valid + +/-- Vault.withdraw#6: its hypotheses refute. -/ +theorem withdraw_ob6 : (refute SolarVerifyVc.Vault.withdraw.ob6).Valid := by + unfold refute; first | vc_bounded_valid | vc_valid + +/-- Vault.withdraw#7 (side): its hypotheses refute. -/ +theorem withdraw_ob7 : (refute SolarVerifyVc.Vault.withdraw.ob7).Valid := by + unfold refute; first | vc_bounded_valid | vc_valid + +/-- Vault.withdraw#8: its hypotheses refute (its goal is already `false`). -/ +theorem withdraw_ob8 : (refute SolarVerifyVc.Vault.withdraw.ob8).Valid := by + unfold refute; first | vc_bounded_valid | vc_valid + +end Contracts.Vault.Vacuous diff --git a/Contracts/Vault/Proofs/Vault/constructor.lean b/Contracts/Vault/Proofs/Vault/constructor.lean new file mode 100644 index 00000000..a3d5d50a --- /dev/null +++ b/Contracts/Vault/Proofs/Vault/constructor.lean @@ -0,0 +1,20 @@ +import Contracts.ArrayMax.Bounded +import Contracts.Vault.Vc.Vault.constructor + +set_option maxHeartbeats 0 +set_option maxRecDepth 100000 + +/-! Kernel proofs of the required obligations of Vault.constructor, as the frozen v1 export states them +(`Vc/Vault/constructor.lean`). -/ + +namespace Contracts.Vault.constructor + +/-- Vault.constructor#1 (obligation): contract invariant not established by constructor: totalShares == sumShares. -/ +theorem ob1 : SolarVerifyVc.Vault.constructor.ob1.Valid := by + first | vc_bounded_valid | vc_valid + +/-- Vault.constructor#2 (obligation): contract invariant not established by constructor: totalShares <= totalAssets. -/ +theorem ob2 : SolarVerifyVc.Vault.constructor.ob2.Valid := by + first | vc_bounded_valid | vc_valid + +end Contracts.Vault.constructor diff --git a/Contracts/Vault/Proofs/Vault/deposit.lean b/Contracts/Vault/Proofs/Vault/deposit.lean new file mode 100644 index 00000000..8ac0a56e --- /dev/null +++ b/Contracts/Vault/Proofs/Vault/deposit.lean @@ -0,0 +1,40 @@ +import Contracts.ArrayMax.Bounded +import Contracts.Vault.Vc.Vault.deposit + +set_option maxHeartbeats 0 +set_option maxRecDepth 100000 + +/-! Kernel proofs of the required obligations of Vault.deposit, as the frozen v1 export states them +(`Vc/Vault/deposit.lean`). -/ + +namespace Contracts.Vault.deposit + +/-- Vault.deposit#0 (side): side. -/ +theorem ob0 : SolarVerifyVc.Vault.deposit.ob0.Valid := by + first | vc_bounded_valid | vc_valid + +/-- Vault.deposit#2 (obligation): postcondition not satisfied: shares[msg.sender] == old(shares[msg.sender]) + amount. -/ +theorem ob2 : SolarVerifyVc.Vault.deposit.ob2.Valid := by + first | vc_bounded_valid | vc_valid + +/-- Vault.deposit#3 (obligation): postcondition not satisfied: !locked. -/ +theorem ob3 : SolarVerifyVc.Vault.deposit.ob3.Valid := by + first | vc_bounded_valid | vc_valid + +/-- Vault.deposit#4 (obligation): contract invariant not preserved: totalShares == sumShares. -/ +theorem ob4 : SolarVerifyVc.Vault.deposit.ob4.Valid := by + first | vc_bounded_valid | vc_valid + +/-- Vault.deposit#5 (obligation): contract invariant not preserved: totalShares <= totalAssets. -/ +theorem ob5 : SolarVerifyVc.Vault.deposit.ob5.Valid := by + first | vc_bounded_valid | vc_valid + +/-- Vault.deposit#6 (side): side. -/ +theorem ob6 : SolarVerifyVc.Vault.deposit.ob6.Valid := by + first | vc_bounded_valid | vc_valid + +/-- Vault.deposit#7 (obligation): entry point does not revert while reentrancy guard 'locked' is held. -/ +theorem ob7 : SolarVerifyVc.Vault.deposit.ob7.Valid := by + first | vc_bounded_valid | vc_valid + +end Contracts.Vault.deposit diff --git a/Contracts/Vault/Proofs/Vault/withdraw.lean b/Contracts/Vault/Proofs/Vault/withdraw.lean new file mode 100644 index 00000000..59e308bf --- /dev/null +++ b/Contracts/Vault/Proofs/Vault/withdraw.lean @@ -0,0 +1,44 @@ +import Contracts.ArrayMax.Bounded +import Contracts.Vault.Vc.Vault.withdraw + +set_option maxHeartbeats 0 +set_option maxRecDepth 100000 + +/-! Kernel proofs of the required obligations of Vault.withdraw, as the frozen v1 export states them +(`Vc/Vault/withdraw.lean`). -/ + +namespace Contracts.Vault.withdraw + +/-- Vault.withdraw#0 (obligation): assertion failed: totalShares == sumShares && totalShares <= totalAssets. -/ +theorem ob0 : SolarVerifyVc.Vault.withdraw.ob0.Valid := by + first | vc_bounded_valid | vc_valid + +/-- Vault.withdraw#1 (side): side. -/ +theorem ob1 : SolarVerifyVc.Vault.withdraw.ob1.Valid := by + first | vc_bounded_valid | vc_valid + +/-- Vault.withdraw#3 (obligation): postcondition not satisfied: !locked. -/ +theorem ob3 : SolarVerifyVc.Vault.withdraw.ob3.Valid := by + first | vc_bounded_valid | vc_valid + +/-- Vault.withdraw#4 (obligation): contract invariant not preserved: totalShares == sumShares. -/ +theorem ob4 : SolarVerifyVc.Vault.withdraw.ob4.Valid := by + first | vc_bounded_valid | vc_valid + +/-- Vault.withdraw#5 (obligation): contract invariant not preserved: totalShares <= totalAssets. -/ +theorem ob5 : SolarVerifyVc.Vault.withdraw.ob5.Valid := by + first | vc_bounded_valid | vc_valid + +/-- Vault.withdraw#6 (obligation): assertion failed: totalShares == sumShares && totalShares <= totalAssets. -/ +theorem ob6 : SolarVerifyVc.Vault.withdraw.ob6.Valid := by + first | vc_bounded_valid | vc_valid + +/-- Vault.withdraw#7 (side): side. -/ +theorem ob7 : SolarVerifyVc.Vault.withdraw.ob7.Valid := by + first | vc_bounded_valid | vc_valid + +/-- Vault.withdraw#8 (obligation): entry point does not revert while reentrancy guard 'locked' is held. -/ +theorem ob8 : SolarVerifyVc.Vault.withdraw.ob8.Valid := by + first | vc_bounded_valid | vc_valid + +end Contracts.Vault.withdraw diff --git a/Contracts/Vault/README.md b/Contracts/Vault/README.md new file mode 100644 index 00000000..fe06d503 --- /dev/null +++ b/Contracts/Vault/README.md @@ -0,0 +1,28 @@ +# Vault: solar-verify's obligations in the Lean kernel + +`Vc/` holds the frozen v1 export of `crates/verify/examples/Vault.sol` (paradigmxyz/solar +7f4e94e, `solar-verify --emit-lean`), with its first line `import SolarVerify` read as +`import Verify.Obligation`; `Vc/frozen.sha256` locks the unchanged export. `Proofs/Vault/` proves +every required obligation with `vc_valid` or the bounded search of `../ArrayMax/Bounded.lean`, and +`Audit.lean` fails unless every theorem uses only `propext`, `Classical.choice` and `Quot.sound`. + +## Vacuous obligations + +Five obligations hold only because their hypotheses refute: `Proofs/Vacuous.lean` proves, for +each, the obligation with its goal replaced by `false`. Their proofs say nothing about their +goals, so they are not evidence for the property they name: + +| Obligation | Kind | +| --- | --- | +| Vault.deposit#6 | side | +| Vault.deposit#7 | entry point does not revert while the reentrancy guard is held | +| Vault.withdraw#6 | assertion `totalShares == sumShares && totalShares <= totalAssets` | +| Vault.withdraw#7 | side | +| Vault.withdraw#8 | entry point does not revert while the reentrancy guard is held | + +They are the queries of each entry point's second script (`script1`), which models a call +that enters while `locked` is held: its first guard is `locked` and the next conjoins +`!locked` (the entry point's `require(!locked)`), so every path of the script is infeasible. For +the reentrancy checks (#7, #8) that refutation is the intended answer: a reentrant call cannot get +past the guard. withdraw#6 is the invariant assertion on that infeasible path; the same +assertion on the feasible path is withdraw#0, which is not vacuous. diff --git a/Contracts/Vault/Vc/Vault/constructor.lean b/Contracts/Vault/Vc/Vault/constructor.lean new file mode 100644 index 00000000..4ac9c2da --- /dev/null +++ b/Contracts/Vault/Vc/Vault/constructor.lean @@ -0,0 +1,78 @@ +-- Generated by solar-verify --emit-lean (format 1); do not edit. +import Verify.Obligation + +set_option maxRecDepth 100000 + +namespace SolarVerifyVc.Vault.constructor +open SolarVerify.Smt SolarVerify.Vc + +/-- Script 0 of Vault.constructor: the solver's assertion stack. -/ +def script0 : Script where + decls := [ + ⟨"|this@1|", [], .int⟩, + ⟨"|msg.sender@2|", [], .int⟩, + ⟨"|msg.value@3|", [], .int⟩, + ⟨"|block.timestamp@4|", [], .int⟩, + ⟨"|block.number@5|", [], .int⟩, + ⟨"|block.chainid@6|", [], .int⟩, + ⟨"|tx.origin@7|", [], .int⟩, + ⟨"|tx.gasprice@8|", [], .int⟩, + ⟨"|msg.sig@9|", [], .int⟩, + ⟨"|msg.data@10|", [], .int⟩, + ⟨"|block.basefee@11|", [], .int⟩, + ⟨"|block.blobbasefee@12|", [], .int⟩, + ⟨"|block.coinbase@13|", [], .int⟩, + ⟨"|block.prevrandao@14|", [], .int⟩, + ⟨"|block.difficulty@15|", [], .int⟩, + ⟨"|block.gaslimit@16|", [], .int⟩, + ⟨"|asset@17|", [], .int⟩, + ⟨"|__balance@18|", [], (.array .int .int)⟩, + ⟨"|__code_epoch@19|", [], .int⟩, + ⟨"|_asset@20|", [], .int⟩, + ⟨"|g@21|", [], .bool⟩ + ] + asserts := [ + .app .and [.app .le [.int 0, .fn 0 []], .app .le [.fn 0 [], .int 1461501637330902918203684832716283019655932542975]], + .app .and [.app .le [.int 0, .fn 1 []], .app .le [.fn 1 [], .int 1461501637330902918203684832716283019655932542975]], + .app .not [.app .eq [.fn 1 [], .int 0]], + .app .and [.app .le [.int 0, .fn 2 []], .app .le [.fn 2 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .and [.app .le [.int 0, .fn 3 []], .app .le [.fn 3 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .and [.app .le [.int 0, .fn 4 []], .app .le [.fn 4 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .and [.app .le [.int 0, .fn 5 []], .app .le [.fn 5 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .and [.app .le [.int 0, .fn 6 []], .app .le [.fn 6 [], .int 1461501637330902918203684832716283019655932542975]], + .app .and [.app .le [.int 0, .fn 7 []], .app .le [.fn 7 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .and [.app .le [.int 0, .fn 8 []], .app .le [.fn 8 [], .int 4294967295]], + .app .and [.app .le [.int 0, .fn 10 []], .app .le [.fn 10 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .and [.app .le [.int 0, .fn 11 []], .app .le [.fn 11 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .and [.app .le [.int 0, .fn 12 []], .app .le [.fn 12 [], .int 1461501637330902918203684832716283019655932542975]], + .app .and [.app .le [.int 0, .fn 13 []], .app .le [.fn 13 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .and [.app .le [.int 0, .fn 14 []], .app .le [.fn 14 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .and [.app .le [.int 0, .fn 15 []], .app .le [.fn 15 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .and [.app .le [.int 0, .fn 16 []], .app .le [.fn 16 [], .int 1461501637330902918203684832716283019655932542975]], + .app .and [.app .le [.int 0, .fn 18 []], .app .le [.fn 18 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .and [.app .le [.int 0, .fn 19 []], .app .le [.fn 19 [], .int 1461501637330902918203684832716283019655932542975]], + .app .eq [.fn 20 [], .app .and [.bool true, .app .eq [.fn 2 [], .int 0]]] + ] + +/-- Vault.constructor#0: a query only a warning reads (sat). -/ +def ob0 : Obligation where + script := script0 + upto := 20 + guard := .fn 20 [] + goal := .bool false + +/-- Vault.constructor#1: contract invariant not established by constructor: `totalShares == sumShares` (unsat). -/ +def ob1 : Obligation where + script := script0 + upto := 20 + guard := .fn 20 [] + goal := .app .eq [.int 0, .int 0] + +/-- Vault.constructor#2: contract invariant not established by constructor: `totalShares <= totalAssets` (unsat). -/ +def ob2 : Obligation where + script := script0 + upto := 20 + guard := .fn 20 [] + goal := .app .le [.int 0, .int 0] + +end SolarVerifyVc.Vault.constructor diff --git a/Contracts/Vault/Vc/Vault/deposit.lean b/Contracts/Vault/Vc/Vault/deposit.lean new file mode 100644 index 00000000..e45fd54e --- /dev/null +++ b/Contracts/Vault/Vc/Vault/deposit.lean @@ -0,0 +1,237 @@ +-- Generated by solar-verify --emit-lean (format 1); do not edit. +import Verify.Obligation + +set_option maxRecDepth 100000 + +namespace SolarVerifyVc.Vault.deposit +open SolarVerify.Smt SolarVerify.Vc + +/-- Script 0 of Vault.deposit: the solver's assertion stack. -/ +def script0 : Script where + decls := [ + ⟨"|this@1|", [], .int⟩, + ⟨"|msg.sender@2|", [], .int⟩, + ⟨"|msg.value@3|", [], .int⟩, + ⟨"|block.timestamp@4|", [], .int⟩, + ⟨"|block.number@5|", [], .int⟩, + ⟨"|block.chainid@6|", [], .int⟩, + ⟨"|tx.origin@7|", [], .int⟩, + ⟨"|tx.gasprice@8|", [], .int⟩, + ⟨"|msg.sig@9|", [], .int⟩, + ⟨"|msg.data@10|", [], .int⟩, + ⟨"|block.basefee@11|", [], .int⟩, + ⟨"|block.blobbasefee@12|", [], .int⟩, + ⟨"|block.coinbase@13|", [], .int⟩, + ⟨"|block.prevrandao@14|", [], .int⟩, + ⟨"|block.difficulty@15|", [], .int⟩, + ⟨"|block.gaslimit@16|", [], .int⟩, + ⟨"|sumShares@17|", [], .int⟩, + ⟨"|asset@18|", [], .int⟩, + ⟨"|totalShares@19|", [], .int⟩, + ⟨"|totalAssets@20|", [], .int⟩, + ⟨"|shares@21|", [], (.array .int .int)⟩, + ⟨"|locked@22|", [], .bool⟩, + ⟨"|__balance@23|", [], (.array .int .int)⟩, + ⟨"|__code_epoch@24|", [], .int⟩, + ⟨"|amount@25|", [], .int⟩, + ⟨"|g@26|", [], .bool⟩, + ⟨"|g@27|", [], .bool⟩, + ⟨"|g@28|", [], .bool⟩, + ⟨"|g@29|", [], .bool⟩, + ⟨"|__code_epoch@30|", [], .int⟩, + ⟨"|__balance@31|", [], (.array .int .int)⟩, + ⟨"|g@32|", [], .bool⟩, + ⟨"|ext_ret@33|", [], .bool⟩, + ⟨"|g@34|", [], .bool⟩, + ⟨"|arith@35|", [], .int⟩, + ⟨"|g@36|", [], .bool⟩, + ⟨"|arith@37|", [], .int⟩, + ⟨"|g@38|", [], .bool⟩, + ⟨"|sumShares@39|", [], .int⟩, + ⟨"|arith@40|", [], .int⟩, + ⟨"|g@41|", [], .bool⟩, + ⟨"|shares@42|", [], (.array .int .int)⟩ + ] + asserts := [ + .app .and [.app .le [.int 0, .fn 0 []], .app .le [.fn 0 [], .int 1461501637330902918203684832716283019655932542975]], + .app .and [.app .le [.int 0, .fn 1 []], .app .le [.fn 1 [], .int 1461501637330902918203684832716283019655932542975]], + .app .not [.app .eq [.fn 1 [], .int 0]], + .app .and [.app .le [.int 0, .fn 2 []], .app .le [.fn 2 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .and [.app .le [.int 0, .fn 3 []], .app .le [.fn 3 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .and [.app .le [.int 0, .fn 4 []], .app .le [.fn 4 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .and [.app .le [.int 0, .fn 5 []], .app .le [.fn 5 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .and [.app .le [.int 0, .fn 6 []], .app .le [.fn 6 [], .int 1461501637330902918203684832716283019655932542975]], + .app .and [.app .le [.int 0, .fn 7 []], .app .le [.fn 7 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .and [.app .le [.int 0, .fn 8 []], .app .le [.fn 8 [], .int 4294967295]], + .app .and [.app .le [.int 0, .fn 10 []], .app .le [.fn 10 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .and [.app .le [.int 0, .fn 11 []], .app .le [.fn 11 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .and [.app .le [.int 0, .fn 12 []], .app .le [.fn 12 [], .int 1461501637330902918203684832716283019655932542975]], + .app .and [.app .le [.int 0, .fn 13 []], .app .le [.fn 13 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .and [.app .le [.int 0, .fn 14 []], .app .le [.fn 14 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .and [.app .le [.int 0, .fn 15 []], .app .le [.fn 15 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .and [.app .le [.int 0, .fn 16 []], .app .le [.fn 16 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .and [.app .le [.int 0, .fn 17 []], .app .le [.fn 17 [], .int 1461501637330902918203684832716283019655932542975]], + .app .and [.app .le [.int 0, .fn 18 []], .app .le [.fn 18 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .and [.app .le [.int 0, .fn 19 []], .app .le [.fn 19 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .and [.app .le [.int 0, .fn 23 []], .app .le [.fn 23 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .and [.app .le [.int 0, .fn 24 []], .app .le [.fn 24 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .eq [.fn 25 [], .app .and [.bool true, .app .eq [.fn 18 [], .fn 16 []]]], + .app .eq [.fn 26 [], .app .and [.fn 25 [], .app .le [.fn 18 [], .fn 19 []]]], + .app .eq [.fn 27 [], .app .and [.fn 26 [], .app .eq [.fn 2 [], .int 0]]], + .app .eq [.fn 28 [], .app .and [.fn 27 [], .app .not [.fn 21 []]]], + .app .and [.app .le [.int 0, .fn 29 []], .app .le [.fn 29 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .eq [.fn 31 [], .app .and [.fn 28 [], .app .ge [.app .select [.fn 30 [], .fn 0 []], .app .select [.fn 22 [], .fn 0 []]]]], + .app .eq [.fn 33 [], .app .and [.fn 31 [], .fn 32 []]], + .app .eq [.fn 34 [], .app .add [.fn 19 [], .fn 24 []]], + .app .eq [.fn 35 [], .app .and [.fn 33 [], .app .and [.app .le [.int 0, .fn 34 []], .app .le [.fn 34 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]]]], + .app .eq [.fn 36 [], .app .add [.fn 18 [], .fn 24 []]], + .app .eq [.fn 37 [], .app .and [.fn 35 [], .app .and [.app .le [.int 0, .fn 36 []], .app .le [.fn 36 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]]]], + .app .eq [.fn 38 [], .app .add [.fn 16 [], .fn 24 []]], + .app .and [.app .le [.int 0, .app .select [.fn 20 [], .fn 1 []]], .app .le [.app .select [.fn 20 [], .fn 1 []], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .eq [.fn 39 [], .app .add [.app .select [.fn 20 [], .fn 1 []], .fn 24 []]], + .app .eq [.fn 40 [], .app .and [.fn 37 [], .app .and [.app .le [.int 0, .fn 39 []], .app .le [.fn 39 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]]]], + .app .eq [.fn 41 [], .app .store [.fn 20 [], .fn 1 [], .fn 39 []]], + .app .and [.app .le [.int 0, .app .select [.fn 41 [], .fn 1 []]], .app .le [.app .select [.fn 41 [], .fn 1 []], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .and [.app .le [.int 0, .app .select [.fn 20 [], .fn 1 []]], .app .le [.app .select [.fn 20 [], .fn 1 []], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]] + ] + +/-- Script 1 of Vault.deposit: the solver's assertion stack. -/ +def script1 : Script where + decls := [ + ⟨"|this@43|", [], .int⟩, + ⟨"|msg.sender@44|", [], .int⟩, + ⟨"|msg.value@45|", [], .int⟩, + ⟨"|block.timestamp@46|", [], .int⟩, + ⟨"|block.number@47|", [], .int⟩, + ⟨"|block.chainid@48|", [], .int⟩, + ⟨"|tx.origin@49|", [], .int⟩, + ⟨"|tx.gasprice@50|", [], .int⟩, + ⟨"|msg.sig@51|", [], .int⟩, + ⟨"|msg.data@52|", [], .int⟩, + ⟨"|block.basefee@53|", [], .int⟩, + ⟨"|block.blobbasefee@54|", [], .int⟩, + ⟨"|block.coinbase@55|", [], .int⟩, + ⟨"|block.prevrandao@56|", [], .int⟩, + ⟨"|block.difficulty@57|", [], .int⟩, + ⟨"|block.gaslimit@58|", [], .int⟩, + ⟨"|sumShares@59|", [], .int⟩, + ⟨"|asset@60|", [], .int⟩, + ⟨"|totalShares@61|", [], .int⟩, + ⟨"|totalAssets@62|", [], .int⟩, + ⟨"|shares@63|", [], (.array .int .int)⟩, + ⟨"|locked@64|", [], .bool⟩, + ⟨"|__balance@65|", [], (.array .int .int)⟩, + ⟨"|__code_epoch@66|", [], .int⟩, + ⟨"|amount@67|", [], .int⟩, + ⟨"|g@68|", [], .bool⟩, + ⟨"|g@69|", [], .bool⟩, + ⟨"|__code_epoch@70|", [], .int⟩, + ⟨"|__balance@71|", [], (.array .int .int)⟩, + ⟨"|g@72|", [], .bool⟩, + ⟨"|ext_ret@73|", [], .bool⟩, + ⟨"|g@74|", [], .bool⟩, + ⟨"|arith@75|", [], .int⟩, + ⟨"|g@76|", [], .bool⟩, + ⟨"|arith@77|", [], .int⟩, + ⟨"|g@78|", [], .bool⟩, + ⟨"|sumShares@79|", [], .int⟩, + ⟨"|arith@80|", [], .int⟩, + ⟨"|g@81|", [], .bool⟩, + ⟨"|shares@82|", [], (.array .int .int)⟩ + ] + asserts := [ + .app .and [.app .le [.int 0, .fn 0 []], .app .le [.fn 0 [], .int 1461501637330902918203684832716283019655932542975]], + .app .and [.app .le [.int 0, .fn 1 []], .app .le [.fn 1 [], .int 1461501637330902918203684832716283019655932542975]], + .app .not [.app .eq [.fn 1 [], .int 0]], + .app .and [.app .le [.int 0, .fn 2 []], .app .le [.fn 2 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .and [.app .le [.int 0, .fn 3 []], .app .le [.fn 3 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .and [.app .le [.int 0, .fn 4 []], .app .le [.fn 4 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .and [.app .le [.int 0, .fn 5 []], .app .le [.fn 5 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .and [.app .le [.int 0, .fn 6 []], .app .le [.fn 6 [], .int 1461501637330902918203684832716283019655932542975]], + .app .and [.app .le [.int 0, .fn 7 []], .app .le [.fn 7 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .and [.app .le [.int 0, .fn 8 []], .app .le [.fn 8 [], .int 4294967295]], + .app .and [.app .le [.int 0, .fn 10 []], .app .le [.fn 10 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .and [.app .le [.int 0, .fn 11 []], .app .le [.fn 11 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .and [.app .le [.int 0, .fn 12 []], .app .le [.fn 12 [], .int 1461501637330902918203684832716283019655932542975]], + .app .and [.app .le [.int 0, .fn 13 []], .app .le [.fn 13 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .and [.app .le [.int 0, .fn 14 []], .app .le [.fn 14 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .and [.app .le [.int 0, .fn 15 []], .app .le [.fn 15 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .and [.app .le [.int 0, .fn 16 []], .app .le [.fn 16 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .and [.app .le [.int 0, .fn 17 []], .app .le [.fn 17 [], .int 1461501637330902918203684832716283019655932542975]], + .app .and [.app .le [.int 0, .fn 18 []], .app .le [.fn 18 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .and [.app .le [.int 0, .fn 19 []], .app .le [.fn 19 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .and [.app .le [.int 0, .fn 23 []], .app .le [.fn 23 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .and [.app .le [.int 0, .fn 24 []], .app .le [.fn 24 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .eq [.fn 25 [], .app .and [.bool true, .fn 21 []]], + .app .eq [.fn 26 [], .app .and [.fn 25 [], .app .not [.fn 21 []]]], + .app .and [.app .le [.int 0, .fn 27 []], .app .le [.fn 27 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .eq [.fn 29 [], .app .and [.fn 26 [], .app .ge [.app .select [.fn 28 [], .fn 0 []], .app .select [.fn 22 [], .fn 0 []]]]], + .app .eq [.fn 31 [], .app .and [.fn 29 [], .fn 30 []]], + .app .eq [.fn 32 [], .app .add [.fn 19 [], .fn 24 []]], + .app .eq [.fn 33 [], .app .and [.fn 31 [], .app .and [.app .le [.int 0, .fn 32 []], .app .le [.fn 32 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]]]], + .app .eq [.fn 34 [], .app .add [.fn 18 [], .fn 24 []]], + .app .eq [.fn 35 [], .app .and [.fn 33 [], .app .and [.app .le [.int 0, .fn 34 []], .app .le [.fn 34 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]]]], + .app .eq [.fn 36 [], .app .add [.fn 16 [], .fn 24 []]], + .app .and [.app .le [.int 0, .app .select [.fn 20 [], .fn 1 []]], .app .le [.app .select [.fn 20 [], .fn 1 []], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .eq [.fn 37 [], .app .add [.app .select [.fn 20 [], .fn 1 []], .fn 24 []]], + .app .eq [.fn 38 [], .app .and [.fn 35 [], .app .and [.app .le [.int 0, .fn 37 []], .app .le [.fn 37 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]]]], + .app .eq [.fn 39 [], .app .store [.fn 20 [], .fn 1 [], .fn 37 []]] + ] + +/-- Vault.deposit#0: a query the encoding relies on (unsat). -/ +def ob0 : Obligation where + script := script0 + upto := 27 + guard := .fn 28 [] + goal := .bool true + +/-- Vault.deposit#1: a query only a warning reads (sat). -/ +def ob1 : Obligation where + script := script0 + upto := 38 + guard := .fn 40 [] + goal := .bool false + +/-- Vault.deposit#2: postcondition not satisfied: `shares[msg.sender] == old(shares[msg.sender]) + amount` (unsat). -/ +def ob2 : Obligation where + script := script0 + upto := 40 + guard := .fn 40 [] + goal := .app .eq [.app .select [.fn 41 [], .fn 1 []], .app .add [.app .select [.fn 20 [], .fn 1 []], .fn 24 []]] + +/-- Vault.deposit#3: postcondition not satisfied: `!locked` (unsat). -/ +def ob3 : Obligation where + script := script0 + upto := 40 + guard := .fn 40 [] + goal := .app .not [.bool false] + +/-- Vault.deposit#4: contract invariant not preserved: `totalShares == sumShares` (unsat). -/ +def ob4 : Obligation where + script := script0 + upto := 40 + guard := .fn 40 [] + goal := .app .eq [.fn 36 [], .fn 38 []] + +/-- Vault.deposit#5: contract invariant not preserved: `totalShares <= totalAssets` (unsat). -/ +def ob5 : Obligation where + script := script0 + upto := 40 + guard := .fn 40 [] + goal := .app .le [.fn 36 [], .fn 34 []] + +/-- Vault.deposit#6: a query the encoding relies on (unsat). -/ +def ob6 : Obligation where + script := script1 + upto := 25 + guard := .fn 26 [] + goal := .bool true + +/-- Vault.deposit#7: entry point does not revert while reentrancy guard `locked` is held (unsat). -/ +def ob7 : Obligation where + script := script1 + upto := 36 + guard := .fn 38 [] + goal := .bool false + +end SolarVerifyVc.Vault.deposit diff --git a/Contracts/Vault/Vc/Vault/withdraw.lean b/Contracts/Vault/Vc/Vault/withdraw.lean new file mode 100644 index 00000000..585c9b6c --- /dev/null +++ b/Contracts/Vault/Vc/Vault/withdraw.lean @@ -0,0 +1,252 @@ +-- Generated by solar-verify --emit-lean (format 1); do not edit. +import Verify.Obligation + +set_option maxRecDepth 100000 + +namespace SolarVerifyVc.Vault.withdraw +open SolarVerify.Smt SolarVerify.Vc + +/-- Script 0 of Vault.withdraw: the solver's assertion stack. -/ +def script0 : Script where + decls := [ + ⟨"|this@1|", [], .int⟩, + ⟨"|msg.sender@2|", [], .int⟩, + ⟨"|msg.value@3|", [], .int⟩, + ⟨"|block.timestamp@4|", [], .int⟩, + ⟨"|block.number@5|", [], .int⟩, + ⟨"|block.chainid@6|", [], .int⟩, + ⟨"|tx.origin@7|", [], .int⟩, + ⟨"|tx.gasprice@8|", [], .int⟩, + ⟨"|msg.sig@9|", [], .int⟩, + ⟨"|msg.data@10|", [], .int⟩, + ⟨"|block.basefee@11|", [], .int⟩, + ⟨"|block.blobbasefee@12|", [], .int⟩, + ⟨"|block.coinbase@13|", [], .int⟩, + ⟨"|block.prevrandao@14|", [], .int⟩, + ⟨"|block.difficulty@15|", [], .int⟩, + ⟨"|block.gaslimit@16|", [], .int⟩, + ⟨"|sumShares@17|", [], .int⟩, + ⟨"|asset@18|", [], .int⟩, + ⟨"|totalShares@19|", [], .int⟩, + ⟨"|totalAssets@20|", [], .int⟩, + ⟨"|shares@21|", [], (.array .int .int)⟩, + ⟨"|locked@22|", [], .bool⟩, + ⟨"|__balance@23|", [], (.array .int .int)⟩, + ⟨"|__code_epoch@24|", [], .int⟩, + ⟨"|amount@25|", [], .int⟩, + ⟨"|g@26|", [], .bool⟩, + ⟨"|g@27|", [], .bool⟩, + ⟨"|g@28|", [], .bool⟩, + ⟨"|g@29|", [], .bool⟩, + ⟨"|g@30|", [], .bool⟩, + ⟨"|arith@31|", [], .int⟩, + ⟨"|g@32|", [], .bool⟩, + ⟨"|shares@33|", [], (.array .int .int)⟩, + ⟨"|sumShares@34|", [], .int⟩, + ⟨"|arith@35|", [], .int⟩, + ⟨"|g@36|", [], .bool⟩, + ⟨"|arith@37|", [], .int⟩, + ⟨"|g@38|", [], .bool⟩, + ⟨"|g@39|", [], .bool⟩, + ⟨"|__code_epoch@40|", [], .int⟩, + ⟨"|__balance@41|", [], (.array .int .int)⟩, + ⟨"|g@42|", [], .bool⟩, + ⟨"|ext_ret@43|", [], .bool⟩, + ⟨"|g@44|", [], .bool⟩ + ] + asserts := [ + .app .and [.app .le [.int 0, .fn 0 []], .app .le [.fn 0 [], .int 1461501637330902918203684832716283019655932542975]], + .app .and [.app .le [.int 0, .fn 1 []], .app .le [.fn 1 [], .int 1461501637330902918203684832716283019655932542975]], + .app .not [.app .eq [.fn 1 [], .int 0]], + .app .and [.app .le [.int 0, .fn 2 []], .app .le [.fn 2 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .and [.app .le [.int 0, .fn 3 []], .app .le [.fn 3 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .and [.app .le [.int 0, .fn 4 []], .app .le [.fn 4 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .and [.app .le [.int 0, .fn 5 []], .app .le [.fn 5 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .and [.app .le [.int 0, .fn 6 []], .app .le [.fn 6 [], .int 1461501637330902918203684832716283019655932542975]], + .app .and [.app .le [.int 0, .fn 7 []], .app .le [.fn 7 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .and [.app .le [.int 0, .fn 8 []], .app .le [.fn 8 [], .int 4294967295]], + .app .and [.app .le [.int 0, .fn 10 []], .app .le [.fn 10 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .and [.app .le [.int 0, .fn 11 []], .app .le [.fn 11 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .and [.app .le [.int 0, .fn 12 []], .app .le [.fn 12 [], .int 1461501637330902918203684832716283019655932542975]], + .app .and [.app .le [.int 0, .fn 13 []], .app .le [.fn 13 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .and [.app .le [.int 0, .fn 14 []], .app .le [.fn 14 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .and [.app .le [.int 0, .fn 15 []], .app .le [.fn 15 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .and [.app .le [.int 0, .fn 16 []], .app .le [.fn 16 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .and [.app .le [.int 0, .fn 17 []], .app .le [.fn 17 [], .int 1461501637330902918203684832716283019655932542975]], + .app .and [.app .le [.int 0, .fn 18 []], .app .le [.fn 18 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .and [.app .le [.int 0, .fn 19 []], .app .le [.fn 19 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .and [.app .le [.int 0, .fn 23 []], .app .le [.fn 23 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .and [.app .le [.int 0, .fn 24 []], .app .le [.fn 24 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .eq [.fn 25 [], .app .and [.bool true, .app .eq [.fn 18 [], .fn 16 []]]], + .app .eq [.fn 26 [], .app .and [.fn 25 [], .app .le [.fn 18 [], .fn 19 []]]], + .app .eq [.fn 27 [], .app .and [.fn 26 [], .app .eq [.fn 2 [], .int 0]]], + .app .eq [.fn 28 [], .app .and [.fn 27 [], .app .not [.fn 21 []]]], + .app .and [.app .le [.int 0, .app .select [.fn 20 [], .fn 1 []]], .app .le [.app .select [.fn 20 [], .fn 1 []], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .eq [.fn 29 [], .app .and [.fn 28 [], .app .ge [.app .select [.fn 20 [], .fn 1 []], .fn 24 []]]], + .app .and [.app .le [.int 0, .app .select [.fn 20 [], .fn 1 []]], .app .le [.app .select [.fn 20 [], .fn 1 []], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .eq [.fn 30 [], .app .sub [.app .select [.fn 20 [], .fn 1 []], .fn 24 []]], + .app .eq [.fn 31 [], .app .and [.fn 29 [], .app .and [.app .le [.int 0, .fn 30 []], .app .le [.fn 30 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]]]], + .app .eq [.fn 32 [], .app .store [.fn 20 [], .fn 1 [], .fn 30 []]], + .app .eq [.fn 33 [], .app .sub [.fn 16 [], .fn 24 []]], + .app .eq [.fn 34 [], .app .sub [.fn 18 [], .fn 24 []]], + .app .eq [.fn 35 [], .app .and [.fn 31 [], .app .and [.app .le [.int 0, .fn 34 []], .app .le [.fn 34 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]]]], + .app .eq [.fn 36 [], .app .sub [.fn 19 [], .fn 24 []]], + .app .eq [.fn 37 [], .app .and [.fn 35 [], .app .and [.app .le [.int 0, .fn 36 []], .app .le [.fn 36 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]]]], + .app .eq [.fn 38 [], .app .and [.fn 37 [], .app .and [.app .eq [.fn 34 [], .fn 33 []], .app .le [.fn 34 [], .fn 36 []]]]], + .app .and [.app .le [.int 0, .fn 39 []], .app .le [.fn 39 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .eq [.fn 41 [], .app .and [.fn 38 [], .app .ge [.app .select [.fn 40 [], .fn 0 []], .app .select [.fn 22 [], .fn 0 []]]]], + .app .eq [.fn 43 [], .app .and [.fn 41 [], .fn 42 []]] + ] + +/-- Script 1 of Vault.withdraw: the solver's assertion stack. -/ +def script1 : Script where + decls := [ + ⟨"|this@45|", [], .int⟩, + ⟨"|msg.sender@46|", [], .int⟩, + ⟨"|msg.value@47|", [], .int⟩, + ⟨"|block.timestamp@48|", [], .int⟩, + ⟨"|block.number@49|", [], .int⟩, + ⟨"|block.chainid@50|", [], .int⟩, + ⟨"|tx.origin@51|", [], .int⟩, + ⟨"|tx.gasprice@52|", [], .int⟩, + ⟨"|msg.sig@53|", [], .int⟩, + ⟨"|msg.data@54|", [], .int⟩, + ⟨"|block.basefee@55|", [], .int⟩, + ⟨"|block.blobbasefee@56|", [], .int⟩, + ⟨"|block.coinbase@57|", [], .int⟩, + ⟨"|block.prevrandao@58|", [], .int⟩, + ⟨"|block.difficulty@59|", [], .int⟩, + ⟨"|block.gaslimit@60|", [], .int⟩, + ⟨"|sumShares@61|", [], .int⟩, + ⟨"|asset@62|", [], .int⟩, + ⟨"|totalShares@63|", [], .int⟩, + ⟨"|totalAssets@64|", [], .int⟩, + ⟨"|shares@65|", [], (.array .int .int)⟩, + ⟨"|locked@66|", [], .bool⟩, + ⟨"|__balance@67|", [], (.array .int .int)⟩, + ⟨"|__code_epoch@68|", [], .int⟩, + ⟨"|amount@69|", [], .int⟩, + ⟨"|g@70|", [], .bool⟩, + ⟨"|g@71|", [], .bool⟩, + ⟨"|g@72|", [], .bool⟩, + ⟨"|arith@73|", [], .int⟩, + ⟨"|g@74|", [], .bool⟩, + ⟨"|shares@75|", [], (.array .int .int)⟩, + ⟨"|sumShares@76|", [], .int⟩, + ⟨"|arith@77|", [], .int⟩, + ⟨"|g@78|", [], .bool⟩, + ⟨"|arith@79|", [], .int⟩, + ⟨"|g@80|", [], .bool⟩, + ⟨"|g@81|", [], .bool⟩, + ⟨"|__code_epoch@82|", [], .int⟩, + ⟨"|__balance@83|", [], (.array .int .int)⟩, + ⟨"|g@84|", [], .bool⟩, + ⟨"|ext_ret@85|", [], .bool⟩, + ⟨"|g@86|", [], .bool⟩ + ] + asserts := [ + .app .and [.app .le [.int 0, .fn 0 []], .app .le [.fn 0 [], .int 1461501637330902918203684832716283019655932542975]], + .app .and [.app .le [.int 0, .fn 1 []], .app .le [.fn 1 [], .int 1461501637330902918203684832716283019655932542975]], + .app .not [.app .eq [.fn 1 [], .int 0]], + .app .and [.app .le [.int 0, .fn 2 []], .app .le [.fn 2 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .and [.app .le [.int 0, .fn 3 []], .app .le [.fn 3 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .and [.app .le [.int 0, .fn 4 []], .app .le [.fn 4 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .and [.app .le [.int 0, .fn 5 []], .app .le [.fn 5 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .and [.app .le [.int 0, .fn 6 []], .app .le [.fn 6 [], .int 1461501637330902918203684832716283019655932542975]], + .app .and [.app .le [.int 0, .fn 7 []], .app .le [.fn 7 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .and [.app .le [.int 0, .fn 8 []], .app .le [.fn 8 [], .int 4294967295]], + .app .and [.app .le [.int 0, .fn 10 []], .app .le [.fn 10 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .and [.app .le [.int 0, .fn 11 []], .app .le [.fn 11 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .and [.app .le [.int 0, .fn 12 []], .app .le [.fn 12 [], .int 1461501637330902918203684832716283019655932542975]], + .app .and [.app .le [.int 0, .fn 13 []], .app .le [.fn 13 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .and [.app .le [.int 0, .fn 14 []], .app .le [.fn 14 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .and [.app .le [.int 0, .fn 15 []], .app .le [.fn 15 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .and [.app .le [.int 0, .fn 16 []], .app .le [.fn 16 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .and [.app .le [.int 0, .fn 17 []], .app .le [.fn 17 [], .int 1461501637330902918203684832716283019655932542975]], + .app .and [.app .le [.int 0, .fn 18 []], .app .le [.fn 18 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .and [.app .le [.int 0, .fn 19 []], .app .le [.fn 19 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .and [.app .le [.int 0, .fn 23 []], .app .le [.fn 23 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .and [.app .le [.int 0, .fn 24 []], .app .le [.fn 24 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .eq [.fn 25 [], .app .and [.bool true, .fn 21 []]], + .app .eq [.fn 26 [], .app .and [.fn 25 [], .app .not [.fn 21 []]]], + .app .and [.app .le [.int 0, .app .select [.fn 20 [], .fn 1 []]], .app .le [.app .select [.fn 20 [], .fn 1 []], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .eq [.fn 27 [], .app .and [.fn 26 [], .app .ge [.app .select [.fn 20 [], .fn 1 []], .fn 24 []]]], + .app .and [.app .le [.int 0, .app .select [.fn 20 [], .fn 1 []]], .app .le [.app .select [.fn 20 [], .fn 1 []], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .eq [.fn 28 [], .app .sub [.app .select [.fn 20 [], .fn 1 []], .fn 24 []]], + .app .eq [.fn 29 [], .app .and [.fn 27 [], .app .and [.app .le [.int 0, .fn 28 []], .app .le [.fn 28 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]]]], + .app .eq [.fn 30 [], .app .store [.fn 20 [], .fn 1 [], .fn 28 []]], + .app .eq [.fn 31 [], .app .sub [.fn 16 [], .fn 24 []]], + .app .eq [.fn 32 [], .app .sub [.fn 18 [], .fn 24 []]], + .app .eq [.fn 33 [], .app .and [.fn 29 [], .app .and [.app .le [.int 0, .fn 32 []], .app .le [.fn 32 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]]]], + .app .eq [.fn 34 [], .app .sub [.fn 19 [], .fn 24 []]], + .app .eq [.fn 35 [], .app .and [.fn 33 [], .app .and [.app .le [.int 0, .fn 34 []], .app .le [.fn 34 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]]]], + .app .eq [.fn 36 [], .app .and [.fn 35 [], .app .and [.app .eq [.fn 32 [], .fn 31 []], .app .le [.fn 32 [], .fn 34 []]]]], + .app .and [.app .le [.int 0, .fn 37 []], .app .le [.fn 37 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .eq [.fn 39 [], .app .and [.fn 36 [], .app .ge [.app .select [.fn 38 [], .fn 0 []], .app .select [.fn 22 [], .fn 0 []]]]], + .app .eq [.fn 41 [], .app .and [.fn 39 [], .fn 40 []]] + ] + +/-- Vault.withdraw#0: assertion failed: `totalShares == sumShares && totalShares <= totalAssets` (unsat). -/ +def ob0 : Obligation where + script := script0 + upto := 37 + guard := .fn 37 [] + goal := .app .and [.app .eq [.fn 34 [], .fn 33 []], .app .le [.fn 34 [], .fn 36 []]] + +/-- Vault.withdraw#1: a query the encoding relies on (unsat). -/ +def ob1 : Obligation where + script := script0 + upto := 39 + guard := .fn 38 [] + goal := .bool true + +/-- Vault.withdraw#2: a query only a warning reads (sat). -/ +def ob2 : Obligation where + script := script0 + upto := 41 + guard := .fn 43 [] + goal := .bool false + +/-- Vault.withdraw#3: postcondition not satisfied: `!locked` (unsat). -/ +def ob3 : Obligation where + script := script0 + upto := 41 + guard := .fn 43 [] + goal := .app .not [.bool false] + +/-- Vault.withdraw#4: contract invariant not preserved: `totalShares == sumShares` (unsat). -/ +def ob4 : Obligation where + script := script0 + upto := 41 + guard := .fn 43 [] + goal := .app .eq [.fn 34 [], .fn 33 []] + +/-- Vault.withdraw#5: contract invariant not preserved: `totalShares <= totalAssets` (unsat). -/ +def ob5 : Obligation where + script := script0 + upto := 41 + guard := .fn 43 [] + goal := .app .le [.fn 34 [], .fn 36 []] + +/-- Vault.withdraw#6: assertion failed: `totalShares == sumShares && totalShares <= totalAssets` (unsat). -/ +def ob6 : Obligation where + script := script1 + upto := 35 + guard := .fn 35 [] + goal := .app .and [.app .eq [.fn 32 [], .fn 31 []], .app .le [.fn 32 [], .fn 34 []]] + +/-- Vault.withdraw#7: a query the encoding relies on (unsat). -/ +def ob7 : Obligation where + script := script1 + upto := 37 + guard := .fn 36 [] + goal := .bool true + +/-- Vault.withdraw#8: entry point does not revert while reentrancy guard `locked` is held (unsat). -/ +def ob8 : Obligation where + script := script1 + upto := 39 + guard := .fn 41 [] + goal := .bool false + +end SolarVerifyVc.Vault.withdraw diff --git a/Contracts/Vault/Vc/frozen.sha256 b/Contracts/Vault/Vc/frozen.sha256 new file mode 100644 index 00000000..0014a46c --- /dev/null +++ b/Contracts/Vault/Vc/frozen.sha256 @@ -0,0 +1,4 @@ +2589125ac7c0b22969b81edb8b4f4bba10b7404351cd3e1276974c2b25849edb manifest.json +93b5b6971bf6f4c4c907a55e8d270c15b831e41ce858493d1c02da1ddcacfc41 Vault/constructor.lean +de6d589769c68862abcf874f9f8a316923ce34478346ebd2ef62d9af5cd0ca74 Vault/deposit.lean +b7fc9bfd454493489523a9c64689393906408761f5f5fb42612e2fdd4b71320a Vault/withdraw.lean diff --git a/Contracts/Vault/Vc/manifest.json b/Contracts/Vault/Vc/manifest.json new file mode 100644 index 00000000..4c7b722f --- /dev/null +++ b/Contracts/Vault/Vc/manifest.json @@ -0,0 +1,716 @@ +{ + "arguments": [ + "--emit-lean", + "vc-exports/Vault", + "crates/verify/examples/Vault.sol" + ], + "compiler": "0.8.38+commit.7f4e94e0.solar.0.3.0-dev", + "errors": [], + "format": "solar-verify-lean", + "lean": { + "library": "SolarVerify", + "smt_sha256": "2c92f3bcd927369da89250662bd5a6174d3c06d0c3c38f5021509fe8810036e3", + "toolchain": "leanprover/lean4:v4.35.0", + "vc_sha256": "7275fa354f077a4826dd9fe56124cbffee2337d7a21975b477534fc5f45d7cfe" + }, + "options": { + "dry_run": false, + "only": null, + "strict": false, + "timeout_ms": 10000 + }, + "solvers": { + "bitwuzla": null, + "cvc5": "This is cvc5 version 1.3.1 [git ea1b484 on branch HEAD]", + "z3": "Z3 version 4.13.4 - 64 bit" + }, + "sources": [ + { + "path": "/home/hand/wt-inferred/crates/verify/examples/Vault.sol", + "sha256": "0e2017a2679b3fc98aa539d29ce350f9776dd0d14a0085aed88d9b26a9921526" + } + ], + "units": [ + { + "module": "Vault/constructor.lean", + "name": "Vault.constructor", + "namespace": "SolarVerifyVc.Vault.constructor", + "obligations": [ + { + "answer": "sat", + "asserts": 20, + "commands": 41, + "goal": "false", + "guard": "|g@21|", + "id": "Vault.constructor#0", + "lean": "SolarVerifyVc.Vault.constructor.ob0", + "required": false, + "role": "advisory", + "script": 0, + "smt_sha256": "be9fed92fdf387b9caa157050c55e1204e8292bab32c407b116b85ec1d83eb85", + "solver": "z3" + }, + { + "answer": "unsat", + "asserts": 20, + "commands": 41, + "goal": "(= 0 0)", + "guard": "|g@21|", + "id": "Vault.constructor#1", + "kind": "contract invariant not established by constructor", + "lean": "SolarVerifyVc.Vault.constructor.ob1", + "required": true, + "role": "obligation", + "script": 0, + "site": { + "column": 5, + "file": "crates/verify/examples/Vault.sol", + "line": 29 + }, + "smt_sha256": "cf9fc5408ee75df3d38cb1ed2d9d5da6a295560630661aa6e182a4ce3ef25911", + "solver": "z3", + "spec": { + "column": 6, + "file": "crates/verify/examples/Vault.sol", + "line": 12, + "text": "totalShares == sumShares" + } + }, + { + "answer": "unsat", + "asserts": 20, + "commands": 41, + "goal": "(<= 0 0)", + "guard": "|g@21|", + "id": "Vault.constructor#2", + "kind": "contract invariant not established by constructor", + "lean": "SolarVerifyVc.Vault.constructor.ob2", + "required": true, + "role": "obligation", + "script": 0, + "site": { + "column": 5, + "file": "crates/verify/examples/Vault.sol", + "line": 29 + }, + "smt_sha256": "f6f3a0446b0723589b121ca64f30214516787a05675926cd3863d1188000cd08", + "solver": "z3", + "spec": { + "column": 6, + "file": "crates/verify/examples/Vault.sol", + "line": 13, + "text": "totalShares <= totalAssets" + } + } + ], + "scripts": [ + { + "commands": 41, + "decls": [ + "|this@1|", + "|msg.sender@2|", + "|msg.value@3|", + "|block.timestamp@4|", + "|block.number@5|", + "|block.chainid@6|", + "|tx.origin@7|", + "|tx.gasprice@8|", + "|msg.sig@9|", + "|msg.data@10|", + "|block.basefee@11|", + "|block.blobbasefee@12|", + "|block.coinbase@13|", + "|block.prevrandao@14|", + "|block.difficulty@15|", + "|block.gaslimit@16|", + "|asset@17|", + "|__balance@18|", + "|__code_epoch@19|", + "|_asset@20|", + "|g@21|" + ], + "lean": "SolarVerifyVc.Vault.constructor.script0", + "smt": "Vault/constructor.script0.smt2" + } + ], + "status": "verified" + }, + { + "module": "Vault/deposit.lean", + "name": "Vault.deposit", + "namespace": "SolarVerifyVc.Vault.deposit", + "obligations": [ + { + "answer": "unsat", + "asserts": 27, + "commands": 57, + "goal": "true", + "guard": "|g@29|", + "id": "Vault.deposit#0", + "lean": "SolarVerifyVc.Vault.deposit.ob0", + "required": true, + "role": "side", + "script": 0, + "smt_sha256": "1bb13ffa737fca394f363c54a28e6230cbb4cfd769d2e2597c6707db6751f5e9", + "solver": "z3" + }, + { + "answer": "sat", + "asserts": 38, + "commands": 80, + "goal": "false", + "guard": "|g@41|", + "id": "Vault.deposit#1", + "lean": "SolarVerifyVc.Vault.deposit.ob1", + "required": false, + "role": "advisory", + "script": 0, + "smt_sha256": "298965751598e4d2a186c287e1401a935a5127ccea2ef00d9a5c7039e7082cf5", + "solver": "z3" + }, + { + "answer": "unsat", + "asserts": 40, + "commands": 82, + "goal": "(= (select |shares@42| |msg.sender@2|) (+ (select |shares@21| |msg.sender@2|) |amount@25|))", + "guard": "|g@41|", + "id": "Vault.deposit#2", + "kind": "postcondition not satisfied", + "lean": "SolarVerifyVc.Vault.deposit.ob2", + "required": true, + "role": "obligation", + "script": 0, + "site": { + "column": 10, + "file": "crates/verify/examples/Vault.sol", + "line": 33 + }, + "smt_sha256": "43c09697a2aba1cf1ac56b6328745301a9db8423ecb22680ebdbc7fa2583a9dc", + "solver": "z3", + "spec": { + "column": 10, + "file": "crates/verify/examples/Vault.sol", + "line": 33, + "text": "shares[msg.sender] == old(shares[msg.sender]) + amount" + } + }, + { + "answer": "unsat", + "asserts": 40, + "commands": 82, + "goal": "(not false)", + "guard": "|g@41|", + "id": "Vault.deposit#3", + "kind": "postcondition not satisfied", + "lean": "SolarVerifyVc.Vault.deposit.ob3", + "required": true, + "role": "obligation", + "script": 0, + "site": { + "column": 10, + "file": "crates/verify/examples/Vault.sol", + "line": 34 + }, + "smt_sha256": "502e56422a7eb88762cb36aaf99ff065e45e3c9f3c8aa94f4c9caf06ffe86fb7", + "solver": "z3", + "spec": { + "column": 10, + "file": "crates/verify/examples/Vault.sol", + "line": 34, + "text": "!locked" + } + }, + { + "answer": "unsat", + "asserts": 40, + "commands": 82, + "goal": "(= |arith@37| |sumShares@39|)", + "guard": "|g@41|", + "id": "Vault.deposit#4", + "kind": "contract invariant not preserved", + "lean": "SolarVerifyVc.Vault.deposit.ob4", + "required": true, + "role": "obligation", + "script": 0, + "site": { + "column": 5, + "file": "crates/verify/examples/Vault.sol", + "line": 35 + }, + "smt_sha256": "d240866e7adba02c2d167d110e95694e9e8d4fbae70f3161f60bd3fb907e7621", + "solver": "z3", + "spec": { + "column": 6, + "file": "crates/verify/examples/Vault.sol", + "line": 12, + "text": "totalShares == sumShares" + } + }, + { + "answer": "unsat", + "asserts": 40, + "commands": 82, + "goal": "(<= |arith@37| |arith@35|)", + "guard": "|g@41|", + "id": "Vault.deposit#5", + "kind": "contract invariant not preserved", + "lean": "SolarVerifyVc.Vault.deposit.ob5", + "required": true, + "role": "obligation", + "script": 0, + "site": { + "column": 5, + "file": "crates/verify/examples/Vault.sol", + "line": 35 + }, + "smt_sha256": "31d1668788e1beb06c7486ae834e50bba336d7f221b3510a921101d0d75ccef5", + "solver": "z3", + "spec": { + "column": 6, + "file": "crates/verify/examples/Vault.sol", + "line": 13, + "text": "totalShares <= totalAssets" + } + }, + { + "answer": "unsat", + "asserts": 25, + "commands": 53, + "goal": "true", + "guard": "|g@69|", + "id": "Vault.deposit#6", + "lean": "SolarVerifyVc.Vault.deposit.ob6", + "required": true, + "role": "side", + "script": 1, + "smt_sha256": "96336f40e2b3e9767e82579f08cbdff75976151a531f72d566b25e72124c3c2a", + "solver": "z3" + }, + { + "answer": "unsat", + "asserts": 36, + "commands": 76, + "goal": "false", + "guard": "|g@81|", + "id": "Vault.deposit#7", + "kind": "entry point does not revert while reentrancy guard `locked` is held", + "lean": "SolarVerifyVc.Vault.deposit.ob7", + "required": true, + "role": "obligation", + "script": 1, + "site": { + "column": 5, + "file": "crates/verify/examples/Vault.sol", + "line": 35 + }, + "smt_sha256": "97b1ef4bdf747896c6021c3e7822679cfe8502b8db97a1eb8770ec12d32aa602", + "solver": "z3", + "spec": null + } + ], + "scripts": [ + { + "commands": 82, + "decls": [ + "|this@1|", + "|msg.sender@2|", + "|msg.value@3|", + "|block.timestamp@4|", + "|block.number@5|", + "|block.chainid@6|", + "|tx.origin@7|", + "|tx.gasprice@8|", + "|msg.sig@9|", + "|msg.data@10|", + "|block.basefee@11|", + "|block.blobbasefee@12|", + "|block.coinbase@13|", + "|block.prevrandao@14|", + "|block.difficulty@15|", + "|block.gaslimit@16|", + "|sumShares@17|", + "|asset@18|", + "|totalShares@19|", + "|totalAssets@20|", + "|shares@21|", + "|locked@22|", + "|__balance@23|", + "|__code_epoch@24|", + "|amount@25|", + "|g@26|", + "|g@27|", + "|g@28|", + "|g@29|", + "|__code_epoch@30|", + "|__balance@31|", + "|g@32|", + "|ext_ret@33|", + "|g@34|", + "|arith@35|", + "|g@36|", + "|arith@37|", + "|g@38|", + "|sumShares@39|", + "|arith@40|", + "|g@41|", + "|shares@42|" + ], + "lean": "SolarVerifyVc.Vault.deposit.script0", + "smt": "Vault/deposit.script0.smt2" + }, + { + "commands": 76, + "decls": [ + "|this@43|", + "|msg.sender@44|", + "|msg.value@45|", + "|block.timestamp@46|", + "|block.number@47|", + "|block.chainid@48|", + "|tx.origin@49|", + "|tx.gasprice@50|", + "|msg.sig@51|", + "|msg.data@52|", + "|block.basefee@53|", + "|block.blobbasefee@54|", + "|block.coinbase@55|", + "|block.prevrandao@56|", + "|block.difficulty@57|", + "|block.gaslimit@58|", + "|sumShares@59|", + "|asset@60|", + "|totalShares@61|", + "|totalAssets@62|", + "|shares@63|", + "|locked@64|", + "|__balance@65|", + "|__code_epoch@66|", + "|amount@67|", + "|g@68|", + "|g@69|", + "|__code_epoch@70|", + "|__balance@71|", + "|g@72|", + "|ext_ret@73|", + "|g@74|", + "|arith@75|", + "|g@76|", + "|arith@77|", + "|g@78|", + "|sumShares@79|", + "|arith@80|", + "|g@81|", + "|shares@82|" + ], + "lean": "SolarVerifyVc.Vault.deposit.script1", + "smt": "Vault/deposit.script1.smt2" + } + ], + "status": "verified" + }, + { + "module": "Vault/withdraw.lean", + "name": "Vault.withdraw", + "namespace": "SolarVerifyVc.Vault.withdraw", + "obligations": [ + { + "answer": "unsat", + "asserts": 37, + "commands": 75, + "goal": "(and (= |arith@35| |sumShares@34|) (<= |arith@35| |arith@37|))", + "guard": "|g@38|", + "id": "Vault.withdraw#0", + "kind": "assertion failed", + "lean": "SolarVerifyVc.Vault.withdraw.ob0", + "required": true, + "role": "obligation", + "script": 0, + "site": { + "column": 14, + "file": "crates/verify/examples/Vault.sol", + "line": 52 + }, + "smt_sha256": "1252b739085b0777efae91e71682c72aea3adcc162f5f042167c7ca2f10b17a7", + "solver": "z3", + "spec": { + "column": 14, + "file": "crates/verify/examples/Vault.sol", + "line": 52, + "text": "totalShares == sumShares && totalShares <= totalAssets" + } + }, + { + "answer": "unsat", + "asserts": 39, + "commands": 79, + "goal": "true", + "guard": "|g@39|", + "id": "Vault.withdraw#1", + "lean": "SolarVerifyVc.Vault.withdraw.ob1", + "required": true, + "role": "side", + "script": 0, + "smt_sha256": "d701c0d47a6853af394b695af44112daf8fe8eacdf48bfbb521c3d0cf529264c", + "solver": "z3" + }, + { + "answer": "sat", + "asserts": 41, + "commands": 85, + "goal": "false", + "guard": "|g@44|", + "id": "Vault.withdraw#2", + "lean": "SolarVerifyVc.Vault.withdraw.ob2", + "required": false, + "role": "advisory", + "script": 0, + "smt_sha256": "8c305b6846feade818b296c08020d0df18f059f6d7b87febd2fa6c372a9d60f7", + "solver": "z3" + }, + { + "answer": "unsat", + "asserts": 41, + "commands": 85, + "goal": "(not false)", + "guard": "|g@44|", + "id": "Vault.withdraw#3", + "kind": "postcondition not satisfied", + "lean": "SolarVerifyVc.Vault.withdraw.ob3", + "required": true, + "role": "obligation", + "script": 0, + "site": { + "column": 10, + "file": "crates/verify/examples/Vault.sol", + "line": 45 + }, + "smt_sha256": "5bbdce5d21562334b7321c071b7bdeee3531c6d507d3732b79f18781e81610fe", + "solver": "z3", + "spec": { + "column": 10, + "file": "crates/verify/examples/Vault.sol", + "line": 45, + "text": "!locked" + } + }, + { + "answer": "unsat", + "asserts": 41, + "commands": 85, + "goal": "(= |arith@35| |sumShares@34|)", + "guard": "|g@44|", + "id": "Vault.withdraw#4", + "kind": "contract invariant not preserved", + "lean": "SolarVerifyVc.Vault.withdraw.ob4", + "required": true, + "role": "obligation", + "script": 0, + "site": { + "column": 5, + "file": "crates/verify/examples/Vault.sol", + "line": 46 + }, + "smt_sha256": "bb349cd02022a8e7e21c04526b093b282ad13f4c280cc72689154a8bdfda81e6", + "solver": "z3", + "spec": { + "column": 6, + "file": "crates/verify/examples/Vault.sol", + "line": 12, + "text": "totalShares == sumShares" + } + }, + { + "answer": "unsat", + "asserts": 41, + "commands": 85, + "goal": "(<= |arith@35| |arith@37|)", + "guard": "|g@44|", + "id": "Vault.withdraw#5", + "kind": "contract invariant not preserved", + "lean": "SolarVerifyVc.Vault.withdraw.ob5", + "required": true, + "role": "obligation", + "script": 0, + "site": { + "column": 5, + "file": "crates/verify/examples/Vault.sol", + "line": 46 + }, + "smt_sha256": "db9c8d9b57a1c9be630a4a120d997b956b17a3b36e17b626230fb95922fa714a", + "solver": "z3", + "spec": { + "column": 6, + "file": "crates/verify/examples/Vault.sol", + "line": 13, + "text": "totalShares <= totalAssets" + } + }, + { + "answer": "unsat", + "asserts": 35, + "commands": 71, + "goal": "(and (= |arith@77| |sumShares@76|) (<= |arith@77| |arith@79|))", + "guard": "|g@80|", + "id": "Vault.withdraw#6", + "kind": "assertion failed", + "lean": "SolarVerifyVc.Vault.withdraw.ob6", + "required": true, + "role": "obligation", + "script": 1, + "site": { + "column": 14, + "file": "crates/verify/examples/Vault.sol", + "line": 52 + }, + "smt_sha256": "9a76d82676eeca0203f21ca31646bc50d18b6a2cb5048151957e039a57974d48", + "solver": "z3", + "spec": { + "column": 14, + "file": "crates/verify/examples/Vault.sol", + "line": 52, + "text": "totalShares == sumShares && totalShares <= totalAssets" + } + }, + { + "answer": "unsat", + "asserts": 37, + "commands": 75, + "goal": "true", + "guard": "|g@81|", + "id": "Vault.withdraw#7", + "lean": "SolarVerifyVc.Vault.withdraw.ob7", + "required": true, + "role": "side", + "script": 1, + "smt_sha256": "9fc0c8a347d0b5e7e0d4a61a94ff5518a3c81ca9f410bc8a019859df55d311e3", + "solver": "z3" + }, + { + "answer": "unsat", + "asserts": 39, + "commands": 81, + "goal": "false", + "guard": "|g@86|", + "id": "Vault.withdraw#8", + "kind": "entry point does not revert while reentrancy guard `locked` is held", + "lean": "SolarVerifyVc.Vault.withdraw.ob8", + "required": true, + "role": "obligation", + "script": 1, + "site": { + "column": 5, + "file": "crates/verify/examples/Vault.sol", + "line": 46 + }, + "smt_sha256": "b45831738ad0a31289afbaf330f5e0f6f7f55eec0759397684871a31b4e3f869", + "solver": "z3", + "spec": null + } + ], + "scripts": [ + { + "commands": 85, + "decls": [ + "|this@1|", + "|msg.sender@2|", + "|msg.value@3|", + "|block.timestamp@4|", + "|block.number@5|", + "|block.chainid@6|", + "|tx.origin@7|", + "|tx.gasprice@8|", + "|msg.sig@9|", + "|msg.data@10|", + "|block.basefee@11|", + "|block.blobbasefee@12|", + "|block.coinbase@13|", + "|block.prevrandao@14|", + "|block.difficulty@15|", + "|block.gaslimit@16|", + "|sumShares@17|", + "|asset@18|", + "|totalShares@19|", + "|totalAssets@20|", + "|shares@21|", + "|locked@22|", + "|__balance@23|", + "|__code_epoch@24|", + "|amount@25|", + "|g@26|", + "|g@27|", + "|g@28|", + "|g@29|", + "|g@30|", + "|arith@31|", + "|g@32|", + "|shares@33|", + "|sumShares@34|", + "|arith@35|", + "|g@36|", + "|arith@37|", + "|g@38|", + "|g@39|", + "|__code_epoch@40|", + "|__balance@41|", + "|g@42|", + "|ext_ret@43|", + "|g@44|" + ], + "lean": "SolarVerifyVc.Vault.withdraw.script0", + "smt": "Vault/withdraw.script0.smt2" + }, + { + "commands": 81, + "decls": [ + "|this@45|", + "|msg.sender@46|", + "|msg.value@47|", + "|block.timestamp@48|", + "|block.number@49|", + "|block.chainid@50|", + "|tx.origin@51|", + "|tx.gasprice@52|", + "|msg.sig@53|", + "|msg.data@54|", + "|block.basefee@55|", + "|block.blobbasefee@56|", + "|block.coinbase@57|", + "|block.prevrandao@58|", + "|block.difficulty@59|", + "|block.gaslimit@60|", + "|sumShares@61|", + "|asset@62|", + "|totalShares@63|", + "|totalAssets@64|", + "|shares@65|", + "|locked@66|", + "|__balance@67|", + "|__code_epoch@68|", + "|amount@69|", + "|g@70|", + "|g@71|", + "|g@72|", + "|arith@73|", + "|g@74|", + "|shares@75|", + "|sumShares@76|", + "|arith@77|", + "|g@78|", + "|arith@79|", + "|g@80|", + "|g@81|", + "|__code_epoch@82|", + "|__balance@83|", + "|g@84|", + "|ext_ret@85|", + "|g@86|" + ], + "lean": "SolarVerifyVc.Vault.withdraw.script1", + "smt": "Vault/withdraw.script1.smt2" + } + ], + "status": "verified" + } + ], + "version": 1 +} diff --git a/Loom.lean b/Loom.lean new file mode 100644 index 00000000..48e759e0 --- /dev/null +++ b/Loom.lean @@ -0,0 +1,12 @@ +import Loom.MonadUtil +import Loom.SpecMonad +import Loom.MonadAlgebras.Defs +import Loom.MonadAlgebras.Instances.Basic +import Loom.MonadAlgebras.Instances.StateT +import Loom.MonadAlgebras.Instances.ExceptT +import Loom.MonadAlgebras.Instances.ExceptTErr +import Loom.MonadAlgebras.Instances.ReaderT +import Loom.MonadAlgebras.Instances.Gen +import Loom.MonadAlgebras.WP.Basic +import Loom.MonadAlgebras.WP.Liberal +import Loom.MonadAlgebras.WP.Variant diff --git a/vendor/loom/LICENSE b/Loom/LICENSE similarity index 100% rename from vendor/loom/LICENSE rename to Loom/LICENSE diff --git a/vendor/loom/Loom/MonadAlgebras/Defs.lean b/Loom/MonadAlgebras/Defs.lean similarity index 100% rename from vendor/loom/Loom/MonadAlgebras/Defs.lean rename to Loom/MonadAlgebras/Defs.lean diff --git a/Loom/MonadAlgebras/Instances/Basic.lean b/Loom/MonadAlgebras/Instances/Basic.lean new file mode 100644 index 00000000..25af5d15 --- /dev/null +++ b/Loom/MonadAlgebras/Instances/Basic.lean @@ -0,0 +1,123 @@ +import Loom.MonadAlgebras.Defs +universe u v w + +instance : MAlgOrdered Id Prop where + μ := id + μ_ord_pure := by simp [pure] + μ_ord_bind := by solve_by_elim + +instance : MAlgDet Id Prop where + demonic := by + intros α c p q; + simp [MAlg.lift, MAlg.μ, MAlgOrdered.μ] + solve_by_elim + angelic := by + intros α c p q; + simp [MAlg.lift, MAlg.μ, MAlgOrdered.μ] + solve_by_elim + +inductive DivM (α : Type u) where + | res (x : α) + | div + +def DivM.run {α : Type u} [Inhabited α] : DivM α -> α + | DivM.res x => x + | DivM.div => default + +instance : Monad DivM where + pure := DivM.res + bind := fun x y => match x with + | DivM.res x => y x + | DivM.div => DivM.div + +class CCPOBot (m : Type u -> Type v) where + compBot {α} : m α + +class CCPOBotLawful (m : Type u -> Type v) [∀ α, Lean.Order.CCPO (m α)] [CCPOBot m] where + prop {α} : CCPOBot.compBot (m := m) (α := α) = Lean.Order.bot + +instance : LawfulMonad DivM := by + refine LawfulMonad.mk' _ ?_ ?_ ?_ + { introv; cases x <;> rfl } + { introv; rfl } + introv; cases x <;> rfl + +noncomputable instance : Lean.Order.CCPO (DivM α) := inferInstanceAs (Lean.Order.CCPO (Lean.Order.FlatOrder .div)) +/-- solidity-lean (Lean 4.35): the supremum of a chain of `DivM` is the flat order's. -/ +theorem DivM.csup_eq {α : Type u} (c : DivM α → Prop) (hc : Lean.Order.chain c) : + Lean.Order.CCPO.csup hc = Lean.Order.flat_csup (b := (DivM.div : DivM α)) c := + (Lean.Order.flat_csup_eq (b := (DivM.div : DivM α)) c hc).symm + +instance : CCPOBot DivM where + compBot := .div + +instance : CCPOBotLawful DivM where + prop {α} := by + show (DivM.div : DivM α) = Lean.Order.CCPO.csup (Lean.Order.chain_empty _) + rw [DivM.csup_eq] + simp [Lean.Order.flat_csup, Lean.Order.empty_chain]; rfl + +instance : Lean.Order.MonoBind DivM where + bind_mono_left := by + rintro _ _ (_|_) _ _ (_|_) <;> solve_by_elim + bind_mono_right := by + rintro _ _ (_|_) <;> solve_by_elim + +namespace PartialCorrectness + + +scoped instance : MAlgOrdered DivM Prop where + μ := fun x => match x with + | .res x => x + | .div => ⊤ + μ_ord_pure := by intro; rfl + μ_ord_bind {α} f g := by + rintro h (_|_) + · exact h _ + · exact le_refl _ + +scoped instance : MAlgDet DivM Prop where + demonic := by + rintro _ _ (_|_) <;> simp [MAlg.lift, MAlgOrdered.μ, Functor.map] + angelic := by + rintro _ _ (_|_) <;> simp [MAlg.lift, MAlgOrdered.μ, Functor.map] + +instance : MAlgPartial DivM where + csup_lift {α} chain := by + intro post hchain + erw [DivM.csup_eq] + simp only [Lean.Order.flat_csup] + split_ifs with ch + · exact iInf₂_le _ (Classical.choose_spec ch).1 + · exact fun _ => trivial + +instance : NoFailure DivM where + noFailure := by + rintro _ (_|_) <;> simp [MAlg.lift, MAlgOrdered.μ, Functor.map] + +end PartialCorrectness + +namespace TotalCorrectness + +scoped instance : MAlgOrdered DivM Prop where + μ := fun x => match x with + | .res x => ⌜x⌝ + | .div => ⊥ + μ_ord_pure := by intro l; show ⌜l⌝ = l; simp [LE.pure] + μ_ord_bind {α} f g := by + rintro h (_|_) + · exact h _ + · exact le_refl _ + +scoped instance : MAlgDet DivM Prop where + angelic := by + rintro _ _ (_|_) <;> simp [MAlg.lift, MAlgOrdered.μ, Functor.map, LE.pure] + demonic := by + rintro _ _ (_|_) <;> simp [MAlg.lift, MAlgOrdered.μ, Functor.map, LE.pure] + +instance : MAlgTotal DivM where + bot_lift {α} post := by + rw [← CCPOBotLawful.prop (m := DivM)] + exact fun h => h + +end TotalCorrectness diff --git a/Loom/MonadAlgebras/Instances/ExceptT.lean b/Loom/MonadAlgebras/Instances/ExceptT.lean new file mode 100644 index 00000000..7ca79332 --- /dev/null +++ b/Loom/MonadAlgebras/Instances/ExceptT.lean @@ -0,0 +1,150 @@ +import Loom.MonadAlgebras.Defs +import Loom.MonadAlgebras.Instances.Basic + +abbrev Except.getD {ε α} (default : ε -> α) : Except ε α -> α + | Except.ok p => p + | Except.error e => default e + +abbrev Except.bind' {m : Type u -> Type v} {ε α β} [Monad m] : Except ε α -> (α -> ExceptT ε m β) -> ExceptT ε m β := + fun x f => bind (m := ExceptT ε m) (pure (f := m) x) f + +lemma Except.bind'_bind {m : Type u -> Type v} {ε α β} [Monad m] [LawfulMonad m] (i : m (Except ε α)) (f : α -> ExceptT ε m β) : + (i >>= fun a => Except.bind' a f) = bind (m := ExceptT ε m) i f := by + simp [Except.bind', bind, ExceptT.bind]; rfl + +/- Ordered Monad Algebra instance for ExceptT -/ +noncomputable +def MAlgExcept (ε : Type u) (df : ε -> Prop) (l : Type u) (m : Type u -> Type v) + [CompleteLattice l] + [Monad m] [LawfulMonad m] [inst: MAlgOrdered m l] : MAlgOrdered (ExceptT ε m) l where + μ := fun e => inst.μ $ Except.getD (⌜df ·⌝) <$> e + μ_ord_pure := by + intro l + show inst.μ (Except.getD (⌜df ·⌝) <$> (pure (Except.ok l) : m _)) = l + rw [map_pure]; exact MAlgOrdered.μ_ord_pure _ + μ_ord_bind := by + intro α f g le x + have leM := inst.μ_ord_bind (α := Except ε α) + (fun x => Except.getD (⌜df ·⌝) <$> Except.bind' x f) + (fun x => Except.getD (⌜df ·⌝) <$> Except.bind' x g) ?_ x + · simp only [← map_bind, Except.bind'_bind] at leM; exact leM + · rintro (e | p) + · show inst.μ (Except.getD (⌜df ·⌝) <$> (ExceptT.mk (pure (Except.error e) >>= ExceptT.bindCont f) : m _)) ≤ + inst.μ (Except.getD (⌜df ·⌝) <$> (ExceptT.mk (pure (Except.error e) >>= ExceptT.bindCont g) : m _)) + simp only [ExceptT.mk, pure_bind, ExceptT.bindCont]; exact le_refl _ + · show inst.μ (Except.getD (⌜df ·⌝) <$> (ExceptT.mk (pure (Except.ok p) >>= ExceptT.bindCont f) : m _)) ≤ + inst.μ (Except.getD (⌜df ·⌝) <$> (ExceptT.mk (pure (Except.ok p) >>= ExceptT.bindCont g) : m _)) + simp only [ExceptT.mk, pure_bind, ExceptT.bindCont]; exact le p + +section ExeceptHandler + +variable (ε : Type u) (l : Type u) (m : Type u -> Type v) [Monad m] [LawfulMonad m] + +class IsHandler {ε : Type*} (handler : outParam (ε -> Prop)) where + +set_option linter.unusedVariables false in +noncomputable +instance OfHd {hd : ε -> Prop} [hdInst : IsHandler hd] + [CompleteLattice l] [inst: MAlgOrdered m l] : MAlgOrdered (ExceptT ε m) l := MAlgExcept ε hd l m + + +lemma MAlg.lift_ExceptT ε (hd : ε -> Prop) [IsHandler hd] [CompleteLattice l] [inst: MAlgOrdered m l] + (c : ExceptT ε m α) post : + MAlg.lift c post = MAlg.lift (m := m) c (fun | .ok x => post x | .error e => ⌜hd e⌝) := by + show MAlgOrdered.μ (Except.getD (⌜hd ·⌝) <$> (ExceptT.map post c : m _)) = + MAlgOrdered.μ ((fun (r : Except ε α) => match r with + | .ok x => post x | .error e => ⌜hd e⌝) <$> (c : m _)) + simp only [ExceptT.map, ExceptT.mk, map_bind] + rw [map_eq_pure_bind]; apply MAlgOrdered.bind; funext a; cases a <;> simp [Except.getD] + + +instance MAlgExceptHdDet (hd : ε -> Prop) + [CompleteLattice l] [inst: MAlgOrdered m l] [IsHandler hd] + [inst': MAlgDet m l] : MAlgDet (ExceptT ε m) l where + angelic := by + intro α ι c p _ + have h := inst'.angelic (α := Except ε α) (c := c) + (p := fun i e => match e with + | Except.ok a => p i a + | Except.error e => ⌜hd e⌝) + simp only [MAlg.lift_ExceptT (l := l) (m := m) (hd := hd)] + refine le_trans (le_of_eq ?_) (le_trans h (le_of_eq ?_)) + · congr 1; funext e; cases e <;> simp [iSup_const] + · congr 1; funext i; congr 1; funext e; cases e <;> rfl + demonic := by + intro α ι c p _ + have h := inst'.demonic (α := Except ε α) (c := c) + (p := fun i e => match e with + | Except.ok a => p i a + | Except.error e => ⌜hd e⌝) + simp only [MAlg.lift_ExceptT (l := l) (m := m) (hd := hd)] + refine le_trans (le_of_eq ?_) (le_trans h (le_of_eq ?_)) + · congr 1; funext i; congr 1; funext e; cases e <;> rfl + · congr 1; funext e; cases e <;> simp [iInf_const] + +instance + [CompleteLattice l] [inst: MAlgOrdered m l] [IsHandler (fun (_ : ε) => True)] + [inst': NoFailure m] : NoFailure (ExceptT ε m) where + noFailure := by + intro α c + rw [MAlg.lift_ExceptT (l := l) (m := m) (hd := fun _ => True)] + rw (occs := [2]) [← inst'.noFailure (c := c)] + congr 1; funext e; cases e <;> simp [LE.pure] + +/- Monad Transformer Algebra instance for ExceptT -/ +noncomputable +instance [Monad m] [LawfulMonad m] [_root_.CompleteLattice l] + [IsHandler (ε := ε) hd] + [inst: MAlgOrdered m l] : + MAlgLift m l (ExceptT ε m) l where + cl := by exact LogicLift.refl + μ_lift := by + intro α f x + rw [MAlg.lift_ExceptT (l := l) (m := m) (hd := hd)] + show MAlgOrdered.μ (_ <$> (Except.ok <$> x : m _)) = MAlgOrdered.μ (f <$> x) + rw [Functor.map_map] + +end ExeceptHandler + +namespace ExceptionAsSuccess +scoped instance PartialHandler {ε} : IsHandler (ε := ε) fun _ => True where +end ExceptionAsSuccess + +namespace ExceptionAsFailure +scoped instance TotalHandler {ε} : IsHandler (ε := ε) fun _ => False where +end ExceptionAsFailure + +open Lean.Order + +instance [Monad m] [inst : ∀ α, CCPO (m α)] : CCPO (ExceptT ε m α) := inst _ +instance [Monad m] [∀ α, CCPO (m α)] [MonoBind m] : MonoBind (ExceptT ε m) where + bind_mono_left h₁₂ := by + apply MonoBind.bind_mono_left (m := m) + exact h₁₂ + bind_mono_right h₁₂ := by + apply MonoBind.bind_mono_right (m := m) + intro x + cases x + · apply PartialOrder.rel_refl + · apply h₁₂ + +instance [Monad m] [CCPOBot m] : CCPOBot (ExceptT ε m) where + compBot := CCPOBot.compBot (m := m) + +instance [Monad m] [inst : ∀ α, Lean.Order.CCPO (m α)] [CCPOBot m] [CCPOBotLawful m] : CCPOBotLawful (ExceptT ε m) where + prop := CCPOBotLawful.prop (m := m) + +instance (hd : ε -> _) [IsHandler hd] [_root_.CompleteLattice l] [Monad m] [LawfulMonad m] [inst: MAlgOrdered m l] + [∀ α, CCPO (m α)] [MonoBind m] + [MAlgPartial m] : MAlgPartial (ExceptT ε m) where + csup_lift {α} chain := by + intro post hchain; simp [MAlg.lift_ExceptT] + solve_by_elim [MAlgPartial.csup_lift (m := m)] + +attribute [-simp] le_bot_iff in +instance (hd : ε -> _) [IsHandler hd] [_root_.CompleteLattice l] [Monad m] [LawfulMonad m] [inst: MAlgOrdered m l] + [∀ α, CCPO (m α)] [MonoBind m] + [MAlgTotal m] : MAlgTotal (ExceptT ε m) where + bot_lift := by + intro post hchain; simp [MAlg.lift_ExceptT] + solve_by_elim [MAlgTotal.bot_lift (m := m)] diff --git a/Loom/MonadAlgebras/Instances/ExceptTErr.lean b/Loom/MonadAlgebras/Instances/ExceptTErr.lean new file mode 100644 index 00000000..2830a940 --- /dev/null +++ b/Loom/MonadAlgebras/Instances/ExceptTErr.lean @@ -0,0 +1,102 @@ +import Loom.MonadAlgebras.Instances.ExceptT +import Loom.MonadAlgebras.Instances.StateT + +/-! +# An error-aware algebra for `ExceptT` + +Loom's `ExceptT` algebra (`MAlgExcept`) fixes, by a handler, what an exception means: +`ε → Prop` once and for all. Here the assertion instead takes the predicate an exception must +meet as an argument: over an algebra of `m` on `l`, `ExceptT ε m` has an ordered algebra on +`(ε → l) → l`. Its weakest precondition, given `herr`, is the weakest precondition of `m` +for the postcondition on a result and `herr` on an exception, so one weakest precondition +covers both outcomes, which is what a specification of a reverting call needs. + +The same construction is given directly for `Except ε`, the monad of a state program that +fails with data (`StateT σ (Except ε)`), whose assertions are then, by Loom's `StateT` +algebra, `σ → (ε → Prop) → Prop`. +-/ + +universe u v + +section ExceptTErr + +variable {ε : Type u} {l : Type u} {m : Type u → Type v} [Monad m] [LawfulMonad m] + [CompleteLattice l] [inst : MAlgOrdered m l] + +/-- What an outcome means for an error-aware assertion, given the exception predicate. -/ +def Except.errAssn (herr : ε → l) : Except ε ((ε → l) → l) → l + | .ok p => p herr + | .error e => herr e + +/-- The error-aware ordered algebra of `ExceptT ε m` on `(ε → l) → l`. -/ +noncomputable def MAlgExceptErr : MAlgOrdered (ExceptT ε m) ((ε → l) → l) where + μ x := fun herr => inst.μ (Except.errAssn herr <$> (x : m _)) + μ_ord_pure := by + intro p; funext herr + show inst.μ (Except.errAssn herr <$> (pure (Except.ok p) : m _)) = p herr + rw [map_pure]; exact MAlgOrdered.μ_ord_pure _ + μ_ord_bind := by + intro α f g hfg x herr + show inst.μ (Except.errAssn herr <$> ((x : m (Except ε α)) >>= ExceptT.bindCont f)) ≤ + inst.μ (Except.errAssn herr <$> ((x : m (Except ε α)) >>= ExceptT.bindCont g)) + rw [map_bind, map_bind] + apply inst.μ_ord_bind + rintro (e | a) + · exact le_refl _ + · exact hfg a herr + +attribute [local instance] MAlgExceptErr + +theorem MAlgExceptErr.lift_eq (c : ExceptT ε m α) (post : α → (ε → l) → l) (herr : ε → l) : + MAlg.lift c post herr = + MAlg.lift (m := m) (c : m (Except ε α)) (fun | .ok a => post a herr | .error e => herr e) := by + show inst.μ (Except.errAssn herr <$> (ExceptT.map post c : m _)) = inst.μ (_ <$> (c : m _)) + simp only [ExceptT.map, ExceptT.mk, map_bind] + rw [map_eq_pure_bind] + apply MAlgOrdered.bind; funext r; cases r <;> simp [Except.errAssn] + +end ExceptTErr + +/-! ## `Except ε` directly -/ + +section ExceptErr + +variable {ε : Type u} + +/-- What an outcome means for an error-aware assertion on `Prop`. -/ +def Except.errProp (herr : ε → Prop) : Except ε ((ε → Prop) → Prop) → Prop + | .ok p => p herr + | .error e => herr e + +/-- The error-aware ordered algebra of `Except ε` on `(ε → Prop) → Prop`. -/ +instance MAlgExceptErrProp : MAlgOrdered (Except ε) ((ε → Prop) → Prop) where + μ x := fun herr => Except.errProp herr x + μ_ord_pure := by intro p; rfl + μ_ord_bind := by + intro α f g hfg x herr + cases x with + | error e => exact le_refl _ + | ok a => exact hfg a herr + +theorem MAlgExceptErrProp.lift_eq (c : Except ε α) (post : α → (ε → Prop) → Prop) + (herr : ε → Prop) : + MAlg.lift c post herr = match c with + | .ok a => post a herr + | .error e => herr e := by + cases c <;> rfl + +instance : MAlgDet (Except ε) ((ε → Prop) → Prop) where + demonic := by + intro α ι c p _ herr + simp only [iInf_apply, MAlgExceptErrProp.lift_eq] + cases c with + | error e => simp + | ok a => simp + angelic := by + intro α ι c p _ herr + simp only [iSup_apply, MAlgExceptErrProp.lift_eq] + cases c with + | error e => simp + | ok a => simp + +end ExceptErr diff --git a/Loom/MonadAlgebras/Instances/Gen.lean b/Loom/MonadAlgebras/Instances/Gen.lean new file mode 100644 index 00000000..a3d1f8c2 --- /dev/null +++ b/Loom/MonadAlgebras/Instances/Gen.lean @@ -0,0 +1,19 @@ +import Loom.MonadAlgebras.Defs +import Loom.MonadAlgebras.Instances.Basic +import Loom.MonadAlgebras.Instances.ReaderT +import Loom.MonadAlgebras.Instances.StateT +import Plausible.Gen + +open Plausible + +universe u + +-- TODO: Fix this instance +/- Ordered Monad Algebra instance for Gen -/ +-- instance MAlgGenInst : MAlgOrdered Gen (ULift Nat -> ULift StdGen -> Prop) := +-- inferInstanceAs +-- (MAlgOrdered +-- (ReaderT (ULift Nat) +-- (StateT (ULift StdGen) Id)) +-- (ULift Nat -> +-- ULift StdGen -> Prop)) diff --git a/Loom/MonadAlgebras/Instances/ReaderT.lean b/Loom/MonadAlgebras/Instances/ReaderT.lean new file mode 100644 index 00000000..4a0a48e7 --- /dev/null +++ b/Loom/MonadAlgebras/Instances/ReaderT.lean @@ -0,0 +1,117 @@ +import Loom.MonadAlgebras.Defs +import Loom.MonadAlgebras.Instances.Basic + +/- Ordered Monad Algebra instance for ReaderT -/ +instance (σ : Type u) (l : Type u) (m : Type u -> Type v) + [CompleteLattice l] + [Monad m] [LawfulMonad m] [inst: MAlgOrdered m l] : MAlgOrdered (ReaderT σ m) (σ -> l) where + μ := fun rp r => inst.μ $ (· r) <$> rp r + μ_ord_pure := by + intros l; simp [pure, ReaderT.pure]; ext r + solve_by_elim [MAlgOrdered.μ_ord_pure] + μ_ord_bind := by + intro α f g le x r + have leM := inst.μ_ord_bind (α := α) (fun a => (fun y : σ → l => y r) <$> f a r) (fun a => (fun y : σ → l => y r) <$> g a r) + (fun a => le a r) (x r) + show MAlgOrdered.μ ((fun y : σ → l => y r) <$> (x r >>= fun a => f a r)) ≤ + MAlgOrdered.μ ((fun y : σ → l => y r) <$> (x r >>= fun a => g a r)) + rw [map_bind, map_bind]; exact leM + + +instance (σ : Type u) (l : Type u) (m : Type u -> Type v) + [CompleteLattice l] + [Monad m] [LawfulMonad m] [inst: MAlgOrdered m l] [inst': MAlgDet m l] + : MAlgDet (ReaderT σ m) (σ -> l) where + angelic := by + intros α ι c p _ s; + simp [MAlg.lift, MAlg.μ, MAlgOrdered.μ, Functor.map] + have h := inst'.angelic (α := α) (c := c s) (p := fun i x => p i x s) + simp [MAlg.lift, MAlg.μ] at h + apply h + demonic := by + intros α ι c p _ s; + simp [MAlg.lift, MAlg.μ, MAlgOrdered.μ, Functor.map] + have h := inst'.demonic (α := α) (c := c s) (p := fun i x => p i x s) + simp [MAlg.lift, MAlg.μ] at h + apply h + + +instance [Monad m] [inst : ∀ α, Lean.Order.CCPO (m α)] : Lean.Order.CCPO (ReaderT ε m α) := by + unfold ReaderT + infer_instance +instance [Monad m] [∀ α, Lean.Order.CCPO (m α)] [Lean.Order.MonoBind m] : Lean.Order.MonoBind (ReaderT ε m) where + bind_mono_left h₁₂ _ := by + simp [bind, ReaderT.bind] + apply Lean.Order.MonoBind.bind_mono_left (m := m) + apply h₁₂ + bind_mono_right h₁₂ _ := by + simp [bind] + apply Lean.Order.MonoBind.bind_mono_right (m := m) + intro x; apply h₁₂ + +/-- solidity-lean (Lean 4.35): the supremum of a chain of readers, at an environment, is the +supremum of their results there. -/ +theorem ReaderT.csup_apply [Monad m] [∀ α, Lean.Order.CCPO (m α)] {α : Type u} + (c : ReaderT ε m α → Prop) (hc : Lean.Order.chain c) (s : ε) : + (Lean.Order.CCPO.csup hc : ReaderT ε m α) s = + Lean.Order.CCPO.csup (Lean.Order.chain_apply (β := fun _ : ε => m α) hc s) := + congrFun (Lean.Order.fun_csup_eq (β := fun _ : ε => m α) c hc).symm s + +theorem ReaderT.bot_apply [Monad m] [∀ α, Lean.Order.CCPO (m α)] {α : Type u} (s : ε) : + (Lean.Order.bot : ReaderT ε m α) s = Lean.Order.bot := by + unfold Lean.Order.bot + rw [ReaderT.csup_apply] + apply Lean.Order.is_sup_unique (Lean.Order.CCPO.csup_spec _) + intro x; constructor + · intro _ y hy; obtain ⟨f, hf, _⟩ := hy; exact hf.elim + · intro _; apply Lean.Order.csup_le; intro y hy; exact hy.elim + +instance [Monad m] [CCPOBot m] : CCPOBot (ReaderT σ m) where + compBot := fun _ => CCPOBot.compBot + +instance [Monad m] [inst : ∀ α, Lean.Order.CCPO (m α)] [CCPOBot m] [CCPOBotLawful m] : CCPOBotLawful (ReaderT σ m) where + prop {α} := by + funext s + rw [ReaderT.bot_apply] + exact CCPOBotLawful.prop (m := m) + +lemma MAlg.lift_ReaderT [Monad m] [LawfulMonad m] [CompleteLattice l] [inst: MAlgOrdered m l] (x : ReaderT σ m α) : + MAlg.lift x post = fun s => MAlg.lift (x s) (fun xs => post xs s) := by + simp [MAlg.lift, Functor.map, MAlgOrdered.μ] + +open Lean.Order +instance [Monad m] [LawfulMonad m] [_root_.CompleteLattice l] [inst: MAlgOrdered m l] + [∀ α, CCPO (m α)] [MonoBind m] + [MAlgPartial m] : MAlgPartial (ReaderT σ m) where + csup_lift {α} chain := by + intro post hchain s + simp only [MAlg.lift_ReaderT, iInf_apply] + erw [ReaderT.csup_apply] + apply le_trans' (MAlgPartial.csup_lift (m := m) _ _ _) + refine le_iInf₂ ?_ + rintro y ⟨f, hf, rfl⟩ + exact iInf₂_le f hf + +attribute [-simp] le_bot_iff in +instance [Monad m] [LawfulMonad m] [_root_.CompleteLattice l] [inst: MAlgOrdered m l] + [∀ α, CCPO (m α)] [MonoBind m] + [MAlgTotal m] : MAlgTotal (ReaderT σ m) where + bot_lift {α} post := by + intro s + simp only [MAlg.lift_ReaderT] + rw [ReaderT.bot_apply] + exact MAlgTotal.bot_lift (m := m) _ + +instance [Monad m] [LawfulMonad m] [_root_.CompleteLattice l] [inst: MAlgOrdered m l] + [inst': NoFailure m] : NoFailure (ReaderT σ m) where + noFailure := by + intro _ _; simp [MAlg.lift_ReaderT, inst'.noFailure]; rfl + +/- Monad Transformer Algebra instance for ReaderT -/ +instance [Monad m] [LawfulMonad m] [_root_.CompleteLattice l] [inst: MAlgOrdered m l] : + MAlgLift m l (ReaderT σ m) (σ -> l) where + μ_lift := by + intro α f x + rw [MAlg.lift_ReaderT] + funext s + rfl diff --git a/Loom/MonadAlgebras/Instances/StateT.lean b/Loom/MonadAlgebras/Instances/StateT.lean new file mode 100644 index 00000000..98ee4e1d --- /dev/null +++ b/Loom/MonadAlgebras/Instances/StateT.lean @@ -0,0 +1,122 @@ +import Loom.MonadAlgebras.Defs +import Loom.MonadAlgebras.Instances.Basic + +/- Ordered Monad Algebra instance for StateT -/ +instance (σ : Type u) (l : Type u) (m : Type u -> Type v) + [CompleteLattice l] + [Monad m] [LawfulMonad m] [inst: MAlgOrdered m l] : MAlgOrdered (StateT σ m) (σ -> l) where + μ := (MAlgOrdered.μ $ (fun fs => fs.1 fs.2) <$> · ·) + μ_ord_pure := by + intro f; funext s₁ + show MAlgOrdered.μ ((fun fs : (σ → l) × σ => fs.1 fs.2) <$> (pure (f, s₁) : m _)) = f s₁ + rw [map_pure, MAlgOrdered.μ_ord_pure] + μ_ord_bind := by + intro α f g le x s + have leM := inst.μ_ord_bind (α := α × σ) + (fun as => (fun fs : (σ → l) × σ => fs.1 fs.2) <$> f as.1 as.2) + (fun as => (fun fs : (σ → l) × σ => fs.1 fs.2) <$> g as.1 as.2) + (fun as => le as.1 as.2) (x s) + show MAlgOrdered.μ ((fun fs : (σ → l) × σ => fs.1 fs.2) <$> (x s >>= fun p => f p.1 p.2)) ≤ + MAlgOrdered.μ ((fun fs : (σ → l) × σ => fs.1 fs.2) <$> (x s >>= fun p => g p.1 p.2)) + rw [map_bind, map_bind]; exact leM + +instance (σ : Type u) (l : Type u) (m : Type u -> Type v) + [CompleteLattice l] + [Monad m] [LawfulMonad m] [inst: MAlgOrdered m l] [inst': MAlgDet m l] + : MAlgDet (StateT σ m) (σ -> l) where + angelic := by + intros α ι c p _ s; + simp [MAlg.lift, MAlg.μ, MAlgOrdered.μ, Functor.map, StateT.map] + have h := inst'.angelic (α := α × σ) (c := c s) (ι := ι) (p := fun i x => p i x.1 x.2) + simp [MAlg.lift, MAlg.μ] at h + apply h + demonic := by + intros α ι c p _ s; + simp [MAlg.lift, MAlg.μ, MAlgOrdered.μ, Functor.map, StateT.map] + have h := inst'.demonic (α := α × σ) (c := c s) (ι := ι) (p := fun i x => p i x.1 x.2) + simp [MAlg.lift, MAlg.μ] at h + apply h + +instance [Monad m] [inst : ∀ α, Lean.Order.CCPO (m α)] : Lean.Order.CCPO (StateT ε m α) := by + unfold StateT + infer_instance +instance [Monad m] [∀ α, Lean.Order.CCPO (m α)] [Lean.Order.MonoBind m] : Lean.Order.MonoBind (StateT ε m) where + bind_mono_left h₁₂ _ := by + simp [bind, StateT.bind] + apply Lean.Order.MonoBind.bind_mono_left (m := m) + apply h₁₂ + bind_mono_right h₁₂ _ := by + simp [bind, StateT.bind] + apply Lean.Order.MonoBind.bind_mono_right (m := m) + intro x; apply h₁₂ + +/-- solidity-lean (Lean 4.35): the supremum of a chain of state transformers, at a state, is +the supremum of their results there; `CCPO.csup` is now a choice, so this replaces unfolding +it to `fun_csup`. -/ +theorem StateT.csup_apply [Monad m] [∀ α, Lean.Order.CCPO (m α)] {α : Type u} + (c : StateT ε m α → Prop) (hc : Lean.Order.chain c) (s : ε) : + (Lean.Order.CCPO.csup hc : StateT ε m α) s = + Lean.Order.CCPO.csup (Lean.Order.chain_apply (β := fun _ : ε => m (α × ε)) hc s) := + congrFun (Lean.Order.fun_csup_eq (β := fun _ : ε => m (α × ε)) c hc).symm s + +theorem StateT.bot_apply [Monad m] [∀ α, Lean.Order.CCPO (m α)] {α : Type u} (s : ε) : + (Lean.Order.bot : StateT ε m α) s = Lean.Order.bot := by + unfold Lean.Order.bot + rw [StateT.csup_apply] + apply Lean.Order.is_sup_unique (Lean.Order.CCPO.csup_spec _) + intro x; constructor + · intro _ y hy; obtain ⟨f, hf, _⟩ := hy; exact hf.elim + · intro _; apply Lean.Order.csup_le; intro y hy; exact hy.elim + +instance [Monad m] [CCPOBot m] : CCPOBot (StateT σ m) where + compBot := fun _ => CCPOBot.compBot + +instance [Monad m] [inst : ∀ α, Lean.Order.CCPO (m α)] [CCPOBot m] [CCPOBotLawful m] : CCPOBotLawful (StateT σ m) where + prop {α} := by + funext s + rw [StateT.bot_apply] + exact CCPOBotLawful.prop (m := m) + + +lemma MAlg.lift_StateT [Monad m] [LawfulMonad m] [CompleteLattice l] [inst: MAlgOrdered m l] (x : StateT σ m α) : + MAlg.lift x post = fun s => MAlg.lift (x s) (fun xs => post xs.1 xs.2) := by + simp [MAlg.lift, Functor.map, MAlgOrdered.μ, StateT.map] + +open Lean.Order +instance [Monad m] [LawfulMonad m] [_root_.CompleteLattice l] [inst: MAlgOrdered m l] + [∀ α, CCPO (m α)] [MonoBind m] + [MAlgPartial m] : MAlgPartial (StateT σ m) where + csup_lift {α} chain := by + intro post hchain s + simp only [MAlg.lift_StateT, iInf_apply] + erw [StateT.csup_apply] + apply le_trans' (MAlgPartial.csup_lift (m := m) _ _ _) + refine le_iInf₂ ?_ + rintro y ⟨f, hf, rfl⟩ + exact iInf₂_le f hf + +attribute [-simp] le_bot_iff in +instance [Monad m] [LawfulMonad m] [_root_.CompleteLattice l] [inst: MAlgOrdered m l] + [∀ α, CCPO (m α)] [MonoBind m] + [MAlgTotal m] : MAlgTotal (StateT σ m) where + bot_lift {α} post := by + intro s + simp only [MAlg.lift_StateT] + rw [StateT.bot_apply] + exact MAlgTotal.bot_lift (m := m) _ + +instance [Monad m] [LawfulMonad m] [_root_.CompleteLattice l] [inst: MAlgOrdered m l] + [inst': NoFailure m] : NoFailure (StateT σ m) where + noFailure := by + intro _ _; simp [MAlg.lift_StateT, inst'.noFailure]; rfl + +/- Monad Transformer Algebra instance for StateT -/ +instance [Monad m] [LawfulMonad m] [_root_.CompleteLattice l] [inst: MAlgOrdered m l] : + MAlgLift m l (StateT σ m) (σ -> l) where + μ_lift := by + intro α f x + rw [MAlg.lift_StateT] + funext s + show MAlg.lift (liftM (n := StateT σ m) x s) (fun xs => f xs.1 xs.2) = MAlg.lift x (f · s) + simp only [MAlg.lift, liftM, monadLift, MonadLift.monadLift, StateT.lift, map_bind, map_pure] + rw [map_eq_pure_bind] diff --git a/Loom/MonadAlgebras/WP/Basic.lean b/Loom/MonadAlgebras/WP/Basic.lean new file mode 100644 index 00000000..f52dd2ab --- /dev/null +++ b/Loom/MonadAlgebras/WP/Basic.lean @@ -0,0 +1,537 @@ +import Loom.MonadAlgebras.Defs + +import Loom.MonadAlgebras.Instances.Basic +import Loom.MonadAlgebras.Instances.ExceptT +import Loom.MonadAlgebras.Instances.StateT +import Loom.MonadAlgebras.Instances.ReaderT +import Loom.MonadAlgebras.Instances.Gen + +universe u v w + +variable {m : Type u -> Type v} [Monad m] [LawfulMonad m] {α : Type u} {l : Type u} + +section +variable [CompleteLattice l] +section +variable [mprop : MAlgOrdered m l] + +/- WP definition -/ +def wp (c : m α) (post : α -> l) : l := liftM (n := Cont l) c post +/- Hoare triple definition -/ +def triple (pre : l) (c : m α) (post : α -> l) : Prop := + pre ≤ wp c post + +/- WP of pure (defintion 4 from the paper) -/ +lemma wp_pure (x : α) (post : α -> l) : wp (m := m) (pure x) post = post x := by + simp [wp, liftM] + rfl + +/- WP of bind (defintion 5 from the paper) -/ +lemma triple_pure (pre : l) (x : α) (post : α -> l) : + triple pre (pure (f := m) x) post <-> pre ≤ (post x) + := by + rw [triple, wp]; simp [liftM]; rfl + +end + +variable [MAlgOrdered m l] + +lemma wp_bind {β} (x : m α) (f : α -> m β) (post : β -> l) : + wp (x >>= f) post = wp x (fun x => wp (f x) post) := by + simp [wp, liftM]; rfl + +lemma wp_map {β} (x : m α) (f : α -> β) (post : β -> l) : + wp (f <$> x) post = wp x (fun x => post (f x)) := by + rw [map_eq_pure_bind, wp_bind]; simp [wp_pure] + +/- monotonicity for WP (definition 9 from the paper) -/ +lemma wp_cons (x : m α) (post post' : α -> l) : + (∀ y, post y ≤ post' y) -> + wp x post ≤ wp x post' := by + intros h; simp [wp, liftM, monadLift]; apply Cont.monotone_lift; intros y + apply h + +lemma triple_cons (x : m α) {pre pre' : l} {post post' : α -> l} : + pre' ≤ pre -> + (∀ y, post y ≤ post' y) -> + triple pre x post -> + triple pre' x post' := by + intros hpre hpost h + apply le_trans'; apply wp_cons; apply hpost + solve_by_elim [le_trans] + +lemma triple_bind {β} (pre : l) (x : m α) (cut : α -> l) + (f : α -> m β) (post : β -> l) : + triple pre x cut -> + (∀ y, triple (cut y) (f y) post) -> + triple pre (x >>= f) post := by + intros; simp [triple, wp_bind] + solve_by_elim [le_trans', wp_cons] + +omit [LawfulMonad m] in +@[simp] +lemma wp_top (c : m α) [NoFailure m] : + wp c (fun _ => ⊤) = ⊤ := by + simp [wp, liftM, monadLift, NoFailure.noFailure] + +end + +section +variable [CompleteLattice l] [MAlgOrdered m l] + +noncomputable +def spec (pre : l) (post : α -> l) : Cont l α := + fun p => pre ⊓ ⌜post ≤ p⌝ + +lemma triple_spec (pre : l) (c : m α) (post : α -> l) : + spec pre post <= wp c <-> + triple pre c post := by + constructor + { intro h; unfold triple + specialize h post; apply le_trans'; apply h + unfold spec; simp [trueE] } + intro t p; unfold spec + by_cases h: post ≤ p + { apply inf_le_of_left_le; apply le_trans; apply t + solve_by_elim [Cont.monotone_lift (x := c)] } + have : (post ≤ p) = False := by simp [h] + simp [this, falseE] + +end + +section Determinism + +variable [inst: CompleteLattice l] [MAlgOrdered m l] + +lemma wp_iInf {ι : Type u} [Nonempty ι] [MAlgDet m l] (c : m α) (post : ι -> α -> l) : + wp c (fun x => ⨅ i, post i x) = ⨅ i, wp c (post i) := by + apply le_antisymm + { refine le_iInf ?_; intros i; apply wp_cons; intro y + exact iInf_le (fun i ↦ post i y) i } + apply MAlgDet.demonic + +lemma wp_and [MAlgDet m l] (c : m α) (post₁ post₂ : α -> l) : + wp c (fun x => post₁ x ⊓ post₂ x) = wp c post₁ ⊓ wp c post₂ := by + apply le_antisymm + { simp; constructor <;> apply wp_cons <;> simp } + have h := MAlgDet.demonic (l := l) (ι := ULift Bool) (c := c) (p := fun | .up true => post₁ | .up false => post₂) + simp at h + apply le_trans; apply le_trans'; apply h + { simp [wp]; constructor; exact inf_le_right + exact inf_le_left } + apply wp_cons (m := m); simp; intros; constructor + { refine iInf_le_of_le true ?_; simp } + refine iInf_le_of_le false ?_; simp + +lemma wp_iSup {ι : Type u} [Nonempty ι] [MAlgDet m l] (c : m α) (post : ι -> α -> l) : + wp c (fun x => ⨆ i, post i x) = ⨆ i, wp c (post i) := by + apply le_antisymm + { apply MAlgDet.angelic } + refine iSup_le ?_; intros i; apply wp_cons; intro y + exact le_iSup (fun i ↦ post i y) i + + +lemma wp_or [MAlgDet m l] (c : m α) (post₁ post₂ : α -> l) : + wp c (fun x => post₁ x ⊔ post₂ x) = wp c post₁ ⊔ wp c post₂ := by + apply le_antisymm + { have h := MAlgDet.angelic (l := l) (ι := ULift Bool) (c := c) (p := fun | .up true => post₁ | .up false => post₂) + simp [-iSup_le_iff] at h + apply le_trans; apply le_trans'; apply h + { apply wp_cons (m := m); simp; intros; constructor + { refine le_iSup_of_le true ?_; simp } + refine le_iSup_of_le false ?_; simp } + simp [wp]; constructor; exact le_sup_right + exact le_sup_left } + simp; constructor <;> apply wp_cons <;> simp + + +end Determinism + + +section Loops + +open Lean.Order + +/- partial loop from MonoBind and CCPO instances -/ +@[specialize, inline] +def Loop.forIn.loop {m : Type u -> Type v} [Monad m] [∀ α, CCPO (m α)] [MonoBind m] (f : Unit → β → m (ForInStep β)) (b : β) : m β := do + match ← f () b with + | ForInStep.done b => pure b + | ForInStep.yield b => loop f b + partial_fixpoint + +@[inline] +def Loop.forIn {β : Type u} [Monad m] [∀ α, CCPO (m α)] [MonoBind m] + (_ : Lean.Loop) (init : β) (f : Unit → β → m (ForInStep β)) : m β := + Loop.forIn.loop f init + +@[instance high] +instance [md : Monad m] [ccpo : ∀ α, CCPO (m α)] [mono : MonoBind m] : ForIn m Lean.Loop Unit where + forIn {β} := @Loop.forIn m β md ccpo mono + +variable [inst: _root_.CompleteLattice l] [MAlgOrdered m l] + +namespace PartialCorrectness + +variable [∀ α, CCPO (m α)] [MonoBind m] [MAlgPartial m] + +omit [MonoBind m] [LawfulMonad m] in +lemma wp_csup (xc : Set (m α)) (post : α -> l) (hc : Lean.Order.chain xc) : + ⨅ c ∈ xc, wp c post ≤ wp (Lean.Order.CCPO.csup hc) post := by + apply MAlgPartial.csup_lift + +omit [MonoBind m] [LawfulMonad m] in +lemma wp_bot : + wp (bot : m α) = fun _ => (⊤ : l) := by + ext post; refine eq_top_iff.mpr ?_ + apply le_trans' (wp_csup (empty_chain (m α)) post (chain_empty _)) + refine le_iInf₂ ?_ + intro _ h; exact h.elim + +lemma repeat_inv (f : Unit -> β -> m (ForInStep β)) + (inv : ForInStep β -> l) + init : + (∀ b, triple (inv (.yield b)) (f () b) (inv)) -> + triple (inv (.yield init)) (Loop.forIn.loop f init) (fun b => inv (.done b)) := by + intro hstep + revert init + apply Loop.forIn.loop.fixpoint_induct (f := f) (motive := + fun loop => ∀ init, triple (inv (.yield init)) (loop init) (fun b =>inv (.done b))) + { apply Lean.Order.admissible_pi_apply + (P := fun init loop => triple (inv (.yield init)) (loop) (fun b =>inv (.done b))) + intro init loops cl h + simp only [triple] at h ⊢ + apply le_trans' (wp_csup _ _ cl) + exact le_iInf₂ h } + intro loop ih init; simp [triple, wp_bind]; apply le_trans; apply hstep + apply wp_cons; rintro (_|_); simp [wp_pure] + apply ih + +lemma repeat_inv_split (f : Unit -> β -> m (ForInStep β)) + (inv : β -> l) (doneWith : β -> l) + init : + (∀ b, triple (inv b) (f () b) (fun | .yield b' => inv b' | .done b' => inv b' ⊓ doneWith b')) -> + triple (inv init) (Loop.forIn.loop f init) (fun b => inv b ⊓ doneWith b) := by + intro hstep + apply repeat_inv f (fun | .yield b => inv b | .done b => inv b ⊓ doneWith b) init + apply hstep + +end PartialCorrectness + +namespace TotalCorrectness + +variable [∀ α, CCPO (m α)] [MonoBind m] + +lemma repeat_inv (f : Unit -> β -> m (ForInStep β)) + (inv : ForInStep β -> l) (measure : β -> Nat) + init : + (∀ b, triple (inv (.yield b)) (f () b) (fun | .yield b' => inv (.yield b') ⊓ ⌜ measure b' < measure b ⌝ | .done b' => inv (.done b'))) -> + triple (inv (.yield init)) (Loop.forIn.loop f init) (fun b => inv (.done b)) := by + intro hstep + have induc (C : β → Prop) (a : β) (h : ∀ x, (∀ y, measure y < measure x → C y) → C x): C a := by + have lem: ∀ n: Nat, ∀ x, measure x ≤ n → C x := by + intro n + induction n with + | zero => + intro x hx + exact h x (fun y => by omega) + | succ m ih => + intro x hx + by_cases neq: measure x ≤ m + { exact ih x neq } + have eq: measure x = m + 1 := by omega + exact h x (fun y hy => ih y (by omega)) + exact lem (measure a) a (by simp) + apply induc + (fun ini => triple (inv (.yield ini)) (Loop.forIn.loop f ( ini)) (fun b => inv (.done b))) init + intro b ih; unfold Loop.forIn.loop; simp [triple, wp_bind]; apply le_trans + apply hstep; apply wp_cons; rintro (_|_) + { simp [wp_pure] } + rename_i a + match ForInStep.yield a with + | .yield b' => + simp; intro m_lt + have ihb := ih b' m_lt + simp [triple] at ihb + exact ihb + | .done b' => + simp + rw [wp_pure b' (fun s: β => inv (ForInStep.done s))] + + +lemma repeat_inv_split (f : Unit -> β -> m (ForInStep β)) + (inv : β -> l) (doneWith : β -> l) + init (measure: β -> Nat): + (∀ b, triple (inv b) (f () b) (fun | .yield b' => inv b' ⊓ ⌜ measure b' < measure b ⌝ | .done b' => inv b' ⊓ doneWith b')) -> + triple (inv init) (Loop.forIn.loop f init) (fun b => inv b ⊓ doneWith b) := by + intro hstep + apply repeat_inv f (fun | .yield b => inv b | .done b => inv b ⊓ doneWith b) measure init + apply hstep + +variable [MAlgTotal m] + +omit [LawfulMonad m] [MonoBind m] in +attribute [-simp] le_bot_iff in +@[simp] +lemma wp_bot : + wp (bot : m α) = fun _ => (⊥ : l) := by + ext post; refine eq_bot_iff.mpr ?_ + simp [wp, liftM, monadLift]; apply MAlgTotal.bot_lift + +end TotalCorrectness + +theorem triple_forIn_list {α β} + {xs : List α} {init : β} {f : α → β → m (ForInStep β)} + (inv : List α → β → l) + (hstep : ∀ hd tl b, + triple + (inv (hd :: tl) b) + (f hd b) + (fun | .yield b' => inv tl b' | .done b' => inv [] b')) : + triple (inv xs init) (forIn xs init f) (inv []) := by + induction xs generalizing init + { simp; rw [triple_pure] } + simp only [List.forIn_cons] + apply triple_bind; apply hstep; intros y + cases y <;> simp <;> solve_by_elim [(triple_pure ..).mpr, le_refl] + +theorem triple_forIn_range'_aux {β} + {xstart : ℕ} {step : ℕ} (n : ℕ) (init : β) {f : ℕ → β → m (ForInStep β)} + (inv : ℕ → β → l) + (hstep : ∀ i b, + triple + (inv i b) + (f i b) + (fun | .yield b' => inv (i + step) b' | .done b' => inv (xstart + n * step) b')) : + i <= n -> + triple (inv (xstart + (n - i) * step) init) (forIn (List.range' (xstart + (n - i) * step) i step) init f) (inv (xstart + n * step)) := by + unhygienic induction i generalizing init + { simp [triple_pure] } + intro le + simp [List.range']; apply triple_bind; apply hstep + rintro (_|_) <;> simp [triple_pure] + simp [Nat.add_assoc, <-Nat.add_one_mul] + have : (n - (n_1 + 1) + 1) = n - n_1 := by omega + rw [this]; apply a; omega + + +theorem triple_forIn_range' {β} + {xstart : ℕ} {step : ℕ} (n : ℕ) {init : β} {f : ℕ → β → m (ForInStep β)} + (inv : ℕ → β → l) + (hstep : ∀ i b, + triple + (inv i b) + (f i b) + (fun | .yield b' => inv (i + step) b' | .done b' => inv (xstart + n * step) b')) : + triple (inv xstart init) (forIn (List.range' xstart n step) init f) (inv (xstart + n * step)) := by + have := triple_forIn_range'_aux (i := n) (m := m) n init inv hstep (by omega) + simp_all only [Nat.sub_self, Nat.zero_mul, Nat.add_zero] + +theorem triple_forIn_range {β} + (xs : Std.Legacy.Range) (init : β) (f : ℕ → β → m (ForInStep β)) + (inv : ℕ → β → l) + (hstep : ∀ i b, + triple + (inv i b) + (f i b) + (fun | .yield b' => inv (i + xs.step) b' | .done b' => inv (xs.start + ((xs.stop - xs.start + xs.step - 1) / xs.step) * xs.step) b')) : + triple (inv xs.start init) (forIn xs init f) (inv (xs.start + ((xs.stop - xs.start + xs.step - 1) / xs.step) * xs.step)) := by + simp; apply triple_forIn_range'; apply hstep + +theorem triple_forIn_range_step1 {β} + {xs : Std.Legacy.Range} {init : β} {f : ℕ → β → m (ForInStep β)} + (inv : ℕ → β → l) + (hstep : ∀ i b, + triple + (inv i b) + (f i b) + (fun | .yield b' => inv (i + xs.step) b' | .done b' => inv xs.stop b')) : + xs.step = 1 -> + xs.start <= xs.stop -> + triple (inv xs.start init) (forIn xs init f) (inv xs.stop) := by + have := triple_forIn_range (m := m) xs init f inv + intro h eq; + simp [h] at * + rw [Nat.add_sub_of_le eq] at this; + solve_by_elim + +end Loops + + +section Lift + +variable [inst: CompleteLattice l] [MAlgOrdered m l] + +lemma wp_except_handler_eq ε (hd : ε -> Prop) [IsHandler hd] (c : ExceptT ε m α) post : + wp c post = wp (m := m) c (fun | .ok x => post x | .error e => ⌜hd e⌝) := by + apply MAlg.lift_ExceptT + + +open ExceptionAsSuccess in +lemma wp_part_eq ε (c : ExceptT ε m α) post : + wp c post = wp (m := m) c (fun | .ok x => post x | .error _ => ⊤) := by + simp [wp_except_handler_eq] + +open ExceptionAsFailure in +lemma wp_tot_eq ε (c : ExceptT ε m α) post : + wp c post = wp (m := m) c (fun | .ok x => post x | .error _ => ⊥) := by + simp [wp_except_handler_eq] + + +lemma ExceptT.wp_lift_hd {hd : ε -> Prop} (c : m α) (post : α -> l) [IsHandler hd] : + wp (liftM (n := ExceptT ε m) c) post = wp (m := m) c post := by + simp [wp_except_handler_eq, liftM, monadLift, MonadLift.monadLift, ExceptT.lift, mk] + rw [map_eq_pure_bind, wp_bind]; simp [wp_pure] + +lemma ExceptionAsSuccess.ExceptT.wp_lift (c : m α) (post : α -> l) : + wp (liftM (n := ExceptT ε m) c) post = wp (m := m) c post := by + apply ExceptT.wp_lift_hd + +lemma ExceptionAsFailure.ExceptT.wp_lift (c : m α) (post : α -> l) : + wp (liftM (n := ExceptT ε m) c) post = wp (m := m) c post := by + apply ExceptT.wp_lift_hd + +/- WP for DivM in TotalCorrectness -/ +open TotalCorrectness in +lemma TotalCorrectness.DivM.wp_eq (α : Type) (x : DivM α) (post : α -> Prop) : + wp x post = + match x with + | .div => False + | .res r => post r := by + cases x + · show ⌜post _⌝ = post _; simp [LE.pure] + · rfl + +/- WP for DivM in PartialCorrectness -/ +lemma PartialCorrectness.DivM.wp_eq (α : Type) (x : DivM α) (post : α -> Prop) : + wp x post = + match x with + | .div => True + | .res r => post r := by + cases x <;> rfl + +/- WP for StateT in underlying monad -/ +lemma StateT.wp_eq (c : StateT σ m α) (post : α -> σ -> l) : + wp c post = fun s => wp (m := m) (c s) (fun xs => post xs.1 xs.2) := by + simp [wp, liftM, monadLift, MAlg.lift_StateT]; + +/- WP for lift to StateT -/ +lemma StateT.wp_lift (c : m α) (post : α -> σ -> l) : + wp (liftM (n := StateT σ m) c) post = fun s => wp (m := m) c (post · s) := by + simp [wp, liftM, monadLift, MAlg.lift_StateT, MonadLift.monadLift, StateT.lift]; + have liftE : ∀ α, MAlg.lift (m := m) (α := α) = wp := by intros; ext; simp [wp, liftM, monadLift] + ext s; rw [map_eq_pure_bind, liftE, liftE, wp_bind]; simp [wp_pure] + +/- WP for ReaderT in underlying monad -/ +lemma ReaderT.wp_eq (c : ReaderT σ m α) (post : α -> σ -> l) : + wp c post = fun s => wp (m := m) (c s) (post · s) := by + simp [wp, liftM, monadLift, MAlg.lift_ReaderT]; + +/- WP for lift to ReaderT -/ +lemma ReaderT.wp_lift (c : m α) (post : α -> σ -> l) : + wp (liftM (n := ReaderT σ m) c) post = fun s => wp (m := m) c (post · s) := by + simp [wp, liftM, monadLift, MAlg.lift_ReaderT, MonadLift.monadLift] + +/- WP lift from MAlgLift-/ +omit [LawfulMonad m] in +lemma MAlgLift.wp_lift [Monad n] [CompleteLattice k] [MAlgOrdered n k] [MonadLiftT m n] + -- [MonadLiftT (Cont l) (Cont k)] + [mAlgLift : MAlgLiftT m l n k] (c : m α): + wp (liftM (n := n) c) = fun (post : α -> k) => mAlgLift.cl.lift.monadLift (wp c) post := by + ext; + apply MAlgLiftT.μ_lift + +end Lift + +section ExceptT + +variable [inst: CompleteLattice l] [MAlgOrdered m l] [IsHandler (ε := ε) hd] + +/- WP for exception in ExceptT -/ +lemma ExceptT.wp_throw (e : ε) : + wp (α := α) (throw (m := ExceptT ε m) e) = fun _ => ⌜hd e⌝ := by + ext; simp [wp_except_handler_eq, throw, throwThe, MonadExceptOf.throw, mk, wp_pure] + +/- WP lift from Monad Transformer Algebra -/ +lemma MAlgLift.wp_throw + [Monad n] [CompleteLattice k] [MAlgOrdered n k] [MonadLiftT m n] + [MonadLiftT (ExceptT ε m) n] + [inst: MAlgLiftT (ExceptT ε m) l n k] : + wp (liftM (n := n) (throw (m := ExceptT ε m) e)) post = ⌜hd e⌝ := by + rw [MAlgLift.wp_lift, ExceptT.wp_throw] + simp only [LE.pure]; split <;> simp [inst.cl.lift_top, inst.cl.lift_bot] + +end ExceptT + +section StateT + +variable [inst: CompleteLattice l] [MAlgOrdered m l] + +/- WP for get in StateT -/ +lemma StateT.wp_get (post : σ -> σ -> l) : + wp (get (m := StateT σ m)) post = fun s => post s s := by + simp [StateT.wp_eq, get, getThe, MonadStateOf.get, StateT.get, wp_pure] + +/- WP for set in StateT -/ +lemma StateT.wp_set {res: σ} (post : PUnit -> σ -> l) : + wp (set (m := StateT σ m) res) post = fun _ => post PUnit.unit res := by + simp [StateT.wp_eq, set, StateT.set, wp_pure] + +/- WP for modifyGet in StateT -/ +lemma StateT.wp_modifyGet (post : α -> σ -> l) : + wp (modifyGet (m := StateT σ m) f) post = fun s => post (f s).1 (f s).2 := by + simp [StateT.wp_eq, modifyGet, MonadStateOf.modifyGet, StateT.modifyGet, wp_pure] + +end StateT + +section ReaderT + +variable [inst: CompleteLattice l] [MAlgOrdered m l] + +/- WP for read in ReaderT -/ +lemma ReaderT.wp_read (post : σ -> σ -> l) : + wp (read (m := ReaderT σ m)) post = fun s => post s s := by + simp [ReaderT.wp_eq, read, readThe, MonadReaderOf.read, ReaderT.read, wp_pure] + + +end ReaderT + +section Gen + +open Plausible + +-- TODO: Fix this instance +/- WP for rand in Gen -/ +-- lemma Gen.wp_rand {α : Type} (c : Gen α) : +-- triple ⊤ c (fun _ => ⊤) := by +-- simp [triple, MAlgGenInst, ReaderT.wp_eq, StateT.wp_eq] +-- simp [wp, liftM, monadLift, MAlg.lift, MAlgOrdered.μ]; rfl + +end Gen + + +-- section StrongestPostcondition + +-- variable [inst: CompleteLattice l] [MAlgOrdered m l] + +-- def sp (x : m α) (pre : l) : α -> l := (sInf fun post => pre <= wp x post) + +-- lemma le_wp_sp_le (x : m α) [LawfulMonad m] [MAlgDet m l] : +-- post ≠ ⊤ -> +-- (sp x pre <= post -> pre <= wp x post) := by +-- intro pne +-- by_cases ex: Nonempty (Set.Elem fun post ↦ pre ≤ wp x post) +-- { have : pre <= wp x (sp x pre) := by { +-- unfold sp; simp [sInf]; rw [@wp_iInf] +-- revert ex; simp [Set.Elem, Set.Mem, Membership.mem] } +-- solve_by_elim [wp_cons, le_trans] } +-- rw [@Set.not_nonempty_iff_eq_empty'] at ex +-- simp [sp, ex, *] + +-- lemma sp_le_le_wp (x : m α) : +-- (pre <= wp x post -> sp x pre <= post) := by +-- intro a; --refine inf_le_of_left_le ?_ +-- exact CompleteSemilatticeInf.sInf_le (fun post ↦ pre ≤ wp x post) post a + + +-- end StrongestPostcondition diff --git a/Loom/MonadAlgebras/WP/Liberal.lean b/Loom/MonadAlgebras/WP/Liberal.lean new file mode 100644 index 00000000..0a27c3e0 --- /dev/null +++ b/Loom/MonadAlgebras/WP/Liberal.lean @@ -0,0 +1,222 @@ +import Mathlib.Order.CompleteBooleanAlgebra + +import Loom.MonadAlgebras.Defs +import Loom.MonadAlgebras.WP.Basic + +import Loom.MonadAlgebras.Instances.Basic +import Loom.MonadAlgebras.Instances.ExceptT + +variable {m : Type u -> Type v} [Monad m] [LawfulMonad m] {α : Type u} {l : Type u} +variable [inst: CompleteBooleanAlgebra l] [mprop: MAlgOrdered m l] + +attribute [simp] trueE falseE +@[local simp] +private lemma compl_fun {α} (x y : α -> l) : + (fun a => x a ⊔ y a)ᶜ = (fun a => (x a)ᶜ ⊓ (y a)ᶜ) := by simp [compl] + +@[local simp] +private lemma compl_fun' {α} (x y : α -> l) : + (fun a => x a ⊓ y a)ᶜ = (fun a => (x a)ᶜ ⊔ (y a)ᶜ) := by simp [compl] + +@[local simp] +private lemma compl_fun'' {α} (x : α -> l) : + (fun a => (x a)ᶜ) = xᶜ := by simp [compl] + + +@[local simp] +private lemma compl_fun_true {α} : + (fun (_ : α) => ⊤)ᶜ = fun _ => (⊥ : l) := by simp [compl] + +abbrev iwp (c : m α) : Cont l α := Cont.inv (wp c) + +omit [LawfulMonad m] in +@[simp] +lemma iwp_eq (c : m α) (post : α -> l) : + iwp c post = (wp c postᶜ)ᶜ := by + simp [iwp, Cont.inv] + +def wlp (c : m α) (post : α -> l) : l := iwp c post ⊔ wp c post + +@[simp] +lemma wlp_true (c : m α) : wlp c (fun _ => ⊤) = ⊤ := by + simp [wlp]; rw [@eq_top_iff, sup_comm, <-himp_eq]; simp + apply wp_cons; simp + +@[simp] +lemma wlp_pure (x : α) (post : α -> l) : + wlp (pure (f := m) x) post = post x := by + simp [wlp, wp_pure] + +omit [LawfulMonad m] in +lemma wp_wlp (c : m α) (post : α -> l) : + wp c post <= wlp c post := by + simp [wlp, wp] + +section Determinism +variable [MAlgDet m l] + +lemma wlp_and (c : m α) (post₁ post₂ : α -> l) : + wlp c (fun x => post₁ x ⊓ post₂ x) = wlp c post₁ ⊓ wlp c post₂ := by + simp [wlp]; apply le_antisymm + { simp [wp_or, wp_and] } + rw (occs := .pos [3]) [sup_comm]; rw [<-himp_eq]; simp + rw [inf_inf_distrib_right] + conv => + enter [1,1] + rw [inf_sup_right, <-wp_and]; + simp [inf_sup_left]; rw [wp_or, inf_sup_left]; simp + erw [wp_and, <-inf_sup_right] + conv => + enter [1,2] + rw [inf_sup_right, <-wp_and]; + simp [inf_sup_left]; rw [wp_or, inf_sup_left]; simp + erw [wp_and, <-inf_sup_right] + rw (occs := .pos [3]) [inf_comm] + rw [inf_assoc] + rw (occs := .pos [2]) [<-inf_assoc] + rw (occs := .pos [3]) [inf_comm] + repeat rw [<-inf_assoc] + rw [inf_sup_right, <-wp_and]; simp + apply inf_le_of_left_le + apply inf_le_of_left_le + apply wp_cons; simp + +lemma wlp_bind {β} (x : m α) (f : α -> m β) (post : β -> l) : + wlp (x >>= f) post = wlp x (fun x => wlp (f x) post) := by + simp [wlp, wp_bind]; apply le_antisymm + { simp [wp_and, wp_or]; constructor + { repeat apply le_sup_of_le_left; simp } + repeat apply le_sup_of_le_right; simp } + simp [wp_and, wp_or]; constructor + { rw [<-compl_compl (x := wp x fun a ↦ wp (f a) post)] + rw [<-himp_eq, le_himp_iff, ← compl_sup, <-wp_or] + simp; apply wp_cons; simp } + rw [sup_comm]; simp [<-himp_eq, <-wp_and] + apply wp_cons; simp + + +lemma wlp_himp (c : m α) (post post' : α -> l) : + wp c (fun x => post' x ⇨ post x) = wlp c post' ⇨ wp c post := by + rw [himp_eq, wlp]; simp [himp_eq, wp_or] + apply le_antisymm <;> simp + rw [<-compl_compl (x := wp c post'ᶜ ⊓ (wp c post')ᶜ)] + rw [<-himp_eq]; simp; rw [@inf_sup_left]; simp [<-wp_and] + apply wp_cons; simp + +lemma wlp_join_wp (c : m α) (post post' : α -> l) : + wlp c post ⊓ wp c post' = wp c (fun x => post x ⊓ post' x) := by + apply le_antisymm + { rw [← @le_himp_iff', <-wlp_himp]; + apply wp_cons; simp } + simp; constructor + { apply le_trans'; apply wp_wlp; apply wp_cons; simp } + apply wp_cons; simp + +lemma wp_top_wlp (c : m α) (post : α -> l) : + wp c ⊤ ⊓ wlp c post = wp c post := by + rw [inf_comm, wlp_join_wp]; simp + +omit [MAlgDet m l] in +lemma wlp_cons (c : m α) (post post' : α -> l) : + post <= post' -> + wlp c post <= wlp c post' := by + intro; unfold wlp iwp; simp; constructor + { refine le_sup_of_le_left ?_; simp; apply wp_cons; simp; solve_by_elim } + solve_by_elim [le_sup_of_le_right, wp_cons] + +lemma wp_top_iwp (c : m α) (post : α -> l) : + wp c ⊥ = ⊥ -> + wp c ⊤ ⊓ iwp c post = wp c post := by + intro wpb + apply le_antisymm + { simp; simp [<-le_himp_iff, himp_eq, <-wp_or]; rfl } + simp; constructor + { apply wp_cons; simp } + rw [@le_compl_iff_disjoint_left]; intro _ _ _ + apply le_trans'; rewrite [<- wpb]; + rw [<-compl_inf_eq_bot (a := post)] + erw [wp_and]; simp; solve_by_elim + +set_option quotPrecheck false in +notation "[totl|" t "]" => open ExceptionAsFailure in t +set_option quotPrecheck false in +notation "[part|" t "]" => open ExceptionAsSuccess in t +set_option quotPrecheck false in +notation "[handler" hd "|" t "]" => have : IsHandler hd := ⟨⟩; t + +lemma wp_tot_part ε (c : ExceptT ε m α) post : + [totl| wp c ⊤] ⊓ [part| wp c post] = [totl| wp c post] := by + rw [wp_part_eq, wp_tot_eq, wp_tot_eq, <-wp_and] + congr; ext x; cases x <;> simp + +lemma wp_compl (c : m α) post (wp_bot : ∀ α (c : m α), wp c ⊤ = ⊤) : + (wp c postᶜ)ᶜ <= wp c post := by + refine compl_le_iff_compl_le.mp ?_ + rw [← @codisjoint_iff_compl_le_right]; intro b + rw [<-wp_bot (c := c)]; intros; apply le_trans + apply wp_cons; intro a; apply BooleanAlgebra.top_le_sup_compl (x := post) + erw [wp_or]; simp_all + +lemma wp_compl' (c : m α) post (wp_bot : ∀ α (c : m α), wp c ⊥ = ⊥) : + wp c post <= (wp c postᶜ)ᶜ := by + have : wp c post = ⊤ ⊓ wp c post := by simp + rw [this, <-le_himp_iff, himp_eq]; rw [← @compl_inf, <-wp_and]; simp + solve_by_elim + +-- lemma wp_tot_eq_iwp_part ε (c : ExceptT ε m α) (post : α -> l) +-- (wp_bot : ∀ α (c : m α), wp c ⊥ = ⊥) +-- (wp_top : ∀ α (c : m α), wp c ⊤ = ⊤) : +-- [totl| wp c post] = [part| iwp c post] := by +-- simp only [iwp, wp_tot_eq, wp_part_eq] +-- apply le_antisymm <;> try simp +-- { apply le_trans; apply wp_compl'; simp [*] +-- simp; apply wp_cons (x := c); rintro (_|_) <;> simp } +-- apply le_trans'; apply wp_compl; simp [*] +-- simp; apply wp_cons; rintro (_|_) <;> simp + +private lemma le_coml_sup (x y z : l) : + y <= x ⊔ z -> xᶜ <= yᶜ ⊔ z := by + intro h; + rw [sup_comm, <-himp_eq]; simp + rw [inf_comm, <-le_himp_iff, himp_eq]; simp + rwa [sup_comm] + +lemma wlp_part_wlp_handler ε (α : Type u) (c : ExceptT ε m α) (post : α → l) (hd : ε -> Prop) : + [part| wlp c post] = + [handler hd| wlp c post] := by + simp [wlp, wp_part_eq, wp_except_handler_eq] + apply le_antisymm <;> simp + { constructor + { apply le_coml_sup; rw [<-wp_or]; apply wp_cons + rintro (_|_) <;> simp } + rw [sup_comm, <-himp_eq]; simp [<-wp_and] + apply wp_cons; rintro (_|_) <;> simp } + constructor + { apply le_coml_sup; rw [<-wp_or]; apply wp_cons + rintro (_|_) <;> simp } + rw [sup_comm, <-himp_eq]; simp [<-wp_and] + apply wp_cons; rintro (_|_) <;> simp + +lemma TotalCorrectness.DivM.wlp_eq (α : Type) (x : DivM α) (post : α -> Prop) : + (open TotalCorrectness in wlp x post) = (open PartialCorrectness in wp x post) := by + simp [wlp, TotalCorrectness.DivM.wp_eq, PartialCorrectness.DivM.wp_eq] + split <;> simp + +lemma PartialCorrectness.DivM.wlp_eq (α : Type) (x : DivM α) (post : α -> Prop) : + wlp x post = wp x post := by + simp [wlp, PartialCorrectness.DivM.wp_eq] + split <;> simp + +omit [MAlgDet m l] in +lemma StateT.wlp_eq (c : StateT σ m α) (post : α -> σ -> l) : + wlp c post = fun s => wlp (m := m) (c s) (fun xs => post xs.1 xs.2) := by + simp [wlp, StateT.wp_eq]; rfl + +omit [MAlgDet m l] in +lemma ReaderT.wlp_eq (c : ReaderT σ m α) (post : α -> σ -> l) : + wlp c post = fun s => wlp (m := m) (c s) (post · s) := by + simp [wlp, ReaderT.wp_eq]; rfl + +lemma ExceptT.wlp_eq (c : ExceptT ε m α) (post : α -> l) : + [totl| wlp c post] = [part| wlp c post] := by + rw [wlp_part_wlp_handler] diff --git a/Loom/MonadAlgebras/WP/Variant.lean b/Loom/MonadAlgebras/WP/Variant.lean new file mode 100644 index 00000000..4980004e --- /dev/null +++ b/Loom/MonadAlgebras/WP/Variant.lean @@ -0,0 +1,107 @@ +import Loom.MonadAlgebras.WP.Basic + +/-! +# Loops with an invariant and a variant, in any monad + +Loom's unbounded loop (`Loop.forIn.loop`) is a `partial_fixpoint`, so it needs a monad +that can diverge (`CCPO`, `MonoBind`), and its total-correctness rule +(`TotalCorrectness.repeat_inv`) an algebra that sends divergence to `⊥`. A monad without +divergence, such as a state program that fails with data, runs a loop for a number of +iterations it is given. `Loop.bounded exhaust f fuel b` runs `f` from `b` until it returns +`done`, at most `fuel` times, and runs `exhaust` on what it reached if it never did. + +`triple_bounded` is the total-correctness rule: an invariant that each step keeps, and a +natural-number variant that each step that continues decreases, give the loop's triple once +the fuel exceeds the initial variant, whatever `exhaust` does, since the loop then never +reaches it. `triple_while` is the same rule for a `while` loop with a condition and a body. +`bounded_eq_of_variant` says that such a loop does not depend on its fuel or `exhaust`. +-/ + +universe u v + +variable {m : Type u → Type v} [Monad m] [LawfulMonad m] {β : Type u} {l : Type u} + +/-- At most `fuel` iterations of `f` from `b`; `exhaust` on what is reached if `f` never +returned `done`. -/ +def Loop.bounded (exhaust : β → m β) (f : β → m (ForInStep β)) : Nat → β → m β + | 0, b => exhaust b + | n + 1, b => do + match ← f b with + | .done b => pure b + | .yield b => Loop.bounded exhaust f n b + +/-- A `while` loop: while `cond` holds, run `body`, at most `fuel` times. -/ +def Loop.whileBounded (exhaust : β → m β) (cond : β → Bool) (body : β → m β) + (fuel : Nat) (b : β) : m β := + Loop.bounded exhaust (fun b => if cond b then ForInStep.yield <$> body b else pure (.done b)) + fuel b + +section +variable [CompleteLattice l] [MAlgOrdered m l] + +/-- Total correctness of a bounded loop: an invariant each step keeps and a variant each +continuing step decreases give the triple once the fuel exceeds the variant. -/ +theorem triple_bounded (exhaust : β → m β) (f : β → m (ForInStep β)) + (inv : β → l) (doneWith : β → l) (measure : β → Nat) + (hstep : ∀ b, triple (inv b) (f b) (fun + | .yield b' => inv b' ⊓ ⌜measure b' < measure b⌝ + | .done b' => inv b' ⊓ doneWith b')) : + ∀ fuel init, measure init < fuel → + triple (inv init) (Loop.bounded exhaust f fuel init) (fun b => inv b ⊓ doneWith b) := by + intro fuel + induction fuel with + | zero => intro _ h; omega + | succ n ih => + intro init hlt + simp only [triple, Loop.bounded, wp_bind] + apply le_trans (hstep init) + apply wp_cons + rintro (b' | b') + · simp only [wp_pure]; exact le_refl _ + · simp only [pure_intro_l] + intro hm + exact ih b' (by omega) + +/-- Total correctness of a bounded `while` loop: the body keeps the invariant and decreases +the variant while the condition holds; the loop ends where the invariant holds and the +condition does not. -/ +theorem triple_while (exhaust : β → m β) (cond : β → Bool) (body : β → m β) + (inv : β → l) (measure : β → Nat) + (hbody : ∀ b, cond b = true → + triple (inv b) (body b) (fun b' => inv b' ⊓ ⌜measure b' < measure b⌝)) + (fuel : Nat) (init : β) (hfuel : measure init < fuel) : + triple (inv init) (Loop.whileBounded exhaust cond body fuel init) + (fun b => inv b ⊓ ⌜cond b = false⌝) := by + apply triple_bounded exhaust _ inv (fun b => ⌜cond b = false⌝) measure _ fuel init hfuel + intro b + by_cases hc : cond b = true + · simp only [hc, if_true, triple, wp_map] + exact hbody b hc + · have hc' : cond b = false := by simpa using hc + simp only [hc', triple, Bool.false_eq_true, if_false] + rw [wp_pure] + simp [LE.pure, hc'] + +end + +/-- A loop whose variant decreases does not depend on its fuel past the variant. -/ +theorem bounded_eq_of_variant (exhaust exhaust' : β → m β) (f : β → m (ForInStep β)) + (good : β → Prop) (measure : β → Nat) + (hstep : ∀ b, good b → ∃ r : ForInStep β, f b = pure r ∧ + match r with | .yield b' => good b' ∧ measure b' < measure b | .done _ => True) : + ∀ fuel fuel' b, good b → measure b < fuel → measure b < fuel' → + Loop.bounded exhaust f fuel b = Loop.bounded exhaust' f fuel' b := by + intro fuel + induction fuel with + | zero => intro _ _ _ h; omega + | succ n ih => + intro fuel' b hg h h' + cases fuel' with + | zero => omega + | succ n' => + obtain ⟨r, hr, hgood⟩ := hstep b hg + simp only [Loop.bounded, hr, pure_bind] + cases r with + | done b' => rfl + | yield b' => + exact ih n' b' hgood.1 (by have := hgood.2; omega) (by have := hgood.2; omega) diff --git a/vendor/loom/Loom/MonadUtil.lean b/Loom/MonadUtil.lean similarity index 100% rename from vendor/loom/Loom/MonadUtil.lean rename to Loom/MonadUtil.lean diff --git a/Loom/README.md b/Loom/README.md new file mode 100644 index 00000000..b19b3b9f --- /dev/null +++ b/Loom/README.md @@ -0,0 +1,61 @@ +# Loom, vendored + +**Port in progress (branch loom-4.35).** All of upstream Loom (and its case studies) is under +vendor/loom. Built on Lean 4.35 so far: Defs, Instances/Basic (with DivM and its partial and +total correctness algebras), Instances/StateT, ExceptT, ReaderT, Gen, WP/Basic (with the loop, +lifting, ExceptT, StateT and ReaderT sections) and WP/Liberal; the lean_lib Loom lists the +built modules as roots. The VC tactic layer (DoNames', Options, Gen, Attr, Matcher, Tactic), +NonDetT, Meta, TacticAsync and the SMT layer are not ported yet and nothing builds them. + +Statements changed by the Lean 4.35 API: + +* `MAlgPartial.csup_lift` and `PartialCorrectness.wp_csup` take the chain proof + (`Lean.Order.CCPO.csup` now takes a proof of `chain`, not the set). +* `triple_forIn_range` and `triple_forIn_range_step1` are on `Std.Legacy.Range` (Lean renamed + `Std.Range`). +* The `ForIn m Lean.Loop Unit` instance's `forIn` no longer takes the loop value separately + (`ForIn.forIn`'s signature changed). + +Added (not upstream; candidates for an upstream PR): + +* `DivM.csup_eq`, `StateT.csup_apply`, `StateT.bot_apply`, `ReaderT.csup_apply`, + `ReaderT.bot_apply`: the supremum of a chain, now a choice, as the flat or pointwise one. +* `Instances/ExceptTErr.lean`: an error-aware algebra, `MAlgExceptErr` on `ExceptT ε m` with + assertions `(ε → l) → l`, and `MAlgExceptErrProp` on `Except ε` with `(ε → Prop) → Prop` + (and `MAlgDet`), whose weakest precondition takes the predicate an exception must meet. +* `WP/Variant.lean`: `Loop.bounded`, `Loop.whileBounded`, and the total-correctness rules + `triple_bounded` and `triple_while` (invariant plus a natural-number variant) for monads + that cannot diverge, with `bounded_eq_of_variant`. + +The sections below describe the earlier, partial vendoring. + +## Kept + +* `Loom/MonadUtil.lean`, `Loom/SpecMonad.lean`: unchanged. +* `Loom/MonadAlgebras/Defs.lean`: monad algebras (`MAlg`, `MAlgOrdered`, `MAlgDet`), logic + lifts and monad-transformer algebras. +* `Loom/MonadAlgebras/Instances/Basic.lean`: the algebra of `Id` on `Prop`, and the + `CCPOBot` classes. +* `Loom/MonadAlgebras/WP/Basic.lean`: `wp`, `triple` and their generic rules (`wp_pure`, + `wp_bind`, `wp_map`, `wp_cons`, `triple_*`, `wp_and`, `wp_or`, ...). + +## Changed for Lean 4.35 + +* `MAlgPartial.csup_lift` takes the chain proof explicitly, since `Lean.Order.CCPO.csup` now + takes a proof of `chain` rather than the set. +* The `LogicLiftT` composition instance's `lift_top` and `lift_bot`, and `MAlgLiftTTrans`'s + `μ_lift`, are reproved: their `simp` calls no longer make progress. +* `Loom.lean` imports only what is kept. + +## Dropped + +* `Instances/StateT.lean`, `ExceptT.lean`, `ReaderT.lean`, `Gen.lean`, and the matching + sections of `WP/Basic.lean` (loops, lifting, `ExceptT`, `StateT`, `ReaderT`, `Gen`): their + proofs depend on Lean 4.24's `simp` normal forms and on the old `CCPO` API throughout. + `SolidCore/Verify/Basic.lean` gives its own ordered algebra for the one stack it needs, + `StateT Storage (Except Revert)`. +* `DivM` and its partial- and total-correctness algebras (`Instances/Basic.lean`). +* `WP/Liberal.lean`, `WP/Gen.lean`, `WP/Attr.lean`, `WP/Tactic.lean`, `WP/Matcher.lean`, + `WP/DoNames'.lean`, `WP/Options.lean`, `Meta.lean`, `TacticAsync.lean`, `SMT.lean` and + `NonDetT`: the VC tactic layer, SMT (lean-auto, z3, cvc5) and nondeterminism. SolidCore's + generator computes weakest preconditions with `simp` and Loom's `wp` rules instead. diff --git a/vendor/loom/Loom/SpecMonad.lean b/Loom/SpecMonad.lean similarity index 100% rename from vendor/loom/Loom/SpecMonad.lean rename to Loom/SpecMonad.lean diff --git a/Verify.lean b/Verify.lean new file mode 100644 index 00000000..f918fed1 --- /dev/null +++ b/Verify.lean @@ -0,0 +1,13 @@ +import Verify.Basic +import Verify.Abi +import Verify.Finite +import Verify.Run +import Verify.Tactic +import Verify.C1 +import Verify.W1 +import Verify.W4 +import Verify.C4 +import Verify.W5 +import Verify.Fuel +import Verify.CounterBump +import Verify.Final diff --git a/Verify/Abi.lean b/Verify/Abi.lean new file mode 100644 index 00000000..23717aa8 --- /dev/null +++ b/Verify/Abi.lean @@ -0,0 +1,38 @@ +import Verify.Basic +import SolidCore.Refinement.Wide.Refines + +/-! +# Argument words of a call + +A specification speaks about a call's argument words. `argWords n call` reads the +first `n` of them from the call data after the selector, as SolidCore's ABI decoder +does; on a call of `Abi.fullScope` they are the words the call was built from +(`argWords_calldata`). +-/ + +namespace SolidCore.Verify + +open SolidCore.Refinement SolidCore.Solidity SolidCore.Solidity.Source + +/-- The first `n` argument words of `call`: the 32-byte words after the selector. -/ +def argWords (n : Nat) (call : Call) : List Nat := + (List.range n).map fun i => + (ABI.readWord? ((call.calldata.data.toList.map (·.toNat)).drop 4) (32 * i)).getD 0 + +theorem argWords_calldata (sel : Nat) (args : List Nat) (hargs : ∀ a ∈ args, a < 2 ^ 256) + (cv : Nat) (st : List (Nat × Nat)) : + argWords args.length { calldata := Abi.calldata sel args, callvalue := cv, storage := st } = + args := by + simp only [argWords, Dirty.bytes_calldata, Wide.drop_selector] + apply List.ext_getElem (by simp) + intro i h1 h2 + simp [Dirty.readWord_argBytes args hargs i h2] + +/-- The bytes of a 32-byte big-endian word. -/ +def word (v : Nat) : List Nat := (EthLib.Base.natToBytes 32 v).map (·.toNat) + +/-- The revert data of `Panic(code)`. -/ +def panic (code : Nat) : List Nat := (EthLib.Base.natToBytes 4 0x4e487b71).map (·.toNat) ++ word code + +end SolidCore.Verify + diff --git a/Verify/Basic.lean b/Verify/Basic.lean new file mode 100644 index 00000000..fcaad920 --- /dev/null +++ b/Verify/Basic.lean @@ -0,0 +1,306 @@ +import Loom.MonadAlgebras.WP.Basic +import Loom.MonadAlgebras.WP.Variant +import Loom.MonadAlgebras.Instances.ExceptTErr +import SolidCore.Refinement.Compose + +/-! +# A verification-condition generator for SolidCore, on Loom + +A specification of an external function says what a call must show, from what holds +before it. Its triple (`Triple`) is stated directly against SolidCore's +`Source.run`: every call of the scope that meets the precondition finishes with some +observable, and every observable it can finish with meets the postcondition. + +The verification conditions come from Loom's weakest preconditions. A function is +modelled as a program in `SolM`, a state monad over the callee's storage whose +failures are reverts with their revert data. `SolM` is a Loom ordered monad algebra +(`MAlgOrdered`) whose assertions take, besides the storage, a predicate on the revert +data a failure must meet, so that one weakest precondition covers both outcomes of a +call. Loom's `wp_bind` and `wp_pure` and the rules below for storage and reverts +compute the weakest precondition of a model by `simp`; what is left is a goal on words +that `omega` or `bv_decide` closes. + +A model is tied to SolidCore by `Implements`: on every call of the scope, +`Source.run` finishes with the observable the model's outcome shows. Each contract +proves it once, by symbolic evaluation of SolidCore's interpreter (`Wide.Tactic`). +`triple_of_wp` then turns the weakest precondition into the triple, and +`satisfies_of_triple` into `Satisfies` on `solidCore fuel`, the form the refinement +theorems carry to bytecode. + +The triple is total: it includes that `Source.run` returns `some`, so running out +of fuel or an interpreter failure refutes it. +-/ + +namespace SolidCore.Verify + +open SolidCore.Refinement + +/-- The callee's storage, slot to word. -/ +abbrev Storage := Nat → Nat + +/-- The data a call reverts with. -/ +abbrev Revert := List Nat + +/-- A model of an external function: a program over the storage that fails with its +revert data. -/ +abbrev SolM := StateT Storage (Except Revert) + +/-- An assertion on what a model leaves: given the predicate a revert's data must meet, +a predicate on the storage. -/ +abbrev Assn := (Revert → Prop) → Storage → Prop + +/-- What a model's outcome means for an assertion: a result's assertion at its final +storage, or the revert predicate on the revert data. -/ +def Assn.ofOutcome : Except Revert (Assn × Storage) → (Revert → Prop) → Prop + | .ok (p, s'), herr => p herr s' + | .error e, herr => herr e + +/-- `SolM` is a Loom ordered monad algebra on `Assn`. -/ +instance : MAlgOrdered SolM Assn where + μ x := fun herr s => Assn.ofOutcome (x s) herr + μ_ord_pure := by intro l; rfl + μ_ord_bind := by + intro α f g h x herr s + show Assn.ofOutcome ((x s).bind fun a => f a.1 a.2) herr → + Assn.ofOutcome ((x s).bind fun a => g a.1 a.2) herr + rcases x s with e | ⟨a, s'⟩ + · exact id + · exact h a herr s' + +/-! ## Weakest preconditions of the model's primitives -/ + +theorem wp_eq (x : SolM α) (post : α → Assn) : + wp x post = fun herr s => match x s with + | .ok (a, s') => post a herr s' + | .error e => herr e := by + funext herr s + show Assn.ofOutcome ((post <$> x) s) herr = _ + simp only [Functor.map, StateT.map] + rcases h : x s with e | ⟨a, s'⟩ <;> simp [h, Assn.ofOutcome, bind, Except.bind, pure, Except.pure] + +/-- Read a storage slot. -/ +def sload (slot : Nat) : SolM Nat := fun s => .ok (s slot, s) + +/-- Write a storage slot. Slots and values are 256-bit words, as in `slotValue` and +SolidCore's storage: a write to `slot` is a write to every slot equal to it modulo +`2 ^ 256`. -/ +def sstore (slot v : Nat) : SolM Unit := + fun s => .ok ((), fun k => if k % 2 ^ 256 = slot % 2 ^ 256 then v % 2 ^ 256 else s k) + +/-- Revert with `data`. -/ +def revert (data : Revert) : SolM α := fun _ => .error data + +@[simp] theorem wp_sload (slot : Nat) (post : Nat → Assn) : + wp (sload slot) post = fun herr s => post (s slot) herr s := by + rw [wp_eq]; rfl + +@[simp] theorem wp_sstore (slot v : Nat) (post : Unit → Assn) : + wp (sstore slot v) post = fun herr s => + post () herr (fun k => if k % 2 ^ 256 = slot % 2 ^ 256 then v % 2 ^ 256 else s k) := by + rw [wp_eq]; rfl + +@[simp] theorem wp_revert (data : Revert) (post : α → Assn) : + wp (revert data : SolM α) post = fun herr _ => herr data := by + rw [wp_eq]; rfl + +@[simp] theorem wp_ite (c : Prop) [Decidable c] (x y : SolM α) (post : α → Assn) : + wp (if c then x else y) post = if c then wp x post else wp y post := by + split <;> rfl + + +/-! ## `SolM`'s algebra is Loom's `StateT` algebra over the error-aware `Except` algebra + +Loom's `StateT` algebra over `Except Revert`'s error-aware algebra (`MAlgExceptErrProp`) +has assertions `Storage → (Revert → Prop) → Prop`; `Assn` takes the same two arguments in +the other order. `wp_eq_loom` says that the two weakest preconditions are the same, so every +rule of Loom's generic algebras holds of `SolM`'s. -/ + +/-- Loom's algebra of `SolM`: the `StateT` algebra over `Except Revert`'s error-aware one. -/ +noncomputable abbrev loomAlg : MAlgOrdered SolM (Storage → (Revert → Prop) → Prop) := + instMAlgOrderedStateTForallOfLawfulMonad Storage ((Revert → Prop) → Prop) (Except Revert) + +theorem wp_eq_loom (x : SolM α) (post : α → Assn) : + wp x post = fun herr s => + wp (mprop := loomAlg) x (fun a s' herr' => post a herr' s') s herr := by + funext herr s + rw [wp_eq] + show _ = Except.errProp herr ((fun fs : (Storage → (Revert → Prop) → Prop) × Storage => fs.1 fs.2) <$> + (StateT.map (fun a s' herr' => post a herr' s') x s)) + simp only [StateT.map] + rcases h : x s with e | ⟨a, s'⟩ <;> rfl + +@[simp] theorem wp_get (post : Storage → Assn) : + wp (get : SolM Storage) post = fun herr s => post s herr s := by + rw [wp_eq]; rfl + +@[simp] theorem wp_set (s' : Storage) (post : PUnit → Assn) : + wp (set s' : SolM PUnit) post = fun herr _ => post () herr s' := by + rw [wp_eq]; rfl + +@[simp] theorem wp_modify (f : Storage → Storage) (post : PUnit → Assn) : + wp (modify f : SolM PUnit) post = fun herr s => post () herr (f s) := by + rw [wp_eq]; rfl + +@[simp] theorem wp_throw (e : Revert) (post : α → Assn) : + wp (throw e : SolM α) post = fun herr _ => herr e := by + rw [wp_eq]; rfl + +/-! ## Loops + +A loop of a model is `Loop.whileBounded` (Loom's `WP.Variant`): a model cannot diverge, so +it is given the number of iterations to allow. `triple_while` proves it from an invariant and +a variant; with fuel above the variant the loop never runs out, so the model is the +unbounded loop's. -/ + +/-- A `while` loop of a model, run at most `fuel` times; out of fuel, it reverts with no data +(which the variant rule shows unreachable). -/ +abbrev whileM (cond : β → Bool) (body : β → SolM β) (fuel : Nat) (b : β) : SolM β := + Loop.whileBounded (fun _ => revert []) cond body fuel b + +/-- The total-correctness rule for a model's loop, on `Assn`. -/ +theorem triple_whileM (cond : β → Bool) (body : β → SolM β) (inv : β → Assn) + (measure : β → Nat) + (hbody : ∀ b, cond b = true → + triple (inv b) (body b) (fun b' => inv b' ⊓ ⌜measure b' < measure b⌝)) + (fuel : Nat) (init : β) (hfuel : measure init < fuel) : + triple (inv init) (whileM cond body fuel init) (fun b => inv b ⊓ ⌜cond b = false⌝) := + triple_while _ cond body inv measure hbody fuel init hfuel + +/-! ## Models, triples and the generator -/ + +/-- The observable of a model's outcome, from the initial storage `s`: a returned word +list and the final storage, or a revert with its data and the initial storage. A model +emits no logs. -/ +def observe (s : Storage) : Except Revert (List Nat × Storage) → Observable + | .ok (out, s') => { success := true, output := out, logs := [], storage := s' } + | .error e => { success := false, output := e, logs := [], storage := s } + +/-- The storage a call starts from, as a function. -/ +def initStorage (call : Call) : Storage := slotValue call.storage + +/-- `model` implements `contract` on `scope`: on every call of it, SolidCore with `fuel` +finishes with the observable of the model on the call's argument words `args call`. -/ +def Implements (fuel : Nat) (contract : SolidCore.Solidity.TypeCheck.CheckedContract) + (scope : Call → Prop) (args : Call → List Nat) (model : List Nat → SolM (List Nat)) : Prop := + ∀ call, scope call → + Source.run fuel contract call = some (observe (initStorage call) (model (args call) (initStorage call))) + +/-- The triple `{pre} contract {post}` on `scope`, against SolidCore: every call of the +scope that meets `pre` finishes, and every observable it finishes with meets `post`. -/ +def Triple (fuel : Nat) (contract : SolidCore.Solidity.TypeCheck.CheckedContract) + (scope : Call → Prop) (pre : Call → Prop) (post : Call → Observable → Prop) : Prop := + ∀ call, scope call → pre call → + (Source.run fuel contract call).isSome ∧ + ∀ obs, Source.run fuel contract call = some obs → post call obs + +/-- Total correctness of `p` in `S` on `scope`: every call that meets `pre` finishes with an +observable that meets `post`. The same statement as the refinement's `Satisfies`. -/ +def Satisfies (S : Sem) (p : S.Prog) (scope : Call → Prop) (pre : Call → Prop) + (post : Call → Observable → Prop) : Prop := + ∀ call, scope call → pre call → ∃ obs, S.run p call = some obs ∧ post call obs + +/-- The verification condition of a model: Loom's weakest precondition of the model on +the call's argument words, for the postcondition on a success and on a revert, at the +call's initial storage. -/ +def vc (model : List Nat → SolM (List Nat)) (args : Call → List Nat) + (post : Call → Observable → Prop) (call : Call) : Prop := + wp (model (args call)) + (fun out _ s' => post call { success := true, output := out, logs := [], storage := s' }) + (fun e => post call { success := false, output := e, logs := [], storage := initStorage call }) + (initStorage call) + +/-- The generator's soundness: a model that implements the contract and whose +verification condition holds under the precondition gives the triple. -/ +theorem triple_of_wp {fuel : Nat} {contract : SolidCore.Solidity.TypeCheck.CheckedContract} + {scope : Call → Prop} {args : Call → List Nat} {model : List Nat → SolM (List Nat)} + {pre : Call → Prop} {post : Call → Observable → Prop} + (himpl : Implements fuel contract scope args model) + (hvc : ∀ call, scope call → pre call → vc model args post call) : + Triple fuel contract scope pre post := by + intro call hs hp + have hrun := himpl call hs + have h := hvc call hs hp + simp only [vc, wp_eq] at h + refine ⟨by simp [hrun], fun obs hobs => ?_⟩ + rw [hrun] at hobs + cases hobs + revert h + rcases model (args call) (initStorage call) with e | ⟨out, s'⟩ <;> exact id + +theorem satisfies_iff_triple {fuel : Nat} {contract : SolidCore.Solidity.TypeCheck.CheckedContract} + {scope pre : Call → Prop} {post : Call → Observable → Prop} : + Satisfies (solidCore fuel) contract scope pre post ↔ Triple fuel contract scope pre post := by + constructor + · intro h call hs hp + obtain ⟨obs, hrun, hpost⟩ := h call hs hp + exact ⟨by simp [solidCore] at hrun; simp [hrun], fun o ho => by + simp [solidCore] at hrun; rw [hrun] at ho; cases ho; exact hpost⟩ + · intro h call hs hp + obtain ⟨hsome, hpost⟩ := h call hs hp + obtain ⟨obs, hobs⟩ := Option.isSome_iff_exists.mp hsome + exact ⟨obs, hobs, hpost obs hobs⟩ + +theorem satisfies_of_triple {fuel : Nat} {contract : SolidCore.Solidity.TypeCheck.CheckedContract} + {scope pre : Call → Prop} {post : Call → Observable → Prop} + (h : Triple fuel contract scope pre post) : + Satisfies (solidCore fuel) contract scope pre post := + satisfies_iff_triple.mpr h + + +/-! ## Termination + +The triple includes that the call finishes: `Triple.finishes` gives the observable at the +triple's fuel. A model with a loop needs fuel that grows with its arguments, so +`ImplementsSome` asks for some fuel per call, `TripleSome` concludes that each call finishes +at some fuel with an observable that meets the postcondition, and `tripleSome_of_wp` is the +generator's soundness for it. -/ + +theorem Triple.finishes {fuel : Nat} {contract : SolidCore.Solidity.TypeCheck.CheckedContract} + {scope pre : Call → Prop} {post : Call → Observable → Prop} + (h : Triple fuel contract scope pre post) : + ∀ call, scope call → pre call → ∃ obs, Source.run fuel contract call = some obs ∧ post call obs := by + intro call hs hp + obtain ⟨hsome, hpost⟩ := h call hs hp + obtain ⟨obs, hobs⟩ := Option.isSome_iff_exists.mp hsome + exact ⟨obs, hobs, hpost obs hobs⟩ + +/-- `model` implements `contract` on `scope` at some fuel per call. -/ +def ImplementsSome (contract : SolidCore.Solidity.TypeCheck.CheckedContract) + (scope : Call → Prop) (args : Call → List Nat) (model : List Nat → SolM (List Nat)) : Prop := + ∀ call, scope call → ∃ fuel, + Source.run fuel contract call = some (observe (initStorage call) (model (args call) (initStorage call))) + +/-- Every call of the scope that meets `pre` finishes at some fuel, and every observable it +finishes with at that fuel meets `post`. -/ +def TripleSome (contract : SolidCore.Solidity.TypeCheck.CheckedContract) + (scope : Call → Prop) (pre : Call → Prop) (post : Call → Observable → Prop) : Prop := + ∀ call, scope call → pre call → ∃ fuel obs, Source.run fuel contract call = some obs ∧ post call obs + +theorem Implements.some {fuel : Nat} {contract : SolidCore.Solidity.TypeCheck.CheckedContract} + {scope : Call → Prop} {args : Call → List Nat} {model : List Nat → SolM (List Nat)} + (h : Implements fuel contract scope args model) : ImplementsSome contract scope args model := + fun call hs => ⟨fuel, h call hs⟩ + +theorem tripleSome_of_wp {contract : SolidCore.Solidity.TypeCheck.CheckedContract} + {scope : Call → Prop} {args : Call → List Nat} {model : List Nat → SolM (List Nat)} + {pre : Call → Prop} {post : Call → Observable → Prop} + (himpl : ImplementsSome contract scope args model) + (hvc : ∀ call, scope call → pre call → vc model args post call) : + TripleSome contract scope pre post := by + intro call hs hp + obtain ⟨fuel, hrun⟩ := himpl call hs + have h := hvc call hs hp + simp only [vc, wp_eq] at h + refine ⟨fuel, _, hrun, ?_⟩ + revert h + rcases model (args call) (initStorage call) with e | ⟨out, s'⟩ <;> exact id + +theorem Triple.some {fuel : Nat} {contract : SolidCore.Solidity.TypeCheck.CheckedContract} + {scope pre : Call → Prop} {post : Call → Observable → Prop} + (h : Triple fuel contract scope pre post) : TripleSome contract scope pre post := by + intro call hs hp + obtain ⟨obs, hobs, hpost⟩ := h.finishes call hs hp + exact ⟨fuel, obs, hobs, hpost⟩ + +end SolidCore.Verify + diff --git a/Verify/C1.lean b/Verify/C1.lean new file mode 100644 index 00000000..8558a063 --- /dev/null +++ b/Verify/C1.lean @@ -0,0 +1,222 @@ +import Verify.Tactic +import SolidCore.Refinement.Corpus.C1 + +/-! +# c1: `f(uint8 x)` returns `x * 3 + 1`, or panics on overflow + +The specification of `Main.f` in `scripts/refinement/corpus/c1.sol`, proved against SolidCore +with the Loom VC generator of `Verify.Basic`: on every call of `f` with a clean argument +word `x < 256`, from the deployed (empty) storage, the call returns the word `3 * x + 1` when +`x ≤ 84`, and reverts with `Panic(0x11)` when `x ≥ 85`, the first argument for which +`x * 3 + 1` does not fit in `uint8`; it emits no logs and leaves storage empty. + +`model` is the function as a `SolM` program. `run_f` ties it to SolidCore by symbolic +evaluation of the interpreter on a free clean word (`wide_symex`), once `shape_of` gives +that the checked contract's core is the literal `coreLit` and its constructor leaves empty +storage and no logs, from c1's refinement (`Corpus.C1.shape_of`, the kernel's one conversion +check of the type checker's output, `kernel_rfl`); `implements_of_run` turns it into +`Implements`. `sc_vcgen` proves the verification conditions on every argument word, which +`vcs_mono` restricts to the scope. +-/ + +namespace SolidCore.Verify.C1 + +open EthLib.Base SolidCore.Refinement SolidCore.Refinement.Abi SolidCore.Refinement.Wide +open SolidCore.Refinement.Evm.Wide SolidCore.Solidity SolidCore.Solidity.Source +open SolidCore.Refinement.Corpus.C1 + +/-- `f` as a Loom program over the storage. -/ +def model (ws : List Nat) : SolM (List Nat) := + if ws.getD 0 0 * 3 + 1 < 2 ^ 8 then pure (word (ws.getD 0 0 * 3 + 1)) else revert (panic 0x11) + +/-- The calls of the specification: `f` on every clean argument word, from the deployed +storage, the scope of c1's refinement (`Corpus.C1.scope []`). -/ +def scope : Call → Prop := (· ∈ calls fns [[]]) + +/-- The precondition: none beyond the scope. -/ +def pre : Call → Prop := fun _ => True + +/-- `f(x)` returns `3 * x + 1` for `x ≤ 84` and reverts with `Panic(0x11)` for `x ≥ 85`, +with no logs and empty storage. -/ +def post (call : Call) (obs : Observable) : Prop := + let x := (argWords 1 call).getD 0 0 + (x ≤ 84 → obs.success = true ∧ obs.output = word (3 * x + 1)) ∧ + (85 ≤ x → obs.success = false ∧ obs.output = panic 0x11) ∧ + obs.logs = [] ∧ ∀ slot, obs.storage slot = 0 + +/-- SolidCore's core contract of c1's `Main`, as the type checker leaves it. -/ +def coreLit : Contract := + { storageFields := [], + immutableFields := [], + eventDecls := [], + errorDecls := [], + functions := [{ name := "f", + selector? := some 824235060, + payable := false, + params := [{ name := "x", ty := SolidCore.Solidity.Source.Ty.uint256, isStorageRef := false }], + paramAbiCleanups := [SolidCore.Solidity.Source.AbiCleanup.uint 8], + returns := [{ name := "_ret0", ty := SolidCore.Solidity.Source.Ty.uint256, isStorageRef := false }], + body := SolidCore.Solidity.Source.Stmt.block + [SolidCore.Solidity.Source.Stmt.assign + (SolidCore.Solidity.Source.LValue.var "x") + (SolidCore.Solidity.Source.Expr.castOp + (SolidCore.Solidity.Source.CastKind.uintCleanup) + 8 + (SolidCore.Solidity.Source.Expr.var "x")), + SolidCore.Solidity.Source.Stmt.skip, + SolidCore.Solidity.Source.Stmt.block + [SolidCore.Solidity.Source.Stmt.returnValues + [SolidCore.Solidity.Source.Expr.castOp + (SolidCore.Solidity.Source.CastKind.uintCleanup) + 8 + (SolidCore.Solidity.Source.Expr.castOp + (SolidCore.Solidity.Source.CastKind.uintCleanup) + 8 + (SolidCore.Solidity.Source.Expr.binary + (SolidCore.Solidity.Source.BinaryOp.add) + (SolidCore.Solidity.Source.Expr.castOp + (SolidCore.Solidity.Source.CastKind.uintCleanup) + 8 + (SolidCore.Solidity.Source.Expr.castOp + (SolidCore.Solidity.Source.CastKind.uintCleanup) + 8 + (SolidCore.Solidity.Source.Expr.binary + (SolidCore.Solidity.Source.BinaryOp.mul) + (SolidCore.Solidity.Source.Expr.castOp + (SolidCore.Solidity.Source.CastKind.uintCleanup) + 8 + (SolidCore.Solidity.Source.Expr.var "x")) + (SolidCore.Solidity.Source.Expr.castOp + (SolidCore.Solidity.Source.CastKind.uintCast) + 8 + (SolidCore.Solidity.Source.Expr.word 3))))) + (SolidCore.Solidity.Source.Expr.castOp + (SolidCore.Solidity.Source.CastKind.uintCast) + 8 + (SolidCore.Solidity.Source.Expr.word 1))))]]], + dispatchId? := none }, + { name := "__internal_f(uint8)#[SolidCore.Solidity.Ty.uint 8]", + selector? := none, + payable := false, + params := [{ name := "x", ty := SolidCore.Solidity.Source.Ty.uint256, isStorageRef := false }], + paramAbiCleanups := [SolidCore.Solidity.Source.AbiCleanup.uint 8], + returns := [{ name := "_ret0", ty := SolidCore.Solidity.Source.Ty.uint256, isStorageRef := false }], + body := SolidCore.Solidity.Source.Stmt.block + [SolidCore.Solidity.Source.Stmt.assign + (SolidCore.Solidity.Source.LValue.var "x") + (SolidCore.Solidity.Source.Expr.castOp + (SolidCore.Solidity.Source.CastKind.uintCleanup) + 8 + (SolidCore.Solidity.Source.Expr.var "x")), + SolidCore.Solidity.Source.Stmt.skip, + SolidCore.Solidity.Source.Stmt.block + [SolidCore.Solidity.Source.Stmt.returnValues + [SolidCore.Solidity.Source.Expr.castOp + (SolidCore.Solidity.Source.CastKind.uintCleanup) + 8 + (SolidCore.Solidity.Source.Expr.castOp + (SolidCore.Solidity.Source.CastKind.uintCleanup) + 8 + (SolidCore.Solidity.Source.Expr.binary + (SolidCore.Solidity.Source.BinaryOp.add) + (SolidCore.Solidity.Source.Expr.castOp + (SolidCore.Solidity.Source.CastKind.uintCleanup) + 8 + (SolidCore.Solidity.Source.Expr.castOp + (SolidCore.Solidity.Source.CastKind.uintCleanup) + 8 + (SolidCore.Solidity.Source.Expr.binary + (SolidCore.Solidity.Source.BinaryOp.mul) + (SolidCore.Solidity.Source.Expr.castOp + (SolidCore.Solidity.Source.CastKind.uintCleanup) + 8 + (SolidCore.Solidity.Source.Expr.var "x")) + (SolidCore.Solidity.Source.Expr.castOp + (SolidCore.Solidity.Source.CastKind.uintCast) + 8 + (SolidCore.Solidity.Source.Expr.word 3))))) + (SolidCore.Solidity.Source.Expr.castOp + (SolidCore.Solidity.Source.CastKind.uintCast) + 8 + (SolidCore.Solidity.Source.Expr.word 1))))]]], + dispatchId? := none }] } + +/-- `coreLit` is the refinement's print of the core, `Corpus.C1.coreLit`. -/ +theorem coreLit_eq : coreLit = Corpus.C1.coreLit := rfl + +/-- The checked contract has the core `coreLit`, and its constructor leaves empty storage and +no logs: `Corpus.C1.shape_of`, the kernel's conversion check of the type checker's output +(`kernel_rfl`). -/ +theorem shape_of {c : TypeCheck.CheckedContract} (hc : contract? = .ok c) : + c.core = coreLit ∧ deployedStorage fuel c = some [] ∧ ∃ d, DeployedAt fuel c d [] := by + obtain ⟨hk, hs, he⟩ := Corpus.C1.shape_of hc + obtain ⟨d, hd⟩ := deployed_of he + exact ⟨hk.trans coreLit_eq.symm, hs, d, deployedAt_of_deployed hd⟩ + +set_option maxHeartbeats 0 in +set_option maxRecDepth 100000 in +/-- SolidCore runs `f` on any clean argument word as `model` does. -/ +theorem run_f {c : TypeCheck.CheckedContract} (hcore : c.core = coreLit) {d : Source.State} + (hd : DeployedAt fuel c d []) (w : U256) (hw : w.toNat < 2 ^ 8) : + Source.run fuel c (callAt Bytecode.C1.Main.fSelector [w] []) = + some (observe (slotValue []) (model [w.toNat] (slotValue []))) := by + rw [run_eq_at hd] + have hev := hd.events + have hs : d.storage.isEmpty = true := by + rw [← Std.HashMap.isEmpty_toList, hd.storage]; rfl + simp only [Nat.reducePow] at hw + simp only [hcore, List.map_cons, List.map_nil, List.foldl_nil] + wide_symex [coreLit, fuel, ctxOf, hcore, Bytecode.C1.Main.fSelector] + all_goals + simp only [model, List.getD_cons_zero] + split + all_goals + try rw [Nat.mod_eq_of_lt (by omega)] + simp [Source.observe, observe, revert, pure, StateT.pure, Except.pure, panic, word, + State.logEntries, State.loadSlot, StorageMap.lookup?, getElem?_of_isEmpty hs, hev, + slotValue, callAt] + all_goals first + | (funext k; rfl) + | (simp (disch := omega) only [Nat.reducePow, Nat.mod_eq_of_lt] at *; omega) + +/-- Every call of the scope is a call of `Abi.fullScope` on a clean word. -/ +theorem scope_sub (call : Call) (h : scope call) : + fullScope fns [] call ∧ (argWords 1 call).getD 0 0 < 2 ^ 8 := by + simp only [scope, calls, fns, tuples, Param.values, List.flatMap_cons, List.flatMap_nil, + List.append_nil, List.mem_flatMap, List.mem_map, List.mem_range, List.mem_cons, + List.not_mem_nil, or_false, exists_eq_left] at h + obtain ⟨_, ⟨a, ha, rfl⟩, rfl⟩ := h + have hb : ∀ b ∈ [a], b < 2 ^ 256 := by simp; omega + refine ⟨⟨_, List.mem_singleton_self _, [a], rfl, hb, rfl⟩, ?_⟩ + rw [show argWords 1 _ = [a] from argWords_calldata _ [a] hb 0 []] + simpa using ha + +/-- `model` implements SolidCore's `Main` on every call of the scope. -/ +theorem implements {c : TypeCheck.CheckedContract} (hcore : c.core = coreLit) {d : Source.State} + (hd : DeployedAt fuel c d []) : Implements fuel c scope (argWords 1) model := + (implements_of_run (ok := fun ws => ws.getD 0 0 < 2 ^ 8) (by simp [fns]) + fun fn hfn ws hl hok => by + simp only [fns, List.mem_cons, List.not_mem_nil, or_false] at hfn + subst hfn + rcases ws with _ | ⟨w, _ | _⟩ <;> simp at hl + exact run_f hcore hd w (by simpa using hok)).mono scope_sub + +/-- The verification conditions of `f`, by Loom's weakest preconditions. -/ +theorem vcs : ∀ call, scope call → pre call → vc model (argWords 1) post call := + vcs_mono (scope := fullScope fns []) (by sc_vcgen [fns, model, post]) + fun call h => (scope_sub call h).1 + +/-- **The specification of `c1`'s `f`**, as a triple against SolidCore. -/ +theorem spec : ∃ c, contract? = .ok c ∧ deployedStorage fuel c = some [] ∧ + Triple fuel c scope pre post := by + obtain ⟨c, hc⟩ := contract_ok + obtain ⟨hk, hs, d, hd⟩ := shape_of hc + exact ⟨c, hc, hs, triple_of_wp (implements hk hd) vcs⟩ + +/-- The specification of `c1`'s `f` as `Satisfies` on SolidCore. -/ +theorem satisfies : ∃ c, contract? = .ok c ∧ deployedStorage fuel c = some [] ∧ + Satisfies (solidCore fuel) c scope pre post := by + obtain ⟨c, hc, hs, h⟩ := spec + exact ⟨c, hc, hs, satisfies_of_triple h⟩ + +end SolidCore.Verify.C1 diff --git a/Verify/C4.lean b/Verify/C4.lean new file mode 100644 index 00000000..f2d170af --- /dev/null +++ b/Verify/C4.lean @@ -0,0 +1,458 @@ +import Verify.Tactic +import SolidCore.Refinement.Corpus.C4 + +/-! +# c4: `add(uint8 x)` adds to a packed `uint8 v` and xors a packed `uint8 w` + +The specification of `Main.add` in `scripts/refinement/corpus/c4.sol` +(`uint8 v; uint8 w = 7;` `v += x; w ^= x; return v;`), proved against SolidCore with the Loom +VC generator of `Verify.Basic`, on the scope of c4's refinement: every call of `add` on any +argument word below `2 ^ 256`, from the storage the constructor leaves. `v` and `w` share +slot 0, `v` in its low byte and `w` in the next, so the deployed storage is slot 0 = `7 * 256`. + +From there `v + x` never overflows, so a clean `x < 2 ^ 8` returns `x` and leaves slot 0 +holding `x + (7 ^ x) * 256`; the `Panic(0x11)` branch of the model is unreachable on the +scope. A dirty word reverts with empty data in SolidCore's ABI decoder and keeps the storage. + +`model` is the function as a `SolM` program on any storage: it reads slot 0, panics when +`v + x` does not fit in `uint8`, and writes the packed `(v + x, w ^ x)` back, keeping the +slot's higher bytes. `run_add` ties it to SolidCore by symbolic evaluation of the interpreter +on a free word (`wide_symex`, clean and dirty alike), from the deployed state with the call's +storage written over it (`run_eq_at`), once `shape_of` gives that the checked contract's core +is the literal `coreLit` and its constructor leaves exactly slot 0 = `7 * 256` and no logs, +from c4's refinement (`Corpus.C4.shape_of`, the kernel's one conversion check of the type +checker's output, `kernel_rfl`). `sc_vcgen` proves the verification conditions. + +`specAt` widens it to any storage that writes slot 0 (`scopeAt`): `run_add_at` runs SolidCore +on a symbolic slot-0 word, and `postAt` is the model's outcome from it (`model_ok`, +`model_panic`, `model_dirty`). +-/ + +namespace SolidCore.Verify.C4 + +open EthLib.Base SolidCore.Refinement SolidCore.Refinement.Abi SolidCore.Refinement.Wide +open SolidCore.Refinement.Evm.Wide SolidCore.Solidity SolidCore.Solidity.Source +open SolidCore.Refinement.Corpus.C4 + +/-- SolidCore's core contract of c4's `Main`, as the type checker leaves it. -/ +def coreLit : Contract := + { storageFields := [{ name := "v", + slot := 0, + ty? := some (SolidCore.Solidity.Source.Ty.uint256), + layout? := some (SolidCore.Solidity.Source.StorageLayout.scalar + (SolidCore.Solidity.Source.Ty.uint256)), + transient := false, + packedOffset := 0, + packedBytes := 1, + packedSigned := false }, + { name := "w", + slot := 0, + ty? := some (SolidCore.Solidity.Source.Ty.uint256), + layout? := some (SolidCore.Solidity.Source.StorageLayout.scalar + (SolidCore.Solidity.Source.Ty.uint256)), + transient := false, + packedOffset := 1, + packedBytes := 1, + packedSigned := false }], + immutableFields := [], + eventDecls := [], + errorDecls := [], + functions := [{ name := "add", + selector? := some 33980010, + payable := false, + params := [{ name := "x", ty := SolidCore.Solidity.Source.Ty.uint256, isStorageRef := false }], + paramAbiCleanups := [SolidCore.Solidity.Source.AbiCleanup.uint 8], + returns := [{ name := "_ret0", ty := SolidCore.Solidity.Source.Ty.uint256, isStorageRef := false }], + body := SolidCore.Solidity.Source.Stmt.block + [SolidCore.Solidity.Source.Stmt.assign + (SolidCore.Solidity.Source.LValue.var "x") + (SolidCore.Solidity.Source.Expr.castOp + (SolidCore.Solidity.Source.CastKind.uintCleanup) + 8 + (SolidCore.Solidity.Source.Expr.var "x")), + SolidCore.Solidity.Source.Stmt.skip, + SolidCore.Solidity.Source.Stmt.block + [SolidCore.Solidity.Source.Stmt.exprStmt + (SolidCore.Solidity.Source.Expr.assignment + (some (SolidCore.Solidity.Source.BinaryOp.add)) + (some (SolidCore.Solidity.Source.ValueCleanup.uint 8)) + (SolidCore.Solidity.Source.Expr.storageRead + (SolidCore.Solidity.Source.StorageReadMode.header) + "v" + []) + (SolidCore.Solidity.Source.Expr.var "x")), + SolidCore.Solidity.Source.Stmt.exprStmt + (SolidCore.Solidity.Source.Expr.assignment + (some (SolidCore.Solidity.Source.BinaryOp.bitXor)) + (some (SolidCore.Solidity.Source.ValueCleanup.uint 8)) + (SolidCore.Solidity.Source.Expr.storageRead + (SolidCore.Solidity.Source.StorageReadMode.header) + "w" + []) + (SolidCore.Solidity.Source.Expr.var "x")), + SolidCore.Solidity.Source.Stmt.returnValues + [SolidCore.Solidity.Source.Expr.castOp + (SolidCore.Solidity.Source.CastKind.uintCleanup) + 8 + (SolidCore.Solidity.Source.Expr.storageRead + (SolidCore.Solidity.Source.StorageReadMode.ref) + "v" + [])]]], + dispatchId? := none }, + { name := "__internal_add(uint8)#[SolidCore.Solidity.Ty.uint 8]", + selector? := none, + payable := false, + params := [{ name := "x", ty := SolidCore.Solidity.Source.Ty.uint256, isStorageRef := false }], + paramAbiCleanups := [SolidCore.Solidity.Source.AbiCleanup.uint 8], + returns := [{ name := "_ret0", ty := SolidCore.Solidity.Source.Ty.uint256, isStorageRef := false }], + body := SolidCore.Solidity.Source.Stmt.block + [SolidCore.Solidity.Source.Stmt.assign + (SolidCore.Solidity.Source.LValue.var "x") + (SolidCore.Solidity.Source.Expr.castOp + (SolidCore.Solidity.Source.CastKind.uintCleanup) + 8 + (SolidCore.Solidity.Source.Expr.var "x")), + SolidCore.Solidity.Source.Stmt.skip, + SolidCore.Solidity.Source.Stmt.block + [SolidCore.Solidity.Source.Stmt.exprStmt + (SolidCore.Solidity.Source.Expr.assignment + (some (SolidCore.Solidity.Source.BinaryOp.add)) + (some (SolidCore.Solidity.Source.ValueCleanup.uint 8)) + (SolidCore.Solidity.Source.Expr.storageRead + (SolidCore.Solidity.Source.StorageReadMode.header) + "v" + []) + (SolidCore.Solidity.Source.Expr.var "x")), + SolidCore.Solidity.Source.Stmt.exprStmt + (SolidCore.Solidity.Source.Expr.assignment + (some (SolidCore.Solidity.Source.BinaryOp.bitXor)) + (some (SolidCore.Solidity.Source.ValueCleanup.uint 8)) + (SolidCore.Solidity.Source.Expr.storageRead + (SolidCore.Solidity.Source.StorageReadMode.header) + "w" + []) + (SolidCore.Solidity.Source.Expr.var "x")), + SolidCore.Solidity.Source.Stmt.returnValues + [SolidCore.Solidity.Source.Expr.castOp + (SolidCore.Solidity.Source.CastKind.uintCleanup) + 8 + (SolidCore.Solidity.Source.Expr.storageRead + (SolidCore.Solidity.Source.StorageReadMode.ref) + "v" + [])]]], + dispatchId? := none }] } + +/-- `coreLit` is the refinement's print of the core, `Corpus.C4.coreLit`. -/ +theorem coreLit_eq : coreLit = Corpus.C4.coreLit := rfl + +/-- The storage the constructor leaves: `v = 0` in the low byte of slot 0, `w = 7` in the +next. -/ +def deployed : List (Nat × Nat) := [(0, 7 * 256)] + +/-- `add` as a Loom program over the storage: a dirty word reverts with empty data; else +`v` (the low byte of slot 0) plus `x` panics when it overflows `uint8`, and otherwise slot 0 +gets `v + x` in its low byte and `w ^ x` in the next, and the call returns `v + x`. -/ +def model (ws : List Nat) : SolM (List Nat) := + if ws.getD 0 0 < 2 ^ 8 then do + let s0 ← sload 0 + if s0 % 2 ^ 8 + ws.getD 0 0 < 2 ^ 8 then do + sstore 0 (s0 / 2 ^ 16 * 2 ^ 16 + (s0 / 2 ^ 8 % 2 ^ 8 ^^^ ws.getD 0 0) * 2 ^ 8 + + (s0 % 2 ^ 8 + ws.getD 0 0)) + pure (word (s0 % 2 ^ 8 + ws.getD 0 0)) + else revert (panic 0x11) + else revert [] + +set_option maxHeartbeats 0 in +set_option maxRecDepth 100000 in +/-- SolidCore runs `add` on any argument word, from the deployed storage, as `model` does. -/ +theorem run_add {c : TypeCheck.CheckedContract} (hcore : c.core = coreLit) {d : Source.State} + (hd : DeployedAt fuel c d deployed) (w : U256) : + Source.run fuel c (callAt Bytecode.C4.Main.addSelector [w] deployed) = + some (observe (slotValue deployed) (model [w.toNat] (slotValue deployed))) := by + rw [run_eq_at hd] + have hev := hd.events + have hnone : ∀ k, k ≠ 0 → d.storage.get? k = none := fun k hk => by + rw [Std.HashMap.get?_eq_getElem?] + exact hd.getElem?_eq_none (by simp [deployed]; omega) + simp only [hcore, List.map_cons, List.map_nil, deployed, List.foldl_cons, List.foldl_nil] + wide_symex [coreLit, fuel, ctxOf, hcore, Bytecode.C4.Main.addSelector, + get?_insert] + all_goals + have hw := w.isLt + generalize BitVec.toNat w = x at * + simp only [Nat.reducePow] at hw + · have h1 : (1792 + x) % 2 ^ 256 = 1792 + x := Nat.mod_eq_of_lt (by omega) + simp only [Nat.reducePow] at h1 + have h2 : (1792 + x) / 256 % 256 = 7 := by omega + have h3 : 1792 + x - 7 * 256 = x := by omega + have h4 : (7 ^^^ x) < 256 := Nat.xor_lt_two_pow (n := 8) (by omega) (by omega) + simp only [h1, h2, h3] + simp [Source.observe, observe, model, sload, sstore, bind, StateT.bind, pure, StateT.pure, + Except.bind, Except.pure, slotValue, callAt, State.loadSlot, StorageMap.lookup?, get?_insert, + hev, State.logEntries, *, Nat.mod_eq_of_lt, word] + funext slot + simp only [Std.HashMap.getElem?_insert, Shared.norm, Shared.wordModulus, beq_iff_eq] + try rw [show EvmYul.UInt256.size = 2 ^ 256 from rfl] + generalize slot % 115792089237316195423570985008687907853269984665640564039457584007913129639936 = k + by_cases h : k = 0 + · subst h; simp; rw [Nat.add_comm] + · have h' : ¬0 = k := fun e => h e.symm + have := hnone k h + rw [Std.HashMap.get?_eq_getElem?] at this + simp [h, h', this] + · simp [Source.observe, observe, model, revert, slotValue, callAt, State.loadSlot, + StorageMap.lookup?, get?_insert, hev, State.logEntries, *] + funext k + simp only [slotValue, List.foldl_cons, List.foldl_nil] + +/-- The calls of the specification: `add` on any argument word, clean or dirty, from the +deployed storage, the scope of c4's refinement (`Corpus.C4.refines_full`). -/ +def scope : Call → Prop := fullScope fns deployed + +/-- No precondition beyond the scope. -/ +def pre : Call → Prop := fun _ => True + +/-- `add(x)` from the deployed storage (`v = 0`, `w = 7`): on a clean `x < 2 ^ 8` it returns +`v + x = x` and leaves slot 0 holding `v' = x` in its low byte and `w' = 7 ^ x` in the next, +every other slot 0; on a dirty word it reverts with empty data and keeps the storage. It +emits no logs. -/ +def post (call : Call) (obs : Observable) : Prop := + let x := (argWords 1 call).getD 0 0 + (if x < 2 ^ 8 then + obs.success = true ∧ obs.output = word x ∧ + ∀ slot, obs.storage slot = if slot % 2 ^ 256 = 0 then x + (7 ^^^ x) * 2 ^ 8 else 0 + else + obs.success = false ∧ obs.output = [] ∧ ∀ slot, obs.storage slot = slotValue deployed slot) ∧ + obs.logs = [] + +/-- The checked contract has the core `coreLit`, and its constructor leaves exactly +`deployed` and no logs: `Corpus.C4.shape_of`, the kernel's conversion check of the type +checker's output (`kernel_rfl`). -/ +theorem shape_of {c : TypeCheck.CheckedContract} (hc : contract? = .ok c) : + c.core = coreLit ∧ deployedStorage fuel c = some deployed ∧ + deployedAt fuel c deployed = true := by + obtain ⟨hk, hs, he⟩ := Corpus.C4.shape_of hc + exact ⟨hk.trans coreLit_eq.symm, hs, he⟩ + +/-- `model` implements SolidCore's `Main` on every call of the scope. -/ +theorem implements {c : TypeCheck.CheckedContract} (hcore : c.core = coreLit) {d : Source.State} + (hd : DeployedAt fuel c d deployed) : Implements fuel c scope (argWords 1) model := + implements_of_run' (by simp [fns]) fun fn hfn ws hl => by + simp only [fns, List.mem_cons, List.not_mem_nil, or_false] at hfn + subst hfn + rcases ws with _ | ⟨w, _ | _⟩ <;> simp at hl + exact run_add hcore hd w + +/-- The verification conditions of `add`, by Loom's weakest preconditions. -/ +theorem vcs : ∀ call, scope call → pre call → vc model (argWords 1) post call := by + sc_vcgen [scope, fns, model, post, deployed] + +/-- **The specification of `c4`'s `add`**, as a triple against SolidCore. -/ +theorem spec : ∃ c, contract? = .ok c ∧ deployedStorage fuel c = some deployed ∧ + Triple fuel c scope pre post := by + obtain ⟨c, hc⟩ := contract_ok + obtain ⟨hk, hs, hdep⟩ := shape_of hc + obtain ⟨d, hd⟩ := deployedAt_of hdep + exact ⟨c, hc, hs, triple_of_wp (implements hk hd) vcs⟩ + +/-- The specification of `c4`'s `add` as `Satisfies` on SolidCore. -/ +theorem satisfies : ∃ c, contract? = .ok c ∧ deployedStorage fuel c = some deployed ∧ + Satisfies (solidCore fuel) c scope pre post := by + obtain ⟨c, hc, hs, h⟩ := spec + exact ⟨c, hc, hs, satisfies_of_triple h⟩ + +/-! ## From any storage + +specAt states the specification on scopeAt, every call of add with no value from any storage σ +that gives slot 0 a word (an entry whose key is 0 modulo 2 ^ 256), the slot v and w share. +SolidCore runs a call from σ written over the deployed storage (run_eq_at), so a storage without +an entry for slot 0 would read the constructor's word 7 * 256 there, which the call's storage +does not show; every other slot reads as σ's, since the constructor writes slot 0 alone. +postAt is the model's outcome from σ: with s0 = slotValue σ 0, a clean x < 2 ^ 8 returns +v + x = s0 % 2 ^ 8 + x and leaves slot 0 with its high bytes kept, w ^ x in its second byte and +v + x in its low byte when v + x fits in uint8, and otherwise reverts with Panic(0x11); a dirty +word reverts with empty data. A revert keeps σ, and no call logs. -/ + +/-- The last write of a slot among σ, over any earlier word, is slotValue's when σ writes the +slot. -/ +theorem foldl_some_of_mem (σ : List (Nat × Nat)) (q : Nat) (hq : q < 2 ^ 256) (a : Option Nat) + (b : Nat) (h : a = some b ∨ ∃ kv ∈ σ, kv.1 % 2 ^ 256 = q) : + σ.foldl (fun acc kv => if Shared.norm kv.1 = q then some (Shared.norm kv.2) else acc) a = + some (σ.foldl (fun acc kv => if kv.1 % 2 ^ 256 = q % 2 ^ 256 then kv.2 % 2 ^ 256 else acc) b) := by + induction σ generalizing a b with + | nil => + rcases h with h | ⟨_, h, _⟩ + · simpa using h + · simp at h + | cons kv σ ih => + simp only [List.foldl_cons] + apply ih + by_cases hk : kv.1 % 2 ^ 256 = q + · left + rw [ite_eq_left_of_eq_true _ _ (eq_true (show Shared.norm kv.1 = q from hk)), + ite_eq_left_of_eq_true _ _ (eq_true (show kv.1 % 2 ^ 256 = q % 2 ^ 256 by + rw [Nat.mod_eq_of_lt hq]; exact hk))] + rfl + · rw [ite_eq_right_of_eq_false _ _ (eq_false (show ¬ Shared.norm kv.1 = q from hk)), + ite_eq_right_of_eq_false _ _ (eq_false (show ¬ kv.1 % 2 ^ 256 = q % 2 ^ 256 by + rw [Nat.mod_eq_of_lt hq]; exact hk))] + rcases h with h | ⟨kv', h', hq'⟩ + · exact Or.inl h + · rcases List.mem_cons.1 h' with rfl | h' + · exact absurd hq' hk + · exact Or.inr ⟨kv', h', hq'⟩ + +theorem model_dirty (x : Nat) (s : Storage) (hx : ¬ x < 256) : model [x] s = .error [] := by + simp [model, hx, revert] + +theorem model_panic (x : Nat) (s : Storage) (hx : x < 256) (h : ¬ s 0 % 256 + x < 256) : + model [x] s = .error (panic 0x11) := by + simp [model, hx, h, revert, sload, bind, StateT.bind, Except.bind] + +theorem model_ok (x : Nat) (s : Storage) (hx : x < 256) (h : s 0 % 256 + x < 256) : + model [x] s = .ok (word (s 0 % 256 + x), fun k => if k % 2 ^ 256 = 0 then + (s 0 / 65536 * 65536 + (s 0 / 256 % 256 ^^^ x) * 256 + (s 0 % 256 + x)) % 2 ^ 256 + else s k) := by + simp [model, hx, h, sload, sstore, bind, StateT.bind, Except.bind, pure, StateT.pure, Except.pure] + +/-- The calls of add on any argument word, with no value, from any storage that writes slot 0. -/ +def scopeAt : Call → Prop := fun call => ∃ σ, (∃ kv ∈ σ, kv.1 % 2 ^ 256 = 0) ∧ fullScope fns σ call + +/-- The deployed scope is the scope from any storage at the deployed storage, which writes +slot 0. -/ +theorem scopeAt_of_scope {call : Call} (h : scope call) : scopeAt call := + ⟨deployed, ⟨(0, 7 * 256), List.mem_singleton_self _, rfl⟩, h⟩ + +/-- add(x) from the storage of the call, with s0 its slot 0: v + x = s0 % 2 ^ 8 + x returned and +slot 0 holding s0's high bytes, w ^ x and v + x when x is clean and v + x fits in uint8, a +Panic(0x11) revert when it does not, and a revert with empty data on a dirty word. A revert +keeps the storage, and no call logs. -/ +def postAt (call : Call) (obs : Observable) : Prop := + let x := (argWords 1 call).getD 0 0 + let s0 := slotValue call.storage 0 + (if x < 2 ^ 8 then + if s0 % 2 ^ 8 + x < 2 ^ 8 then + obs.success = true ∧ obs.output = word (s0 % 2 ^ 8 + x) ∧ + ∀ slot, obs.storage slot = if slot % 2 ^ 256 = 0 then + s0 / 2 ^ 16 * 2 ^ 16 + (s0 / 2 ^ 8 % 2 ^ 8 ^^^ x) * 2 ^ 8 + (s0 % 2 ^ 8 + x) + else slotValue call.storage slot + else + obs.success = false ∧ obs.output = panic 0x11 ∧ + ∀ slot, obs.storage slot = slotValue call.storage slot + else + obs.success = false ∧ obs.output = [] ∧ ∀ slot, obs.storage slot = slotValue call.storage slot) ∧ + obs.logs = [] + +set_option maxHeartbeats 0 in +set_option maxRecDepth 100000 in +/-- SolidCore runs add on any argument word, from any storage σ that writes slot 0, as model +does. -/ +theorem run_add_at {c : TypeCheck.CheckedContract} (hcore : c.core = coreLit) {d : Source.State} + (hd : DeployedAt fuel c d deployed) (w : U256) (σ : List (Nat × Nat)) + (hσ : ∃ kv ∈ σ, kv.1 % 2 ^ 256 = 0) : + Source.run fuel c (callAt Bytecode.C4.Main.addSelector [w] σ) = + some (observe (slotValue σ) (model [w.toNat] (slotValue σ))) := by + rw [run_eq_at hd] + have hev := hd.events + have hm0 : (σ.foldl (fun acc kv => StorageMap.insertLoop acc kv.1 kv.2) d.storage)[0]? = + some (slotValue σ 0) := by + rw [getElem?_foldl_insertLoop] + exact foldl_some_of_mem σ 0 (by decide) _ 0 (Or.inr hσ) + have hmk : ∀ k, k % 2 ^ 256 ≠ 0 → + ((σ.foldl (fun acc kv => StorageMap.insertLoop acc kv.1 kv.2) d.storage)[k % 2 ^ 256]?).getD 0 = + slotValue σ k := by + intro k hk + rw [getElem?_foldl_insertLoop, hd.getElem?_eq_none (by simp [deployed]; omega)] + exact getD_foldl σ k none 0 rfl + generalize σ.foldl (fun acc kv => StorageMap.insertLoop acc kv.1 kv.2) d.storage = m at hm0 hmk + simp only [hcore, List.map_cons, List.map_nil] + wide_symex [coreLit, fuel, ctxOf, hcore, Bytecode.C4.Main.addSelector, hm0] + all_goals + have hw := w.isLt + have hs := slotValue_lt σ 0 + generalize BitVec.toNat w = x at * + simp only [Nat.reducePow] at hw hs + · -- Panic(0x11): v + x overflows uint8. + rw [model_panic x _ (by omega) (by omega)] + simp [Source.observe, observe, callAt, panic, word] + · -- v + x fits. + rw [model_ok x _ (by omega) (by omega)] + generalize slotValue σ 0 = s0 at * + have hA : (s0 % 2 ^ 256 - s0 % 256 + (s0 + x) % 256) % 2 ^ 256 = s0 + x := by omega + have hW : (s0 + x) / 256 % 256 = s0 / 256 % 256 := by omega + have hO : (s0 + x - s0 / 256 % 256 * 256) % 256 = s0 % 256 + x := by omega + simp only [Nat.reducePow] at hA + simp only [hA, hW, hO] + have hy : (s0 / 256 % 256 ^^^ x) < 256 := Nat.xor_lt_two_pow (n := 8) (by omega) (by omega) + generalize (s0 / 256 % 256 ^^^ x) = y at * + have hB : s0 + x - s0 / 256 % 256 * 256 + y * 256 = + s0 / 65536 * 65536 + y * 256 + (s0 % 256 + x) := by omega + simp only [hB] + simp [Source.observe, observe, State.loadSlot, StorageMap.lookup?, State.logEntries, word] + funext slot + have hk := hmk slot + simp only [Std.HashMap.getElem?_insert, Shared.norm, Shared.wordModulus, beq_iff_eq, + EvmYul.UInt256.size, Nat.reducePow] at hk ⊢ + generalize slot % 115792089237316195423570985008687907853269984665640564039457584007913129639936 = k at hk ⊢ + by_cases h : k = 0 + · subst h + simp + · have h' : ¬0 = k := fun e => h e.symm + rw [← hk h] + simp only [h, h', ↓reduceIte] + cases m[k]? <;> rfl + · -- A dirty word reverts with no data. + rw [model_dirty x _ (by omega)] + simp [Source.observe, observe, callAt] + +/-- model implements SolidCore's Main on every call of scopeAt. -/ +theorem implementsAt {c : TypeCheck.CheckedContract} (hcore : c.core = coreLit) {d : Source.State} + (hd : DeployedAt fuel c d deployed) : Implements fuel c scopeAt (argWords 1) model := by + rintro call ⟨σ, hσ, hs⟩ + refine implements_of_run' (s := σ) (by simp [fns]) (fun fn hfn ws hl => ?_) call hs + simp only [fns, List.mem_cons, List.not_mem_nil, or_false] at hfn + subst hfn + rcases ws with _ | ⟨w, _ | _⟩ <;> simp at hl + exact run_add_at hcore hd w σ hσ + +/-- The verification conditions of add from any storage, from model's outcomes. -/ +theorem vcsAt : ∀ call, scopeAt call → pre call → vc model (argWords 1) postAt call := by + rintro call ⟨σ, -, hs⟩ hp + refine vcs_of_fullScope (fns := fns) (s := σ) (n := 1) (by simp [fns]) ?_ call hs hp + intro fn hfn call args hcall hw hlen hargs hinit _ + subst hcall + match args, hlen with + | [x], _ => + have hx : x < 2 ^ 256 := hargs x (by simp) + have hs0 := slotValue_lt σ 0 + rw [wp_eq] + simp only [postAt, hw, List.getD_cons_zero] + by_cases h1 : x < 256 + · by_cases h2 : slotValue σ 0 % 256 + x < 256 + · rw [model_ok x _ h1 h2] + simp only [Nat.reducePow, h1, h2, ↓reduceIte, true_and] + refine ⟨fun slot => ?_, trivial⟩ + split + · exact Nat.mod_eq_of_lt (by + have := Nat.xor_lt_two_pow (n := 8) (x := slotValue σ 0 / 256 % 256) (y := x) + (by omega) (by omega) + omega) + · rfl + · rw [model_panic x _ h1 h2] + simp [h1, h2] + · rw [model_dirty x _ h1] + simp [h1] + +/-- **The specification of c4's add from any storage**, as a triple against SolidCore. -/ +theorem specAt : ∃ c, contract? = .ok c ∧ Triple fuel c scopeAt pre postAt := by + obtain ⟨c, hc⟩ := contract_ok + obtain ⟨hk, _, hdep⟩ := shape_of hc + obtain ⟨d, hd⟩ := deployedAt_of hdep + exact ⟨c, hc, triple_of_wp (implementsAt hk hd) vcsAt⟩ + +/-- The specification from any storage as Satisfies on SolidCore. -/ +theorem satisfiesAt : ∃ c, contract? = .ok c ∧ Satisfies (solidCore fuel) c scopeAt pre postAt := by + obtain ⟨c, hc, h⟩ := specAt + exact ⟨c, hc, satisfies_of_triple h⟩ + +end SolidCore.Verify.C4 diff --git a/Verify/CounterBump.lean b/Verify/CounterBump.lean new file mode 100644 index 00000000..09fb7d72 --- /dev/null +++ b/Verify/CounterBump.lean @@ -0,0 +1,110 @@ +import Verify.Abi + +/-! +# Counter's `bump(n)`: a loop proved with Loom's invariant and variant rule + +`bump` of `crates/verify/examples/Counter.sol` (solar), with `count` in slot 0 and `limit` +in slot 1: + + function bump(uint256 n) external { + require(count + n <= limit, "over"); + /// @custom:invariant i <= n + /// @custom:invariant count == old(count) + i + /// @custom:decreases n - i + for (uint256 i = 0; i < n; i++) { count++; } + } + +`model` is the function as a `SolM` program: the checked `count + n` of the `require` panics +with `Panic(0x11)` when it overflows, the `require` reverts with `Error("over")`, and the loop +is `whileM` over `i` with the checked `count++` in its body. The loop is given `n + 1` +iterations, more than its variant `n - i` allows, so it never runs out (`triple_whileM`). + +`bump_spec` proves the annotated specification from the annotated invariant and variant with +Loom's loop rule: from storage whose `count` is a word, a call either returns with `count` +increased by `n` and every other slot unchanged, or reverts with `Error("over")` when +`count + n > limit`, or with `Panic(0x11)` when `count + n` overflows. `bump_vc` is the same +statement as the verification condition `vc` of `Verify.Basic` against the observable. +-/ + +namespace SolidCore.Verify.CounterBump + +open SolidCore.Refinement + +/-- The revert data of `require(..., msg)`: `Error(string)` with `msg`. -/ +def errorString (msg : String) : List Nat := + let bytes := msg.toUTF8.toList.map (·.toNat) + (EthLib.Base.natToBytes 4 0x08c379a0).map (·.toNat) ++ word 32 ++ word bytes.length ++ + bytes ++ List.replicate ((32 - bytes.length % 32) % 32) 0 + +/-- One iteration: the checked `count++`, then `i++`. -/ +def body (i : Nat) : SolM Nat := do + let c ← sload 0 + if c + 1 < 2 ^ 256 then pure () else revert (panic 0x11) + sstore 0 (c + 1) + pure (i + 1) + +/-- `bump(n)` as a `SolM` program. -/ +def model (n : Nat) : SolM (List Nat) := do + let c ← sload 0 + let lim ← sload 1 + if c + n < 2 ^ 256 then pure () else revert (panic 0x11) + if c + n ≤ lim then pure () else revert (errorString "over") + let _ ← whileM (fun i => decide (i < n)) body (n + 1) 0 + pure [] + +/-- The loop's invariant, from the annotations, with what the loop must keep about the +storage: `i <= n`, `count == old(count) + i`, the other slots unchanged, and the bound the +`require` established. -/ +def inv (n : Nat) (s : Storage) (i : Nat) : Assn := fun _ s' => + i ≤ n ∧ s' 0 = s 0 + i ∧ (∀ k, k % 2 ^ 256 ≠ 0 → s' k = s k) ∧ + s 0 + n < 2 ^ 256 + +/-- The annotated variant. -/ +def variant (n : Nat) (i : Nat) : Nat := n - i + +theorem body_step (n : Nat) (s : Storage) (i : Nat) (hi : decide (i < n) = true) : + triple (inv n s i) (body i) (fun i' => inv n s i' ⊓ ⌜variant n i' < variant n i⌝) := by + have hlt : i < n := by simpa using hi + intro herr s' ⟨hle, hc, hframe, hbound⟩ + simp only [body, wp_bind, wp_sload, wp_ite, wp_pure, wp_revert, wp_sstore] + have h1 : s' 0 + 1 < 2 ^ 256 := by omega + simp only [h1, ite_true] + refine ⟨⟨by omega, ?_, ?_, hbound⟩, ?_⟩ + · simp only [ite_true] + rw [Nat.mod_eq_of_lt h1]; omega + · intro k hk + simp only [Nat.zero_mod, hk, ite_false] + exact hframe k hk + · show (⌜variant n (i + 1) < variant n i⌝ : Assn) herr _ + have hv : variant n (i + 1) < variant n i := by simp only [variant]; omega + simp only [LE.pure, hv]; trivial + +/-- `bump`'s specification, proved with Loom's loop rule from the annotated invariant and +variant. -/ +theorem bump_spec (n : Nat) (s : Storage) (herr : Revert → Prop) + (hover : s 0 + n < 2 ^ 256 → ¬ s 0 + n ≤ s 1 → herr (errorString "over")) + (hpanic : ¬ s 0 + n < 2 ^ 256 → herr (panic 0x11)) : + wp (model n) + (fun _ _ s' => s' 0 = s 0 + n ∧ ∀ k, k % 2 ^ 256 ≠ 0 → s' k = s k) + herr s := by + simp only [model, wp_bind, wp_sload, wp_ite, wp_pure, wp_revert] + by_cases hb : s 0 + n < 2 ^ 256 + · simp only [hb, ite_true] + by_cases hl : s 0 + n ≤ s 1 + · simp only [hl, ite_true] + have hloop := triple_whileM (fun i => decide (i < n)) body (inv n s) (variant n) + (body_step n s) (n + 1) 0 (by simp [variant]) + have h0 : inv n s 0 herr s := ⟨Nat.zero_le _, by simp, fun _ _ => rfl, hb⟩ + have := wp_cons _ _ (fun (_ : Nat) => fun (_ : Revert → Prop) s' => + s' 0 = s 0 + n ∧ ∀ k, k % 2 ^ 256 ≠ 0 → s' k = s k) ?_ herr s (hloop herr s h0) + · simpa [wp_pure] using this + · intro i herr' s' ⟨⟨hle, hc, hframe, _⟩, hdone⟩ + have hni : n ≤ i := by + by_contra hne + have : decide (i < n) = true := by simp; omega + simp [LE.pure, this] at hdone + exact ⟨by rw [hc]; congr 1; omega, hframe⟩ + · simp only [hl, ite_false]; exact hover hb hl + · simp only [hb, ite_false]; exact hpanic hb + +end SolidCore.Verify.CounterBump diff --git a/Verify/Discharge.lean b/Verify/Discharge.lean new file mode 100644 index 00000000..caddecf3 --- /dev/null +++ b/Verify/Discharge.lean @@ -0,0 +1,20 @@ +import Verify.Obligation +import Verify.Discharge.Lemmas +import Verify.Discharge.Search +import Verify.Discharge.Valid +import Verify.Discharge.Sat +import Verify.Discharge.Leaf + +/-! Kernel-checked certificates for exported obligations. A VC counts as discharged only when a +certificate the Lean kernel checks proves `ob.Valid` (Verify/Obligation/Vc.lean), and the proof +uses only the axioms `propext`, `Classical.choice` and `Quot.sound`. The certificate kinds are: + +- `search`: `vc_valid` (`Search`, `Valid`) builds the proof itself; its leaves are `omega` and + `vc_ground`, which decides closed hypotheses by kernel evaluation (`Sat.Ground`, `Leaf`). +- `smt`: `vc_smt` (Verify/Reconstruct, a package of its own) reconstructs a cvc5 proof step by + step as a Lean term. +- `lean`: a theorem written for the obligation, such as one under Contracts//, named in + a certificate list; its proof may check an LRAT certificate with `Sat` (`check_sound`). + +The driver, Verify/Discharge/discharge.sh, states every obligation itself and applies every +check to every kind alike; see Verify/Discharge/README.md. -/ diff --git a/Verify/Discharge/Leaf.lean b/Verify/Discharge/Leaf.lean new file mode 100644 index 00000000..65e6c448 --- /dev/null +++ b/Verify/Discharge/Leaf.lean @@ -0,0 +1,9 @@ +import Verify.Discharge.Search +import Verify.Discharge.Sat.Ground + +/-! The search's leaves (`vc_leaf`, Search.lean): besides `omega`, a goal one of whose closed +hypotheses the kernel decides to be false is closed by `vc_ground` (Sat/Ground.lean). Lean tries +the rules from the last one added, so `vc_ground` runs first and fails at once when no hypothesis +is closed; `omega` then gets the goal unchanged. -/ + +macro_rules | `(tactic| vc_leaf) => `(tactic| vc_ground) diff --git a/Verify/Discharge/Lemmas.lean b/Verify/Discharge/Lemmas.lean new file mode 100644 index 00000000..b8c97ee5 --- /dev/null +++ b/Verify/Discharge/Lemmas.lean @@ -0,0 +1,65 @@ +/- +Lemmas the discharge tactic (`SolarVerify.Discharge`) builds proofs from. Nothing an obligation +means depends on this file. +-/ +namespace SolarVerify.Discharge + +/-! Rewrites the tactic uses; `omega` reads disjunctions but not implications. -/ + +theorem imp_iff_not_or (a b : Prop) : (a → b) ↔ ¬a ∨ b := + ⟨fun h => (Classical.em a).elim (fun ha => .inr (h ha)) .inl, + fun h ha => h.elim (fun hn => absurd ha hn) id⟩ + +theorem ite_pos {α : Type} {c : Prop} {_ : Decidable c} (h : c) (a b : α) : ite c a b = a := by + simp [h] + +theorem ite_neg {α : Type} {c : Prop} {_ : Decidable c} (h : ¬c) (a b : α) : ite c a b = b := by + simp [h] + +/-! Congruence, as disjunctions `omega` can case on (Ackermann's reduction). -/ + +theorem congr1 {β : Type} (f : Int → β) (a b : Int) : ¬a = b ∨ f a = f b := + (Classical.em (a = b)).elim (fun h => .inr (h ▸ rfl)) .inl + +theorem congr2 {β : Type} (f : Int → Int → β) (a b c d : Int) : + ¬a = c ∨ ¬b = d ∨ f a b = f c d := + (Classical.em (a = c)).elim + (fun h => (Classical.em (b = d)).elim (fun h' => .inr (.inr (h ▸ h' ▸ rfl))) (fun h' => .inr (.inl h'))) + .inl + +theorem congr3 {β : Type} (f : Int → Int → Int → β) (a b c d e g : Int) : + ¬a = d ∨ ¬b = e ∨ ¬c = g ∨ f a b c = f d e g := + (Classical.em (a = d)).elim + (fun h => (Classical.em (b = e)).elim + (fun h' => (Classical.em (c = g)).elim (fun h'' => .inr (.inr (.inr (h ▸ h' ▸ h'' ▸ rfl)))) + (fun h'' => .inr (.inr (.inl h'')))) + (fun h' => .inr (.inl h'))) + .inl + +theorem true_eq_iff (b : Bool) : (true = b) ↔ (b = true) := ⟨Eq.symm, Eq.symm⟩ + +theorem false_eq_iff (b : Bool) : (false = b) ↔ (b = false) := ⟨Eq.symm, Eq.symm⟩ + +/-- `decide` at any instance, such as the classical one quantifiers evaluate with. -/ +theorem decide_any_eq_true {p : Prop} {_ : Decidable p} : (decide p = true) = p := by simp + +/-- The classical `if` a quantifier evaluates with, as a function of its condition alone, so +`simp` can rewrite the condition without a `Decidable` instance for the new one. -/ +noncomputable def qite {α : Type} (p : Prop) (a b : α) : α := @ite α p (Classical.propDecidable p) a b + +/-- The classical `decide` a quantifier evaluates with. -/ +noncomputable def qdec (p : Prop) : Bool := @decide p (Classical.propDecidable p) + +theorem qite_true {α : Type} (a b : α) : qite True a b = a := by simp [qite] +theorem qite_false {α : Type} (a b : α) : qite False a b = b := by simp [qite] +theorem qdec_eq_true (p : Prop) : (qdec p = true) = p := by simp [qdec] + +/-- Every `if` as a `qite`, whose condition `simp` rewrites like any other proposition. -/ +theorem ite_eq_qite {α : Type} {c : Prop} {_ : Decidable c} (a b : α) : ite c a b = qite c a b := by + unfold qite; split <;> simp_all + +theorem qite_pos {α : Type} {c : Prop} (h : c) (a b : α) : qite c a b = a := by simp [qite, h] + +theorem qite_neg {α : Type} {c : Prop} (h : ¬c) (a b : α) : qite c a b = b := by simp [qite, h] + +end SolarVerify.Discharge diff --git a/Verify/Discharge/README.md b/Verify/Discharge/README.md new file mode 100644 index 00000000..bdcbf138 --- /dev/null +++ b/Verify/Discharge/README.md @@ -0,0 +1,48 @@ +# Discharging solar-verify's VCs in the kernel + +`solar-verify --emit-lean DIR FILE.sol` (solar, `crates/verify`) writes each query it sends a +solver as a Lean term `ob : Obligation` whose `ob.Valid` (Verify/Obligation/Vc.lean) holds exactly +when the query is unsatisfiable. This directory decides which of them are proved. A VC is +accepted only when a certificate the Lean kernel checks proves `ob.Valid` and the proof uses no +axiom but `propext`, `Classical.choice` and `Quot.sound`; a solver's answer alone never counts. + +## Certificate kinds + +| Kind | What proves `ob.Valid` | Where | +| --- | --- | --- | +| `search` | `vc_valid`: unfolds the obligation to a shallow goal and searches for a proof (case splits, congruence, `omega`, and `vc_ground`, which decides closed hypotheses by kernel evaluation) | Search.lean, Valid.lean, Leaf.lean, Sat/Ground.lean | +| `smt` | `vc_smt`: cvc5 refutes the goal and lean-smt rebuilds its proof step by step as a Lean term; a step it cannot rebuild is a `sorryAx` and fails the axiom check | ../Reconstruct (a package of its own, so building this repository fetches no solver) | +| `lean` | a theorem written for the obligation (such as one under Contracts//), named in a certificate list; its proof may check an LRAT certificate with `Sat` | DISCHARGE_CERTS | + +`Sat` (Cnf, Lrat, Load) checks LRAT refutations of CNF formulas in the kernel (`check_sound`); +test/sat/Sat.lean checks one. It reaches a VC only through a `lean` certificate: turning an +obligation into CNF needs a bit-blaster with a soundness proof, which is parked until a VC needs it. + +## Running + +```text +lake build VerifyDischarge +DISCHARGE_KINDS=search,smt Verify/Discharge/discharge.sh DIR [TIMEOUT_SECONDS] +``` + +The script states every obligation itself (`theorem obligation : .Valid := ...`), so every +kind is checked against the exported statement, and applies the same checks to all: the manifest +format and version, the hashes of Smt.lean and Vc.lean the export was written for, no unchecked +construct in the libraries, every required obligation present once, the inputs against +DISCHARGE_LOCK, and per proof the exit status, errors, a timeout and the axioms. It writes +DIR/discharge/results.tsv (one row per obligation and kind) and summary.tsv (per obligation, the +kinds that proved it), and exits 0 only when every required obligation is proved. DISCHARGE_ALL=1 +tries every kind on every obligation to measure each kind's coverage. The header of discharge.sh +lists the other settings. + +Version-1 exports (and the version-2 locks derived from them) say `import SolarVerify` and record the hash of +Vc.lean with its old first line; the script compiles them with `import Verify.Obligation` and +accepts either hash, nothing else. + +## Frozen inputs and negatives + +frozen/.sha256 and frozen/PINS are solar's version-1 locks of the Counter, Token, Vault and +ArrayMax exports, kept as they were. frozen/v2/ holds the version-2 locks (frozen/v2/PINS says +how they were made). test/negatives.sh corrupts one input at a time (an edited source, an edited +module, a deleted required obligation without a lock, a duplicated obligation, an absolute source +path, version 1) and requires each run to fail with its message before any Lean runs. diff --git a/Verify/Discharge/Sat.lean b/Verify/Discharge/Sat.lean new file mode 100644 index 00000000..c0c8a560 --- /dev/null +++ b/Verify/Discharge/Sat.lean @@ -0,0 +1,4 @@ +import Verify.Discharge.Sat.Cnf +import Verify.Discharge.Sat.Lrat +import Verify.Discharge.Sat.Load +import Verify.Discharge.Sat.Ground diff --git a/Verify/Discharge/Sat/Cnf.lean b/Verify/Discharge/Sat/Cnf.lean new file mode 100644 index 00000000..dfaa48b1 --- /dev/null +++ b/Verify/Discharge/Sat/Cnf.lean @@ -0,0 +1,74 @@ +/-! +Propositional formulas in conjunctive normal form, with literals coded as natural numbers so +that the kernel evaluates them with its built-in arithmetic. + +This is the meaning of what `SolarVerify.Sat.Lrat` checks: a formula is unsatisfiable when every +assignment of its variables falsifies one of its clauses. +-/ +namespace SolarVerify.Sat + +/-- A literal: `2 * v` is variable `v`, and `2 * v + 1` its negation. -/ +abbrev Lit := Nat + +/-- A clause: the disjunction of its literals. -/ +abbrev Clause := List Lit + +/-- A formula: the conjunction of its clauses. -/ +abbrev Cnf := List Clause + +/-- A value for every variable. -/ +abbrev Assignment := Nat → Bool + +/-- The literal of variable `v` with polarity `pos`. -/ +def Lit.mk (v : Nat) (pos : Bool) : Lit := if pos then 2 * v else 2 * v + 1 + +/-- The negation of a literal. -/ +def Lit.neg (l : Lit) : Lit := bif Nat.beq (l % 2) 0 then l + 1 else l - 1 + +/-- The value of a literal. -/ +def Lit.eval (a : Assignment) (l : Lit) : Bool := if l % 2 = 0 then a (l / 2) else !a (l / 2) + +/-- The value of a clause: some literal is true. -/ +def Clause.eval (a : Assignment) (c : Clause) : Bool := c.any (Lit.eval a) + +/-- The value of a formula: every clause is true. -/ +def Cnf.eval (a : Assignment) (f : Cnf) : Bool := f.all (Clause.eval a) + +/-- No assignment satisfies the formula. -/ +def Cnf.Unsat (f : Cnf) : Prop := ∀ a, Cnf.eval a f = false + +theorem Lit.eval_neg (a : Assignment) (l : Nat) : Lit.eval a (Lit.neg l) = !Lit.eval a l := by + unfold Lit.eval Lit.neg + by_cases h : l % 2 = 0 + · have h1 : ¬ (l + 1) % 2 = 0 := by omega + have h2 : (l + 1) / 2 = l / 2 := by omega + simp [h, h1, h2] + · have h1 : (l - 1) % 2 = 0 := by omega + have h2 : (l - 1) / 2 = l / 2 := by omega + have hb : Nat.beq (l % 2) 0 = false := by + cases e : Nat.beq (l % 2) 0 + · rfl + · exact absurd (Nat.eq_of_beq_eq_true e) h + simp [hb, h, h1, h2] + +theorem Lit.eval_mk (a : Assignment) (v : Nat) (pos : Bool) : + Lit.eval a (Lit.mk v pos) = (a v == pos) := by + have h1 : 2 * v % 2 = 0 := by omega + have h2 : 2 * v / 2 = v := by omega + have h3 : ¬ (2 * v + 1) % 2 = 0 := by omega + have h4 : (2 * v + 1) / 2 = v := by omega + cases pos <;> cases h : a v <;> simp [Lit.mk, Lit.eval, h1, h2, h4, h] + +theorem Clause.eval_cons (a : Assignment) (l : Lit) (c : Clause) : + Clause.eval a (l :: c) = (Lit.eval a l || Clause.eval a c) := by + simp [Clause.eval] + +theorem Clause.eval_eq_true (a : Assignment) (c : Clause) : + Clause.eval a c = true ↔ ∃ l ∈ c, Lit.eval a l = true := by + simp [Clause.eval] + +theorem Cnf.eval_eq_true (a : Assignment) (f : Cnf) : + Cnf.eval a f = true ↔ ∀ c ∈ f, Clause.eval a c = true := by + simp [Cnf.eval] + +end SolarVerify.Sat diff --git a/Verify/Discharge/Sat/Ground.lean b/Verify/Discharge/Sat/Ground.lean new file mode 100644 index 00000000..285df597 --- /dev/null +++ b/Verify/Discharge/Sat/Ground.lean @@ -0,0 +1,73 @@ +import Lean +/-! +A leaf for the discharge search: hypotheses without free variables are decided by kernel +evaluation. + +After `vc_valid_prep`, a hypothesis built only from literals (such as one about +`(511#256 &&& 255#256).toNat`) still carries the casts `Val.as` leaves at bit-vector sorts and +`List.foldl` from n-ary operators, which `omega` cannot read. Their value needs no search: the +kernel computes it, reducing the casts over proofs of `s = s` as it reduces any `Eq.rec` whose +indices agree. + +`vc_ground` looks for a closed hypothesis `h : P` whose negation the kernel decides: +`decide (¬P)` must be definitionally `true` to the kernel itself (`Kernel.isDefEq`, not the +elaborator's reduction). It then closes the goal with `absurd h (of_decide_eq_true rfl)`, which +the kernel checks again when the theorem is added. Nothing runs natively and nothing joins the trusted base. +It fails, leaving the goal to the rest of the search, when no closed hypothesis is false. +-/ +namespace SolarVerify.Sat +open Lean Elab Tactic Meta + +/-- A `Decidable` instance the kernel reduces, built along `¬`, `∧`, `∨` and `=`; an equation +is decided by the instance of its type's weak head normal form, so that `Srt.Den .bool` reads as +`Bool`. -/ +partial def mkDecidable (p : Expr) : MetaM (Option Expr) := do + match_expr p with + | Not q => + let some d ← mkDecidable q | return none + return some (mkApp2 (mkConst ``instDecidableNot) q d) + | And a b => + let some da ← mkDecidable a | return none + let some db ← mkDecidable b | return none + return some (mkApp4 (mkConst ``instDecidableAnd) a b da db) + | Or a b => + let some da ← mkDecidable a | return none + let some db ← mkDecidable b | return none + return some (mkApp4 (mkConst ``instDecidableOr) a b da db) + | Eq ty a b => + let ty' ← whnfD ty + let some u ← (try pure (some (← getLevel ty')) catch _ => pure none) | return none + let some inst ← (try synthInstance? (mkApp (mkConst ``DecidableEq [u]) ty') catch _ => pure none) + | return none + return some (mkApp2 inst a b) + | _ => try synthInstance? (mkApp (mkConst ``Decidable) p) catch _ => pure none + +/-- `absurd h (of_decide_eq_true rfl)` for a closed hypothesis `h : P` that the kernel decides +false, or none. -/ +def refuteClosed (goalTy : Expr) (d : LocalDecl) : MetaM (Option Expr) := do + let ty ← instantiateMVars d.type + if ty.hasFVar || ty.hasMVar || ty.hasLooseBVars then return none + unless ← isProp ty do return none + let notTy := mkNot ty + let some inst ← mkDecidable notTy | return none + let inst ← instantiateMVars inst + let dec := mkApp2 (mkConst ``Decidable.decide) notTy inst + let ok ← try ofExceptKernelException (Kernel.isDefEq (← getEnv) {} dec (mkConst ``Bool.true)) + catch _ => pure false + unless ok do return none + let rflTrue := mkApp2 (mkConst ``Eq.refl [1]) (mkConst ``Bool) (mkConst ``Bool.true) + let hn := mkApp3 (mkConst ``of_decide_eq_true) notTy inst rflTrue + return some (mkApp4 (mkConst ``absurd [← getLevel goalTy]) ty goalTy d.toExpr hn) + +elab "vc_ground" : tactic => withMainContext do + let g ← getMainGoal + let goalTy ← g.getType + for d in ← getLCtx do + if d.isImplementationDetail then continue + if let some p ← refuteClosed goalTy d then + g.assign p + replaceMainGoal [] + return + throwError "vc_ground: no closed hypothesis is false" + +end SolarVerify.Sat diff --git a/Verify/Discharge/Sat/Load.lean b/Verify/Discharge/Sat/Load.lean new file mode 100644 index 00000000..5d660fa8 --- /dev/null +++ b/Verify/Discharge/Sat/Load.lean @@ -0,0 +1,218 @@ +import Lean +import Verify.Discharge.Sat.Lrat +/-! +Reading a DIMACS formula and a textual LRAT proof from files into terms the kernel checks. + +Nothing here is trusted: a wrong term only makes `check` return `false`. Long lists and the proof +become balanced trees of appends and `Proof.seq`, so the terms stay shallow. +-/ +namespace SolarVerify.Sat.Load +open Lean Elab Command Meta + +/-- The literal code of a nonzero DIMACS literal. -/ +def litOfInt (i : Int) : Nat := if i > 0 then 2 * i.toNat else 2 * i.natAbs + 1 + +def ints (line : String) : Except String (List Int) := + (line.splitOn " ").filter (· ≠ "") |>.mapM fun w => + match w.toInt? with + | some i => .ok i + | none => .error s!"not a number: {w}" + +/-- The clauses of a DIMACS file. -/ +def parseDimacs (s : String) : Except String (Array (List Nat)) := do + let mut out := #[] + let mut cur : List Nat := [] + for line in s.splitOn "\n" do + let line := line.trimAscii.toString + if line.isEmpty || line.startsWith "c" || line.startsWith "p" then continue + for i in ← ints line do + if i == 0 then + out := out.push cur.reverse + cur := [] + else + cur := litOfInt i :: cur + return out + +/-- The addition steps of a textual LRAT proof; deletions are skipped and RAT hints rejected. -/ +def parseLrat (s : String) : Except String (Array Step) := do + let mut out := #[] + for line in s.splitOn "\n" do + let line := line.trimAscii.toString + if line.isEmpty || line.startsWith "c" then continue + let ws := (line.splitOn " ").filter (· ≠ "") + if ws.length ≥ 2 && ws[1]! == "d" then continue + let xs ← ints line + match xs with + | [] => continue + | id :: rest => + let literals := rest.takeWhile (· ≠ 0) + let hints := (rest.dropWhile (· ≠ 0)).drop 1 |>.takeWhile (· ≠ 0) + if hints.any (· < 0) then throw s!"step {id}: RAT steps are not supported" + out := out.push { id := id.toNat, clause := literals.map litOfInt, hints := hints.map Int.toNat } + return out + +def listTy (ty : Expr) : Expr := mkApp (mkConst ``List [0]) ty + +/-- A list literal, as a balanced tree of appends above 64 elements. -/ +partial def mkList (ty : Expr) (xs : Array Expr) (lo hi : Nat) : Expr := + if hi - lo ≤ 64 then + (List.range (hi - lo)).foldr (init := mkApp (mkConst ``List.nil [0]) ty) fun i acc => + mkApp3 (mkConst ``List.cons [0]) ty xs[lo + i]! acc + else + let mid := (lo + hi) / 2 + mkApp3 (mkConst ``List.append [0]) ty (mkList ty xs lo mid) (mkList ty xs mid hi) + +def mkNatList (xs : List Nat) : Expr := + let a := xs.toArray.map mkRawNatLit + mkList (mkConst ``Nat) a 0 a.size + +def mkStep (s : Step) : Expr := + mkApp (mkConst ``Proof.step) <| + mkApp3 (mkConst ``Step.mk) (mkRawNatLit s.id) (mkNatList s.clause) (mkNatList s.hints) + +partial def mkProof (ss : Array Step) (lo hi : Nat) : Expr := + if hi - lo == 1 then mkStep ss[lo]! + else + let mid := (lo + hi) / 2 + mkApp2 (mkConst ``Proof.seq) (mkProof ss lo mid) (mkProof ss mid hi) + +def addDef (n : Name) (ty v : Expr) : CoreM Unit := + addDecl <| .defnDecl (mkDefinitionValEx n [] ty v (.regular 0) .safe []) + +/-- `sat_load n "f.cnf" "f.lrat"` defines `n.cnf : Cnf` and `n.proof : Proof` from the files, +relative to the current file. -/ +elab "sat_load " n:ident cnf:str lrat:str : command => do + let dir := (System.FilePath.mk (← getFileName)).parent.getD "." + let cs ← IO.FS.readFile (dir / cnf.getString) + let ps ← IO.FS.readFile (dir / lrat.getString) + let clauses ← match parseDimacs cs with | .ok c => pure c | .error e => throwError e + let steps ← match parseLrat ps with | .ok c => pure c | .error e => throwError e + if steps.isEmpty then throwError "the proof adds no clauses" + let base := (← getCurrNamespace) ++ n.getId + let cnfVal := mkList (listTy (mkConst ``Nat)) (clauses.map (mkNatList ·)) 0 clauses.size + liftCoreM do + addDef (base ++ `cnf) (mkConst ``Cnf) cnfVal + addDef (base ++ `proof) (mkConst ``Proof) (mkProof steps 0 steps.size) + logInfo m!"{clauses.size} clauses, {steps.size} proof steps" + + +/-! ## One declaration per step -/ + +def natE (n : Nat) : Expr := mkRawNatLit n +def boolTrue : Expr := mkConst ``Bool.true +def eqTrue (b : Expr) : Expr := mkApp3 (mkConst ``Eq [1]) (mkConst ``Bool) b boolTrue +def reflTrue : Expr := mkApp2 (mkConst ``Eq.refl [1]) (mkConst ``Bool) boolTrue +def clauseListTy : Expr := listTy (mkConst ``Clause) +def consE (ty x xs : Expr) : Expr := mkApp3 (mkConst ``List.cons [0]) ty x xs +def nilE (ty : Expr) : Expr := mkApp (mkConst ``List.nil [0]) ty + +/-- The formula as a balanced tree of appends over chunks of at most 16 clauses, each subtree its +own definition `base.cnfN` so that the kernel reads its type rather than inferring it again in +every lemma. Returns the subtree's constant and, for each of its clauses, a function giving the +proof that the clause is a member. -/ +partial def cnfTree (base : Name) (cs : Array Expr) (lo hi : Nat) : + StateT Nat CoreM (Expr × Array (Unit → Expr)) := do + let idx ← modifyGet fun n => (n, n + 1) + let name := base ++ Name.mkSimple s!"cnf{idx}" + let k := mkConst name + if hi - lo ≤ 16 then + let n := hi - lo + let mut acc : Array Expr := #[nilE (mkConst ``Clause)] + for j in [0:n] do + acc := acc.push (consE (mkConst ``Clause) cs[hi - 1 - j]! acc.back!) + let suffixes := acc.reverse -- suffixes[j] is the list from lo + j + liftM (addDef name clauseListTy suffixes[0]! : CoreM Unit) + let mems := (List.range n).toArray.map fun j => fun (_ : Unit) => Id.run do + let mut p := mkApp2 (mkConst ``SolarVerify.Sat.mem_head) cs[lo + j]! suffixes[j + 1]! + for k' in [0:j] do + let i := j - 1 - k' + p := mkApp4 (mkConst ``SolarVerify.Sat.mem_tail) cs[lo + j]! cs[lo + i]! suffixes[i + 1]! p + return p + return (k, mems) + else + let mid := (lo + hi) / 2 + let (l, ml) ← cnfTree base cs lo mid + let (r, mr) ← cnfTree base cs mid hi + liftM (addDef name clauseListTy (mkApp3 (mkConst ``List.append [0]) (mkConst ``Clause) l r) : CoreM Unit) + let ml' := (List.range ml.size).toArray.map fun i => fun (_ : Unit) => + mkApp4 (mkConst ``SolarVerify.Sat.mem_append_left) cs[lo + i]! l r (ml[i]! ()) + let mr' := (List.range mr.size).toArray.map fun i => fun (_ : Unit) => + mkApp4 (mkConst ``SolarVerify.Sat.mem_append_right) cs[mid + i]! l r (mr[i]! ()) + return (k, ml' ++ mr') + +def addThm (n : Name) (ty v : Expr) : CoreM Unit := + addDecl <| .thmDecl { name := n, levelParams := [], type := ty, value := v } + +/-- `∀ a, Cnf.eval a F = true → Clause.eval a c = true` -/ +def stepTy (F c : Expr) : Expr := + mkForall `a .default (mkConst ``Assignment) <| + mkForall `h .default (eqTrue (mkApp2 (mkConst ``Cnf.eval) (.bvar 0) F)) <| + eqTrue (mkApp2 (mkConst ``Clause.eval) (.bvar 1) c) + +def lamAH (F body : Expr) : Expr := + mkLambda `a .default (mkConst ``Assignment) <| + mkLambda `h .default (eqTrue (mkApp2 (mkConst ``Cnf.eval) (.bvar 0) F)) body + +/-- `sat_prove n "f.cnf" "f.lrat"` defines `n.cnf : Cnf` from the DIMACS file and proves +`n.unsat : n.cnf.Unsat` from the LRAT proof, one kernel-checked lemma per needed step. -/ +elab "sat_prove " n:ident cnf:str lrat:str : command => do + let dir := (System.FilePath.mk (← getFileName)).parent.getD "." + let cs ← IO.FS.readFile (dir / cnf.getString) + let ps ← IO.FS.readFile (dir / lrat.getString) + let clauses ← match parseDimacs cs with | .ok c => pure c | .error e => throwError e + let steps ← match parseLrat ps with | .ok c => pure c | .error e => throwError e + let some last := steps.findIdx? (·.clause.isEmpty) | throwError "the proof never adds the empty clause" + -- Keep only the steps the empty clause depends on. + let nIn := clauses.size + let mut byId : Std.HashMap Nat Nat := {} + for i in [0:last + 1] do byId := byId.insert steps[i]!.id i + let mut need : Std.HashSet Nat := {} + let mut needIn : Std.HashSet Nat := {} + let mut todo := [last] + need := need.insert last + while !todo.isEmpty do + let i := todo.head! + todo := todo.tail! + for h in steps[i]!.hints do + if h ≥ 1 && h ≤ nIn then needIn := needIn.insert h + else match byId[h]? with + | some j => if !need.contains j then need := need.insert j; todo := j :: todo + | none => throwError "step {steps[i]!.id}: unknown hint {h}" + let base := (← getCurrNamespace) ++ n.getId + let cExprs := clauses.map mkNatList + let ((fRoot, mems), _) ← liftCoreM <| (cnfTree base cExprs 0 nIn).run 0 + let F := mkConst (base ++ `cnf) + liftCoreM <| addDef (base ++ `cnf) (mkConst ``Cnf) fRoot + let lemmaOf (h : Nat) : Name := + if h ≤ nIn then base ++ Name.mkSimple s!"in{h}" else base ++ Name.mkSimple s!"s{h}" + -- Input clauses the proof uses. + for h in needIn.toArray.qsort (· < ·) do + let c := cExprs[h - 1]! + let v := lamAH F <| mkApp5 (mkConst ``Cnf.eval_mem) (.bvar 1) F c (.bvar 0) (mems[h - 1]! ()) + liftCoreM <| addThm (lemmaOf h) (stepTy F c) v + -- Derived clauses, in order. + let mut stepClause : Std.HashMap Nat Expr := {} + let mut count : Nat := 0 + for i in [0:last + 1] do + unless need.contains i do continue + let s := steps[i]! + let c := mkNatList s.clause + stepClause := stepClause.insert s.id c + let hcs := s.hints.toArray.map fun h => if h ≤ nIn then cExprs[h - 1]! else stepClause[h]! + -- suffix lists of hint clauses and the AllSat proof, from the end + let mut lst := nilE (mkConst ``Clause) + let mut prf := mkApp (mkConst ``AllSat.nil) (.bvar 1) + for j' in [0:hcs.size] do + let j := hcs.size - 1 - j' + let hp := mkApp2 (mkConst (lemmaOf s.hints[j]!)) (.bvar 1) (.bvar 0) + prf := mkApp5 (mkConst ``AllSat.cons) (.bvar 1) hcs[j]! lst hp prf + lst := consE (mkConst ``Clause) hcs[j]! lst + let v := lamAH F <| mkApp5 (mkConst ``rup_clause) (.bvar 1) c lst reflTrue prf + liftCoreM <| addThm (lemmaOf s.id) (stepTy F c) v + count := count + 1 + let emptyLemma := mkConst (lemmaOf steps[last]!.id) + liftCoreM <| addThm (base ++ `unsat) (mkApp (mkConst ``Cnf.Unsat) F) + (mkApp2 (mkConst ``unsat_of_empty) F emptyLemma) + logInfo m!"{nIn} clauses, {steps.size} proof steps, {count} needed, {needIn.size} input clauses used" + +end SolarVerify.Sat.Load diff --git a/Verify/Discharge/Sat/Lrat.lean b/Verify/Discharge/Sat/Lrat.lean new file mode 100644 index 00000000..b87e3dac --- /dev/null +++ b/Verify/Discharge/Sat/Lrat.lean @@ -0,0 +1,410 @@ +import Verify.Discharge.Sat.Cnf +/-! +A checker for LRAT proofs of unsatisfiability that the kernel runs, and its soundness. + +A proof adds clauses, each by reverse unit propagation (RUP) from earlier clauses its hints name, +until it adds the empty clause. RAT steps are not supported: a proof that needs one fails to +check. Deletions only free memory, so a proof here leaves them out and every clause stays +available. + +Everything reduces in the kernel by structural recursion over lists, the proof tree and a fuel +bound, with arithmetic on `Nat` literals (which the kernel computes natively), so +`check f p = true` closes by `decide +kernel` and `check_sound` turns it into `f.Unsat`. +-/ +namespace SolarVerify.Sat + +noncomputable section + +/-- Membership of a number in a list, by the kernel's `Nat.beq`. Written with the recursor, as are +`unfalsified` and `rup`, because the kernel reduces that in fewer steps than structural recursion +compiled through `brecOn`. -/ +noncomputable def memb (x : Nat) (l : List Nat) : Bool := + List.rec false (fun y _ r => Nat.beq x y || r) l + +theorem memb_nil (x : Nat) : memb x [] = false := rfl +theorem memb_cons (x y : Nat) (ys : List Nat) : memb x (y :: ys) = (Nat.beq x y || memb x ys) := rfl + +theorem memb_iff {x : Nat} {l : List Nat} : memb x l = true ↔ x ∈ l := by + induction l with + | nil => simp [memb_nil] + | cons y ys ih => simp [memb_cons, ih, Nat.beq_eq] + +/-- The literals of `c` that the literals `A` (assumed true) do not falsify. -/ +noncomputable def unfalsified (A : List Lit) (c : Clause) : List Lit := + List.rec [] (fun l _ r => bif memb (Lit.neg l) A then r else l :: r) c + +theorem unfalsified_cons (A : List Lit) (l : Lit) (ls : Clause) : + unfalsified A (l :: ls) = + bif memb (Lit.neg l) A then unfalsified A ls else l :: unfalsified A ls := rfl + +/-- One hint clause: it must leave one literal, which then holds while propagation goes on with +`r`, or none, a conflict, which ends the check successfully. -/ +def rupStep (r : List Lit → Bool) (A : List Lit) (c : Clause) : Bool := + match unfalsified A c with + | [] => true + | [l] => r (l :: A) + | _ => false + +/-- Unit propagation along the hint clauses `hs`, from the literals `A`. -/ +noncomputable def rup (hs : List Clause) (A : List Lit) : Bool := + List.rec (motive := fun _ => List Lit → Bool) (fun _ => false) (fun c _ r A => rupStep r A c) hs A + +theorem rup_nil (A : List Lit) : rup [] A = false := rfl +theorem rup_cons (c : Clause) (cs : List Clause) (A : List Lit) : + rup (c :: cs) A = rupStep (rup cs) A c := rfl + +/-- A binary trie from clause IDs to clauses: key 0 at the root, then the key's bits from the +least significant one choose the left (1) or right (0) branch. -/ +inductive Trie where + | leaf + | node (v : Option Clause) (l r : Trie) + +namespace Trie + +def root : Trie → Option Clause + | leaf => none + | node v _ _ => v + +def left : Trie → Trie + | leaf => leaf + | node _ l _ => l + +def right : Trie → Trie + | leaf => leaf + | node _ _ r => r + +/-- The clause at key `k`, looking at most `fuel` levels down. -/ +def find? : (fuel : Nat) → Trie → Nat → Option Clause + | 0, t, k => if k = 0 then t.root else none + | f + 1, t, k => + if k = 0 then t.root + else if k % 2 = 1 then find? f t.left (k / 2) else find? f t.right (k / 2) + +/-- Store a clause at key `k`; a key deeper than `fuel` is dropped. -/ +def insert : (fuel : Nat) → Trie → Nat → Clause → Trie + | 0, t, k, c => if k = 0 then node (some c) t.left t.right else t + | f + 1, t, k, c => + if k = 0 then node (some c) t.left t.right + else if k % 2 = 1 then node t.root (insert f t.left (k / 2) c) t.right + else node t.root t.left (insert f t.right (k / 2) c) + +/-- Every clause stored in the trie has property `P`. -/ +def All (P : Clause → Prop) : Trie → Prop + | leaf => True + | node v l r => (∀ c, v = some c → P c) ∧ All P l ∧ All P r + +theorem All.root {P : Clause → Prop} {t : Trie} (h : t.All P) {c : Clause} (e : t.root = some c) : + P c := by + cases t with + | leaf => simp [Trie.root] at e + | node v l r => exact h.1 c e + +theorem All.left {P : Clause → Prop} {t : Trie} (h : t.All P) : t.left.All P := by + cases t with + | leaf => trivial + | node v l r => exact h.2.1 + +theorem All.right {P : Clause → Prop} {t : Trie} (h : t.All P) : t.right.All P := by + cases t with + | leaf => trivial + | node v l r => exact h.2.2 + +theorem find?_all {P : Clause → Prop} : + ∀ (fuel : Nat) (t : Trie) (k : Nat) (c : Clause), t.All P → t.find? fuel k = some c → P c + | 0, t, k, c, h, e => by + simp only [find?] at e + split at e + · exact h.root e + · simp at e + | f + 1, t, k, c, h, e => by + simp only [find?] at e + split at e + · exact h.root e + · split at e + · exact find?_all f _ _ c h.left e + · exact find?_all f _ _ c h.right e + +theorem insert_all {P : Clause → Prop} : + ∀ (fuel : Nat) (t : Trie) (k : Nat) (c : Clause), t.All P → P c → (t.insert fuel k c).All P + | 0, t, k, c, h, hc => by + simp only [insert] + split + · exact ⟨fun d e => by cases e; exact hc, h.left, h.right⟩ + · exact h + | f + 1, t, k, c, h, hc => by + simp only [insert] + split + · exact ⟨fun d e => by cases e; exact hc, h.left, h.right⟩ + · split + · exact ⟨fun d e => h.root e, insert_all f _ _ c h.left hc, h.right⟩ + · exact ⟨fun d e => h.root e, h.left, insert_all f _ _ c h.right hc⟩ + +end Trie + +/-- How deep the clause trie goes: IDs below `2 ^ 64` are stored. -/ +def fuel : Nat := 64 + +/-- One added clause: its ID, its literals, and the IDs of the clauses its RUP check uses, in +order. -/ +structure Step where + id : Nat + clause : Clause + hints : List Nat + deriving Inhabited + +/-- A proof: its steps in order, as a tree so that the term stays shallow for the kernel. -/ +inductive Proof where + | step (s : Step) + | seq (a b : Proof) + +/-- How running a proof ends: it failed, it derived the empty clause, or it goes on with these +clauses. -/ +inductive Res where + | fail + | done + | db (t : Trie) + +/-- The clauses hint IDs name, or none when one is missing. -/ +def lookupAll (t : Trie) : List Nat → Option (List Clause) + | [] => some [] + | i :: is => + match t.find? fuel i with + | none => none + | some c => + match lookupAll t is with + | none => none + | some cs => some (c :: cs) + +def Step.run (t : Trie) (s : Step) : Res := + match lookupAll t s.hints with + | none => .fail + | some hs => + if rup hs (s.clause.map Lit.neg) then + match s.clause with + | [] => .done + | _ :: _ => .db (t.insert fuel s.id s.clause) + else .fail + +def Proof.run : Trie → Proof → Res + | t, .step s => s.run t + | t, .seq p q => + match p.run t with + | .db t' => q.run t' + | r => r + +/-- The clauses of a formula, numbered from `i`. -/ +def Trie.ofCnf (t : Trie) (i : Nat) : Cnf → Trie + | [] => t + | c :: cs => Trie.ofCnf (t.insert fuel i c) (i + 1) cs + +/-- The formula's clauses, numbered from 1 as in DIMACS, then the proof, which must end by adding +the empty clause. -/ +def check (f : Cnf) (p : Proof) : Bool := + match p.run (Trie.ofCnf .leaf 1 f) with + | .done => true + | _ => false + +/-! ## Soundness -/ + +section sound +variable (a : Assignment) + +/-- Every literal of `A` is true. -/ +def AllTrue (A : List Lit) : Prop := ∀ l ∈ A, Lit.eval a l = true + +/-- The clauses an assignment satisfies. -/ +abbrev Sat (c : Clause) : Prop := Clause.eval a c = true + +theorem unfalsified_spec {A : List Lit} (hA : AllTrue a A) : + ∀ c : Clause, Clause.eval a c = true → ∃ l ∈ unfalsified A c, Lit.eval a l = true + | [], h => by simp [Clause.eval] at h + | l :: ls, h => by + rw [Clause.eval_cons] at h + rw [unfalsified_cons] + cases hm : memb (Lit.neg l) A + · simp only [Bool.cond_false] + by_cases hl : Lit.eval a l = true + · exact ⟨l, List.mem_cons_self, hl⟩ + · have hls : Clause.eval a ls = true := by simpa [hl] using h + obtain ⟨x, hx, hxv⟩ := unfalsified_spec hA ls hls + exact ⟨x, List.mem_cons_of_mem _ hx, hxv⟩ + · simp only [Bool.cond_true] + have hn := hA _ (memb_iff.mp hm) + rw [Lit.eval_neg] at hn + have hl : Lit.eval a l = false := by simpa using hn + rw [hl] at h + exact unfalsified_spec hA ls (by simpa using h) + +theorem rup_sound : + ∀ (hs : List Clause) (A : List Lit), AllTrue a A → (∀ c ∈ hs, Clause.eval a c = true) → + rup hs A = true → False + | [], _, _, _, h => by simp [rup_nil] at h + | c :: cs, A, hA, hc, h => by + obtain ⟨l, hl, hlv⟩ := unfalsified_spec a hA c (hc c List.mem_cons_self) + rw [rup_cons] at h + unfold rupStep at h + split at h + · next e => rw [e] at hl; simp at hl + · next l' e => + rw [e] at hl + simp at hl + subst hl + refine rup_sound cs (l :: A) ?_ (fun d hd => hc d (List.mem_cons_of_mem _ hd)) h + intro x hx + rcases List.mem_cons.mp hx with rfl | hx + · exact hlv + · exact hA x hx + · simp at h + +theorem allTrue_neg_of_false (c : Clause) (h : Clause.eval a c = false) : + AllTrue a (c.map Lit.neg) := by + intro l hl + obtain ⟨x, hx, rfl⟩ := List.mem_map.mp hl + rw [Lit.eval_neg] + have hn : ¬ (∃ l ∈ c, Lit.eval a l = true) := by + rw [← Clause.eval_eq_true]; simp [h] + have hx' : Lit.eval a x ≠ true := fun e => hn ⟨x, hx, e⟩ + simpa using hx' + +theorem lookupAll_sat {t : Trie} (ht : t.All (Sat a)) : + ∀ (is : List Nat) (hs : List Clause), lookupAll t is = some hs → + ∀ c ∈ hs, Clause.eval a c = true + | [], hs, e => by simp [lookupAll] at e; subst e; simp + | i :: is, hs, e => by + simp only [lookupAll] at e + split at e + · simp at e + · next c hc => + split at e + · simp at e + · next cs hcs => + simp at e; subst e + intro d hd + rcases List.mem_cons.mp hd with rfl | hd + · exact Trie.find?_all fuel t i d ht hc + · exact lookupAll_sat ht is cs hcs d hd + +theorem Step.run_sound {t : Trie} (ht : t.All (Sat a)) (s : Step) : + (s.run t = .done → False) ∧ (∀ t', s.run t = .db t' → t'.All (Sat a)) := by + unfold Step.run + split + · simp + · next hs ehs => + have hsat := lookupAll_sat a ht _ hs ehs + split + · next hr => + -- The added clause is true: otherwise its negation propagates to a conflict. + have hc : Clause.eval a s.clause = true := by + cases e : Clause.eval a s.clause + · exact (rup_sound a hs _ (allTrue_neg_of_false a _ e) hsat hr).elim + · rfl + split + · next e => rw [e] at hc; simp [Clause.eval] at hc + · refine ⟨by simp, fun t' e => ?_⟩ + simp at e; subst e + exact Trie.insert_all fuel t s.id s.clause ht hc + · simp + +theorem Proof.run_sound : + ∀ (p : Proof) (t : Trie), t.All (Sat a) → + (p.run t = .done → False) ∧ (∀ t', p.run t = .db t' → t'.All (Sat a)) + | .step s, t, ht => Step.run_sound a ht s + | .seq p q, t, ht => by + simp only [Proof.run] + have hp := Proof.run_sound p t ht + split + · next t' e => exact Proof.run_sound q t' (hp.2 t' e) + · next r h1 => + refine ⟨fun e => hp.1 e, fun t' e => ?_⟩ + exact (h1 t' e).elim + +theorem Trie.ofCnf_all (f : Cnf) (hf : ∀ c ∈ f, Clause.eval a c = true) : + ∀ (t : Trie) (i : Nat), t.All (Sat a) → ∀ g : Cnf, (∀ c ∈ g, c ∈ f) → + (Trie.ofCnf t i g).All (Sat a) + | t, _, ht, [], _ => ht + | t, i, ht, c :: cs, hg => by + simp only [Trie.ofCnf] + exact Trie.ofCnf_all f hf _ _ (Trie.insert_all fuel t i c ht (hf c (hg c List.mem_cons_self))) + cs (fun d hd => hg d (List.mem_cons_of_mem _ hd)) + +end sound + +/-- A proof that checks shows the formula unsatisfiable. -/ +theorem check_sound (f : Cnf) (p : Proof) (h : check f p = true) : f.Unsat := by + intro a + cases e : Cnf.eval a f + · rfl + · have hf := (Cnf.eval_eq_true a f).mp e + have h0 := Trie.ofCnf_all a f hf .leaf 1 trivial f (fun _ h => h) + have hr := (Proof.run_sound a p _ h0).1 + unfold check at h + split at h + · next e' => exact (hr e').elim + · simp at h + + +/-! ## Checking one step at a time + +For large proofs, a single evaluation of `check` keeps every intermediate clause database in the +kernel's caches. Instead, each step can be its own declaration, a lemma that every assignment +satisfying the formula satisfies the step's clause, proved from the lemmas of its hints by one +small `rup` evaluation. The environment then plays the clause database. These are the lemmas such +declarations apply. -/ + +section steps +variable (a : Assignment) + +/-- Every clause of the list is true. -/ +def AllSat : List Clause → Prop + | [] => True + | c :: cs => Clause.eval a c = true ∧ AllSat cs + +theorem AllSat.nil : AllSat a [] := trivial + +theorem AllSat.cons (c : Clause) (cs : List Clause) (h : Clause.eval a c = true) + (hs : AllSat a cs) : AllSat a (c :: cs) := ⟨h, hs⟩ + +theorem AllSat.mem : ∀ (hs : List Clause), AllSat a hs → ∀ c ∈ hs, Clause.eval a c = true + | [], _, c, hc => by simp at hc + | d :: ds, ⟨hd, hds⟩, c, hc => by + rcases List.mem_cons.mp hc with rfl | hc + · exact hd + · exact AllSat.mem ds hds c hc + +/-- A clause that unit propagation derives from true hint clauses is true. -/ +theorem rup_clause (c : Clause) (hs : List Clause) (hr : rup hs (c.map Lit.neg) = true) + (h : AllSat a hs) : Clause.eval a c = true := by + cases e : Clause.eval a c + · exact (rup_sound a hs _ (allTrue_neg_of_false a c e) (AllSat.mem a hs h) hr).elim + · rfl + +theorem Cnf.eval_mem (f : Cnf) (c : Clause) (h : Cnf.eval a f = true) (hc : c ∈ f) : + Clause.eval a c = true := + (Cnf.eval_eq_true a f).mp h c hc + +theorem mem_head (c : Clause) (l : List Clause) : c ∈ c :: l := List.mem_cons_self + +theorem mem_tail (c d : Clause) (l : List Clause) (h : c ∈ l) : c ∈ d :: l := + List.mem_cons_of_mem _ h + +theorem mem_append_left (c : Clause) (l r : List Clause) (h : c ∈ l) : c ∈ List.append l r := + List.mem_append_left r h + +theorem mem_append_right (c : Clause) (l r : List Clause) (h : c ∈ r) : c ∈ List.append l r := + List.mem_append_right l h + +end steps + +/-- A formula from which every satisfying assignment would satisfy the empty clause is +unsatisfiable. -/ +theorem unsat_of_empty (f : Cnf) (h : ∀ a, Cnf.eval a f = true → Clause.eval a [] = true) : + f.Unsat := by + intro a + cases e : Cnf.eval a f + · rfl + · have := h a e + simp [Clause.eval] at this + +end + +end SolarVerify.Sat diff --git a/Verify/Discharge/Search.lean b/Verify/Discharge/Search.lean new file mode 100644 index 00000000..42edc3b1 --- /dev/null +++ b/Verify/Discharge/Search.lean @@ -0,0 +1,409 @@ +/- +The search that closes a shallow obligation: hypotheses over integers, Booleans as propositions, +arrays as functions and quantifiers over the integers, and the goal `False`. It only builds +proof terms; the kernel checks every one, so a bug here can make a proof fail, never make a +false statement proved. + +1. `vc_defs`: definitions `x = t` and `g ↔ φ` of local symbols are substituted away; +2. `vc_norm`: negations are pushed in, implications become disjunctions (which `omega` reads), + constants fold; +3. the search splits conjunctions, existentials (whose witnesses it names) and disjunctions with + quantifiers, instantiates universal hypotheses at the witnesses and at the arguments that + match their array reads (E-matching on one-variable triggers), splits conditionals and + propositional atoms, adds congruence facts for array reads, and runs `omega` (linear integer + arithmetic, with literal divisors) on each case. +-/ +import Lean +import Verify.Discharge.Lemmas + +open Lean Meta Elab Tactic + +namespace SolarVerify.Discharge + +/-- Replaces one hypothesis `h : a ↔ b` whose side is a local proposition by `propext h : a = b`, +so that `subst_vars` can eliminate it, and repeats on the new context until none is left. -/ +partial def iffToEq : TacticM Unit := withMainContext do + for ldecl in (← getLCtx) do + if ldecl.isImplementationDetail then continue + let ty ← instantiateMVars ldecl.type + if let some (a, b) := ty.iff? then + if a.isFVar || b.isFVar then + let pf ← mkAppM `propext #[ldecl.toExpr] + let r ← (← getMainGoal).replace ldecl.fvarId pf + replaceMainGoal [r.mvarId] + iffToEq + return + +/-- Whether `e` has a quantifier: an `∃`, or a `∀` over the integers (the only sort the verifier +quantifies over). -/ +partial def hasQuantifier (e : Expr) : Bool := + match e with + | .forallE _ d b _ => d == mkConst `Int || hasQuantifier d || hasQuantifier b + | .app f a => (e.isAppOfArity `Exists 2) || hasQuantifier f || hasQuantifier a + | .lam _ t b _ => hasQuantifier t || hasQuantifier b + | .mdata _ b => hasQuantifier b + | _ => false + +/-- The prefix of the names of the witnesses `splitHyps` takes out of existentials. -/ +def witnessPrefix : String := "vc_w" + +/-- Splits one hypothesis that is a conjunction or an existential, naming the witness of an +existential `vc_w…`, and repeats until none is left. -/ +partial def splitHyps : TacticM Unit := withMainContext do + for ldecl in (← getLCtx) do + if ldecl.isImplementationDetail then continue + let ty ← instantiateMVars ldecl.type + let isEx := ty.isAppOfArity `Exists 2 + let quantOr := ty.isAppOfArity `Or 2 && hasQuantifier ty + if ty.isAppOfArity `And 2 || isEx || quantOr then + let gs ← (← getMainGoal).cases ldecl.fvarId + let mut out := [] + for sg in gs do + let mut g := sg.mvarId + if isEx then + if let some (Expr.fvar w) := (sg.fields[0]? : Option Expr) then + g ← g.rename w (← mkFreshUserName (Name.mkSimple witnessPrefix)) + out := out ++ [g] + replaceMainGoal out + -- each case of a disjunction is a goal of its own: split them all + let gs ← getGoals + let mut done := [] + for g in gs do + setGoals [g] + splitHyps + done := done ++ (← getGoals) + setGoals done + return + +/-- The witnesses `splitHyps` named. -/ +def witnesses : TacticM (Array Expr) := withMainContext do + let mut out := #[] + for ldecl in (← getLCtx) do + if ldecl.isImplementationDetail then continue + if !(ldecl.userName.toString.startsWith witnessPrefix) then continue + if (← instantiateMVars ldecl.type) == mkConst `Int then out := out.push ldecl.toExpr + return out + +/-- The subterms `f a₁ … aₙ` of `e` whose head `f` is a local, with no loose bound variables. -/ +partial def localApps (e : Expr) (acc : Array Expr := #[]) : Array Expr := + let acc := if e.isApp && e.getAppFn.isFVar && !e.hasLooseBVars then acc.push e else acc + match e with + | .app f a => localApps a (localApps f acc) + | .lam _ t b _ | .forallE _ t b _ => localApps b (localApps t acc) + | .letE _ t v b _ => localApps b (localApps v (localApps t acc)) + | .mdata _ b | .proj _ _ b => localApps b acc + | _ => acc + +/-- The triggers of a quantifier body for its variable `x` (the bound variable `depth`): the local +functions `f` the body applies to `x`, with the arity and the argument position. -/ +partial def triggers (e : Expr) (depth : Nat := 0) (acc : Array (FVarId × Nat × Nat) := #[]) : + Array (FVarId × Nat × Nat) := + let acc := if e.isApp && e.getAppFn.isFVar then + let args := e.getAppArgs + (List.range args.size).foldl (init := acc) fun acc i => + if args[i]! == .bvar depth then acc.push (e.getAppFn.fvarId!, args.size, i) else acc + else acc + match e with + | .app f a => triggers a depth (triggers f depth acc) + | .lam _ t b _ | .forallE _ t b _ => triggers b (depth + 1) (triggers t depth acc) + | .letE _ t v b _ => triggers b (depth + 1) (triggers v depth (triggers t depth acc)) + | .mdata _ b | .proj _ _ b => triggers b depth acc + | _ => acc + +/-- Instantiates each hypothesis `∀ x : Int, P x` at each witness in `ws`, and at each `t` such +that `P` applies a local function `f` to `x` and the context applies `f` to `t` in the same place +(E-matching on single-variable triggers). Returns whether it added an instance. -/ +def instantiate (ws : Array Expr) (seen : Std.HashSet (Expr × Expr)) : + TacticM (Bool × Std.HashSet (Expr × Expr)) := withMainContext do + let mut seen := seen + let mut ground : Array Expr := #[] + for ldecl in (← getLCtx) do + if !ldecl.isImplementationDetail then + ground := localApps (← instantiateMVars ldecl.type) ground + let hyps := (← getLCtx).foldl (init := #[]) fun acc d => + if d.isImplementationDetail then acc else acc.push d + let mut added := false + for ldecl in hyps do + let ty ← instantiateMVars ldecl.type + if let .forallE _ d body _ := ty then + if d == mkConst `Int && (← isProp ty) then + let mut ts := ws + for (f, n, i) in triggers body do + for e in ground do + if e.getAppFn == .fvar f && e.getAppNumArgs == n then + let t := e.getArg! i + if !(ts.contains t) then ts := ts.push t + for t in ts do + -- each quantifier once per term, however later steps rewrite its instance + if seen.contains (ty, t) then continue + seen := seen.insert (ty, t) + let v := mkApp ldecl.toExpr t + let vty ← instantiateMVars (← whnfR (← inferType v)) + -- an instance the context already has adds nothing + let known := (← getLCtx).any fun d => !d.isImplementationDetail && d.type == vty + if known then continue + let g ← getMainGoal + let (_, g') ← (← g.assert (← mkFreshUserName `inst) vty v).intro1P + replaceMainGoal [g'] + added := true + return (added, seen) + +/-- Clears the hypotheses with quantifiers, which `omega` cannot use. -/ +def clearQuantified : TacticM Unit := withMainContext do + let mut g ← getMainGoal + for ldecl in (← getLCtx) do + if ldecl.isImplementationDetail then continue + let ty ← instantiateMVars ldecl.type + if (← isProp ty) && hasQuantifier ty then + g ← g.tryClear ldecl.fvarId + replaceMainGoal [g] + +/-- The condition of the first `if c then _ else _` in the goal or a hypothesis whose condition +has no loose bound variables. -/ +def findIteCond : TacticM (Option Expr) := withMainContext do + let mut tys := #[← getMainTarget] + for ldecl in (← getLCtx) do + if !ldecl.isImplementationDetail then tys := tys.push ldecl.type + for ty in tys do + let ty ← instantiateMVars ty + if let some e := ty.find? (fun e => (e.isAppOfArity `ite 5 || e.isAppOfArity ``SolarVerify.Discharge.qite 4) && !(e.getArg! 1).hasLooseBVars) then + return some (e.getArg! 1) + return none + +/-- A propositional atom of the goal or a hypothesis: a local proposition (an SMT `Bool` +constant), or a local function applied to integers that returns one (a `Bool` array read), with +no loose bound variables. `omega` reads neither, so the search cases on them. -/ +def findPropAtom : TacticM (Option Expr) := withMainContext do + let mut tys := #[← getMainTarget] + for ldecl in (← getLCtx) do + if !ldecl.isImplementationDetail then tys := tys.push (← instantiateMVars ldecl.type) + for ty in tys do + for e in localApps ty do + if !(← whnfR (← inferType e)).isForall && (← isProp e) then return some e + for ldecl in (← getLCtx) do + if ldecl.isImplementationDetail then continue + if (← instantiateMVars ldecl.type).isProp then + for ty in tys do + if ty.containsFVar ldecl.fvarId then return some ldecl.toExpr + return none + +/-- The applications `f a₁ … aₙ` (`n ≤ 3`, not partial) of a local function `f` to integers in the +goal and the hypotheses, grouped by `f`. -/ +def applications : TacticM (Std.HashMap FVarId (Array (Array Expr))) := withMainContext do + let mut out : Std.HashMap FVarId (Array (Array Expr)) := {} + let mut tys := #[← getMainTarget] + for ldecl in (← getLCtx) do + if !ldecl.isImplementationDetail then tys := tys.push (← instantiateMVars ldecl.type) + for ty in tys do + for e in localApps ty do + let f := e.getAppFn.fvarId! + let args := e.getAppArgs + if args.size == 0 || args.size > 3 then continue + if (← whnfR (← inferType e)).isForall then continue + let mut ok := true + for a in args do + if (← inferType a) != mkConst `Int then ok := false + if !ok then continue + let prev := out.getD f #[] + if !(prev.any (· == args)) then out := out.insert f (prev.push args) + return out + +/-- Adds, for each two applications of the same local function, that they are equal or their +arguments differ. -/ +def congruence : TacticM Unit := withMainContext do + for (f, apps) in (← applications) do + for i in [0:apps.size] do + for j in [i+1:apps.size] do + let (a, b) := (apps[i]!, apps[j]!) + let lemma := match a.size with + | 1 => `SolarVerify.Discharge.congr1 + | 2 => `SolarVerify.Discharge.congr2 + | _ => `SolarVerify.Discharge.congr3 + let pf ← mkAppM lemma (#[mkFVar f] ++ a ++ b) + let g ← getMainGoal + let (_, g') ← (← g.assert (← mkFreshUserName `cong) (← inferType pf) pf).intro1P + replaceMainGoal [g'] + +end SolarVerify.Discharge + +open SolarVerify.Discharge + +/-- For each two applications of the same array or function, adds that they are equal or their +arguments differ. -/ +elab "vc_congr" : tactic => congruence + +/-- Substitutes away the definitions `x = t` and `g ↔ φ` of local symbols. -/ +elab "vc_defs" : tactic => do + iffToEq + evalTactic (← `(tactic| subst_vars)) + +/-- The leaf of the search: closes a quantifier-free goal `False` or fails. It is `omega` here; +another module adds a procedure with +`macro_rules | `(tactic| vc_leaf) => `(tactic| my_tactic)`, and Lean then tries the rules from +the last one added back to `omega`, taking the first that closes the goal. Whatever a rule does, +`discharge.sh` still checks the axioms of every proof. -/ +syntax "vc_leaf" : tactic + +macro_rules | `(tactic| vc_leaf) => `(tactic| omega) + +/-- Pushes negations in, turns implications into disjunctions and Booleans into propositions, +and folds constants. -/ +macro "vc_norm" : tactic => `(tactic| simp -failIfUnchanged only [Classical.not_forall, not_exists, not_imp, + Classical.not_and_iff_not_or_not, not_or, SolarVerify.Discharge.imp_iff_not_or, Classical.not_not, ge_iff_le, + gt_iff_lt, true_and, and_true, false_and, and_false, true_or, or_true, false_or, or_false, + not_true_eq_false, not_false_eq_true, eq_self_iff_true, iff_self, true_implies, false_implies, + implies_true, Bool.and_eq_true, Bool.or_eq_true, Bool.not_eq_true', Bool.not_eq_eq_eq_not, + Bool.not_true, Bool.not_false, decide_eq_true_eq, SolarVerify.Discharge.decide_any_eq_true, SolarVerify.Discharge.qdec_eq_true, SolarVerify.Discharge.ite_eq_qite, SolarVerify.Discharge.qite_true, SolarVerify.Discharge.qite_false, Bool.not_eq_false, Bool.and_eq_false_iff, Bool.or_eq_false_iff, decide_eq_false_iff_not, Bool.and_true, + Bool.true_and, Bool.and_false, Bool.false_and, Bool.or_true, Bool.true_or, Bool.or_false, + Bool.false_or, Bool.true_eq_false, Bool.false_eq_true, SolarVerify.Discharge.true_eq_iff, + SolarVerify.Discharge.false_eq_iff] at *) + +/-- Splits conjunctions and existentials among the hypotheses. -/ +elab "vc_split_hyps" : tactic => splitHyps + +namespace SolarVerify.Discharge + +/-- Simplifies the goal and every hypothesis but the last one (the case hypothesis just +introduced, which the simp set rewrites with) by `stx`. Leaving the case hypothesis alone keeps +it: rewriting it with an earlier copy of itself would turn it into `True`. -/ +def simpCase (stx : Syntax) : TacticM Unit := withMainContext do + let some h := (← getLCtx).lastDecl | throwError "no case hypothesis" + let { ctx, simprocs, .. } ← mkSimpContext stx (eraseLocal := false) + let mut fvars := #[] + for ldecl in (← getLCtx) do + if ldecl.isImplementationDetail || ldecl.fvarId == h.fvarId then continue + if ← isProp ldecl.type then fvars := fvars.push ldecl.fvarId + match ← simpGoal (← getMainGoal) ctx simprocs (fvarIdsToSimp := fvars) with + | (none, _) => replaceMainGoal [] + | (some (_, g), _) => replaceMainGoal [g] + +/-- Proves a condition from the context without splitting on it: a conjunction part by part, a +`∀ x : Int` by instantiating every quantified hypothesis at a fresh `x`, an `∃ x : Int` at a +witness or an integer the context applies a function to, and the rest by `assumption` or +`omega`. A condition that guards a loop's next state restates the invariant the context already +has; proving it avoids a split whose negative case unfolds every quantifier again. -/ +partial def provePos (fuel : Nat) : TacticM Unit := withMainContext do + if fuel = 0 then throwError "vc_prove: depth exhausted" + let t ← whnfR (← instantiateMVars (← getMainTarget)) + if t.isAppOfArity ``And 2 then + evalTactic (← `(tactic| constructor)) + let gs ← getGoals + for g in gs do + setGoals [g] + provePos (fuel - 1) + setGoals [] + else if t.isForall && t.bindingDomain! == mkConst ``Int && !(← isProp t.bindingDomain!) then + let (x, g) ← (← getMainGoal).intro1P + replaceMainGoal [g] + withMainContext do + let mut g ← getMainGoal + for ldecl in (← getLCtx) do + if ldecl.isImplementationDetail then continue + let ty ← instantiateMVars ldecl.type + if let .forallE _ d _ _ := ty then + if d == mkConst ``Int && (← isProp ty) then + let v := mkApp ldecl.toExpr (.fvar x) + let vty ← instantiateMVars (← whnfR (← inferType v)) + let (_, g') ← (← g.assert (← mkFreshUserName `inst) vty v).intro1P + g := g' + replaceMainGoal [g] + evalTactic (← `(tactic| omega)) + else if t.isAppOfArity ``Exists 2 && (t.getArg! 0) == mkConst ``Int then + let mut cands := (← witnesses) + for ldecl in (← getLCtx) do + if ldecl.isImplementationDetail then continue + for e in localApps (← instantiateMVars ldecl.type) do + for a in e.getAppArgs do + if !a.hasLooseBVars && (← inferType a) == mkConst ``Int && !cands.contains a then + cands := cands.push a + for c in cands do + let s ← saveState + try + let cStx ← Term.exprToSyntax c + evalTactic (← `(tactic| refine ⟨$cStx, ?_⟩)) + provePos (fuel - 1) + return + catch _ => s.restore + throwError "vc_prove: no witness" + else + evalTactic (← `(tactic| first | assumption | omega)) + +/-- Proves the goal with `provePos`. -/ +elab "vc_prove_pos" : tactic => provePos 8 + +/-- Splits on the condition of one `if`, simplifying each case; fails when there is none. -/ +def splitIte : TacticM Unit := do + let some c ← findIteCond | throwError "no conditional" + let hcI := mkIdent (← mkFreshUserName `hc) + let cStx ← Term.exprToSyntax c + -- a quantified condition the context implies: take the case where it holds, and no other + if hasQuantifier c then + let s ← saveState + try + evalTactic (← `(tactic| have $hcI : $cStx := by vc_prove_pos)) + simpCase (← `(tactic| simp only [↓reduceIte, SolarVerify.Discharge.ite_pos $hcI, SolarVerify.Discharge.qite_pos $hcI])) + return + catch _ => s.restore + evalTactic (← `(tactic| by_cases $hcI : $cStx)) + let gs ← getGoals + let mut out := [] + -- `by_cases` leaves the case where `c` holds first + for (g, pos) in gs.zip [true, false] do + setGoals [g] + if pos then + simpCase (← `(tactic| simp only [↓reduceIte, SolarVerify.Discharge.ite_pos $hcI, SolarVerify.Discharge.qite_pos $hcI])) + else + simpCase (← `(tactic| simp only [↓reduceIte, SolarVerify.Discharge.ite_neg $hcI, SolarVerify.Discharge.qite_neg $hcI])) + out := out ++ (← getGoals) + setGoals out + +/-- Cases on the propositional atom `p`, rewriting it to `True` or `False` everywhere. -/ +def splitProp (p : Expr) : TacticM Unit := do + let hpI := mkIdent (← mkFreshUserName `hp) + let pStx ← Term.exprToSyntax p + evalTactic (← `(tactic| by_cases $hpI : $pStx)) + let gs ← getGoals + let mut out := [] + for g in gs do + setGoals [g] + simpCase (← `(tactic| simp only [$hpI:ident])) + out := out ++ (← getGoals) + setGoals out + +/-- The search: on each goal, split hypotheses, instantiate quantifiers, and split one +conditional, until nothing changes; then clear the quantified hypotheses, add congruence +facts and run `omega`. `fuel` bounds the depth, so a hopeless goal fails rather than loops. -/ +partial def search (seen : Std.HashSet (Expr × Expr)) (fuel : Nat) : TacticM Unit := do + if fuel = 0 then throwError "vc_auto: search depth exhausted" + for g in (← getGoals) do + setGoals [g] + evalTactic (← `(tactic| vc_norm)) + if (← getGoals).isEmpty then continue + splitHyps + let gs ← getGoals + for g in gs do + setGoals [g] + -- what was instantiated is per branch: a sibling's instances are not in this context + let (added, seen) ← instantiate (← witnesses) seen + if added then + search seen (fuel - 1) + else if (← findIteCond).isSome then + splitIte + search seen (fuel - 1) + else if let some p ← findPropAtom then + splitProp p + search seen (fuel - 1) + else + clearQuantified + congruence + evalTactic (← `(tactic| vc_leaf)) + setGoals [] + +end SolarVerify.Discharge + +/-- Closes a shallow obligation whose hypotheses are still in the goal: see the module comment. -/ +elab "vc_search" : tactic => do + evalTactic (← `(tactic| intros)) + SolarVerify.Discharge.iffToEq + evalTactic (← `(tactic| subst_vars)) + SolarVerify.Discharge.search {} 32 diff --git a/Verify/Discharge/Valid.lean b/Verify/Discharge/Valid.lean new file mode 100644 index 00000000..46c86136 --- /dev/null +++ b/Verify/Discharge/Valid.lean @@ -0,0 +1,241 @@ +/- +`vc_valid` proves an obligation `solar-verify --emit-lean` exported: `Obligation.Valid ob`, for +every interpretation `env` of the declared symbols. + +1. It unfolds the obligation's definitions and evaluates `Term.eval` symbolically: on the + exported terms every sort check decides and every `Option` is `some`, so the formula becomes a + Boolean expression over the symbols' values `env.fn f [] s ()` (and `env.divZero`, + `env.modZero`). A formula that does not reduce so, such as an ill-sorted one, leaves the proof + stuck: it fails, and is never vacuous. +2. It generalizes each such value to a variable of its sort's Lean type (`Int`, `Bool`, + `Int → Int`, …), turns the Boolean formula into propositions, and assumes the guard and the + script's assertions. +3. The search of `SolarVerify.Discharge.Search` closes what is left. + +Every step builds a proof term the kernel checks; nothing here is trusted. +-/ +import Lean +import Verify.Obligation.Vc +import Verify.Discharge.Search + +open Lean Meta Elab Tactic + +namespace SolarVerify.Discharge + +open SolarVerify.Smt SolarVerify.Vc + +/-- An SMT `ite` of one sort evaluates to a value of that sort. -/ +theorem ite_val (s : Srt) (c : Bool) (a b : s.Den) : + (if c = true then (⟨s, a⟩ : Val) else ⟨s, b⟩) = ⟨s, if c = true then a else b⟩ := by + cases c <;> rfl + +/-! Binders: a quantifier over the values of a list of sorts becomes one quantifier per sort, +over the sort's Lean type. -/ + +theorem forall_denList_nil {P : Srt.DenList [] → Prop} : (∀ xs, P xs) ↔ P () := + ⟨fun h => h (), fun h _ => h⟩ + +theorem forall_denList_cons {s : Srt} {ss : List Srt} {P : Srt.DenList (s :: ss) → Prop} : + (∀ xs, P xs) ↔ ∀ (x : s.Den) (xs : Srt.DenList ss), P (x, xs) := + ⟨fun h x xs => h (x, xs), fun h p => h p.1 p.2⟩ + +theorem exists_denList_nil {P : Srt.DenList [] → Prop} : (∃ xs, P xs) ↔ P () := + ⟨fun ⟨_, h⟩ => h, fun h => ⟨(), h⟩⟩ + +theorem exists_denList_cons {s : Srt} {ss : List Srt} {P : Srt.DenList (s :: ss) → Prop} : + (∃ xs, P xs) ↔ ∃ (x : s.Den) (xs : Srt.DenList ss), P (x, xs) := + ⟨fun ⟨p, h⟩ => ⟨p.1, p.2, h⟩, fun ⟨x, xs, h⟩ => ⟨(x, xs), h⟩⟩ + +theorem forall_den_int {P : Srt.Den .int → Prop} : (∀ x, P x) ↔ ∀ x : Int, P x := Iff.rfl +theorem forall_den_bool {P : Srt.Den .bool → Prop} : (∀ x, P x) ↔ ∀ x : Bool, P x := Iff.rfl +theorem exists_den_int {P : Srt.Den .int → Prop} : (∃ x, P x) ↔ ∃ x : Int, P x := Iff.rfl +theorem exists_den_bool {P : Srt.Den .bool → Prop} : (∃ x, P x) ↔ ∃ x : Bool, P x := Iff.rfl + + + +/-- Extensional equality of arrays, as a `qdec` `simp` can rewrite inside. -/ +theorem beq_array (i e : Srt) (a b : Srt.Den (.array i e)) : + Srt.beq (.array i e) a b = qdec (∀ k : Srt.Den i, Srt.beq e (a k) (b k) = true) := by + rw [Srt.beq]; rfl + +/-! Quantifiers over one integer, the only ones the exporter emits so far: the binder becomes a +Lean `∀ x : Int` (`∃`), with the bound value at the head of the locals. -/ + +theorem eval_forall_int (env : Env) (decls : List Decl) (locals : Locals) (body : SolarVerify.Smt.Term) : + Term.eval env decls locals (.forall [.int] body) = + qite (∀ x : Int, (boolOf (Term.eval env decls (⟨.int, x⟩ :: locals) body)).isSome) + (some ⟨.bool, qdec (∀ x : Int, + boolOf (Term.eval env decls (⟨.int, x⟩ :: locals) body) = some true)⟩) + none := by + rw [Term.eval] + have h1 : (∀ xs : Srt.DenList [.int], + (boolOf (Term.eval env decls (bindAll [.int] xs locals) body)).isSome) = + ∀ x : Int, (boolOf (Term.eval env decls (⟨.int, x⟩ :: locals) body)).isSome := + propext ⟨fun h x => h (x, ()), fun h p => h p.1⟩ + have h2 : (∀ xs : Srt.DenList [.int], + boolOf (Term.eval env decls (bindAll [.int] xs locals) body) = some true) = + ∀ x : Int, boolOf (Term.eval env decls (⟨.int, x⟩ :: locals) body) = some true := + propext ⟨fun h x => h (x, ()), fun h p => h p.1⟩ + rw [h1, h2]; rfl + +theorem eval_exists_int (env : Env) (decls : List Decl) (locals : Locals) (body : SolarVerify.Smt.Term) : + Term.eval env decls locals (.exists [.int] body) = + qite (∀ x : Int, (boolOf (Term.eval env decls (⟨.int, x⟩ :: locals) body)).isSome) + (some ⟨.bool, qdec (∃ x : Int, + boolOf (Term.eval env decls (⟨.int, x⟩ :: locals) body) = some true)⟩) + none := by + rw [Term.eval] + have h1 : (∀ xs : Srt.DenList [.int], + (boolOf (Term.eval env decls (bindAll [.int] xs locals) body)).isSome) = + ∀ x : Int, (boolOf (Term.eval env decls (⟨.int, x⟩ :: locals) body)).isSome := + propext ⟨fun h x => h (x, ()), fun h p => h p.1⟩ + have h2 : (∃ xs : Srt.DenList [.int], + boolOf (Term.eval env decls (bindAll [.int] xs locals) body) = some true) = + ∃ x : Int, boolOf (Term.eval env decls (⟨.int, x⟩ :: locals) body) = some true := + propext ⟨fun ⟨p, h⟩ => ⟨p.1, h⟩, fun ⟨x, h⟩ => ⟨(x, ()), h⟩⟩ + rw [h1, h2]; rfl +/-- A value's view at its own sort. -/ +theorem as_self (s : Srt) (x : s.Den) : Val.as ⟨s, x⟩ s = some x := by + simp [Val.as] + +theorem as_int (x : Int) : Val.as ⟨.int, x⟩ .int = some x := rfl + +theorem as_bool (x : Bool) : Val.as ⟨.bool, x⟩ .bool = some x := rfl + +/-- A sort check that holds by reflexivity, at any instance. -/ +theorem dite_self {α : Sort u} {s : Srt} {_ : Decidable (s = s)} (t : s = s → α) (e : ¬s = s → α) : + dite (s = s) t e = t rfl := by + simp + +/-! A Boolean value as a value of sort `bool`: the same type, though not syntactically. -/ + +theorem isSome_some_den (b : Srt.Den .bool) : @Option.isSome Bool (@some (Srt.Den .bool) b) = true := + rfl + +theorem some_den_eq_some_true (b : Srt.Den .bool) : + (@Eq (Option Bool) (@some (Srt.Den .bool) b) (some true)) = ((b : Bool) = true) := + propext (Option.some_inj (α := Bool)) + +theorem holds_of {b : Bool} (h : b = true) : (some b : Option Bool) = some true := by + rw [h] + +theorem of_imp {a b : Bool} (h : a = true → b = true) : (!a || b) = true := by + cases a <;> cases b <;> simp_all + +theorem of_imp_and {a b : Bool} (h : a = true → b = true) : (!(a && true) || b) = true := by + cases a <;> cases b <;> simp_all + +/-- Unfolds the definitions of the exported module (namespace `SolarVerifyVc`) in the goal. -/ +def unfoldExported : TacticM Unit := withMainContext do + let g ← getMainGoal + let t ← instantiateMVars (← g.getType) + let t' ← deltaExpand t (fun n => n.getRoot == `SolarVerifyVc) + replaceMainGoal [← g.replaceTargetDefEq t'] + +/-- Replaces `Srt.Den s` by the Lean type it is for each concrete sort `s` in `e` (`Int`, `Bool`, +functions for arrays), and a classical `decide` by `qdec`. The result is definitionally equal; `simp` needs it, since it matches +`Bool` against `Srt.Den .bool` only up to reducible definitions. -/ +partial def normDen (e : Expr) : MetaM Expr := + Meta.transform e (post := fun e => do + if e.isAppOfArity ``SolarVerify.Smt.Srt.Den 1 && !(e.getArg! 0).hasLooseBVars && !(e.getArg! 0).hasFVar then + let r ← whnfD e + if r != e then return .done (← normDen r) + -- a classical `decide` whose instance names its proposition before `simp` rewrote it + if e.isAppOfArity ``Decidable.decide 2 && (e.getArg! 1).isAppOfArity ``Classical.propDecidable 1 then + return .done (mkApp (mkConst ``SolarVerify.Discharge.qdec) (e.getArg! 0)) + return .continue) + +/-- The subterms of `e` that are values of `env`'s symbols: `env.fn f [] s ()`, `env.divZero` and +`env.modZero`, with no loose bound variables. -/ +partial def envAtoms (env : Expr) (e : Expr) (acc : Array Expr := #[]) : Array Expr := + let isAtom := + !e.hasLooseBVars && + ((e.isAppOfArity ``SolarVerify.Smt.Env.fn 5 && e.getArg! 0 == env && (e.getArg! 2).isAppOfArity `List.nil 1) || + ((e.isAppOfArity ``SolarVerify.Smt.Env.divZero 1 || e.isAppOfArity ``SolarVerify.Smt.Env.modZero 1) && e.getArg! 0 == env)) + if isAtom then (if acc.contains e then acc else acc.push e) else + match e with + | .app f a => envAtoms env a (envAtoms env f acc) + | .lam _ t b _ | .forallE _ t b _ => envAtoms env b (envAtoms env t acc) + | .letE _ t v b _ => envAtoms env b (envAtoms env v (envAtoms env t acc)) + | .mdata _ b | .proj _ _ b => envAtoms env b acc + | _ => acc + +/-- Replaces each value of a symbol in the goal by a variable of its sort's Lean type, universally +quantified: the goal becomes `∀ x, G[x]`, which implies `G[env.fn f [] s ()]`. -/ +def generalizeAtoms (env : Expr) : TacticM Unit := withMainContext do + let g ← getMainGoal + let t ← instantiateMVars (← g.getType) + let atoms := envAtoms env t + let mut binders : Array (Name × Expr) := #[] + for (e, i) in atoms.zipIdx do + let ty ← normDen (← Meta.reduce (← inferType e) (skipTypes := false)) + let k := if e.getAppNumArgs ≥ 2 then (e.getArg! 1).nat? else none + binders := binders.push (Name.mkSimple (match k with | some k => s!"x{k}" | none => s!"z{i}"), ty) + let newTy ← withLocalDeclsD (binders.map fun (n, ty) => (n, fun _ => pure ty)) fun xs => do + let mut b := t + for (x, e) in xs.zip atoms do + b := (← kabstract b e).instantiate1 x + normDen (← mkForallFVars xs b) + let ng ← mkFreshExprSyntheticOpaqueMVar newTy + g.assign (mkAppN ng atoms) + replaceMainGoal [ng.mvarId!] + +end SolarVerify.Discharge + +/-- Runs the tactic unless an earlier step already closed the goal. -/ +def SolarVerify.Discharge.step (tac : Syntax) : TacticM Unit := do + unless (← getGoals).isEmpty do evalTactic tac + +/-- Evaluates the exported terms symbolically: see the module comment. -/ +macro "vc_eval" : tactic => `(tactic| simp -failIfUnchanged only [SolarVerify.Vc.Obligation.Valid, SolarVerify.Vc.Obligation.formula, + SolarVerify.Smt.Holds, ↓SolarVerify.Discharge.eval_forall_int, + ↓SolarVerify.Discharge.eval_exists_int, SolarVerify.Smt.Term.eval, SolarVerify.Smt.Term.evalList, + SolarVerify.Smt.Op.apply, SolarVerify.Smt.boolOf, SolarVerify.Smt.bools, SolarVerify.Smt.ints, + SolarVerify.Smt.Val.asList, SolarVerify.Smt.intRel, SolarVerify.Smt.chain, + SolarVerify.Smt.impliesChain, SolarVerify.Smt.foldl2, SolarVerify.Smt.sameSort, + SolarVerify.Smt.pairwise, SolarVerify.Smt.intDiv, SolarVerify.Smt.intMod, Option.bind, + ↓SolarVerify.Discharge.dite_self, ↓SolarVerify.Discharge.beq_array, ↓SolarVerify.Discharge.as_int, ↓SolarVerify.Discharge.as_bool, SolarVerify.Smt.Val.as, + List.take, List.cons_append, List.nil_append, List.all, List.any, + List.reverse, List.reverseAux, List.foldl, id, bind, pure, List.getElem?_cons_succ, + List.getElem?_cons_zero, SolarVerify.Smt.Srt.beq, ↓reduceDIte, ↓reduceIte, Option.some.injEq, SolarVerify.Discharge.ite_val, + SolarVerify.Smt.bindAll, SolarVerify.Smt.Srt.unpack, List.reverse_cons, List.reverse_nil, + List.singleton_append, SolarVerify.Discharge.forall_denList_nil, + SolarVerify.Discharge.forall_denList_cons, SolarVerify.Discharge.exists_denList_nil, + SolarVerify.Discharge.exists_denList_cons, SolarVerify.Discharge.forall_den_int, + SolarVerify.Discharge.forall_den_bool, SolarVerify.Discharge.exists_den_int, + SolarVerify.Discharge.exists_den_bool, SolarVerify.Discharge.decide_any_eq_true, + Option.isSome_some, implies_true, SolarVerify.Discharge.qite_true, + SolarVerify.Discharge.qdec_eq_true, eq_self_iff_true, dite_true, + SolarVerify.Discharge.isSome_some_den, SolarVerify.Discharge.some_den_eq_some_true, + Bool.and_true, Bool.not_not]) + +/-- Rewrites the goal with `normDen`. -/ +def SolarVerify.Discharge.normDenGoal : TacticM Unit := withMainContext do + let g ← getMainGoal + let t ← instantiateMVars (← g.getType) + replaceMainGoal [← g.replaceTargetDefEq (← normDen t)] + +open SolarVerify.Discharge in +/-- Reduces `Obligation.Valid ob` to a shallow goal `False` under its hypotheses. -/ +elab "vc_valid_prep" : tactic => do + unfoldExported + evalTactic (← `(tactic| unfold SolarVerify.Vc.Obligation.Valid)) + let (envFv, g) ← (← getMainGoal).intro `env + replaceMainGoal [g] + evalTactic (← `(tactic| vc_eval)) + unless (← getGoals).isEmpty do normDenGoal + step (← `(tactic| vc_eval)) + step (← `(tactic| first | refine SolarVerify.Discharge.holds_of ?_ | skip)) + unless (← getGoals).isEmpty do generalizeAtoms (.fvar envFv) + step (← `(tactic| intros)) + step (← `(tactic| first | apply SolarVerify.Discharge.of_imp_and | apply SolarVerify.Discharge.of_imp)) + step (← `(tactic| intro hyps)) + step (← `(tactic| simp -failIfUnchanged only [Bool.and_eq_true, Bool.or_eq_true, Bool.not_eq_true', + SolarVerify.Discharge.decide_any_eq_true, SolarVerify.Discharge.qdec_eq_true, decide_eq_true_eq, + decide_eq_false_iff_not, Bool.and_true, Bool.true_and] at *)) + step (← `(tactic| refine Classical.byContradiction ?_)) + step (← `(tactic| intro)) + step (← `(tactic| vc_split_hyps)) + +/-- Proves `Obligation.Valid ob` for an exported obligation `ob`: see the module comment. -/ +macro "vc_valid" : tactic => `(tactic| (vc_valid_prep <;> vc_search)) diff --git a/Verify/Discharge/discharge.sh b/Verify/Discharge/discharge.sh new file mode 100755 index 00000000..8429e012 --- /dev/null +++ b/Verify/Discharge/discharge.sh @@ -0,0 +1,310 @@ +#!/usr/bin/env bash +# Discharges in the Lean kernel the obligations 'solar-verify --emit-lean DIR' exported. An +# obligation is accepted only when a certificate the kernel checks proves '.Valid', with no +# axiom but propext, Classical.choice and Quot.sound. Certificate kinds (DISCHARGE_KINDS, tried +# in order): +# +# search 'vc_valid': a proof the discharge library builds itself (Verify/Discharge). +# smt 'vc_smt': a cvc5 proof reconstructed step by step in Lean (Verify/Reconstruct, a +# package of its own; built on first use). +# lean a theorem written for the obligation, listed in DISCHARGE_CERTS (see below). +# +# Writes DIR/discharge/results.tsv (one row per required obligation and kind tried, with time, +# memory and axioms), DIR/discharge/summary.tsv (per obligation, the kinds that proved it) and +# DIR/discharge/inputs.sha256, and exits 0 only when every required obligation is proved. A unit +# that was not exported, a missing, duplicate or changed input, an error, a timeout, another +# axiom, or a library that is not the one the export was written for is a failure, never a pass. +# +# Verify/Discharge/discharge.sh DIR [TIMEOUT_SECONDS] +# +# Environment: +# DISCHARGE_KINDS comma-separated kinds, default 'search'. +# DISCHARGE_ALL 1: try every kind on every obligation (coverage per kind) rather than stop +# at the first that proves it. +# DISCHARGE_ONLY a regex on obligation ids; the others are skipped (and the run fails). +# DISCHARGE_LOCK a sha256sum file of the inputs (as inputs.sha256 is written): the run fails +# unless the manifest and every exported module match it. +# DISCHARGE_CERTS for kind 'lean': a TSV of 'idmoduletheorem'. The probe imports +# the module and states 'theorem obligation : .Valid := ', so the +# kernel checks that the theorem proves exactly the exported obligation. +# DISCHARGE_CERT_PATH LEAN_PATH entries where those modules are built. +# DISCHARGE_CERT_EXPORTS the directory of the exported modules those modules import: each +# must equal the locked input (or its copy with the import read as below). +# DISCHARGE_SOURCE_ROOT the repository root the manifest's sources are named relative to: +# each must hash as the manifest says, and inputs.sha256 then lists them. +# DISCHARGE_INPUTS_ONLY 1: check the inputs only, then stop before any Lean runs. +# DISCHARGE_HEAVY a command to prefix library builds with (a build-slot wrapper). +# +# The exported modules say 'import SolarVerify' (solar's former Lean package); they are compiled +# with that line read as 'import Verify.Obligation', the same library under its path here. The +# manifest's semantics hashes must match Verify/Obligation/Smt.lean and Vc.lean, Vc.lean read +# with its first line as 'import SolarVerify.Smt' when the export predates the move. +set -euo pipefail +dir=$(cd "$1" && pwd) +limit=${2:-600} +here=$(cd "$(dirname "$0")" && pwd) +root=$(cd "$here/../.." && pwd) +export LEAN_NUM_THREADS=${LEAN_NUM_THREADS:-1} +heavy=${DISCHARGE_HEAVY:-} +manifest="$dir/manifest.json" +allowed="propext Classical.choice Quot.sound" +IFS=',' read -r -a kinds <<<"${DISCHARGE_KINDS:-search}" +only=${DISCHARGE_ONLY:-} +out="$dir/discharge" +rm -rf "$out" +mkdir -p "$out/src" + +fail() { echo "error: $*" >&2; exit 1; } +for k in "${kinds[@]}"; do + case $k in search|smt|lean) ;; *) fail "unknown certificate kind $k" ;; esac +done +[[ $(jq -r .format "$manifest") == solar-verify-lean ]] || fail "not a solar-verify-lean manifest" +[[ $(jq -r .version "$manifest") == 2 ]] || fail "format version $(jq -r .version "$manifest"), this checker reads 2" +# Version 2 names every source relative to the repository root it was exported from, so that an +# export and its lock mean the same files on every machine; run.json (the run's own record, such +# as solver versions and timings) is neither read nor hashed. +nonportable=$(jq -r '(.sources // [])[] | .path | select(type != "string" or startswith("/") or test("(^|/)\\.\\.?(/|$)") or contains("\\") or . == "")' "$manifest") +[[ -z $nonportable ]] || fail "sources not named relative to the repository root: $nonportable" +[[ $(jq '(.sources // []) | length' "$manifest") -gt 0 ]] || fail "the manifest names no sources" +badmod=$(jq -r '.units[] | .module // empty | select(startswith("/") or test("(^|/)\\.\\.?(/|$)") or contains("\\") or (endswith(".lean") | not))' "$manifest") +[[ -z $badmod ]] || fail "modules not named relative to the export: $badmod" + +# The proofs must read the terms with the semantics they were written for. +smt_have=$(sha256sum "$root/Verify/Obligation/Smt.lean" | cut -d' ' -f1) +vc_have=$(sha256sum "$root/Verify/Obligation/Vc.lean" | cut -d' ' -f1) +vc_legacy=$(sed '1s/^import Verify\.Obligation\.Smt$/import SolarVerify.Smt/' "$root/Verify/Obligation/Vc.lean" | sha256sum | cut -d' ' -f1) +[[ $(jq -r '.lean.smt_sha256 // empty' "$manifest") == "$smt_have" ]] || fail "Verify/Obligation/Smt.lean is not the one the export was written for" +vc_want=$(jq -r '.lean.vc_sha256 // empty' "$manifest") +[[ $vc_want == "$vc_have" || $vc_want == "$vc_legacy" ]] || fail "Verify/Obligation/Vc.lean is not the one the export was written for" + +# Nothing a certificate kind runs may assume more than the kernel checks. +if grep -rnE '\b(sorry|admit|native_decide|bv_decide|ofReduceBool|ofReduceNat|implemented_by|extern|unsafe|axiom|decide \+native)\b' \ + "$root"/Verify/Obligation.lean "$root"/Verify/Obligation "$root"/Verify/Discharge.lean "$root"/Verify/Discharge/*.lean \ + "$root"/Verify/Discharge/Sat "$root"/Verify/Reconstruct/*.lean; then + fail "the discharge library uses a construct the kernel does not check" +fi + +# Every list is read whole before any lean runs: Lean's runtime inherits the descriptor a +# 'while read ... done < <(...)' loop reads from, and the loop then ends early. +mapfile -t modules < <(jq -r '.units[] | select(.module != null) | .module' "$manifest" | sort -u) +mapfile -t rows < <(jq -r '.units[] | select(.module != null) as $u | $u.obligations[] | select(.required) | [$u.module, .id, .lean, .role, .answer] | @tsv' "$manifest") +mapfile -t unexported < <(jq -r '.units[] | select(.module == null) | [.name, (.status // "not-exported")] | @tsv' "$manifest") +want=$(jq '[.units[] | .obligations[]? | select(.required)] | length' "$manifest") +total=$(jq '[.units[] | .obligations[]?] | length' "$manifest") +dups=$(jq -r '([.units[] | .obligations[]? | .id], [.units[] | .obligations[]? | select(.required) | .lean]) | group_by(.) | map(select(length > 1) | .[0]) | .[]' "$manifest") +[[ -z $dups ]] || fail "listed twice: $dups" +for module in "${modules[@]}"; do + [[ -f $dir/$module ]] || fail "missing exported module $module" +done +(cd "$dir" && sha256sum manifest.json "${modules[@]}") >"$out/inputs.sha256" +# The sources, from the repository root they are named relative to, must be the ones exported. +mapfile -t sources < <(jq -r '.sources[] | [.path, .sha256] | @tsv' "$manifest") +if [[ -n ${DISCHARGE_SOURCE_ROOT:-} ]]; then + srcroot=$(cd "$DISCHARGE_SOURCE_ROOT" && pwd) + srcpaths=() + for s in "${sources[@]}"; do + IFS=$'\t' read -r path sha <<<"$s" + [[ -f $srcroot/$path ]] || fail "missing source $path" + have=$(sha256sum "$srcroot/$path" | cut -d' ' -f1) + [[ $have == "$sha" ]] || fail "source $path is not the one exported" + srcpaths+=("$path") + done + (cd "$srcroot" && sha256sum "${srcpaths[@]}") >>"$out/inputs.sha256" +fi +# Every obligation a module defines is listed, and every listed one is defined: an obligation +# deleted from the manifest fails here even without a lock. +mapfile -t units < <(jq -r '.units[] | select(.module != null) | [.module, (.obligations | length), ([.obligations[].lean | split(".") | last] | join(" "))] | @tsv' "$manifest") +for u in "${units[@]}"; do + IFS=$'\t' read -r module n names <<<"$u" + defined=$(grep -cE '^def ob[0-9]+ : Obligation' "$dir/$module" || true) + [[ $defined -eq $n ]] || fail "$module defines $defined obligations, the manifest lists $n" + for nm in $names; do + grep -qE "^def $nm : Obligation" "$dir/$module" || fail "$module does not define $nm" + done +done +if [[ -n ${DISCHARGE_LOCK:-} ]]; then + diff <(sort -k2 "$DISCHARGE_LOCK") <(sort -k2 "$out/inputs.sha256") >&2 \ + || fail "the inputs are not the ones $DISCHARGE_LOCK pins" +fi +nunexp=$(jq '[.units[] | select(.module == null) | .obligations[]? | select(.required)] | length' "$manifest") +[[ $(( ${#rows[@]} + nunexp )) -eq $want ]] || fail "$want required obligations, ${#rows[@]} with a module" +echo "discharge: ${#modules[@]} modules, $want required of $total obligations, ${#unexported[@]} units not exported; kinds ${kinds[*]}" >&2 + +# DISCHARGE_INPUTS_ONLY=1 stops here, after every check of the inputs and before any Lean runs. +if [[ ${DISCHARGE_INPUTS_ONLY:-0} == 1 ]]; then + echo "inputs: ok" >&2 + exit 0 +fi + +# The exported modules with the library's import path. +for module in "${modules[@]}"; do + mkdir -p "$out/src/$(dirname "$module")" + sed '1,20s/^import SolarVerify$/import Verify.Obligation/' "$dir/$module" >"$out/src/$module" + grep -q '^import Verify.Obligation$' "$out/src/$module" || fail "$module does not import the obligation library" +done + +# The library each kind's proofs run in ('core' or 'smt'), and the exports compiled against it. +declare -A libpath compiled +family() { if [[ $1 == smt ]]; then echo smt; else echo core; fi; } +build_family() { + local fam=$1 lp module mod + [[ -n ${libpath[$fam]:-} ]] && return 0 + if [[ $fam == core ]]; then + (cd "$root" && $heavy lake build -KleanMemory=3000 -q VerifyDischarge &2) + lp="$root/.lake/build/lib/lean" + else + (cd "$root/Verify/Reconstruct" && $heavy lake build -KleanMemory=3000 -q &2) + lp=$(cd "$root/Verify/Reconstruct" && lake env printenv LEAN_PATH) + fi + libpath[$fam]=$lp + mkdir -p "$out/build-$fam" + for module in "${modules[@]}"; do + mod=${module%.lean} + mkdir -p "$out/build-$fam/$(dirname "$mod")" + (cd "$out/src" && LEAN_PATH="$lp:$out/build-$fam" lean -R "$out/src" -o "$out/build-$fam/$mod.olean" "$out/src/$module" /dev/null) \ + || fail "could not compile the exported module $module" + done +} +for k in "${kinds[@]}"; do build_family "$(family "$k")"; done + +# Certificates written as theorems: the exports they import must be the locked inputs. +declare -A certmod certthm +if [[ " ${kinds[*]} " == *" lean "* ]]; then + [[ -n ${DISCHARGE_CERTS:-} && -f $DISCHARGE_CERTS ]] || fail "kind lean needs DISCHARGE_CERTS" + [[ -n ${DISCHARGE_CERT_EXPORTS:-} ]] || fail "kind lean needs DISCHARGE_CERT_EXPORTS" + for module in "${modules[@]}"; do + f="$DISCHARGE_CERT_EXPORTS/$module" + [[ -f $f ]] || continue + cmp -s "$f" "$dir/$module" || cmp -s "$f" "$out/src/$module" \ + || fail "the certificates import a $module that is not the exported one" + done + mapfile -t certrows < <(grep -v '^#' "$DISCHARGE_CERTS" | grep -v '^$' || true) + for c in "${certrows[@]}"; do + IFS=$'\t' read -r cid cmod cthm <<<"$c" + [[ -z ${certthm[$cid]:-} ]] || fail "two certificates for $cid" + certmod[$cid]=$cmod + certthm[$cid]=$cthm + done +fi + +# Runs a command and prints its wall time and peak memory as 'MEMTIME seconds megabytes'. +measure() { + python3 -c ' +import resource, subprocess, sys, time +t = time.time() +r = subprocess.run(sys.argv[1:], stdin=subprocess.DEVNULL) +mb = resource.getrusage(resource.RUSAGE_CHILDREN).ru_maxrss // 1024 +sys.stderr.write("MEMTIME %.1f %d\n" % (time.time() - t, mb)) +sys.exit(r.returncode)' "$@" +} + +results="$out/results.tsv" +printf 'id\trole\tanswer\tkind\tstatus\tseconds\tpeak_mb\taxioms\n' >"$results" +summary="$out/summary.tsv" +printf 'id\trole\tanswer\tstatus\tkinds\n' >"$summary" +pass=0 bad=0 +for row in "${unexported[@]}"; do + [[ -n $row ]] || continue + IFS=$'\t' read -r name status <<<"$row" + printf '%s\t-\t-\t-\tfailed: unit not exported (%s)\t0\t-\t-\n' "$name" "$status" >>"$results" + printf '%s\t-\t-\tfailed: unit not exported (%s)\t-\n' "$name" "$status" >>"$summary" + bad=$((bad + 1)) +done + +# One probe: states the obligation, proves it with the kind's certificate, reports its axioms. +probe_one() { + local k=$1 id=$2 lean=$3 modname=$4 probe proof imports fam lp res code + local extra=() + mkdir -p "$out/probe" + probe="$out/probe/$(echo "$id.$k" | tr -c 'A-Za-z0-9_\n' '_').lean" + fam=$(family "$k") + lp="${libpath[$fam]}:$out/build-$fam" + case $k in + search) imports="import Verify.Discharge"; proof="by vc_valid" ;; + smt) + imports="import Verify.Reconstruct.Tactic"; proof="by vc_smt" + extra=("--plugin=$root/Verify/Reconstruct/.lake/packages/cvc5/.lake/build/lib/libcvc5_cvc5.so") ;; + lean) + if [[ -z ${certthm[$id]:-} ]]; then echo NOCERT; return 0; fi + imports="import Verify.Discharge +import ${certmod[$id]}" + proof="${certthm[$id]}" + lp="${DISCHARGE_CERT_PATH:+$DISCHARGE_CERT_PATH:}$lp" ;; + esac + { + echo "$imports" + echo "import $modname" + echo + echo "theorem obligation : $lean.Valid := $proof" + echo + echo "open Lean Elab Command in" + echo "#eval show CommandElabM Unit from do" + echo " let axs ← Lean.collectAxioms (Name.mkSimple \"obligation\")" + echo " IO.println s!\"AXIOMS: {String.intercalate \" \" (axs.toList.map toString)}\"" + } >"$probe" + set +e + res=$(cd "$out/probe" && LEAN_PATH="$lp" measure timeout "$limit" lean "${extra[@]}" -DmaxHeartbeats=0 -DmaxRecDepth=100000 "$probe" 2>&1) + code=$? + set -e + printf 'CODE %s\n%s\n' "$code" "$res" +} + +for row in "${rows[@]}"; do + IFS=$'\t' read -r module id lean role answer <<<"$row" + if [[ -n $only && ! $id =~ $only ]]; then + printf '%s\t%s\t%s\t-\tfailed: skipped\t0\t-\t-\n' "$id" "$role" "$answer" >>"$results" + printf '%s\t%s\t%s\tfailed: skipped\t-\n' "$id" "$role" "$answer" >>"$summary" + bad=$((bad + 1)); continue + fi + modname=${module%.lean} + modname=${modname//\//.} + proving=() + for k in "${kinds[@]}"; do + res=$(probe_one "$k" "$id" "$lean" "$modname") + if [[ $res == NOCERT ]]; then + printf '%s\t%s\t%s\t%s\tfailed: no certificate\t0\t-\t-\n' "$id" "$role" "$answer" "$k" >>"$results" + continue + fi + code=$(printf '%s\n' "$res" | sed -n '1s/^CODE //p') + body=$(printf '%s\n' "$res" | sed 1d) + secs=$(printf '%s\n' "$body" | sed -n 's/^MEMTIME \([^ ]*\) .*/\1/p') + peak=$(printf '%s\n' "$body" | sed -n 's/^MEMTIME [^ ]* //p') + axioms=$(printf '%s\n' "$body" | sed -n 's/^AXIOMS: *//p') + status=proved + if [[ $code -eq 124 ]]; then + status="failed: timeout after ${limit}s" + elif [[ $code -ne 0 ]] || printf '%s\n' "$body" | grep -q 'error'; then + status="failed: $(printf '%s\n' "$body" | grep -m1 -A2 'error' | tr '\t\n' ' ' | cut -c1-240)" + elif [[ -z $axioms ]]; then + status="failed: no axiom report" + else + for a in $axioms; do + [[ " $allowed " == *" $a "* ]] || status="failed: uses axiom $a" + done + fi + printf '%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\n' "$id" "$role" "$answer" "$k" "$status" "${secs:-0}" "${peak:--}" "${axioms:-none}" >>"$results" + echo "$k: $status $id (${secs:-0}s, ${peak:--} MB)" >&2 + if [[ $status == proved ]]; then + proving+=("$k") + [[ ${DISCHARGE_ALL:-0} == 1 ]] || break + fi + done + if [[ ${#proving[@]} -gt 0 ]]; then + printf '%s\t%s\t%s\tproved\t%s\n' "$id" "$role" "$answer" "$(IFS=,; echo "${proving[*]}")" >>"$summary" + pass=$((pass + 1)) + else + printf '%s\t%s\t%s\tfailed\t-\n' "$id" "$role" "$answer" >>"$summary" + bad=$((bad + 1)) + fi +done + +if [[ $((pass + bad - ${#unexported[@]})) -ne ${#rows[@]} ]]; then + echo "error: ${#rows[@]} exported required obligations, $((pass + bad - ${#unexported[@]})) checked" >&2 + bad=$((want - pass)) +fi +for k in "${kinds[@]}"; do + n=$(awk -F'\t' -v k="$k" '$4 == k && $5 == "proved"' "$results" | wc -l) + echo "discharge: kind $k proved $n" >&2 +done +echo "discharge: $pass of $want required obligations proved, $bad not ($summary)" >&2 +[[ $bad -eq 0 && $pass -eq $want ]] diff --git a/Verify/Discharge/frozen/ArrayMax.sha256 b/Verify/Discharge/frozen/ArrayMax.sha256 new file mode 100644 index 00000000..62894797 --- /dev/null +++ b/Verify/Discharge/frozen/ArrayMax.sha256 @@ -0,0 +1,5 @@ +fd6ba812db32525b609d720b646fa1db1c6f847553ffe5689aa569c0a0213241 manifest.json +1a02fe322248251cb404d8f56ad9110bbf4ead96cf56ad1117976351eeca0f5a ArrayMax/clamp.lean +a39b2942dcd59cf63faa1ced3aa86bb2834f362bfa894d7be9878f0ba66a44c6 ArrayMax/max.lean +fdda1a5f2c6049ddb1b7136571217dc2d743845728edbd4bbc4cfe2256ef5bd9 ArrayMaxEntry/constructor.lean +9bd919a6e290d34c0723dd1529e9bd64004112cd5c1ba5c91d13425f080329ed ArrayMaxEntry/max.lean diff --git a/Verify/Discharge/frozen/Counter.sha256 b/Verify/Discharge/frozen/Counter.sha256 new file mode 100644 index 00000000..f7b81750 --- /dev/null +++ b/Verify/Discharge/frozen/Counter.sha256 @@ -0,0 +1,5 @@ +98c3c05695d52e1801de6a84ebe49e85f619850a17143583859d2e17e4bde305 manifest.json +4bb27f47e1eced3ed032dbcbcecb69ed2b4632fb0f00f63ad112aa0da7727c0e Counter/bump.lean +a481a4b1e0dc5c77a83729023e710e268cd1c3aa4cdf281a9c5bcc03e1efbcdf Counter/constructor.lean +a60ddafeeec741a6c6f69fe958b7df8f94fb003a0a848024a0e04515e3ce4c74 Counter/increment.lean +cd1d94b409422123ddeb4f7340c349f5eb148e67b1edd1271388bdcffbf4e567 Counter/max.lean diff --git a/Verify/Discharge/frozen/PINS b/Verify/Discharge/frozen/PINS new file mode 100644 index 00000000..fb5b60bd --- /dev/null +++ b/Verify/Discharge/frozen/PINS @@ -0,0 +1,8 @@ +exporter paradigmxyz/solar 7f4e94e065c8e90c2e8d265813533c71cd59c1dc (solar-verify --emit-lean, release build) +sources crates/verify/examples/{Counter,Token,Vault,ArrayMax}.sol at that commit +command solar-verify --emit-lean vc-exports/ crates/verify/examples/.sol, from the repository root +semantics SolarVerify/Smt.lean 2c92f3bcd927369da89250662bd5a6174d3c06d0c3c38f5021509fe8810036e3 + SolarVerify/Vc.lean 7275fa354f077a4826dd9fe56124cbffee2337d7a21975b477534fc5f45d7cfe +toolchain leanprover/lean4:v4.35.0 +solvers z3 4.13.4, cvc5 1.3.1 (recorded in each manifest) +required Counter 14, Token 13, Vault 17, ArrayMax 19 (63) diff --git a/Verify/Discharge/frozen/Token.sha256 b/Verify/Discharge/frozen/Token.sha256 new file mode 100644 index 00000000..45b64a05 --- /dev/null +++ b/Verify/Discharge/frozen/Token.sha256 @@ -0,0 +1,5 @@ +86b2d80ed2642128959ac13bf9dbbc34ad69206dd2e100cfceb8ea6889a2b2f8 manifest.json +7c3e619cb4f5c051df2bee25f1bd6227b815bccda2471249090e0f2e6fbff187 Token/burn.lean +bb81d4917461c58b296936eb8bfc4d3092ffb768a02814deca6e92811d4ff0a7 Token/constructor.lean +e87f0a2d6ebb9410a449656844b724df569d84c317afeb866f1f1a2845b4d2a1 Token/mint.lean +fa074a46ec5bd2686cae08af09ec1af0aecd1aa5eb7720ef1896f237886cc246 Token/transfer.lean diff --git a/Verify/Discharge/frozen/Vault.sha256 b/Verify/Discharge/frozen/Vault.sha256 new file mode 100644 index 00000000..0014a46c --- /dev/null +++ b/Verify/Discharge/frozen/Vault.sha256 @@ -0,0 +1,4 @@ +2589125ac7c0b22969b81edb8b4f4bba10b7404351cd3e1276974c2b25849edb manifest.json +93b5b6971bf6f4c4c907a55e8d270c15b831e41ce858493d1c02da1ddcacfc41 Vault/constructor.lean +de6d589769c68862abcf874f9f8a316923ce34478346ebd2ef62d9af5cd0ca74 Vault/deposit.lean +b7fc9bfd454493489523a9c64689393906408761f5f5fb42612e2fdd4b71320a Vault/withdraw.lean diff --git a/Verify/Discharge/frozen/v2/ArrayMax.sha256 b/Verify/Discharge/frozen/v2/ArrayMax.sha256 new file mode 100644 index 00000000..893d1608 --- /dev/null +++ b/Verify/Discharge/frozen/v2/ArrayMax.sha256 @@ -0,0 +1,6 @@ +dcc0c005e8cbca26ada22669566face573161ce024ca35e78e988cffaf6c9d3d manifest.json +1a02fe322248251cb404d8f56ad9110bbf4ead96cf56ad1117976351eeca0f5a ArrayMax/clamp.lean +a39b2942dcd59cf63faa1ced3aa86bb2834f362bfa894d7be9878f0ba66a44c6 ArrayMax/max.lean +fdda1a5f2c6049ddb1b7136571217dc2d743845728edbd4bbc4cfe2256ef5bd9 ArrayMaxEntry/constructor.lean +9bd919a6e290d34c0723dd1529e9bd64004112cd5c1ba5c91d13425f080329ed ArrayMaxEntry/max.lean +904535ac694498a9823f530ca158ee0c762fd1adcc56f3e7b73ca0e457e61f4a crates/verify/examples/ArrayMax.sol diff --git a/Verify/Discharge/frozen/v2/Counter.sha256 b/Verify/Discharge/frozen/v2/Counter.sha256 new file mode 100644 index 00000000..5c504e93 --- /dev/null +++ b/Verify/Discharge/frozen/v2/Counter.sha256 @@ -0,0 +1,6 @@ +3752220c134c4b5e09b90bc4cc198341a7b7c76a8ed6e65513de7a5b47247f9f manifest.json +4bb27f47e1eced3ed032dbcbcecb69ed2b4632fb0f00f63ad112aa0da7727c0e Counter/bump.lean +a481a4b1e0dc5c77a83729023e710e268cd1c3aa4cdf281a9c5bcc03e1efbcdf Counter/constructor.lean +a60ddafeeec741a6c6f69fe958b7df8f94fb003a0a848024a0e04515e3ce4c74 Counter/increment.lean +cd1d94b409422123ddeb4f7340c349f5eb148e67b1edd1271388bdcffbf4e567 Counter/max.lean +f1c87a334b8db31fc8f80541febeaf8617318d20b685634f44e26c74146ad326 crates/verify/examples/Counter.sol diff --git a/Verify/Discharge/frozen/v2/PINS b/Verify/Discharge/frozen/v2/PINS new file mode 100644 index 00000000..c23060a3 --- /dev/null +++ b/Verify/Discharge/frozen/v2/PINS @@ -0,0 +1,10 @@ +format solar-verify-lean version 2 +derived from the version-1 exports frozen/PINS names (solar 7f4e94e, regenerated byte-identical + to frozen/.sha256): manifest.json with version 2 and each source named relative to + the repository root (crates/verify/examples/.sol); every module is unchanged, as + the module lines of frozen/.sha256 and frozen/v2/.sha256 show +lock frozen/v2/.sha256 lists manifest.json and the modules relative to the export + directory, then the sources relative to the repository root (DISCHARGE_SOURCE_ROOT) +check DISCHARGE_LOCK=frozen/v2/.sha256 DISCHARGE_SOURCE_ROOT= + Verify/Discharge/discharge.sh +required Counter 14, Token 13, Vault 17, ArrayMax 19 (63) diff --git a/Verify/Discharge/frozen/v2/Token.sha256 b/Verify/Discharge/frozen/v2/Token.sha256 new file mode 100644 index 00000000..4f84c276 --- /dev/null +++ b/Verify/Discharge/frozen/v2/Token.sha256 @@ -0,0 +1,6 @@ +ca345407953c0f38594ec92a836909667756115648a5fb362b8ecfe7158e9854 manifest.json +7c3e619cb4f5c051df2bee25f1bd6227b815bccda2471249090e0f2e6fbff187 Token/burn.lean +bb81d4917461c58b296936eb8bfc4d3092ffb768a02814deca6e92811d4ff0a7 Token/constructor.lean +e87f0a2d6ebb9410a449656844b724df569d84c317afeb866f1f1a2845b4d2a1 Token/mint.lean +fa074a46ec5bd2686cae08af09ec1af0aecd1aa5eb7720ef1896f237886cc246 Token/transfer.lean +45b62aa1152c4ec09e76735ac7257a06bf3e4be0f435fdacdc174f41e8c8e75c crates/verify/examples/Token.sol diff --git a/Verify/Discharge/frozen/v2/Vault.sha256 b/Verify/Discharge/frozen/v2/Vault.sha256 new file mode 100644 index 00000000..f303de56 --- /dev/null +++ b/Verify/Discharge/frozen/v2/Vault.sha256 @@ -0,0 +1,5 @@ +b529bd7e3e8b9820785433e8af56262d5fade9247285007e2ff20d0206c697e6 manifest.json +93b5b6971bf6f4c4c907a55e8d270c15b831e41ce858493d1c02da1ddcacfc41 Vault/constructor.lean +de6d589769c68862abcf874f9f8a316923ce34478346ebd2ef62d9af5cd0ca74 Vault/deposit.lean +b7fc9bfd454493489523a9c64689393906408761f5f5fb42612e2fdd4b71320a Vault/withdraw.lean +0e2017a2679b3fc98aa539d29ce350f9776dd0d14a0085aed88d9b26a9921526 crates/verify/examples/Vault.sol diff --git a/Verify/Discharge/test/negatives.sh b/Verify/Discharge/test/negatives.sh new file mode 100755 index 00000000..0cf2b74a --- /dev/null +++ b/Verify/Discharge/test/negatives.sh @@ -0,0 +1,95 @@ +#!/usr/bin/env bash +# Negative checks of discharge.sh's inputs: each corrupts one input of a frozen export and requires +# the run to fail with the expected message before any Lean runs (by mismatch, never a timeout). +# +# Verify/Discharge/test/negatives.sh EXPORT_DIR LOCK SOURCE_ROOT +# +# EXPORT_DIR is a format-2 export that passes LOCK (frozen/v2/.sha256) with SOURCE_ROOT. +set -euo pipefail +src=$(cd "$1" && pwd) +lock=$(cd "$(dirname "$2")" && pwd)/$(basename "$2") +root=$(cd "$3" && pwd) +here=$(cd "$(dirname "$0")/.." && pwd) +work=$(mktemp -d) +trap 'rm -rf "$work"' EXIT +pass=0 bad=0 + +# A copy of the export and of its sources, under a root of their own. +fresh() { + rm -rf "$work/x" "$work/root" + mkdir -p "$work/x" "$work/root" + (cd "$src" && tar cf - --exclude=./discharge --exclude='./discharge-*' .) | (cd "$work/x" && tar xf -) + mapfile -t paths < <(jq -r '.sources[].path' "$src/manifest.json") + for path in "${paths[@]}"; do + mkdir -p "$work/root/$(dirname "$path")" + cp "$root/$path" "$work/root/$path" + done +} + +check() { + if [[ $1 == lock ]]; then + DISCHARGE_LOCK="$lock" DISCHARGE_SOURCE_ROOT="$work/root" DISCHARGE_INPUTS_ONLY=1 "$here/discharge.sh" "$work/x" 2>&1 + else + DISCHARGE_SOURCE_ROOT="$work/root" DISCHARGE_INPUTS_ONLY=1 "$here/discharge.sh" "$work/x" 2>&1 + fi +} + +# expect NAME MESSAGE lock|nolock: the input checks fail with MESSAGE. +expect() { + local name=$1 msg=$2 out code + set +e + out=$(check "$3") + code=$? + set -e + if [[ $code -ne 0 ]] && grep -qF -- "$msg" <<<"$out" && ! grep -q '^inputs: ok' <<<"$out"; then + echo "ok: $name"; pass=$((pass + 1)) + else + echo "FAILED: $name (exit $code): $(tail -2 <<<"$out" | tr '\n' ' ')"; bad=$((bad + 1)) + fi +} + +fresh +set +e +out=$(check lock) +code=$? +set -e +if [[ $code -eq 0 ]] && grep -q '^inputs: ok' <<<"$out"; then + echo "ok: the untouched export passes"; pass=$((pass + 1)) +else + echo "FAILED: the untouched export: $out"; bad=$((bad + 1)) +fi + +fresh +s=$(jq -r '.sources[0].path' "$work/x/manifest.json") +echo '// edited' >>"$work/root/$s" +expect "edited source" "source $s is not the one exported" lock + +fresh +m=$(jq -r '[.units[] | .module // empty][0]' "$work/x/manifest.json") +sed -i 's/^set_option maxRecDepth 100000$/set_option maxRecDepth 100001/' "$work/x/$m" +expect "edited module" "are not the ones" lock + +fresh +jq '(.units[] | select(.module != null) | select([.obligations[] | select(.required)] | length > 0) | .obligations) |= (map(select(.required | not)) + (map(select(.required)) | .[1:]))' \ + "$work/x/manifest.json" >"$work/m" +mv "$work/m" "$work/x/manifest.json" +expect "deleted required obligation, no lock" "obligations, the manifest lists" nolock + +fresh +jq '(.units[[.units[] | .module != null] | index(true)].obligations) |= (. + [.[-1]])' \ + "$work/x/manifest.json" >"$work/m" +mv "$work/m" "$work/x/manifest.json" +expect "duplicated obligation" "listed twice" nolock + +fresh +jq --arg r "$root" '.sources[0].path = ($r + "/" + .sources[0].path)' "$work/x/manifest.json" >"$work/m" +mv "$work/m" "$work/x/manifest.json" +expect "absolute source path" "sources not named relative to the repository root" nolock + +fresh +jq '.version = 1' "$work/x/manifest.json" >"$work/m" +mv "$work/m" "$work/x/manifest.json" +expect "format version 1" "this checker reads 2" nolock + +echo "negatives: $pass passed, $bad failed" +[[ $bad -eq 0 ]] diff --git a/Verify/Discharge/test/sat/Sat.lean b/Verify/Discharge/test/sat/Sat.lean new file mode 100644 index 00000000..960ef397 --- /dev/null +++ b/Verify/Discharge/test/sat/Sat.lean @@ -0,0 +1,58 @@ +import Verify.Discharge.Sat +/-! +Checks of the SAT certificate library on a small proof, run with +`LEAN_PATH=/.lake/build/lib/lean lean Sat.lean` from this directory +after `lake build VerifyDischarge`. + +`b8.cnf` is Lean's bit-blasting of `(x &&& y) + (x ||| y) = x + y` over 8 bits, negated, and +`b8.lrat` CaDiCaL's LRAT proof that it is unsatisfiable. +-/ +open SolarVerify.Sat + +-- The whole proof in one kernel evaluation. +sat_load b8 "b8.cnf" "b8.lrat" +theorem b8_check : Cnf.Unsat b8.cnf := check_sound b8.cnf b8.proof (by decide +kernel) + +/-- info: 'b8_check' depends on axioms: [propext, Quot.sound] -/ +#guard_msgs in #print axioms b8_check + +-- One kernel-checked lemma per step. +namespace stepwise +sat_prove b8 "b8.cnf" "b8.lrat" +end stepwise + +/-- info: 'stepwise.b8.unsat' depends on axioms: [propext, Quot.sound] -/ +#guard_msgs in #print axioms stepwise.b8.unsat + +-- x1 and not x1: the empty clause follows from clauses 1 and 2. +example : check [[2], [3]] (.step ⟨3, [], [1, 2]⟩) = true := by decide +kernel +-- x1 and x2 are satisfiable: the same step does not check. +example : check [[2], [4]] (.step ⟨3, [], [1, 2]⟩) = false := by decide +kernel +-- A hint naming no clause fails. +example : check [[2], [3]] (.step ⟨3, [], [1, 7]⟩) = false := by decide +kernel +-- A proof that never adds the empty clause fails. +example : check [[2, 4], [3]] (.step ⟨3, [4], [1, 2]⟩) = false := by decide +kernel + +-- Mutations of the real proof's inputs. Each flips the first literal of one clause of b8.cnf; +-- CaDiCaL finds every one of these mutated formulas satisfiable, so the proof must not check. +def flipFirst : Cnf → Nat → Cnf + | [], _ => [] + | c :: cs, 0 => (match c with | [] => [] | l :: ls => Lit.neg l :: ls) :: cs + | c :: cs, n + 1 => c :: flipFirst cs n + +example : check (flipFirst b8.cnf 4) b8.proof = false := by decide +kernel +example : check (flipFirst b8.cnf 120) b8.proof = false := by decide +kernel +example : check (flipFirst b8.cnf 346) b8.proof = false := by decide +kernel +-- Dropping the last clause shifts no IDs but removes a clause the proof needs. +example : check b8.cnf.dropLast b8.proof = false := by decide +kernel + +-- vc_ground: a closed hypothesis that the kernel evaluates to false closes the goal. +example (h : ¬ ((511#256 &&& 255#256).toNat = 255)) : False := by vc_ground +example (h : (0xff#8 - (1#8 ||| 2#8 ||| 4#8)) &&& 0x05#8 ≠ 0#8) : False := by vc_ground +-- A closed hypothesis that holds, or one with a free variable, gives no contradiction. +/-- error: vc_ground: no closed hypothesis is false -/ +#guard_msgs in +example (h : (511#256 &&& 255#256).toNat = 255) : False := by vc_ground +/-- error: vc_ground: no closed hypothesis is false -/ +#guard_msgs in +example (x : BitVec 8) (h : x &&& 0xf8#8 ≠ 0#8) : False := by vc_ground diff --git a/Verify/Discharge/test/sat/b8.cnf b/Verify/Discharge/test/sat/b8.cnf new file mode 100644 index 00000000..175ab9a3 --- /dev/null +++ b/Verify/Discharge/test/sat/b8.cnf @@ -0,0 +1,348 @@ +p cnf 168 347 +8 -159 0 +-8 159 0 +16 -167 0 +-16 167 0 +-24 8 0 +-24 16 0 +24 -8 -16 0 +-32 -8 0 +-32 -16 0 +32 8 16 0 +-72 24 0 +-72 -32 0 +72 -24 32 0 +7 -158 0 +-7 158 0 +15 -166 0 +-15 166 0 +-23 7 0 +-23 15 0 +23 -7 -15 0 +-31 -7 0 +-31 -15 0 +31 7 15 0 +-65 23 0 +-65 -31 0 +65 -23 31 0 +6 -157 0 +-6 157 0 +14 -165 0 +-14 165 0 +-22 6 0 +-22 14 0 +22 -6 -14 0 +-30 -6 0 +-30 -14 0 +30 6 14 0 +-58 22 0 +-58 -30 0 +58 -22 30 0 +5 -156 0 +-5 156 0 +13 -164 0 +-13 164 0 +-21 5 0 +-21 13 0 +21 -5 -13 0 +-29 -5 0 +-29 -13 0 +29 5 13 0 +-51 21 0 +-51 -29 0 +51 -21 29 0 +4 -155 0 +-4 155 0 +12 -163 0 +-12 163 0 +-20 4 0 +-20 12 0 +20 -4 -12 0 +-28 -4 0 +-28 -12 0 +28 4 12 0 +-44 20 0 +-44 -28 0 +44 -20 28 0 +3 -154 0 +-3 154 0 +11 -162 0 +-11 162 0 +-19 3 0 +-19 11 0 +19 -3 -11 0 +-27 -3 0 +-27 -11 0 +27 3 11 0 +-37 19 0 +-37 -27 0 +37 -19 27 0 +2 -153 0 +-2 153 0 +10 -161 0 +-10 161 0 +-18 2 0 +-18 10 0 +18 -2 -10 0 +-26 -2 0 +-26 -10 0 +26 2 10 0 +-34 18 0 +-34 -26 0 +34 -18 26 0 +-19 -27 39 0 +-19 27 -39 0 +19 27 39 0 +19 -27 -39 0 +-40 34 0 +-40 39 0 +40 -34 -39 0 +-43 -37 0 +-43 -40 0 +43 37 40 0 +-20 -28 46 0 +-20 28 -46 0 +20 28 46 0 +20 -28 -46 0 +-47 -43 0 +-47 46 0 +47 43 -46 0 +-50 -44 0 +-50 -47 0 +50 44 47 0 +-21 -29 53 0 +-21 29 -53 0 +21 29 53 0 +21 -29 -53 0 +-54 -50 0 +-54 53 0 +54 50 -53 0 +-57 -51 0 +-57 -54 0 +57 51 54 0 +-22 -30 60 0 +-22 30 -60 0 +22 30 60 0 +22 -30 -60 0 +-61 -57 0 +-61 60 0 +61 57 -60 0 +-64 -58 0 +-64 -61 0 +64 58 61 0 +-23 -31 67 0 +-23 31 -67 0 +23 31 67 0 +23 -31 -67 0 +-68 -64 0 +-68 67 0 +68 64 -67 0 +-71 -65 0 +-71 -68 0 +71 65 68 0 +-24 -32 74 0 +-24 32 -74 0 +24 32 74 0 +24 -32 -74 0 +-75 -71 0 +-75 74 0 +75 71 -74 0 +-78 -72 0 +-78 -75 0 +78 72 75 0 +9 -160 0 +-9 160 0 +17 -168 0 +-17 168 0 +-25 9 0 +-25 17 0 +25 -9 -17 0 +-33 -9 0 +-33 -17 0 +33 9 17 0 +-25 -33 81 0 +-25 33 -81 0 +25 33 81 0 +25 -33 -81 0 +78 81 84 0 +78 -81 -84 0 +-78 -81 84 0 +-78 81 -84 0 +-3 11 87 0 +-3 -11 -87 0 +3 -11 87 0 +3 11 -87 0 +-88 18 0 +-88 87 0 +88 -18 -87 0 +-91 -19 0 +-91 -88 0 +91 19 88 0 +-4 12 92 0 +-4 -12 -92 0 +4 -12 92 0 +4 12 -92 0 +-93 -91 0 +-93 92 0 +93 91 -92 0 +-96 -20 0 +-96 -93 0 +96 20 93 0 +-5 13 97 0 +-5 -13 -97 0 +5 -13 97 0 +5 13 -97 0 +-98 -96 0 +-98 97 0 +98 96 -97 0 +-101 -21 0 +-101 -98 0 +101 21 98 0 +-6 14 102 0 +-6 -14 -102 0 +6 -14 102 0 +6 14 -102 0 +-103 -101 0 +-103 102 0 +103 101 -102 0 +-106 -22 0 +-106 -103 0 +106 22 103 0 +-7 15 107 0 +-7 -15 -107 0 +7 -15 107 0 +7 15 -107 0 +-108 -106 0 +-108 107 0 +108 106 -107 0 +-111 -23 0 +-111 -108 0 +111 23 108 0 +-8 16 112 0 +-8 -16 -112 0 +8 -16 112 0 +8 16 -112 0 +-113 -111 0 +-113 112 0 +113 111 -112 0 +-116 -24 0 +-116 -113 0 +116 24 113 0 +-9 17 117 0 +-9 -17 -117 0 +9 -17 117 0 +9 17 -117 0 +116 117 120 0 +116 -117 -120 0 +-116 -117 120 0 +-116 117 -120 0 +-84 -120 145 0 +-84 120 -145 0 +84 120 145 0 +84 -120 -145 0 +71 74 77 0 +71 -74 -77 0 +-71 -74 77 0 +-71 74 -77 0 +111 112 115 0 +111 -112 -115 0 +-111 -112 115 0 +-111 112 -115 0 +-77 -115 142 0 +-77 115 -142 0 +77 115 142 0 +77 -115 -142 0 +64 67 70 0 +64 -67 -70 0 +-64 -67 70 0 +-64 67 -70 0 +106 107 110 0 +106 -107 -110 0 +-106 -107 110 0 +-106 107 -110 0 +-70 -110 139 0 +-70 110 -139 0 +70 110 139 0 +70 -110 -139 0 +57 60 63 0 +57 -60 -63 0 +-57 -60 63 0 +-57 60 -63 0 +101 102 105 0 +101 -102 -105 0 +-101 -102 105 0 +-101 102 -105 0 +-63 -105 136 0 +-63 105 -136 0 +63 105 136 0 +63 -105 -136 0 +50 53 56 0 +50 -53 -56 0 +-50 -53 56 0 +-50 53 -56 0 +96 97 100 0 +96 -97 -100 0 +-96 -97 100 0 +-96 97 -100 0 +-56 -100 133 0 +-56 100 -133 0 +56 100 133 0 +56 -100 -133 0 +43 46 49 0 +43 -46 -49 0 +-43 -46 49 0 +-43 46 -49 0 +91 92 95 0 +91 -92 -95 0 +-91 -92 95 0 +-91 92 -95 0 +-49 -95 130 0 +-49 95 -130 0 +49 95 130 0 +49 -95 -130 0 +-18 -26 36 0 +-18 26 -36 0 +18 26 36 0 +18 -26 -36 0 +-2 10 86 0 +-2 -10 -86 0 +2 -10 86 0 +2 10 -86 0 +-36 -86 124 0 +-36 86 -124 0 +36 86 124 0 +36 -86 -124 0 +-34 39 42 0 +-34 -39 -42 0 +34 -39 42 0 +34 39 -42 0 +-18 87 90 0 +-18 -87 -90 0 +18 -87 90 0 +18 87 -90 0 +-42 -90 127 0 +-42 90 -127 0 +42 90 127 0 +42 -90 -127 0 +-146 124 0 +-146 127 0 +146 -124 -127 0 +-147 130 0 +-147 146 0 +147 -130 -146 0 +-148 133 0 +-148 147 0 +148 -133 -147 0 +-149 136 0 +-149 148 0 +149 -136 -148 0 +-150 139 0 +-150 149 0 +150 -139 -149 0 +-151 142 0 +-151 150 0 +151 -142 -150 0 +-152 145 0 +-152 151 0 +152 -145 -151 0 +-152 0 diff --git a/Verify/Discharge/test/sat/b8.lrat b/Verify/Discharge/test/sat/b8.lrat new file mode 100644 index 00000000..43eeaa7e --- /dev/null +++ b/Verify/Discharge/test/sat/b8.lrat @@ -0,0 +1,240 @@ +348 -2 146 39 87 -10 0 87 307 85 91 303 318 314 312 322 328 0 +349 -3 147 46 92 -10 -11 0 87 74 171 72 78 93 177 99 294 290 298 331 348 83 308 89 321 304 317 310 324 328 0 +350 -18 124 -10 0 87 83 303 307 312 0 +351 124 -10 0 87 350 85 304 308 310 0 +351 d 350 0 +352 18 127 -39 -87 0 89 320 316 322 0 +353 127 -39 -87 26 0 352 91 319 315 324 0 +354 -18 130 -39 -87 46 92 26 0 91 176 98 178 100 294 290 298 0 +355 -4 148 53 97 -10 -11 -12 0 351 87 74 61 181 59 65 103 187 109 282 278 286 334 349 70 172 76 94 353 328 331 354 89 174 96 179 101 297 293 300 0 +356 19 18 -146 -46 -92 20 148 53 97 0 89 96 174 63 76 179 101 184 296 106 292 189 111 298 285 281 331 288 334 0 +357 -19 -146 -46 -92 148 53 97 27 0 78 177 99 295 186 291 108 188 300 110 282 331 278 334 286 0 +358 -146 -46 -92 20 148 53 97 26 -11 0 74 357 72 94 356 172 91 176 98 178 100 295 186 291 108 188 300 110 282 331 278 334 286 0 +359 19 127 26 -11 0 74 72 94 172 353 0 +360 146 -10 -11 0 351 87 74 328 359 70 93 171 348 83 89 321 317 324 0 +361 97 148 -46 -92 -19 -146 27 -13 0 48 192 357 46 113 0 +362 148 -46 -92 -19 -146 27 -13 0 177 295 78 99 291 300 331 108 110 186 188 48 334 361 283 191 288 44 279 114 0 +362 d 361 0 +363 -97 136 -133 50 96 60 102 0 283 196 287 198 278 270 118 274 120 266 0 +364 -92 -19 149 60 102 -146 27 -12 -13 0 78 99 177 61 48 181 186 57 188 104 108 110 362 332 337 363 192 46 52 197 119 270 266 274 0 +365 -148 50 96 149 60 102 -13 0 48 332 337 363 192 46 52 197 119 270 266 274 0 +366 97 148 -4 -10 -11 -12 -13 0 48 192 355 46 113 0 +367 -19 149 60 102 -10 -11 -12 -13 0 360 74 61 48 70 364 182 59 65 103 187 109 349 365 334 366 283 191 288 44 279 114 0 +368 92 130 96 -87 -39 19 26 28 0 76 185 189 103 354 89 174 96 179 101 297 293 300 0 +369 50 100 96 -53 148 -87 -39 19 -146 26 -12 0 61 279 288 334 331 368 181 57 63 104 189 111 184 106 295 291 300 0 +370 96 -53 -97 148 -87 -39 19 -146 26 -12 0 61 283 369 109 110 65 104 189 108 184 100 179 98 174 91 0 +371 -97 148 -87 -39 19 -146 26 -12 -13 0 76 61 48 191 44 114 370 187 188 284 59 63 104 182 186 178 296 176 89 96 101 106 292 111 298 280 331 286 334 0 +372 148 19 -10 -11 -12 -13 0 72 172 74 94 360 87 61 48 371 192 366 46 57 182 113 104 358 0 +373 -21 136 60 102 29 0 52 197 119 270 266 274 0 +374 96 -148 149 60 102 -13 0 48 337 373 46 192 114 332 283 365 287 280 0 +374 d 365 0 +375 -6 150 67 107 -10 -11 -12 -13 -14 0 48 35 201 33 39 123 207 129 258 254 262 340 367 372 332 337 373 46 50 114 192 374 194 284 199 289 273 279 276 116 269 121 0 +376 -96 -53 21 -97 136 -133 -60 -102 0 50 194 284 199 289 272 279 274 116 268 121 0 +377 -53 21 -102 -97 136 -133 -60 0 376 283 196 287 198 280 271 118 276 120 267 0 +377 d 376 0 +378 -97 136 -133 -60 -102 -13 0 48 191 44 114 377 0 +379 -148 149 -60 -102 -13 0 48 332 337 378 192 46 52 197 119 271 267 276 0 +380 4 -19 148 -146 27 -12 -13 0 61 57 182 104 362 0 +381 148 -10 -11 -12 -13 0 360 74 61 48 372 70 380 181 59 366 65 103 187 191 109 349 283 44 334 114 288 279 0 +381 d 372 366 0 +382 -20 -53 -97 139 -60 -102 67 107 28 0 65 187 109 196 118 198 120 206 128 208 130 258 254 262 0 +383 -19 -92 -46 -53 -97 139 -60 -102 67 107 27 0 78 177 99 108 186 110 188 118 196 120 198 128 206 130 208 254 258 262 0 +384 96 -53 -97 139 -60 -102 67 107 -133 0 283 196 287 198 280 206 118 208 120 258 128 262 130 254 0 +385 -101 139 -136 -60 -102 22 67 107 0 37 204 272 209 277 261 267 264 126 257 131 0 +386 139 107 -136 -60 -102 22 67 0 385 271 206 275 208 268 258 128 262 130 254 0 +386 d 385 0 +387 -7 151 74 112 -10 -11 -12 -13 -14 -15 0 381 35 22 211 20 26 133 217 139 246 242 250 343 375 31 202 124 379 335 340 386 0 +388 -115 -142 139 -67 -107 23 74 112 0 24 249 253 219 245 214 141 259 136 264 255 0 +389 -142 139 112 -67 -107 23 74 0 388 246 251 218 242 216 140 260 138 262 256 0 +389 d 388 0 +390 115 142 -136 -60 58 -102 65 -107 74 112 0 246 252 218 245 216 141 208 136 206 131 272 126 277 267 0 +391 142 -136 -60 22 -102 -67 -107 23 74 112 0 37 24 390 249 250 219 242 214 140 209 138 204 130 271 128 275 268 0 +392 -102 -67 -107 23 151 74 112 -148 -13 -14 0 35 201 31 124 379 335 391 343 389 340 0 +393 -8 81 117 -10 -11 -12 -13 -14 -15 -16 0 347 381 332 48 35 22 9 221 7 13 143 227 149 234 166 238 346 387 18 212 134 392 202 33 39 123 207 129 259 216 255 138 218 264 140 246 242 250 343 340 337 374 373 194 46 50 114 199 192 273 284 276 289 269 279 121 116 0 +394 102 -142 -67 -107 -139 -74 -112 81 117 -148 -13 -14 0 347 332 48 35 202 33 39 123 207 129 216 138 218 140 226 148 228 150 234 166 238 346 343 340 337 374 373 194 46 50 114 199 192 273 284 276 289 269 279 121 116 0 +395 111 145 -142 -74 -112 81 117 0 247 226 251 228 244 234 148 238 150 166 0 +396 -142 -67 -107 -139 -74 -112 24 81 117 -148 -13 -14 0 347 11 35 394 201 31 124 379 340 343 346 395 224 248 229 253 237 243 240 146 169 151 0 +397 -111 142 -67 65 -107 -139 -74 -112 0 218 248 216 250 260 244 265 141 255 136 0 +398 -107 -139 -74 -112 24 81 117 -148 -13 -14 -15 0 22 211 18 24 134 396 397 219 247 214 252 259 243 263 140 256 138 0 +399 -139 -74 -112 24 81 117 -10 -11 -12 -13 -14 -15 0 347 381 35 22 398 212 20 26 133 217 139 247 243 252 395 346 343 375 340 31 202 379 124 0 +400 107 111 139 -10 -11 -12 -13 -14 31 0 338 381 35 215 219 133 375 31 202 124 379 386 335 0 +401 111 -142 139 -74 -112 -10 -11 -12 -13 -14 -15 0 22 247 251 244 400 211 18 24 134 219 141 214 136 259 255 264 0 +402 -142 139 -74 -112 -10 -11 -12 -13 -14 -15 0 22 401 217 218 248 20 134 253 212 243 216 140 260 138 262 256 0 +402 d 401 0 +403 -12 43 93 20 148 -13 0 59 182 186 177 178 76 101 96 97 89 95 84 176 381 170 75 0 +404 -13 50 149 98 21 -102 -60 0 46 379 192 196 187 188 63 111 106 107 105 403 62 180 186 177 178 76 101 96 97 89 90 315 95 176 318 325 359 170 75 0 +405 -91 43 0 177 178 76 101 96 97 89 90 315 95 176 318 325 359 170 75 0 +406 12 92 28 0 62 180 0 +407 -102 -61 103 0 127 126 267 206 197 198 272 50 277 121 335 116 117 115 404 49 190 196 187 188 63 111 106 107 105 405 186 406 59 182 0 +408 -14 102 22 0 33 202 0 +409 -61 -106 0 208 207 127 125 407 408 200 36 0 +410 -107 139 -111 0 218 217 216 207 260 37 262 409 131 256 134 21 22 213 0 +411 15 31 107 0 210 23 0 +412 -15 107 23 0 20 212 0 +413 -106 61 67 107 139 0 207 261 37 264 131 257 0 +414 13 53 101 0 45 199 114 195 47 193 0 +415 53 51 101 0 414 48 114 52 0 +416 -20 44 0 57 65 60 0 +417 -21 51 0 44 52 47 0 +418 11 40 91 0 71 179 174 175 83 173 86 73 91 94 98 0 +419 -46 -92 91 -97 47 -53 -60 -102 67 107 139 0 108 100 418 74 383 179 94 174 98 83 91 86 0 +420 -60 -103 61 67 107 139 0 205 204 128 119 120 415 118 109 110 416 417 199 194 195 189 184 185 419 104 60 61 183 0 +421 22 61 67 107 139 0 413 209 205 420 124 34 35 203 0 +422 61 139 67 107 0 413 258 262 254 129 421 31 39 34 0 +422 d 413 0 +423 139 107 67 0 422 130 409 254 258 262 0 +423 d 422 0 +424 139 -111 0 217 410 412 411 135 423 0 +424 d 410 0 +425 -22 -60 0 31 123 34 0 +426 -26 124 10 0 84 86 305 309 312 0 +427 -11 146 91 0 74 360 84 89 174 179 70 93 171 317 321 324 328 426 88 304 306 310 0 +428 146 91 0 427 71 418 179 96 97 174 175 90 84 353 351 328 0 +428 d 427 0 +429 11 -97 50 -53 -93 148 0 185 184 295 279 188 283 288 334 428 331 300 71 418 179 96 97 100 175 90 291 370 107 58 111 63 0 +430 19 26 27 -49 -97 -53 -93 148 0 184 428 188 185 179 94 174 175 370 91 58 183 98 60 100 104 291 0 +431 -20 -92 0 57 58 181 0 +432 51 -93 148 101 57 0 185 431 63 184 428 295 188 121 415 417 116 199 279 195 283 288 334 331 300 111 106 107 291 0 +433 43 -46 -100 53 -146 95 148 0 291 108 300 110 331 278 334 286 0 +434 -46 -100 97 53 -13 -92 91 148 0 431 428 295 433 100 418 74 358 362 86 356 83 0 +435 -93 148 101 57 0 184 185 188 431 432 50 51 44 45 113 191 282 434 104 60 61 183 0 +435 d 432 0 +436 91 147 92 -12 46 -13 148 0 294 428 331 298 290 99 100 418 74 381 78 84 179 174 0 +437 -11 146 19 0 74 360 72 94 84 172 352 328 426 88 304 306 310 0 +438 124 18 0 351 426 88 304 306 310 0 +439 27 127 18 11 19 0 75 94 170 352 0 +440 18 146 19 0 437 89 438 328 439 73 95 173 317 321 324 0 +441 147 92 148 -12 46 -13 0 436 177 178 297 405 100 293 300 331 440 83 84 176 86 348 91 98 0 +441 d 436 0 +442 96 46 97 -13 53 93 148 0 189 282 58 416 431 109 278 286 334 441 0 +443 146 0 428 177 178 405 440 100 83 84 176 86 348 91 98 0 +444 124 0 443 326 0 +445 127 0 443 327 0 +446 -91 130 92 46 0 297 405 300 293 0 +447 130 46 92 0 445 446 294 298 290 99 100 418 74 78 94 179 98 316 174 175 323 319 0 +447 d 446 0 +448 46 97 -13 53 93 148 0 443 107 442 187 285 63 104 111 60 61 281 183 288 334 331 447 0 +448 d 442 0 +449 12 92 -46 0 58 406 105 0 +450 92 -46 0 449 61 182 103 59 0 +450 d 449 0 +451 97 -13 148 53 93 0 443 448 450 186 431 296 405 63 189 106 292 111 285 298 281 331 288 334 0 +451 d 448 0 +452 53 93 148 101 0 414 415 50 44 191 451 0 +453 -13 148 101 57 0 435 452 48 113 50 199 121 194 195 116 189 283 279 58 431 288 450 334 441 0 +454 148 57 101 0 443 435 452 453 45 50 199 121 194 195 116 189 283 279 431 288 450 334 447 331 0 +454 d 435 0 +455 -61 149 0 126 127 409 267 425 209 204 205 271 276 337 454 0 +456 -103 61 67 107 -139 0 205 208 258 265 257 131 37 31 32 201 0 +457 -60 102 0 425 125 408 200 36 0 +458 -28 -92 0 60 61 183 0 +459 101 148 0 454 119 120 415 417 118 199 109 110 194 195 416 189 184 185 458 104 108 99 100 292 418 74 78 179 430 174 87 84 0 +459 d 454 0 +460 -43 91 0 445 99 100 418 74 78 94 179 98 316 174 175 323 319 0 +461 13 29 97 0 49 190 0 +462 -93 148 0 443 459 198 197 184 185 188 295 431 458 196 104 282 460 433 115 461 46 192 0 +463 97 29 21 0 461 46 192 0 +464 -46 -53 148 0 443 459 198 197 115 463 196 187 63 284 462 450 186 296 405 106 292 111 298 280 331 286 334 0 +465 -53 148 0 443 459 198 197 115 463 196 284 187 63 464 107 104 111 458 280 447 286 331 334 0 +465 d 464 0 +466 -100 133 148 0 459 197 465 114 47 48 193 462 285 286 189 278 416 109 0 +467 133 47 148 0 459 197 465 114 47 48 193 466 282 288 187 281 63 111 0 +468 130 46 0 447 431 458 104 0 +468 d 447 0 +469 46 148 0 443 107 467 334 331 468 0 +470 148 0 443 462 469 450 186 296 405 106 292 467 298 334 331 0 +471 133 0 470 332 0 +472 147 0 470 333 0 +473 130 0 472 329 0 +474 102 -57 -101 136 0 457 273 269 276 0 +475 -30 -102 0 34 35 203 0 +476 -57 -101 136 0 474 272 274 268 475 124 31 32 201 0 +476 d 474 0 +477 21 98 54 136 0 50 199 121 476 0 +478 -21 136 103 0 44 197 206 457 373 47 0 +479 101 136 103 0 471 478 50 206 199 415 457 194 195 283 363 287 280 0 +480 98 136 21 0 471 477 116 117 279 115 289 463 196 284 0 +480 d 477 0 +481 136 103 0 478 479 198 480 0 +481 d 478 0 +482 107 81 120 -139 -115 23 72 -74 0 347 470 24 412 411 135 137 141 146 244 151 250 169 240 346 343 340 455 456 337 481 0 +483 81 120 -111 72 -74 -112 0 470 347 424 217 24 248 218 482 216 207 208 260 409 37 481 265 131 337 136 257 340 141 397 343 146 346 151 240 169 0 +484 -96 50 0 187 188 63 111 106 107 405 450 186 0 +485 -17 25 117 0 232 158 0 +486 33 -81 117 0 163 485 230 161 0 +487 -81 117 0 486 159 165 156 0 +487 d 486 0 +488 117 -116 -111 72 -74 -112 0 237 483 487 0 +489 -33 -81 0 159 165 156 0 +490 -107 61 -150 -81 -120 -111 72 -74 -112 0 347 424 217 24 218 216 207 260 37 265 131 136 257 141 397 146 343 151 346 168 238 0 +491 -71 -150 -81 -120 -115 72 -74 0 347 146 244 151 250 168 343 238 346 0 +492 71 -111 -74 -112 0 424 217 24 248 243 141 253 137 135 397 411 412 0 +493 149 -111 0 470 424 218 217 455 337 481 208 216 412 456 411 135 0 +494 -25 -117 0 156 157 231 0 +495 -111 24 -74 -112 0 11 224 248 229 424 488 236 492 493 340 491 494 164 159 160 233 0 +496 -117 81 0 494 164 159 160 233 0 +497 -23 65 0 18 26 21 0 +498 -31 -107 0 21 22 213 0 +499 -71 -139 111 0 139 140 497 219 214 215 259 263 498 134 256 138 0 +500 -22 -102 0 31 32 201 0 +501 149 0 470 471 337 481 204 205 475 500 124 379 45 414 480 377 195 0 +502 136 0 501 335 0 +503 -23 -107 0 18 19 211 0 +504 -107 31 -103 81 111 -74 -112 0 502 501 347 205 475 500 124 204 271 275 268 128 130 208 496 247 259 503 134 138 255 140 264 243 340 252 343 395 346 0 +505 31 -103 81 111 -74 -112 0 501 347 496 247 504 215 219 26 133 139 423 243 340 252 343 395 346 0 +505 d 504 0 +506 -31 111 0 21 498 18 215 219 0 +507 -23 81 111 -74 -112 0 501 347 496 506 247 26 133 503 139 423 243 340 252 343 395 346 0 +508 81 111 -74 -112 0 501 347 506 247 496 505 507 219 134 214 215 209 259 425 122 39 129 138 255 140 264 243 340 252 343 395 346 0 +508 d 507 505 0 +509 71 -67 65 110 120 -81 115 -74 0 347 501 243 148 141 252 150 136 167 255 240 264 346 340 343 0 +510 -22 58 0 425 122 39 0 +511 -108 120 -81 31 115 -74 0 502 214 215 259 503 24 134 509 140 138 129 130 510 209 204 205 271 475 275 124 268 128 0 +512 111 -74 -112 0 501 347 247 226 228 506 508 487 235 511 219 26 133 503 139 423 243 148 340 252 150 343 167 346 240 0 +512 d 508 0 +513 -111 -74 -112 0 495 5 143 8 0 +513 d 495 0 +514 -74 -112 0 512 513 0 +514 d 512 513 0 +515 -24 -112 0 5 6 221 0 +516 -112 0 514 515 144 8 9 223 0 +517 -113 0 516 225 0 +518 107 31 23 0 411 412 0 +519 -81 145 -78 -116 0 487 168 236 238 0 +520 145 -78 -116 0 519 496 169 237 240 0 +520 d 519 0 +521 -111 151 74 0 516 501 217 218 249 424 24 340 343 252 245 141 136 137 255 135 265 518 260 216 0 +522 -142 -107 151 74 0 516 501 521 506 503 134 389 343 340 0 +523 -107 151 74 0 516 502 521 506 246 503 219 134 214 522 250 242 140 138 129 510 209 205 475 391 124 0 +523 d 522 0 +524 151 74 0 501 516 521 246 506 523 518 26 133 139 423 242 340 250 343 0 +524 d 521 0 +525 74 24 0 517 347 229 11 147 151 520 346 524 0 +526 8 32 0 516 222 10 0 +527 -8 24 0 516 7 220 0 +527 d 7 0 +528 -74 24 0 145 526 527 0 +528 d 145 0 +529 24 0 525 528 0 +530 8 0 529 5 0 +531 16 0 529 6 0 +532 -116 0 529 227 0 +533 159 0 530 2 0 +534 -32 0 530 8 0 +535 167 0 531 4 0 +536 -74 0 534 529 143 0 +537 72 0 534 529 13 0 +538 -75 0 536 147 0 +539 151 0 536 524 0 +540 -78 0 537 149 0 +541 142 0 539 341 0 +542 150 0 539 342 0 +543 -145 0 539 347 346 0 +544 139 0 542 338 0 +545 81 0 540 532 543 496 166 234 238 0 +546 117 0 545 487 0 +547 -33 0 545 489 0 +548 -84 0 545 540 167 0 +549 -120 0 546 532 235 0 +550 -25 0 546 494 0 +551 0 548 549 543 240 0 diff --git a/Verify/Final.lean b/Verify/Final.lean new file mode 100644 index 00000000..b29db3d6 --- /dev/null +++ b/Verify/Final.lean @@ -0,0 +1,631 @@ +import SolidCore.Refinement.ComposeSeq +import SolidCore.Refinement.Abi +import Verify.Basic +import EthLib.Cryptography.Hash.Sha256 + +/-! +# The final statement: a verified specification holds of deployed bytecode + +This module states, once and for every contract, what the end-to-end certificate of a +compilation says, and proves how the stages of the pipeline compose into it. + +## What is certified + +A contract is runtime bytecode `code`, bound by a `Manifest` to the source's SHA-256, the +compiler's commit, its options and the bytecode's own SHA-256 (`Bound`, checked by the kernel +for the bytecode: its hex and its SHA-256 by EthLib's FIPS 180-4 implementation). Its +specification (`ContractSpec`) is solar-verify's, read over an abstract state `St` that the +storage layout gives from the slot function of a storage (`abs`): the contract invariants +(`@custom:invariant`) and, for each public or external function of the specification, its +selector, its ABI parameters, its precondition (`@custom:requires`) and its postcondition +(`@custom:ensures`, which may read `old` state, the new state and the return data). + +`Certificate` holds two theorems about `code`: + +* (a) **refinement** (`Agree`): on every call of a specified function, on any clean argument + words, with any call value and from any storage, SolidCore's run of the checked contract and + EthLib's run of `code` both finish and show the same observable: success, return or revert + data, logs and the final storage. SolidCore and EthLib are deterministic, so this is both + directions at once: every bytecode result is a source result (`Agree.backward`), reverts + and exceptional halts included, and every source result is the bytecode's. +* (b) **the specification holds of the bytecode** (`Holds ethLib code spec`), in + solar-verify's semantics: from a storage whose abstract state meets the invariants and the + function's precondition, a call that returns meets the postcondition and the invariants, and + a non-payable function returns only without value (so no balance moves); a call that fails, + for any reason, leaves the storage as it was and logs nothing. + +## Composition + +`Stage A B p q scope` (SolarTV's, which every stage of the pipeline proves) only preserves the +results of runs of `p` that finish: when `p` finishes no call of the scope, every `q` is a +stage of it (`stage_of_never`). A stage chain therefore gives agreement only with the source's +termination (`agree_of_stage`), and a specification holds of the target only through +agreement (`Holds.of_agree`): partial correctness of a source that never finishes says nothing. +`certificate_of_stages` composes the source stage (SolidCore to lowered MIR: solidity-lean's +Generic stage), the backend (solar-tv: lowered MIR through scheduling and the EVM IR passes) and +the assembly stage (EVM IR to bytecode on EthLib) with the source's specification and +termination into (a) and (b). + +## Out of gas + +`Target.run` carries `gasLimit` gas. `Target.runWith gas` is the same run with any gas, and +`ethLibWith gas` its semantics. In solar-verify's semantics a failed call owes nothing but +rolling back, which `runWith` gives for every failure (`runWith_failure`), out of gas included. +So the specification holds at every gas (`Holds.allGas`) once every success at any gas is the +success at `gasLimit` (`GasStable`), and then every bytecode result at any gas is the source's +result or a failure that changes nothing (`RefinesAtAnyGas`, `refinesAtAnyGas`). `GasStable` is +a separate obligation; the stages prove the run at `gasLimit`. + +## Transactions, external calls and reentrancy + +`Holds.trace` lifts the invariants across transactions: on every sequence of calls of the +specification from a storage that meets the invariants, each call starting from the storage the +one before left (`Carries`), the invariants hold at the start of every call and each call whose +precondition holds there meets its specification. This is the whole story for code that runs in +one frame: `FrameLocal code` (decided by the kernel on the linear decoding of the bytecode, which +is every offset execution can reach) says the code has no instruction that runs other code or +reads state outside the frame (`CALL`, `CALLCODE`, `DELEGATECALL`, `STATICCALL`, `CREATE`, +`CREATE2`, `SELFDESTRUCT`, balances, other accounts' code, the block and transaction +environment, the caller and origin, `GAS`, transient storage). Then no other contract runs while +it does, so it cannot be reentered, and the fixed caller, callee and environment of `Target.run` +are not read. A contract that calls out or reads its environment fails the check, so no +certificate exists for it: the README's assumptions for external calls (the invariants hold +before each call, the storage is havocked across it) need a semantics with other frames, which +this one is not. + +## Not covered + +Deployment: `Target.run` starts from the runtime bytecode and the call's storage, so the +constructor's `@custom:ensures` and the invariants after deployment are the source's claims +about the first storage, not theorems about initcode. Calls outside the specified functions' +clean ABI encodings are outside the scope of (a) and (b) unless a contract's certificate widens +it. +-/ + +namespace SolidCore.Refinement.Final + +open SolidCore.Refinement + +/-! ## Agreement: refinement in both directions -/ + +/-- `q` agrees with `p` on `scope`: on every call of the scope both finish with the same +observable. -/ +def Agree (A B : Sem) (p : A.Prog) (q : B.Prog) (scope : Call → Prop) : Prop := + ∀ call, scope call → ∃ obs, A.run p call = some obs ∧ B.run q call = some obs + +/-- A stage whose source finishes every call of the scope is agreement. -/ +theorem agree_of_stage {A B : Sem} {p : A.Prog} {q : B.Prog} {scope : Call → Prop} + (stage : Stage A B p q scope) (fin : ∀ call, scope call → (A.run p call).isSome) : + Agree A B p q scope := by + intro call hc + obtain ⟨obs, h⟩ := Option.isSome_iff_exists.mp (fin call hc) + exact ⟨obs, h, stage call hc obs h⟩ + +/-- Agreement is a stage. -/ +theorem Agree.stage {A B : Sem} {p : A.Prog} {q : B.Prog} {scope : Call → Prop} + (h : Agree A B p q scope) : Stage A B p q scope := by + intro call hc obs hobs + obtain ⟨o, h1, h2⟩ := h call hc + rw [Option.some.inj (hobs.symm.trans h1)] + exact h2 + +/-- **Every result of the target is a result of the source.** -/ +theorem Agree.backward {A B : Sem} {p : A.Prog} {q : B.Prog} {scope : Call → Prop} + (h : Agree A B p q scope) {call : Call} (hc : scope call) {obs : Observable} + (hq : B.run q call = some obs) : A.run p call = some obs := by + obtain ⟨o, h1, h2⟩ := h call hc + rw [Option.some.inj (hq.symm.trans h2)] + exact h1 + +/-- The target finishes every call of the scope. -/ +theorem Agree.finishes {A B : Sem} {p : A.Prog} {q : B.Prog} {scope : Call → Prop} + (h : Agree A B p q scope) {call : Call} (hc : scope call) : (B.run q call).isSome := by + obtain ⟨o, -, h2⟩ := h call hc + simp [h2] + +theorem Agree.trans {A B C : Sem} {p : A.Prog} {q : B.Prog} {r : C.Prog} {scope : Call → Prop} + (first : Agree A B p q scope) (second : Agree B C q r scope) : Agree A C p r scope := by + intro call hc + obtain ⟨o, h1, h2⟩ := first call hc + exact ⟨o, h1, second.stage call hc o h2⟩ + +theorem Agree.mono {A B : Sem} {p : A.Prog} {q : B.Prog} {scope narrower : Call → Prop} + (h : Agree A B p q scope) (within : ∀ call, narrower call → scope call) : + Agree A B p q narrower := + fun call hc => h call (within call hc) + +/-- **What a stage alone does not say.** A source that finishes no call of the scope has a stage +to every target program, whatever it does. -/ +theorem stage_of_never {A B : Sem} {p : A.Prog} (q : B.Prog) {scope : Call → Prop} + (never : ∀ call, scope call → A.run p call = none) : Stage A B p q scope := by + intro call hc obs h + rw [never call hc] at h + cases h + +/-- Agreement rules that out on every call of its scope. -/ +theorem Agree.not_never {A B : Sem} {p : A.Prog} {q : B.Prog} {scope : Call → Prop} + (h : Agree A B p q scope) {call : Call} (hc : scope call) : A.run p call ≠ none := by + obtain ⟨o, h1, -⟩ := h call hc + simp [h1] + +/-- `Refines` is agreement between SolidCore and EthLib. -/ +theorem agree_iff_refines {fuel : Nat} {c : SolidCore.Solidity.TypeCheck.CheckedContract} + {code : ByteArray} {scope : Call → Prop} : + Agree (solidCore fuel) ethLib c code scope ↔ Refines fuel c code scope := Iff.rfl + +/-! ## Specifications -/ + +/-- A public or external function and its specification in solar-verify's terms, over the +abstract state `St`. -/ +structure FnSpec (St : Type) where + /-- The function's name, for reading only. -/ + name : String + /-- Its selector. -/ + sel : Nat + /-- Its ABI parameters. -/ + params : List Abi.Param + /-- `@custom:requires`: of the argument words and the state before the call. -/ + requires : List Nat → St → Prop + /-- `@custom:ensures`: of the argument words, the state before the call (`old`), the state + after it and the return data. -/ + ensures : List Nat → St → St → List Nat → Prop + /-- Whether the function is `payable`. -/ + payable : Bool + +/-- A contract's specification: its storage layout, as the abstract state of a storage read +slot by slot, its invariants and its functions' specifications. -/ +structure ContractSpec (St : Type) where + abs : (Nat → Nat) → St + invariant : St → Prop + fns : List (FnSpec St) + +namespace FnSpec + +variable {St : Type} + +/-- The argument words are a clean ABI encoding of the parameters. -/ +def Typed (f : FnSpec St) (args : List Nat) : Prop := + List.Forall₂ (fun (p : Abi.Param) (a : Nat) => p.clean a = true) f.params args + +/-- The call of `f` on `args` with `value` wei from the storage `storage`. -/ +def call (f : FnSpec St) (args : List Nat) (value : Nat) (storage : List (Nat × Nat)) : Call := + { calldata := Abi.calldata f.sel args, callvalue := value, storage } + +end FnSpec + +namespace ContractSpec + +variable {St : Type} + +/-- The abstract state of the storage a call starts from. -/ +def pre (spec : ContractSpec St) (call : Call) : St := spec.abs (slotValue call.storage) + +/-- The calls of the specification: a specified function, on clean argument words, with any +value below `2 ^ 256`, from any storage. -/ +def Calls (spec : ContractSpec St) (call : Call) : Prop := + ∃ f ∈ spec.fns, ∃ args, f.Typed args ∧ ∃ v, v < 2 ^ 256 ∧ ∃ σ, call = f.call args v σ + +/-- What solar-verify promises of a call of `f` on `args` that shows `obs`: a return meets the +postcondition and the invariants, and is without value unless `f` is payable; a failure, for any +reason, leaves the storage and logs nothing. -/ +def Outcome (spec : ContractSpec St) (f : FnSpec St) (args : List Nat) (call : Call) + (obs : Observable) : Prop := + (obs.success = true → + f.ensures args (spec.pre call) (spec.abs obs.storage) obs.output ∧ + spec.invariant (spec.abs obs.storage) ∧ (f.payable = false → call.callvalue = 0)) ∧ + (obs.success = false → obs.storage = slotValue call.storage ∧ obs.logs = []) + +end ContractSpec + +open ContractSpec + +/-- **The specification holds of `p`**, in solar-verify's semantics (partial correctness): every +result `p` shows for a call of a specified function from a storage that meets the invariants +and the precondition meets `Outcome`. -/ +def Holds {St : Type} (S : Sem) (p : S.Prog) (spec : ContractSpec St) : Prop := + ∀ f ∈ spec.fns, ∀ args, f.Typed args → ∀ v, v < 2 ^ 256 → ∀ σ, + spec.invariant (spec.abs (slotValue σ)) → f.requires args (spec.abs (slotValue σ)) → + ∀ obs, S.run p (f.call args v σ) = some obs → spec.Outcome f args (f.call args v σ) obs + +/-- A specification holds of every program that agrees with one it holds of. -/ +theorem Holds.of_agree {St : Type} {A B : Sem} {p : A.Prog} {q : B.Prog} {spec : ContractSpec St} + (h : Holds A p spec) (agree : Agree A B p q spec.Calls) : Holds B q spec := by + intro f hf args ht v hv σ hinv hreq obs hrun + exact h f hf args ht v hv σ hinv hreq obs + (agree.backward ⟨f, hf, args, ht, v, hv, σ, rfl⟩ hrun) + +/-! ## Composition -/ + +/-- **The composition.** A specification SolidCore's contract meets and finishes, and the stages +from SolidCore to lowered MIR, through the backend to EVM IR and from EVM IR to the bytecode on +EthLib, on the specification's calls, give (a) agreement of the bytecode with the source and (b) +the specification on the bytecode. -/ +theorem certificate_of_stages {St : Type} {fuel : Nat} {mirSem evmirSem : Sem} + {c : SolidCore.Solidity.TypeCheck.CheckedContract} {mir : mirSem.Prog} {evmir : evmirSem.Prog} + {code : ByteArray} {spec : ContractSpec St} + (source : Holds (solidCore fuel) c spec) + (fin : ∀ call, spec.Calls call → (Source.run fuel c call).isSome) + (lowering : Stage (solidCore fuel) mirSem c mir spec.Calls) + (backend : Stage mirSem evmirSem mir evmir spec.Calls) + (assembly : Stage evmirSem ethLib evmir code spec.Calls) : + Agree (solidCore fuel) ethLib c code spec.Calls ∧ Holds ethLib code spec := by + have agree := agree_of_stage ((lowering.trans backend).trans assembly) fin + exact ⟨agree, source.of_agree agree⟩ + +/-! ## What each half alone does not say -/ + +/-- **Partial correctness alone is weak.** Code that fails every call, rolling back, meets every +specification in solar-verify's semantics: this is why a certificate carries agreement too. -/ +theorem Holds.of_fails {St : Type} {S : Sem} {p : S.Prog} (spec : ContractSpec St) + (fails : ∀ call obs, S.run p call = some obs → + obs.success = false ∧ obs.storage = slotValue call.storage ∧ obs.logs = []) : + Holds S p spec := by + intro f _ args _ v _ σ _ _ obs hrun + obtain ⟨hs, hst, hl⟩ := fails _ obs hrun + exact ⟨fun h => absurd (hs.symm.trans h) (by decide), fun _ => ⟨hst, hl⟩⟩ + +/-! ## Any source semantics -/ + +/-- The composition for any source semantics \`S\`, such as SolidCore with as much fuel as a call +needs (\`solidCoreAny\`). -/ +theorem compose {St : Type} {S mirSem evmirSem : Sem} {p : S.Prog} {mir : mirSem.Prog} + {evmir : evmirSem.Prog} {code : ByteArray} {spec : ContractSpec St} + (source : Holds S p spec) (fin : ∀ call, spec.Calls call → (S.run p call).isSome) + (lowering : Stage S mirSem p mir spec.Calls) (backend : Stage mirSem evmirSem mir evmir spec.Calls) + (assembly : Stage evmirSem ethLib evmir code spec.Calls) : + Agree S ethLib p code spec.Calls ∧ Holds ethLib code spec := by + have agree := agree_of_stage ((lowering.trans backend).trans assembly) fin + exact ⟨agree, source.of_agree agree⟩ + +open Classical in +/-- SolidCore with as much fuel as the call needs: the run at the least fuel that finishes it. +A contract whose loops run as many times as an argument says finishes no such call at any fixed +fuel for every argument, while it finishes each call at some fuel. -/ +noncomputable def solidCoreAny : Sem where + Prog := SolidCore.Solidity.TypeCheck.CheckedContract + run c call := if h : ∃ n, (Source.run n c call).isSome then Source.run (Nat.find h) c call else none + +/-- More fuel does not change a finished run of SolidCore: the statement at \`Source.run\` of the +source interpreter's fuel monotonicity (\`SolidCore.Solidity.FuelMonotonicity\` proves it for the +interpreter's trees). -/ +def FuelStable (c : SolidCore.Solidity.TypeCheck.CheckedContract) : Prop := + ∀ n m call obs, n ≤ m → Source.run n c call = some obs → Source.run m c call = some obs + +/-- A run of SolidCore at a fixed fuel is the run with as much fuel as it needs. -/ +theorem solidCoreAny_run {c : SolidCore.Solidity.TypeCheck.CheckedContract} (stable : FuelStable c) + {fuel : Nat} {call : Call} {obs : Observable} (h : Source.run fuel c call = some obs) : + solidCoreAny.run c call = some obs := by + classical + have hex : ∃ n, (Source.run n c call).isSome := ⟨fuel, by simp [h]⟩ + show (if h : ∃ n, (Source.run n c call).isSome then Source.run (Nat.find h) c call else none) = _ + rw [dif_pos hex] + obtain ⟨o, ho⟩ := Option.isSome_iff_exists.mp (Nat.find_spec hex) + have hle : Nat.find hex ≤ fuel := Nat.find_min' hex (by simp [h]) + rw [ho] + have := stable _ _ _ _ hle ho + rw [h] at this + exact this.symm + +/-- The stage from SolidCore at a fixed fuel to SolidCore with as much fuel as a call needs. -/ +theorem stage_solidCoreAny {c : SolidCore.Solidity.TypeCheck.CheckedContract} (stable : FuelStable c) + (fuel : Nat) (scope : Call → Prop) : Stage (solidCore fuel) solidCoreAny c c scope := + fun _ _ _ h => solidCoreAny_run stable h + +/-! ## Loom: the source obligation from a triple -/ + +/-- **The source obligation from Loom.** A triple `{pre} c {post}` against SolidCore on the +specification's calls (`SolidCore.Verify.Triple`, which `triple_of_wp` gives from Loom's weakest +precondition of a model), whose precondition every specified call from a storage meeting the +invariants and the function's precondition meets, and whose postcondition gives `Outcome` there, +gives the specification on SolidCore. -/ +theorem Holds.of_triple {St : Type} {fuel : Nat} {c : SolidCore.Solidity.TypeCheck.CheckedContract} + {spec : ContractSpec St} {pre : Call → Prop} {post : Call → Observable → Prop} + (h : SolidCore.Verify.Triple fuel c spec.Calls pre post) + (hpre : ∀ f ∈ spec.fns, ∀ args, f.Typed args → ∀ v, v < 2 ^ 256 → ∀ σ, + spec.invariant (spec.abs (slotValue σ)) → f.requires args (spec.abs (slotValue σ)) → + pre (f.call args v σ)) + (hpost : ∀ f ∈ spec.fns, ∀ args, f.Typed args → ∀ v, v < 2 ^ 256 → ∀ σ, + spec.invariant (spec.abs (slotValue σ)) → f.requires args (spec.abs (slotValue σ)) → + ∀ obs, post (f.call args v σ) obs → spec.Outcome f args (f.call args v σ) obs) : + Holds (solidCore fuel) c spec := by + intro f hf args ht v hv σ hinv hreq obs hrun + have hc : spec.Calls (f.call args v σ) := ⟨f, hf, args, ht, v, hv, σ, rfl⟩ + exact hpost f hf args ht v hv σ hinv hreq obs + ((h _ hc (hpre f hf args ht v hv σ hinv hreq)).2 obs hrun) + +/-- A triple whose precondition holds on every call of the specification gives the source's +termination there, which agreement needs (`agree_of_stage`). -/ +theorem finishes_of_triple {St : Type} {fuel : Nat} + {c : SolidCore.Solidity.TypeCheck.CheckedContract} {spec : ContractSpec St} + {post : Call → Observable → Prop} + (h : SolidCore.Verify.Triple fuel c spec.Calls (fun _ => True) post) : + ∀ call, spec.Calls call → (Source.run fuel c call).isSome := + fun call hc => (h call hc trivial).1 + +/-! ## Transactions -/ + +/-- One call of a sequence: the function, its argument words and the call value. -/ +structure Step (St : Type) where + f : FnSpec St + args : List Nat + value : Nat + +/-- A sequence of calls run with `run` from `σ`, each from the storage `carry` gives after the one +before: the invariants hold at the start of every call reached, and every call whose precondition +holds there meets its specification on whatever it shows. -/ +def Trace {St : Type} (spec : ContractSpec St) (run : Call → Option Observable) (carry : Carry) : + List (Nat × Nat) → List (Step St) → Prop + | _, [] => True + | σ, s :: rest => spec.invariant (spec.abs (slotValue σ)) ∧ + (s.f.requires s.args (spec.abs (slotValue σ)) → + ∀ obs, run (s.f.call s.args s.value σ) = some obs → + spec.Outcome s.f s.args (s.f.call s.args s.value σ) obs ∧ + Trace spec run carry (carry (s.f.call s.args s.value σ) obs) rest) + +/-- **The invariants across transactions.** When the specification holds of `p` and the storage +carried to each call is exactly the storage the call before left, every sequence of specified +calls from a storage that meets the invariants is a `Trace`. -/ +theorem Holds.trace {St : Type} {S : Sem} {p : S.Prog} {spec : ContractSpec St} {carry : Carry} + (h : Holds S p spec) (exact : ∀ call obs, S.run p call = some obs → Carries carry call obs) : + ∀ σ (steps : List (Step St)), spec.invariant (spec.abs (slotValue σ)) → + (∀ s ∈ steps, s.f ∈ spec.fns ∧ s.f.Typed s.args ∧ s.value < 2 ^ 256) → + Trace spec (S.run p) carry σ steps := by + intro σ steps + induction steps generalizing σ with + | nil => intro _ _; trivial + | cons s rest ih => + intro hinv hsteps + obtain ⟨hf, ht, hv⟩ := hsteps s List.mem_cons_self + refine ⟨hinv, fun hreq obs hrun => ?_⟩ + have hout := h s.f hf s.args ht s.value hv σ hinv hreq obs hrun + refine ⟨hout, ih _ ?_ fun s' hs' => hsteps s' (List.mem_cons_of_mem _ hs')⟩ + rw [exact _ _ hrun] + cases hs : obs.success + · rw [(hout.2 hs).1] + exact hinv + · exact (hout.1 hs).2.1 + +/-! ## Gas -/ + +namespace Target + +open EthLib.Base EthLib.Execution EthLib.Execution.Evm + +/-- The message of `Target.message` with `gas` gas. -/ +def messageWith (gas : Nat) (code : ByteArray) (call : Call) : Message .fusaka := + { Refinement.Target.message code call with gas } + +/-- `Target.run` with the message `msg`. -/ +def runMsg (msg : Message .fusaka) (code : ByteArray) (call : Call) : Option Observable := + match processMessage (Meter := Nat) .fusaka msg (Refinement.Target.preState code call) + Substate.empty with + | .error _ => none + | .ok ⟨evm, _⟩ => + let success := evm.error.isNone + some + { success + output := evm.output.toList.map (·.toNat) + logs := + if success then + evm.substate.logs.toList.map fun log => + (log.topics.map fun topic => bytesToNat topic.toList, + log.data.toList.map (·.toNat)) + else [] + storage := fun slot => + if success then + (evm.state.getStorage (Refinement.Target.address selfAddress) + (Refinement.Target.storageKey slot)).toNat + else slotValue call.storage slot } + +/-- `Target.run` with `gas` gas. -/ +def runWith (gas : Nat) (code : ByteArray) (call : Call) : Option Observable := + runMsg (messageWith gas code call) code call + +theorem messageWith_gasLimit (code : ByteArray) (call : Call) : + messageWith gasLimit code call = Refinement.Target.message code call := rfl + +theorem runMsg_message (code : ByteArray) (call : Call) : + runMsg (Refinement.Target.message code call) code call = Refinement.Target.run code call := by + unfold runMsg Refinement.Target.run + split <;> rename_i h <;> rw [h] + +theorem runWith_gasLimit (code : ByteArray) (call : Call) : + runWith gasLimit code call = Refinement.Target.run code call := by + unfold runWith + rw [messageWith_gasLimit] + exact runMsg_message code call + +/-- A failed run, at any gas and for any reason, out of gas included, leaves the storage as it +was and logs nothing. -/ +theorem runWith_failure {gas : Nat} {code : ByteArray} {call : Call} {obs : Observable} + (h : runWith gas code call = some obs) (hf : obs.success = false) : + obs.storage = slotValue call.storage ∧ obs.logs = [] := by + unfold runWith runMsg at h + split at h + · cases h + · cases h + simp only at hf + simp [hf] + +end Target + +/-- EthLib on runtime bytecode with `gas` gas. -/ +def ethLibWith (gas : Nat) : Sem := { Prog := ByteArray, run := Target.runWith gas } + +/-- Every success at any gas, on a call of the scope, is the success at `gasLimit`. -/ +def GasStable (code : ByteArray) (scope : Call → Prop) : Prop := + ∀ gas call obs, scope call → Target.runWith gas code call = some obs → obs.success = true → + Refinement.Target.run code call = some obs + +/-- **The specification at every gas.** -/ +theorem Holds.allGas {St : Type} {code : ByteArray} {spec : ContractSpec St} + (h : Holds ethLib code spec) (stable : GasStable code spec.Calls) (gas : Nat) : + Holds (ethLibWith gas) code spec := by + intro f hf args ht v hv σ hinv hreq obs hrun + change Target.runWith gas code _ = some obs at hrun + cases hs : obs.success + · exact ⟨fun h' => absurd (hs.symm.trans h') (by decide), + fun _ => Target.runWith_failure hrun hs⟩ + · exact h f hf args ht v hv σ hinv hreq obs + (stable gas _ obs ⟨f, hf, args, ht, v, hv, σ, rfl⟩ hrun hs) + +/-- Every result of the bytecode, at any gas, on a call of the scope, is the source's result or a +failure that leaves the storage and logs nothing. -/ +def RefinesAtAnyGas (fuel : Nat) (c : SolidCore.Solidity.TypeCheck.CheckedContract) + (code : ByteArray) (scope : Call → Prop) : Prop := + ∀ gas call obs, scope call → Target.runWith gas code call = some obs → + Source.run fuel c call = some obs ∨ + (obs.success = false ∧ obs.storage = slotValue call.storage ∧ obs.logs = []) + +theorem refinesAtAnyGas {fuel : Nat} {c : SolidCore.Solidity.TypeCheck.CheckedContract} + {code : ByteArray} {scope : Call → Prop} (agree : Agree (solidCore fuel) ethLib c code scope) + (stable : GasStable code scope) : RefinesAtAnyGas fuel c code scope := by + intro gas call obs hc hrun + cases hs : obs.success + · exact Or.inr ⟨rfl, Target.runWith_failure hrun hs⟩ + · exact Or.inl (agree.backward hc (stable gas call obs hc hrun hs)) + +/-! ## The code runs in one frame -/ + +/-- The bytes of the immediate of an opcode: `PUSH1` to `PUSH32` take 1 to 32. -/ +def immediate (op : Nat) : Nat := if 0x60 ≤ op ∧ op ≤ 0x7f then op - 0x5f else 0 + +/-- The opcodes of the linear decoding of `bytes`, skipping push immediates: every offset +execution can reach, as a jump into an immediate is not a valid jump destination. -/ +def opsFrom : Nat → List Nat → List Nat + | 0, _ => [] + | _, [] => [] + | n + 1, op :: rest => op :: opsFrom n (rest.drop (immediate op)) + +/-- The opcodes of `code`. -/ +def opcodes (code : ByteArray) : List Nat := opsFrom code.size (code.data.toList.map (·.toNat)) + +/-- Opcodes that run other code or read state outside the frame: `ADDRESS`, `BALANCE`, +`ORIGIN`, `CALLER`, `GASPRICE`, `EXTCODESIZE`, `EXTCODECOPY`, `EXTCODEHASH`, the block's +`BLOCKHASH` to `BLOBBASEFEE` (`SELFBALANCE` among them), `GAS`, `TLOAD`, `TSTORE`, `CREATE`, +`CALL`, `CALLCODE`, `DELEGATECALL`, `CREATE2`, `STATICCALL` and `SELFDESTRUCT`. -/ +def outsideFrame : List Nat := + [0x30, 0x31, 0x32, 0x33, 0x3a, 0x3b, 0x3c, 0x3f, 0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, + 0x47, 0x48, 0x49, 0x4a, 0x5a, 0x5c, 0x5d, 0xf0, 0xf1, 0xf2, 0xf4, 0xf5, 0xfa, 0xff] + +/-- `code` runs in one frame and reads nothing of its environment but its call. -/ +def FrameLocal (code : ByteArray) : Bool := (opcodes code).all fun op => !outsideFrame.contains op + +/-! ## Binding -/ + +/-- What a certificate is bound to. -/ +structure Manifest where + contract : String + sourceSha256 : String + compilerCommit : String + options : List String + runtimeHex : String + runtimeSha256 : String + +/-- The lowercase hex of bytes. -/ +def hexOf (bytes : List Nat) : String := + String.join (bytes.map fun b => + let d := fun n : Nat => if n < 10 then Char.ofNat (48 + n) else Char.ofNat (87 + n) + String.ofList [d (b / 16 % 16), d (b % 16)]) + +/-- The bytes of a hex string, two digits a byte. -/ +def bytesOfHex (s : String) : ByteArray := + let digit (c : Char) : Nat := + if '0' ≤ c ∧ c ≤ '9' then c.toNat - 48 else if 'a' ≤ c ∧ c ≤ 'f' then c.toNat - 87 else 0 + let rec go : List Char → List UInt8 + | a :: b :: rest => (digit a * 16 + digit b).toUInt8 :: go rest + | _ => [] + ⟨(go s.toList).toArray⟩ + +/-- The bytecode is the manifest's: its hex and its SHA-256. -/ +def Bound (m : Manifest) (code : ByteArray) : Prop := + hexOf (code.data.toList.map (·.toNat)) = m.runtimeHex ∧ + hexOf ((EthLib.Cryptography.Hash.Sha256.hash code).data.toList.map (·.toNat)) = m.runtimeSha256 + +/-- **The certificate of a compilation**: the bytecode bound to its manifest, running in one +frame, (a) agreeing with SolidCore's checked contract on every call of the specification, and +(b) meeting the specification, which SolidCore's contract meets too. -/ +structure Certificate {St : Type} (spec : ContractSpec St) (m : Manifest) where + code : ByteArray + fuel : Nat + source : SolidCore.Solidity.TypeCheck.CheckedContract + bound : Bound m code + frameLocal : FrameLocal code = true + sourceHolds : Holds (solidCore fuel) source spec + refines : Agree (solidCore fuel) ethLib source code spec.Calls + holds : Holds ethLib code spec + +/-! ## Refinement with out of gas -/ + +/-- **Every result of `q` on the scope is a result of `p`, or a failure that leaves the storage +and logs nothing**: the direction of refinement that admits running out of gas, or any other +exceptional halt, where the source does not. -/ +def Within (A B : Sem) (p : A.Prog) (q : B.Prog) (scope : Call → Prop) : Prop := + ∀ call, scope call → ∀ obs, B.run q call = some obs → + A.run p call = some obs ∨ (obs.success = false ∧ obs.storage = slotValue call.storage ∧ obs.logs = []) + +theorem Agree.within {A B : Sem} {p : A.Prog} {q : B.Prog} {scope : Call → Prop} + (h : Agree A B p q scope) : Within A B p q scope := + fun _ hc _ hq => Or.inl (h.backward hc hq) + +/-- Agreement, then refinement with failures. -/ +theorem Agree.trans_within {A B C : Sem} {p : A.Prog} {q : B.Prog} {r : C.Prog} + {scope : Call → Prop} (first : Agree A B p q scope) (second : Within B C q r scope) : + Within A C p r scope := by + intro call hc obs hr + rcases second call hc obs hr with h | h + · exact Or.inl (first.backward hc h) + · exact Or.inr h + +/-- A specification holds of every program within one it holds of. -/ +theorem Holds.of_within {St : Type} {A B : Sem} {p : A.Prog} {q : B.Prog} {spec : ContractSpec St} + (h : Holds A p spec) (within : Within A B p q spec.Calls) : Holds B q spec := by + intro f hf args ht v hv σ hinv hreq obs hrun + rcases within _ ⟨f, hf, args, ht, v, hv, σ, rfl⟩ obs hrun with h' | ⟨hs, hst, hl⟩ + · exact h f hf args ht v hv σ hinv hreq obs h' + · exact ⟨fun h'' => absurd (hs.symm.trans h'') (by decide), fun _ => ⟨hst, hl⟩⟩ + +/-- With enough gas, the bytecode shows exactly what the source does: every call of the scope has +a gas from which on `runWith` gives the source's result. -/ +def EventuallyAgree (S : Sem) (p : S.Prog) (code : ByteArray) (scope : Call → Prop) : Prop := + ∀ call, scope call → ∃ obs G, S.run p call = some obs ∧ ∀ gas, G ≤ gas → + Target.runWith gas code call = some obs + +/-- **The composition at every gas.** A specification the source meets and finishes, the stages +from the source to lowered MIR and through the backend to EVM IR, and an assembly stage that at +every gas gives the EVM IR's result or a failure, give at every gas: every result of the bytecode +is the source's or a failure that changes nothing, and the specification holds of the bytecode. -/ +theorem compose_anyGas {St : Type} {S mirSem evmirSem : Sem} {p : S.Prog} {mir : mirSem.Prog} + {evmir : evmirSem.Prog} {code : ByteArray} {spec : ContractSpec St} + (source : Holds S p spec) (fin : ∀ call, spec.Calls call → (S.run p call).isSome) + (lowering : Stage S mirSem p mir spec.Calls) (backend : Stage mirSem evmirSem mir evmir spec.Calls) + (assembly : ∀ gas, Within evmirSem (ethLibWith gas) evmir code spec.Calls) (gas : Nat) : + Within S (ethLibWith gas) p code spec.Calls ∧ Holds (ethLibWith gas) code spec := by + have agree := agree_of_stage (lowering.trans backend) fin + have within := agree.trans_within (assembly gas) + exact ⟨within, source.of_within within⟩ + +/-- At `gasLimit`, a stage into EthLib is a stage into `ethLibWith gasLimit`. -/ +theorem stage_ethLibWith_gasLimit {A : Sem} {p : A.Prog} {code : ByteArray} {scope : Call → Prop} + (h : Stage A ethLib p code scope) : Stage A (ethLibWith gasLimit) p code scope := by + intro call hc obs hobs + show Target.runWith gasLimit code call = some obs + rw [Target.runWith_gasLimit] + exact h call hc obs hobs + +/-- **The certificate of a compilation at every gas**, for code whose gas use the call's arguments +bound, such as a loop over one: the bytecode bound to its manifest, running in one frame; at every +gas, every result is SolidCore's (with as much fuel as the call needs) or a failure that changes +nothing; with enough gas, it is SolidCore's; and the specification holds of SolidCore and of the +bytecode at every gas. -/ +structure CertificateAnyGas {St : Type} (spec : ContractSpec St) (m : Manifest) where + code : ByteArray + source : SolidCore.Solidity.TypeCheck.CheckedContract + bound : Bound m code + frameLocal : FrameLocal code = true + sourceHolds : Holds solidCoreAny source spec + within : ∀ gas, Within solidCoreAny (ethLibWith gas) source code spec.Calls + enough : EventuallyAgree solidCoreAny source code spec.Calls + holds : ∀ gas, Holds (ethLibWith gas) code spec + +end SolidCore.Refinement.Final diff --git a/Verify/Finite.lean b/Verify/Finite.lean new file mode 100644 index 00000000..61d2e3a9 --- /dev/null +++ b/Verify/Finite.lean @@ -0,0 +1,75 @@ +import Verify.Abi + +/-! +# Models of functions that touch neither storage nor logs, on finite scopes + +A function with only small parameters has finitely many clean calls, so the +model's agreement with SolidCore (`Implements`) can be checked call by call, as the +refinement corpus checks its finite scopes. `ofPure f` is the model of a function +that returns `f` of its argument words or reverts, leaving storage alone and +emitting no logs; `checkPure` evaluates SolidCore on every call of a list and +compares its result with `f`, and `implements_of_checkPure` turns a successful check +into `Implements` on the list. The check runs by `native_decide`. +-/ + +namespace SolidCore.Verify + +open SolidCore.Refinement SolidCore.Solidity SolidCore.Solidity.Source + +/-- The model of a function that touches neither storage nor logs. -/ +def ofPure (f : List Nat → Except Revert (List Nat)) (ws : List Nat) : SolM (List Nat) := + fun s => (f ws).map (·, s) + +@[simp] theorem wp_ofPure (f : List Nat → Except Revert (List Nat)) (ws : List Nat) + (post : List Nat → Assn) : + wp (ofPure f ws) post = fun herr s => match f ws with + | .ok out => post out herr s + | .error e => herr e := by + rw [wp_eq]; funext herr s + simp only [ofPure] + rcases f ws with e | out <;> rfl + +/-- Whether SolidCore's result `r` is `o`: the same success and output, and on success +empty storage and no logs. -/ +def resultMatches (r : TypeCheck.CoreAbiCallResult) : Except Revert (List Nat) → Bool + | .ok out => r.success && r.output == out && r.state.storage.isEmpty && + (r.state.logEntries selfAddress).isEmpty + | .error e => !r.success && r.output == e + +/-- Whether SolidCore with `fuel` runs every call of `calls`, from empty storage, as `f` +of its first `n` argument words says. -/ +def checkPure (fuel : Nat) (contract : TypeCheck.CheckedContract) (n : Nat) + (f : List Nat → Except Revert (List Nat)) (calls : List Call) : Bool := + calls.all fun call => call.storage.isEmpty && + match Source.result? fuel contract call with + | some r => resultMatches r (f (argWords n call)) + | none => false + +theorem implements_of_checkPure {fuel : Nat} {contract : TypeCheck.CheckedContract} {n : Nat} + {f : List Nat → Except Revert (List Nat)} {calls : List Call} + (h : checkPure fuel contract n f calls = true) : + Implements fuel contract (· ∈ calls) (argWords n) (ofPure f) := by + intro call hcall + have h1 := List.all_eq_true.mp h call hcall + simp only [Bool.and_eq_true, List.isEmpty_iff] at h1 + obtain ⟨hst, h2⟩ := h1 + have hinit : initStorage call = fun _ => 0 := by + funext k; simp [initStorage, hst, slotValue] + split at h2 + next r hr => + simp only [Source.run, hr, Option.map_some, hinit, ofPure] + unfold resultMatches at h2 + rcases hf : f (argWords n call) with e | out <;> rw [hf] at h2 + · simp only [Bool.and_eq_true, Bool.not_eq_true', beq_iff_eq] at h2 + obtain ⟨hs, ho⟩ := h2 + simp [Source.observe, observe, hs, ho, Except.map, hst, slotValue] + · simp only [Bool.and_eq_true, beq_iff_eq, List.isEmpty_iff] at h2 + obtain ⟨⟨⟨hs, ho⟩, hstore⟩, hlogs⟩ := h2 + simp only [Source.observe, observe, hs, ho, hlogs, Except.map, if_true, List.map_nil, + Option.some.injEq] + congr + funext slot + simp [State.loadSlot, StorageMap.lookup?, Wide.getElem?_of_isEmpty hstore] + next => simp at h2 + +end SolidCore.Verify diff --git a/Verify/Fuel.lean b/Verify/Fuel.lean new file mode 100644 index 00000000..8364c9d7 --- /dev/null +++ b/Verify/Fuel.lean @@ -0,0 +1,159 @@ +import Verify.Basic + +/-! +# Termination with as much fuel as a call needs + +A model with a loop needs interpreter fuel that grows with its arguments: each call finishes +at some fuel (`ImplementsSome`, `TripleSome`: for every call, some fuel). That is not one +fuel for every call, and no fuel-monotonicity lemma turns the one into the other: for every +call some fuel is not some fuel for every call. This module gives the two honest ways on. + +**Pointwise, without any monotonicity.** `runAny c call` is SolidCore's run at the least fuel +that finishes the call (`none` if none does): the same definition as the composition's +`Final.solidCoreAny`'s run, so `solidCoreAny.run c call = runAny c call` is `rfl`. +`ImplementsAny` and `TripleAny` state the model and the triple against it, and +`tripleAny_of_wp` is the generator's soundness for them. `TripleAny` is exactly the source's +termination and correctness that `Final.compose` takes with `S := solidCoreAny`. + +**Through fuel stability, as an explicit hypothesis.** `FuelStable c` (the composition's +`Final.FuelStable`, the same definition): more fuel does not change a finished run. It speaks only +of runs that finish (`some`), so an out-of-fuel run (`none`) may become any result, a revert +included, with more fuel, while a revert or a return at some fuel stays that result at every +higher fuel; a revert never stands for running out of fuel. Given it: + +* `runAny_of_run`, `implementsAny_of_some`, `tripleAny_of_some`: the some-fuel forms give the + least-fuel ones; +* `triple_of_within`: a **bounded** some-fuel triple (`TripleWithin B`: every call finishes at + some fuel at most `B`) gives the fixed-fuel `Triple B`. The bound is a hypothesis to prove + for the contract (for a loop over a word, from the word's bound), not an assumption. + +`FuelStable` is not proved here: it is `Source.run`'s fuel monotonicity, whose interpreter-level +parts are `SolidCore.Solidity.FuelMonotonicity` (trees with no out-of-fuel leaf on any branch). +-/ + +namespace SolidCore.Verify + +open SolidCore.Refinement + +open Classical in +/-- SolidCore's run of `c` on `call` at the least fuel that finishes it; `none` when no fuel +does. The same as `Final.solidCoreAny`'s run. -/ +noncomputable def runAny (c : SolidCore.Solidity.TypeCheck.CheckedContract) (call : Call) : + Option Observable := + if h : ∃ n, (Source.run n c call).isSome then Source.run (Nat.find h) c call else none + +/-- More fuel does not change a finished run of `c` (the same as `Final.FuelStable`). -/ +def FuelStable (c : SolidCore.Solidity.TypeCheck.CheckedContract) : Prop := + ∀ n m call obs, n ≤ m → Source.run n c call = some obs → Source.run m c call = some obs + +theorem runAny_isSome_iff {c : SolidCore.Solidity.TypeCheck.CheckedContract} {call : Call} : + (runAny c call).isSome ↔ ∃ n, (Source.run n c call).isSome := by + classical + unfold runAny + constructor + · intro h + by_contra hne + rw [dif_neg hne] at h + simp at h + · intro hex + rw [dif_pos hex] + exact Nat.find_spec hex + +/-- A result of `runAny` is SolidCore's result at some fuel. -/ +theorem runAny_spec {c : SolidCore.Solidity.TypeCheck.CheckedContract} {call : Call} + {obs : Observable} (h : runAny c call = some obs) : ∃ n, Source.run n c call = some obs := by + classical + unfold runAny at h + by_cases hex : ∃ n, (Source.run n c call).isSome + · rw [dif_pos hex] at h; exact ⟨_, h⟩ + · rw [dif_neg hex] at h; cases h + +/-- With fuel stability, a run that finishes at some fuel is `runAny`'s. -/ +theorem runAny_of_run {c : SolidCore.Solidity.TypeCheck.CheckedContract} (stable : FuelStable c) + {fuel : Nat} {call : Call} {obs : Observable} (h : Source.run fuel c call = some obs) : + runAny c call = some obs := by + classical + have hex : ∃ n, (Source.run n c call).isSome := ⟨fuel, by simp [h]⟩ + unfold runAny + rw [dif_pos hex] + obtain ⟨o, ho⟩ := Option.isSome_iff_exists.mp (Nat.find_spec hex) + have hle : Nat.find hex ≤ fuel := Nat.find_min' hex (by simp [h]) + have := stable _ _ _ _ hle ho + rw [h] at this + rw [ho, Option.some.inj this] + +/-- `model` implements `c` on `scope` with as much fuel as each call needs. -/ +def ImplementsAny (c : SolidCore.Solidity.TypeCheck.CheckedContract) (scope : Call → Prop) + (args : Call → List Nat) (model : List Nat → SolM (List Nat)) : Prop := + ∀ call, scope call → + runAny c call = some (observe (initStorage call) (model (args call) (initStorage call))) + +/-- Every call of the scope that meets `pre` finishes with as much fuel as it needs, with an +observable that meets `post`. -/ +def TripleAny (c : SolidCore.Solidity.TypeCheck.CheckedContract) (scope : Call → Prop) + (pre : Call → Prop) (post : Call → Observable → Prop) : Prop := + ∀ call, scope call → pre call → ∃ obs, runAny c call = some obs ∧ post call obs + +/-- The generator's soundness with as much fuel as each call needs; no fuel monotonicity. -/ +theorem tripleAny_of_wp {c : SolidCore.Solidity.TypeCheck.CheckedContract} + {scope : Call → Prop} {args : Call → List Nat} {model : List Nat → SolM (List Nat)} + {pre : Call → Prop} {post : Call → Observable → Prop} + (himpl : ImplementsAny c scope args model) + (hvc : ∀ call, scope call → pre call → vc model args post call) : + TripleAny c scope pre post := by + intro call hs hp + have h := hvc call hs hp + simp only [vc, wp_eq] at h + refine ⟨_, himpl call hs, ?_⟩ + revert h + rcases model (args call) (initStorage call) with e | ⟨out, s'⟩ <;> exact id + +/-- `TripleAny` gives every call of the scope that meets `pre` a finishing fuel. -/ +theorem TripleAny.some {c : SolidCore.Solidity.TypeCheck.CheckedContract} + {scope pre : Call → Prop} {post : Call → Observable → Prop} + (h : TripleAny c scope pre post) : TripleSome c scope pre post := by + intro call hs hp + obtain ⟨obs, hrun, hpost⟩ := h call hs hp + obtain ⟨n, hn⟩ := runAny_spec hrun + exact ⟨n, obs, hn, hpost⟩ + +theorem implementsAny_of_some {c : SolidCore.Solidity.TypeCheck.CheckedContract} + (stable : FuelStable c) {scope : Call → Prop} {args : Call → List Nat} + {model : List Nat → SolM (List Nat)} (h : ImplementsSome c scope args model) : + ImplementsAny c scope args model := by + intro call hs + obtain ⟨fuel, hrun⟩ := h call hs + exact runAny_of_run stable hrun + +theorem tripleAny_of_some {c : SolidCore.Solidity.TypeCheck.CheckedContract} + (stable : FuelStable c) {scope pre : Call → Prop} {post : Call → Observable → Prop} + (h : TripleSome c scope pre post) : TripleAny c scope pre post := by + intro call hs hp + obtain ⟨fuel, obs, hrun, hpost⟩ := h call hs hp + exact ⟨obs, runAny_of_run stable hrun, hpost⟩ + +/-- Every call of the scope that meets `pre` finishes at some fuel at most `B`, with an +observable that meets `post`. -/ +def TripleWithin (B : Nat) (c : SolidCore.Solidity.TypeCheck.CheckedContract) + (scope : Call → Prop) (pre : Call → Prop) (post : Call → Observable → Prop) : Prop := + ∀ call, scope call → pre call → ∃ fuel ≤ B, ∃ obs, Source.run fuel c call = some obs ∧ post call obs + +/-- **A bounded some-fuel triple is a fixed-fuel triple**, given fuel stability. -/ +theorem triple_of_within {B : Nat} {c : SolidCore.Solidity.TypeCheck.CheckedContract} + (stable : FuelStable c) {scope pre : Call → Prop} {post : Call → Observable → Prop} + (h : TripleWithin B c scope pre post) : Triple B c scope pre post := by + intro call hs hp + obtain ⟨fuel, hle, obs, hrun, hpost⟩ := h call hs hp + have hB := stable _ _ _ _ hle hrun + refine ⟨by simp [hB], fun o ho => ?_⟩ + rw [hB] at ho + cases ho + exact hpost + +/-- A fixed-fuel triple is a least-fuel one, given fuel stability. -/ +theorem Triple.any {fuel : Nat} {c : SolidCore.Solidity.TypeCheck.CheckedContract} + (stable : FuelStable c) {scope pre : Call → Prop} {post : Call → Observable → Prop} + (h : Triple fuel c scope pre post) : TripleAny c scope pre post := + tripleAny_of_some stable h.some + +end SolidCore.Verify diff --git a/Verify/FuelStable.lean b/Verify/FuelStable.lean new file mode 100644 index 00000000..81f55591 --- /dev/null +++ b/Verify/FuelStable.lean @@ -0,0 +1,181 @@ +import Verify.Fuel +import Verify.VC.Obligations + +/-! +# Fuel: one fuel for every call, from a run at one fuel + +`Verify.Fuel` keeps two notions apart: **for every call, some fuel** (`TripleSome`, `runAny`) and +**one fuel for every call** (`Triple fuel`). This module adds the uniform notion above a fuel: + +* `UniformFrom n c scope`: on every call of `scope`, every fuel `m ≥ n` gives SolidCore's run at + `n`, the same result, finished or not. It is a property of the scope's calls, not of every call + of `c`, so it is weaker than `FuelStable c` and says nothing below `n`. +* `Triple.mono_of_uniform`: a triple at `n` is a triple at every `m ≥ n`. + +and proves it for the generic source stage, where the fuel enters twice: in the constructor's run +(`Wide.DeployedAt fuel`) and in the erasure (`eraseFn _ fuel`, which runs a statement with the +fuel SolidCore runs it with). + +* `eraseStmt_mono`, `eraseFn_mono` (proved): an erasure that finishes at fuel `n` is the same + tree at every `m ≥ n`. The erasure counts fuel only to stop, so more fuel never changes a + finished erasure. +* `DeployStable n c s`: the constructor leaves the entries `s` at every fuel `m ≥ n`. A + hypothesis: the constructor runs through `constructWithContext?`, whose context installs a + self-dispatch hook built from the fuel, so the interpreter-level monotonicity of + `SolidCore.Solidity.FuelMonotonicity` (one tree, one context) does not reach it as stated. +* `uniformFrom_stage`: with `DeployStable`, every function the stage erases at fuel `n` runs + every call of its scope the same at every `m ≥ n`: as its tree. +* `triple_of_binds_from`: the generic theorem from an erased function to its obligations + (`triple_of_binds`), at every fuel from `n` on. + +None of this turns "for every call, some fuel" into one fuel: `UniformFrom` is proved from one +fuel `n` that already finishes every call of the scope (`source_run` at `n`). A loop whose +calls need fuel that grows with their arguments has no such `n`; for it the honest statements +stay `TripleSome` and `TripleAny` (`Verify.Fuel`), or `TripleWithin B` with a bound `B` +proved for the contract. +-/ + +namespace SolidCore.Verify + +open SolidCore.Refinement SolidCore.Refinement.Abi SolidCore.Refinement.Generic SolidCore.Solidity + +local notation "Br" => SolidCore.Refinement.Generic.Br +local notation "SymState" => SolidCore.Refinement.Generic.SymState + +/-! ## Uniform fuel on a scope -/ + +/-- On every call of `scope`, every fuel from `n` on gives the run at `n`. -/ +def UniformFrom (n : Nat) (c : TypeCheck.CheckedContract) (scope : Call → Prop) : Prop := + ∀ call, scope call → ∀ m, n ≤ m → Source.run m c call = Source.run n c call + +/-- A triple at `n` is a triple at every fuel from `n` on, on a scope where the runs are +uniform from `n`. -/ +theorem Triple.mono_of_uniform {n m : Nat} {c : TypeCheck.CheckedContract} + {scope pre : Call → Prop} {post : Call → Observable → Prop} + (hu : UniformFrom n c scope) (hnm : n ≤ m) (h : Triple n c scope pre post) : + Triple m c scope pre post := by + intro call hs hp + rw [hu call hs m hnm] + exact h call hs hp + +/-! ## The erasure is monotone in its fuel -/ + +namespace Erase + +theorem Br.bind_mono {k k' : SymState → Option Br} + (hk : ∀ S r, k S = some r → k' S = some r) : ∀ {b r : Br}, b.bind k = some r → b.bind k' = some r + | .leaf (.normal S), r, h => hk S r h + | .leaf (.returned _ _), _, h => h + | .leaf (.reverted _), _, h => h + | .ite c t e, r, h => by + simp only [Br.bind, Option.bind_eq_bind, Option.bind_eq_some_iff, Option.some.injEq] at h ⊢ + obtain ⟨t', ht, e', he, rfl⟩ := h + exact ⟨t', Br.bind_mono hk ht, e', Br.bind_mono hk he, rfl⟩ + +theorem eraseSeq_mono {f g : SolidCore.Solidity.Source.Stmt → SymState → Option Br} + (hfg : ∀ s S b, f s S = some b → g s S = some b) : + ∀ (ss : List SolidCore.Solidity.Source.Stmt) (S : SymState) (b : Br), eraseSeq f ss S = some b → eraseSeq g ss S = some b + | [], _, _, h => h + | s :: rest, S, b, h => by + simp only [eraseSeq, Option.bind_eq_bind, Option.bind_eq_some_iff] at h ⊢ + obtain ⟨b0, h0, hb⟩ := h + exact ⟨b0, hfg s S b0 h0, Br.bind_mono (fun S' r hr => eraseSeq_mono hfg rest S' r hr) hb⟩ + +/-- **An erasure that finishes at fuel `n` is the same at every `m ≥ n`.** -/ +theorem eraseStmt_mono (E : EraseEnv) : ∀ (n m : Nat), n ≤ m → + ∀ (s : SolidCore.Solidity.Source.Stmt) (S : SymState) (b : Br), eraseStmt E n s S = some b → eraseStmt E m s S = some b + | 0, _, _, _, _, _, h => by simp [eraseStmt] at h + | n + 1, 0, hnm, _, _, _, _ => absurd hnm (by omega) + | n + 1, m + 1, hnm, s, S, b, h => by + have ih : ∀ s S b, eraseStmt E n s S = some b → eraseStmt E m s S = some b := + eraseStmt_mono E n m (by omega) + unfold eraseStmt at h ⊢ + split at h + all_goals (try dsimp only) + all_goals (try exact h) + all_goals (try (simp at h; done)) + case h_2 => + simp only [Option.bind_eq_bind, Option.bind_eq_some_iff] at h ⊢ + obtain ⟨b0, h0, hb⟩ := h + exact ⟨b0, eraseSeq_mono ih _ _ _ h0, hb⟩ + case h_9 => + simp only [Option.bind_eq_bind, Option.bind_eq_some_iff] at h ⊢ + obtain ⟨⟨gs, v⟩, hp, h⟩ := h + simp only [Option.bind_eq_bind, Option.bind_eq_some_iff] at h + obtain ⟨bt, ht, be, he, hb⟩ := h + exact ⟨⟨gs, v⟩, hp, by + simp only [Option.bind_eq_bind, Option.bind_eq_some_iff] + exact ⟨bt, ih _ _ _ ht, be, ih _ _ _ he, hb⟩⟩ + case h_15 => + simp only [Option.bind_eq_bind, Option.bind_eq_some_iff] at h ⊢ + obtain ⟨fn, hfn, h⟩ := h + refine ⟨fn, hfn, ?_⟩ + split at h + · rename_i hc + rw [if_pos hc] + simp only [Option.bind_eq_bind, Option.bind_eq_some_iff] at h ⊢ + obtain ⟨⟨gs, vs⟩, hp, h⟩ := h + simp only [Option.bind_eq_bind, Option.bind_eq_some_iff] at h + obtain ⟨b0, h0, b1, h1, hb⟩ := h + exact ⟨⟨gs, vs⟩, hp, by + simp only [Option.bind_eq_bind, Option.bind_eq_some_iff] + exact ⟨b0, ih _ _ _ h0, b1, h1, hb⟩⟩ + · simp at h + case h_16 => + simp only [Option.bind_eq_bind, Option.bind_eq_some_iff] at h ⊢ + obtain ⟨b0, h0, hb⟩ := h + exact ⟨b0, ih _ _ _ h0, hb⟩ + +/-- **An erased function's tree at fuel `n` is its tree at every `m ≥ n`.** -/ +theorem eraseFn_mono {E : EraseEnv} {n m : Nat} (hnm : n ≤ m) {fn : Source.FunctionDef} {T : Tree} + (h : eraseFn E n fn = some T) : eraseFn E m fn = some T := by + unfold eraseFn at h ⊢ + split at h + · simp at h + split at h + case isFalse => simp at h + rename_i hret + rw [if_pos hret] + simp only [Option.bind_eq_bind, Option.bind_eq_some_iff] at h ⊢ + obtain ⟨b, hb, t, ht, hT⟩ := h + exact ⟨b, eraseStmt_mono _ n m hnm _ _ _ hb, t, ht, hT⟩ + +end Erase + +/-! ## The generic source stage, uniformly from one fuel -/ + +/-- The constructor of `c` leaves the entries `s` and no logs at every fuel from `n` on. -/ +def DeployStable (n : Nat) (c : TypeCheck.CheckedContract) (s : List (Nat × Nat)) : Prop := + ∀ m, n ≤ m → ∃ d, Wide.DeployedAt m c d s + +/-- **Every function the generic source stage erases at `n` runs uniformly from `n`** on the +stage's scope, given that the constructor's result is stable from `n`. -/ +theorem uniformFrom_stage {n : Nat} {c : TypeCheck.CheckedContract} {s : List (Nat × Nat)} + (hdep : DeployStable n c s) {fn : Fn} {f : Source.FunctionDef} (hsel : fn.sel < 2 ^ 32) + (hfind : c.core.findFunctionBySelector? fn.sel = some f) + (hlen : f.params.length = fn.params.length) {T : Tree} + (hT : eraseFn (envOf c.core) n f = some T) : + UniformFrom n c (VC.stageScope fn s) := by + rintro _ ⟨σ, hcov, fn', hfn', args, hl, hargs, rfl⟩ m hnm + simp only [List.mem_singleton] at hfn' + subst hfn' + obtain ⟨dm, hdm⟩ := hdep m hnm + obtain ⟨dn, hdn⟩ := hdep n (Nat.le_refl n) + rw [source_run hdm hcov hsel hfind (Erase.eraseFn_mono hnm hT) args (hl.trans hlen.symm) hargs, + source_run hdn hcov hsel hfind hT args (hl.trans hlen.symm) hargs] + +/-- **The generic theorem from an erased function to its obligations, at every fuel from `n` +on.** -/ +theorem triple_of_binds_from {n m : Nat} (hnm : n ≤ m) {c : TypeCheck.CheckedContract} + {s : List (Nat × Nat)} (hdep : DeployStable n c s) {fn : Fn} {f : Source.FunctionDef} + (hsel : fn.sel < 2 ^ 32) (hfind : c.core.findFunctionBySelector? fn.sel = some f) + (hlen : f.params.length = fn.params.length) {T : Tree} + (hT : eraseFn (envOf c.core) n f = some T) {obs : List (List VC.Tm × VC.Tm)} + {env : List Nat → Storage → VC.Env} {P : List Nat → Storage → Observable → Prop} + (hobs : VC.ObsValid obs) (hbind : VC.Binds fn T obs env P) : + Triple m c (VC.stageScope fn s) (fun _ => True) (VC.treePost fn P) := by + obtain ⟨d, hd⟩ := hdep n (Nat.le_refl n) + exact Triple.mono_of_uniform (uniformFrom_stage hdep hsel hfind hlen hT) hnm + (VC.triple_of_binds hd hsel hfind hlen hT hobs hbind) + +end SolidCore.Verify diff --git a/Verify/Infer/README.md b/Verify/Infer/README.md new file mode 100644 index 00000000..9bed15fa --- /dev/null +++ b/Verify/Infer/README.md @@ -0,0 +1,41 @@ +# Loop-invariant reconstruction: evidence + +What this directory shows: three loops' invariants, returned unedited by z3's Spacer engine, are +proved by the Lean kernel to satisfy initiation, preservation and use, with no axiom beyond +`propext`, `Classical.choice` and `Quot.sound`. Nothing here is built by `lake build`: the +default library roots are under `SolidCore`, and these files are checked on their own. + +## What is and is not proved + +- The Horn clauses (`chc/*.smt2`) and the Lean statements of each obligation were written by hand + from the Solidity source of each loop. They are **not** solar-verify's emitted verification + conditions, and nothing here proves that they match the EVM, the compiler or solar-verify's + encoding. Treat them as a reconstruction method, not as a certificate for any contract. +- The `*_u256` variants model Solidity 0.8 checked arithmetic as path guards: every arithmetic + result lies in `[0, 2^256)`, and a path that would overflow reverts and is dropped. They do not + prove that the loops never revert. The `*_int` variants use unbounded integers with the + `uint` inputs nonnegative; they say nothing about EVM words. +- Only the invariant is searched for by an untrusted solver; the proofs check it. + +Loops: `counter` (`for (i = 0; i < n; i++) count++` under `require(count + n <= limit)`, ensures +`count == old(count) + n && count <= limit`), `okwhile` (`i = 0; while (i < n) i++`, ensures +`i == n`), `drain` (`a = n; b = 0; while (a > 0) { a--; b++; }`, ensures `b == n`). + +## Files + +- `Reconstruct.lean`: Lean core only. Each `Inv_*` is generated by `smt2lean_inv.py` from the + Spacer model in `chc/*.spacer.out` (a 1:1 operator translation, `let` kept, no simplification), + and each obligation is closed by `simp only [Inv_*]; omega`. Generated by `gen_reconstruct.sh`. + Check with `lean Reconstruct.lean` on `leanprover/lean4:v4.35.0`: 18 theorems, 0.45 s, 480 MB + peak; output in `reconstruct-4.35.axioms.txt`. +- `SpacerPath.lean`: the same three loops through the `spacer` tactic of + [LeanHorn/Flex](https://github.com/LeanHorn/Flex) at `79bdae0d3d7069e5239174d52e1fc26fa035d249` + (it calls Spacer, imports the model, and certifies with `grind`). It needs Flex, so it does + not build here; output in `spacerpath-4.35.out` (6 theorems, 3.5 s, 1.95 GB). Flex builds on + 4.35.0 with the lakefile change in `flex-4.35-bump.diff` and no source change. Flex's + `flex_auto` (a trusted SMT axiom) was not used, and its own certificate check does not reject + `native_decide`, so every theorem was gated by `#print axioms`. Flex's `fix` path fails on + `counter` (recursion depth, then a heartbeat timeout), so it is not used. +- `chc/`: the Horn problems in SMT-LIB and Spacer's answers (z3 5.4.1). + +Checksums are in `SHA256SUMS`. diff --git a/Verify/Infer/Reconstruct.lean b/Verify/Infer/Reconstruct.lean new file mode 100644 index 00000000..93ad4f34 --- /dev/null +++ b/Verify/Infer/Reconstruct.lean @@ -0,0 +1,107 @@ +/-! Kernel-checked initiation / preservation / use for the three loops. + Each Inv_* below is generated by smt2lean_inv.py from the z3 Spacer model, unedited. + Only Lean core is imported (no Flex, no Mathlib). -/ +namespace FlexEval + +/-- Verbatim from chc/counter_int.spacer.out (z3 Spacer model for Inv). -/ +def Inv_counter_int (x_0 : Int) (x_1 : Int) (x_2 : Int) (x_3 : Int) (x_4 : Int) : Prop := + (let a_1 : Prop := (¬ ((x_0 + x_3 + ((-(1 : Int)) * x_4)) ≤ (-(1 : Int)))); (let a_2 : Prop := (¬ ((x_0 + x_1 + ((-(1 : Int)) * x_4)) ≤ (-(1 : Int)))); (let a_3 : Prop := (¬ ((x_0 + x_3 + ((-(1 : Int)) * x_4)) ≥ (1 : Int))); (let a_4 : Prop := (¬ ((x_1 + ((-(1 : Int)) * x_2) + ((-(1 : Int)) * x_3) + x_4) ≥ (1 : Int))); (a_1 ∧ a_2 ∧ a_3 ∧ a_4))))) + +/-- Verbatim from chc/counter_u256.spacer.out (z3 Spacer model for Inv). -/ +def Inv_counter_u256 (x_0 : Int) (x_1 : Int) (x_2 : Int) (x_3 : Int) (x_4 : Int) : Prop := + (let a_1 : Prop := (¬ ((x_0 + x_3 + ((-(1 : Int)) * x_4)) ≤ (-(1 : Int)))); (let a_2 : Prop := (¬ ((x_0 + x_1 + ((-(1 : Int)) * x_4)) ≤ (-(1 : Int)))); (let a_3 : Prop := (¬ ((x_0 + x_3 + ((-(1 : Int)) * x_4)) ≥ (1 : Int))); (let a_4 : Prop := (¬ ((x_1 + ((-(1 : Int)) * x_2) + ((-(1 : Int)) * x_3) + x_4) ≥ (1 : Int))); (a_1 ∧ a_2 ∧ a_3 ∧ a_4))))) + +/-- Verbatim from chc/okwhile_int.spacer.out (z3 Spacer model for Inv). -/ +def Inv_okwhile_int (x_0 : Int) (x_1 : Int) : Prop := + (¬ ((x_0 + ((-(1 : Int)) * x_1)) ≤ (-(1 : Int)))) + +/-- Verbatim from chc/okwhile_u256.spacer.out (z3 Spacer model for Inv). -/ +def Inv_okwhile_u256 (x_0 : Int) (x_1 : Int) : Prop := + (¬ ((x_0 + ((-(1 : Int)) * x_1)) ≤ (-(1 : Int)))) + +/-- Verbatim from chc/drain_int.spacer.out (z3 Spacer model for Inv). -/ +def Inv_drain_int (x_0 : Int) (x_1 : Int) (x_2 : Int) : Prop := + (let a_1 : Prop := (¬ ((x_0 + ((-(1 : Int)) * x_1) + ((-(1 : Int)) * x_2)) ≤ (-(1 : Int)))); (let a_2 : Prop := (¬ ((x_0 + ((-(1 : Int)) * x_2)) ≤ (-(1 : Int)))); (let a_3 : Prop := (¬ ((x_0 + ((-(1 : Int)) * x_1) + ((-(1 : Int)) * x_2)) ≥ (1 : Int))); (a_1 ∧ a_2 ∧ a_3)))) + +/-- Verbatim from chc/drain_u256.spacer.out (z3 Spacer model for Inv). -/ +def Inv_drain_u256 (x_0 : Int) (x_1 : Int) (x_2 : Int) : Prop := + (let a_1 : Prop := (¬ ((x_0 + ((-(1 : Int)) * x_1) + ((-(1 : Int)) * x_2)) ≤ (-(1 : Int)))); (let a_2 : Prop := (¬ ((x_0 + ((-(1 : Int)) * x_2)) ≤ (-(1 : Int)))); (let a_3 : Prop := (¬ ((x_0 + ((-(1 : Int)) * x_1) + ((-(1 : Int)) * x_2)) ≥ (1 : Int))); (a_1 ∧ a_2 ∧ a_3)))) + +/-! ## (a) Counter.bump — vars (c0 = old count, n, lim, i, c = count) -/ + +-- mathematical Int (uint inputs nonnegative, no overflow guards) +theorem counter_int_init : ∀ c0 n lim : Int, + 0 ≤ c0 → 0 ≤ n → 0 ≤ lim → c0 ≤ lim → c0 + n ≤ lim → Inv_counter_int c0 n lim 0 c0 := by + intros; simp only [Inv_counter_int]; omega +theorem counter_int_pres : ∀ c0 n lim i c : Int, + Inv_counter_int c0 n lim i c → i < n → Inv_counter_int c0 n lim (i + 1) (c + 1) := by + intros; simp only [Inv_counter_int] at *; omega +theorem counter_int_use : ∀ c0 n lim i c : Int, + Inv_counter_int c0 n lim i c → ¬ (i < n) → c = c0 + n ∧ c ≤ lim := by + intros; simp only [Inv_counter_int] at *; omega + +-- uint256 with Solidity 0.8 checked arithmetic: every op result must lie in [0, 2^256) +theorem counter_u256_init : ∀ c0 n lim : Int, + 0 ≤ c0 → c0 < 115792089237316195423570985008687907853269984665640564039457584007913129639936 → 0 ≤ n → n < 115792089237316195423570985008687907853269984665640564039457584007913129639936 → 0 ≤ lim → lim < 115792089237316195423570985008687907853269984665640564039457584007913129639936 → c0 ≤ lim → + 0 ≤ c0 + n → c0 + n < 115792089237316195423570985008687907853269984665640564039457584007913129639936 → c0 + n ≤ lim → Inv_counter_u256 c0 n lim 0 c0 := by + intros; simp only [Inv_counter_u256]; omega +theorem counter_u256_pres : ∀ c0 n lim i c : Int, + Inv_counter_u256 c0 n lim i c → i < n → + 0 ≤ c + 1 → c + 1 < 115792089237316195423570985008687907853269984665640564039457584007913129639936 → 0 ≤ i + 1 → i + 1 < 115792089237316195423570985008687907853269984665640564039457584007913129639936 → + Inv_counter_u256 c0 n lim (i + 1) (c + 1) := by + intros; simp only [Inv_counter_u256] at *; omega +theorem counter_u256_use : ∀ c0 n lim i c : Int, + Inv_counter_u256 c0 n lim i c → ¬ (i < n) → c = c0 + n ∧ c ≤ lim := by + intros; simp only [Inv_counter_u256] at *; omega + +/-! ## (b) ok_while — vars (n, i) -/ +theorem okwhile_int_init : ∀ n : Int, 0 ≤ n → Inv_okwhile_int n 0 := by + intros; simp only [Inv_okwhile_int]; omega +theorem okwhile_int_pres : ∀ n i : Int, Inv_okwhile_int n i → i < n → Inv_okwhile_int n (i + 1) := by + intros; simp only [Inv_okwhile_int] at *; omega +theorem okwhile_int_use : ∀ n i : Int, Inv_okwhile_int n i → ¬ (i < n) → i = n := by + intros; simp only [Inv_okwhile_int] at *; omega + +theorem okwhile_u256_init : ∀ n : Int, 0 ≤ n → n < 115792089237316195423570985008687907853269984665640564039457584007913129639936 → Inv_okwhile_u256 n 0 := by + intros; simp only [Inv_okwhile_u256]; omega +theorem okwhile_u256_pres : ∀ n i : Int, Inv_okwhile_u256 n i → i < n → + 0 ≤ i + 1 → i + 1 < 115792089237316195423570985008687907853269984665640564039457584007913129639936 → Inv_okwhile_u256 n (i + 1) := by + intros; simp only [Inv_okwhile_u256] at *; omega +theorem okwhile_u256_use : ∀ n i : Int, Inv_okwhile_u256 n i → ¬ (i < n) → i = n := by + intros; simp only [Inv_okwhile_u256] at *; omega + +/-! ## (c) drain — vars (n, a, b) -/ +theorem drain_int_init : ∀ n : Int, 0 ≤ n → Inv_drain_int n n 0 := by + intros; simp only [Inv_drain_int]; omega +theorem drain_int_pres : ∀ n a b : Int, Inv_drain_int n a b → a > 0 → Inv_drain_int n (a - 1) (b + 1) := by + intros; simp only [Inv_drain_int] at *; omega +theorem drain_int_use : ∀ n a b : Int, Inv_drain_int n a b → ¬ (a > 0) → b = n := by + intros; simp only [Inv_drain_int] at *; omega + +theorem drain_u256_init : ∀ n : Int, 0 ≤ n → n < 115792089237316195423570985008687907853269984665640564039457584007913129639936 → Inv_drain_u256 n n 0 := by + intros; simp only [Inv_drain_u256]; omega +theorem drain_u256_pres : ∀ n a b : Int, Inv_drain_u256 n a b → a > 0 → + 0 ≤ a - 1 → a - 1 < 115792089237316195423570985008687907853269984665640564039457584007913129639936 → 0 ≤ b + 1 → b + 1 < 115792089237316195423570985008687907853269984665640564039457584007913129639936 → Inv_drain_u256 n (a - 1) (b + 1) := by + intros; simp only [Inv_drain_u256] at *; omega +theorem drain_u256_use : ∀ n a b : Int, Inv_drain_u256 n a b → ¬ (a > 0) → b = n := by + intros; simp only [Inv_drain_u256] at *; omega + +end FlexEval +#print axioms FlexEval.counter_int_init +#print axioms FlexEval.counter_int_pres +#print axioms FlexEval.counter_int_use +#print axioms FlexEval.counter_u256_init +#print axioms FlexEval.counter_u256_pres +#print axioms FlexEval.counter_u256_use +#print axioms FlexEval.okwhile_int_init +#print axioms FlexEval.okwhile_int_pres +#print axioms FlexEval.okwhile_int_use +#print axioms FlexEval.okwhile_u256_init +#print axioms FlexEval.okwhile_u256_pres +#print axioms FlexEval.okwhile_u256_use +#print axioms FlexEval.drain_int_init +#print axioms FlexEval.drain_int_pres +#print axioms FlexEval.drain_int_use +#print axioms FlexEval.drain_u256_init +#print axioms FlexEval.drain_u256_pres +#print axioms FlexEval.drain_u256_use diff --git a/Verify/Infer/SHA256SUMS b/Verify/Infer/SHA256SUMS new file mode 100644 index 00000000..d113db79 --- /dev/null +++ b/Verify/Infer/SHA256SUMS @@ -0,0 +1,19 @@ +673aca7661560d45057a06403d02a3a16feca2b1f637dfcee3372ec514e0e1fd Reconstruct.lean +efca9dbbff32afbb2573d138cb1e0e3a38ec56e456172a191d604ebc731b5c90 SpacerPath.lean +157f485074857d8e11eca42524f1116a2b795cc1404e90b845f989246971ae31 smt2lean_inv.py +6a4bb9a858e3e460bcfc250a2972c7b39cad4fbdc9ac845a7eba86b954416583 gen_reconstruct.sh +293cfc981e4fbd1b05d625905bdf6d92b7358bf9f0bc7dbe58e96af84f2c60ff flex-4.35-bump.diff +08369f395413723dccd13dfe9ceb297229dd514f5eac12dc501b5467e33aff3a reconstruct-4.35.axioms.txt +9141801fdacc2936d9133ffc03f3dd6dc84614a4d9ae6dcd643900a6f58794df spacerpath-4.35.out +cc3ee632f13e149b021c78b773c52a9863018b22ec6c13731500ea25f227e396 chc/counter_int.smt2 +4d40ed36d01ce06f15ffa4beabb178d857919ce05cb835121c0e69eded24a9c4 chc/counter_int.spacer.out +7040ff503425ed654fc6be72d31722d752b1918f0aaea19dd4a3c5f7e6985371 chc/counter_u256.smt2 +4d40ed36d01ce06f15ffa4beabb178d857919ce05cb835121c0e69eded24a9c4 chc/counter_u256.spacer.out +a9ca18a4324f01aa5a9db43137178ddc756ef43a2f3c8e81b877c66229496360 chc/drain_int.smt2 +c01c2caa8918b8778822d969b8635241f08b89073c0ab7b866236cb9aa496fce chc/drain_int.spacer.out +0af97cde8a836def4b7789e30bda1cd52a9b424dbae81b0d0479ca7686c18478 chc/drain_u256.smt2 +c01c2caa8918b8778822d969b8635241f08b89073c0ab7b866236cb9aa496fce chc/drain_u256.spacer.out +6e1eb36aaa4cc820b6fdf8c846cf5ef5389cd121cab826cf08086ba1fb4d8c3a chc/okwhile_int.smt2 +a294c8fda0224319cae15af3ddb21f63d69933d769fae83390c0976e7cb6384b chc/okwhile_int.spacer.out +21c65b3c859069bdd10f084da85aefdcc64753dc4f88909fd3fa3637fe1d7ceb chc/okwhile_u256.smt2 +a294c8fda0224319cae15af3ddb21f63d69933d769fae83390c0976e7cb6384b chc/okwhile_u256.spacer.out diff --git a/Verify/Infer/SpacerPath.lean b/Verify/Infer/SpacerPath.lean new file mode 100644 index 00000000..fbcd4695 --- /dev/null +++ b/Verify/Infer/SpacerPath.lean @@ -0,0 +1,64 @@ +import Flex.Tactic.Tactics.Spacer +/-! Flex's spacer path: export CHC to z3 Spacer, import its model, instantiate the invariant, + certify predicate heads (init/step) with grind; the remaining query VC (use) is closed by grind. + No invariant is written by hand. -/ +namespace FlexEval.SpacerPath + +theorem counter_int : + ∃ inv : Int → Int → Int → Int → Int → Prop, + (∀ c0 n lim, 0 ≤ c0 → 0 ≤ n → 0 ≤ lim → c0 ≤ lim → c0 + n ≤ lim → inv c0 n lim 0 c0) ∧ + (∀ c0 n lim i c, inv c0 n lim i c → i < n → inv c0 n lim (i + 1) (c + 1)) ∧ + (∀ c0 n lim i c, inv c0 n lim i c → ¬ (i < n) → c = c0 + n ∧ c ≤ lim) := by + spacer + grind + +theorem counter_u256 : + ∃ inv : Int → Int → Int → Int → Int → Prop, + (∀ c0 n lim, 0 ≤ c0 → c0 < 115792089237316195423570985008687907853269984665640564039457584007913129639936 → 0 ≤ n → n < 115792089237316195423570985008687907853269984665640564039457584007913129639936 → 0 ≤ lim → lim < 115792089237316195423570985008687907853269984665640564039457584007913129639936 → c0 ≤ lim → + 0 ≤ c0 + n → c0 + n < 115792089237316195423570985008687907853269984665640564039457584007913129639936 → c0 + n ≤ lim → inv c0 n lim 0 c0) ∧ + (∀ c0 n lim i c, inv c0 n lim i c → i < n → + 0 ≤ c + 1 → c + 1 < 115792089237316195423570985008687907853269984665640564039457584007913129639936 → 0 ≤ i + 1 → i + 1 < 115792089237316195423570985008687907853269984665640564039457584007913129639936 → inv c0 n lim (i + 1) (c + 1)) ∧ + (∀ c0 n lim i c, inv c0 n lim i c → ¬ (i < n) → c = c0 + n ∧ c ≤ lim) := by + spacer + grind + +theorem okwhile_int : + ∃ inv : Int → Int → Prop, + (∀ n, 0 ≤ n → inv n 0) ∧ + (∀ n i, inv n i → i < n → inv n (i + 1)) ∧ + (∀ n i, inv n i → ¬ (i < n) → i = n) := by + spacer + grind + +theorem okwhile_u256 : + ∃ inv : Int → Int → Prop, + (∀ n, 0 ≤ n → n < 115792089237316195423570985008687907853269984665640564039457584007913129639936 → inv n 0) ∧ + (∀ n i, inv n i → i < n → 0 ≤ i + 1 → i + 1 < 115792089237316195423570985008687907853269984665640564039457584007913129639936 → inv n (i + 1)) ∧ + (∀ n i, inv n i → ¬ (i < n) → i = n) := by + spacer + grind + +theorem drain_int : + ∃ inv : Int → Int → Int → Prop, + (∀ n, 0 ≤ n → inv n n 0) ∧ + (∀ n a b, inv n a b → a > 0 → inv n (a - 1) (b + 1)) ∧ + (∀ n a b, inv n a b → ¬ (a > 0) → b = n) := by + spacer + grind + +theorem drain_u256 : + ∃ inv : Int → Int → Int → Prop, + (∀ n, 0 ≤ n → n < 115792089237316195423570985008687907853269984665640564039457584007913129639936 → inv n n 0) ∧ + (∀ n a b, inv n a b → a > 0 → 0 ≤ a - 1 → a - 1 < 115792089237316195423570985008687907853269984665640564039457584007913129639936 → 0 ≤ b + 1 → b + 1 < 115792089237316195423570985008687907853269984665640564039457584007913129639936 → + inv n (a - 1) (b + 1)) ∧ + (∀ n a b, inv n a b → ¬ (a > 0) → b = n) := by + spacer + grind + +end FlexEval.SpacerPath +#print axioms FlexEval.SpacerPath.counter_int +#print axioms FlexEval.SpacerPath.counter_u256 +#print axioms FlexEval.SpacerPath.okwhile_int +#print axioms FlexEval.SpacerPath.okwhile_u256 +#print axioms FlexEval.SpacerPath.drain_int +#print axioms FlexEval.SpacerPath.drain_u256 diff --git a/Verify/Infer/chc/counter_int.smt2 b/Verify/Infer/chc/counter_int.smt2 new file mode 100644 index 00000000..38b66168 --- /dev/null +++ b/Verify/Infer/chc/counter_int.smt2 @@ -0,0 +1,21 @@ +; Counter.bump CHC, mathematical Int (uint params >= 0, no overflow guards) semantics +; vars: c0 = old(count), n, lim = limit, i, c = count +(set-logic HORN) +(declare-fun Inv (Int Int Int Int Int) Bool) +; init: entry state satisfies param ranges, contract invariant c0 <= lim, require(count + n <= limit) (checked add), i = 0, count = c0 +(assert (forall ((c0 Int) (n Int) (lim Int)) + (=> (and (<= 0 c0) (<= 0 n) (<= 0 lim) (<= c0 lim) + (<= (+ c0 n) lim)) + (Inv c0 n lim 0 c0)))) +; step: body count++ (checked) then i++ (checked); a reverting op drops the path +(assert (forall ((c0 Int) (n Int) (lim Int) (i Int) (c Int)) + (=> (and (Inv c0 n lim i c) (< i n) + ) + (Inv c0 n lim (+ i 1) (+ c 1))))) +; safety: on exit, ensures count == old(count) + n and contract invariant count <= limit +(assert (forall ((c0 Int) (n Int) (lim Int) (i Int) (c Int)) + (=> (and (Inv c0 n lim i c) (not (< i n)) + (not (and (= c (+ c0 n)) (<= c lim)))) + false))) +(check-sat) +(get-model) diff --git a/Verify/Infer/chc/counter_int.spacer.out b/Verify/Infer/chc/counter_int.spacer.out new file mode 100644 index 00000000..716e2ad9 --- /dev/null +++ b/Verify/Infer/chc/counter_int.spacer.out @@ -0,0 +1,9 @@ +sat +( + (define-fun Inv ((x!0 Int) (x!1 Int) (x!2 Int) (x!3 Int) (x!4 Int)) Bool + (let ((a!1 (not (<= (+ x!0 x!3 (* (- 1) x!4)) (- 1)))) + (a!2 (not (<= (+ x!0 x!1 (* (- 1) x!4)) (- 1)))) + (a!3 (not (>= (+ x!0 x!3 (* (- 1) x!4)) 1))) + (a!4 (not (>= (+ x!1 (* (- 1) x!2) (* (- 1) x!3) x!4) 1)))) + (and a!1 a!2 a!3 a!4))) +) diff --git a/Verify/Infer/chc/counter_u256.smt2 b/Verify/Infer/chc/counter_u256.smt2 new file mode 100644 index 00000000..cacc17cf --- /dev/null +++ b/Verify/Infer/chc/counter_u256.smt2 @@ -0,0 +1,21 @@ +; Counter.bump CHC, uint256 checked-arithmetic semantics +; vars: c0 = old(count), n, lim = limit, i, c = count +(set-logic HORN) +(declare-fun Inv (Int Int Int Int Int) Bool) +; init: entry state satisfies param ranges, contract invariant c0 <= lim, require(count + n <= limit) (checked add), i = 0, count = c0 +(assert (forall ((c0 Int) (n Int) (lim Int)) + (=> (and (and (<= 0 c0) (< c0 115792089237316195423570985008687907853269984665640564039457584007913129639936)) (and (<= 0 n) (< n 115792089237316195423570985008687907853269984665640564039457584007913129639936)) (and (<= 0 lim) (< lim 115792089237316195423570985008687907853269984665640564039457584007913129639936)) (<= c0 lim) + (and (<= 0 (+ c0 n)) (< (+ c0 n) 115792089237316195423570985008687907853269984665640564039457584007913129639936)) (<= (+ c0 n) lim)) + (Inv c0 n lim 0 c0)))) +; step: body count++ (checked) then i++ (checked); a reverting op drops the path +(assert (forall ((c0 Int) (n Int) (lim Int) (i Int) (c Int)) + (=> (and (Inv c0 n lim i c) (< i n) + (and (<= 0 (+ c 1)) (< (+ c 1) 115792089237316195423570985008687907853269984665640564039457584007913129639936)) (and (<= 0 (+ i 1)) (< (+ i 1) 115792089237316195423570985008687907853269984665640564039457584007913129639936))) + (Inv c0 n lim (+ i 1) (+ c 1))))) +; safety: on exit, ensures count == old(count) + n and contract invariant count <= limit +(assert (forall ((c0 Int) (n Int) (lim Int) (i Int) (c Int)) + (=> (and (Inv c0 n lim i c) (not (< i n)) + (not (and (= c (+ c0 n)) (<= c lim)))) + false))) +(check-sat) +(get-model) diff --git a/Verify/Infer/chc/counter_u256.spacer.out b/Verify/Infer/chc/counter_u256.spacer.out new file mode 100644 index 00000000..716e2ad9 --- /dev/null +++ b/Verify/Infer/chc/counter_u256.spacer.out @@ -0,0 +1,9 @@ +sat +( + (define-fun Inv ((x!0 Int) (x!1 Int) (x!2 Int) (x!3 Int) (x!4 Int)) Bool + (let ((a!1 (not (<= (+ x!0 x!3 (* (- 1) x!4)) (- 1)))) + (a!2 (not (<= (+ x!0 x!1 (* (- 1) x!4)) (- 1)))) + (a!3 (not (>= (+ x!0 x!3 (* (- 1) x!4)) 1))) + (a!4 (not (>= (+ x!1 (* (- 1) x!2) (* (- 1) x!3) x!4) 1)))) + (and a!1 a!2 a!3 a!4))) +) diff --git a/Verify/Infer/chc/drain_int.smt2 b/Verify/Infer/chc/drain_int.smt2 new file mode 100644 index 00000000..6d260420 --- /dev/null +++ b/Verify/Infer/chc/drain_int.smt2 @@ -0,0 +1,10 @@ +; Drain.drain (a = n; b = 0; while (a > 0) { a--; b++; } return b; ensures result == n) CHC, mathematical Int (uint param >= 0, no overflow guards) semantics +(set-logic HORN) +(declare-fun Inv (Int Int Int) Bool) +(assert (forall ((n Int)) (=> (<= 0 n) (Inv n n 0)))) +(assert (forall ((n Int) (a Int) (b Int)) + (=> (and (Inv n a b) (> a 0) ) (Inv n (- a 1) (+ b 1))))) +(assert (forall ((n Int) (a Int) (b Int)) + (=> (and (Inv n a b) (not (> a 0)) (not (= b n))) false))) +(check-sat) +(get-model) diff --git a/Verify/Infer/chc/drain_int.spacer.out b/Verify/Infer/chc/drain_int.spacer.out new file mode 100644 index 00000000..f0a0494d --- /dev/null +++ b/Verify/Infer/chc/drain_int.spacer.out @@ -0,0 +1,8 @@ +sat +( + (define-fun Inv ((x!0 Int) (x!1 Int) (x!2 Int)) Bool + (let ((a!1 (not (<= (+ x!0 (* (- 1) x!1) (* (- 1) x!2)) (- 1)))) + (a!2 (not (<= (+ x!0 (* (- 1) x!2)) (- 1)))) + (a!3 (not (>= (+ x!0 (* (- 1) x!1) (* (- 1) x!2)) 1)))) + (and a!1 a!2 a!3))) +) diff --git a/Verify/Infer/chc/drain_u256.smt2 b/Verify/Infer/chc/drain_u256.smt2 new file mode 100644 index 00000000..bc04675a --- /dev/null +++ b/Verify/Infer/chc/drain_u256.smt2 @@ -0,0 +1,10 @@ +; Drain.drain (a = n; b = 0; while (a > 0) { a--; b++; } return b; ensures result == n) CHC, uint256 checked-arithmetic semantics +(set-logic HORN) +(declare-fun Inv (Int Int Int) Bool) +(assert (forall ((n Int)) (=> (and (<= 0 n) (< n 115792089237316195423570985008687907853269984665640564039457584007913129639936)) (Inv n n 0)))) +(assert (forall ((n Int) (a Int) (b Int)) + (=> (and (Inv n a b) (> a 0) (and (<= 0 (- a 1)) (< (- a 1) 115792089237316195423570985008687907853269984665640564039457584007913129639936)) (and (<= 0 (+ b 1)) (< (+ b 1) 115792089237316195423570985008687907853269984665640564039457584007913129639936))) (Inv n (- a 1) (+ b 1))))) +(assert (forall ((n Int) (a Int) (b Int)) + (=> (and (Inv n a b) (not (> a 0)) (not (= b n))) false))) +(check-sat) +(get-model) diff --git a/Verify/Infer/chc/drain_u256.spacer.out b/Verify/Infer/chc/drain_u256.spacer.out new file mode 100644 index 00000000..f0a0494d --- /dev/null +++ b/Verify/Infer/chc/drain_u256.spacer.out @@ -0,0 +1,8 @@ +sat +( + (define-fun Inv ((x!0 Int) (x!1 Int) (x!2 Int)) Bool + (let ((a!1 (not (<= (+ x!0 (* (- 1) x!1) (* (- 1) x!2)) (- 1)))) + (a!2 (not (<= (+ x!0 (* (- 1) x!2)) (- 1)))) + (a!3 (not (>= (+ x!0 (* (- 1) x!1) (* (- 1) x!2)) 1)))) + (and a!1 a!2 a!3))) +) diff --git a/Verify/Infer/chc/okwhile_int.smt2 b/Verify/Infer/chc/okwhile_int.smt2 new file mode 100644 index 00000000..60a1a33f --- /dev/null +++ b/Verify/Infer/chc/okwhile_int.smt2 @@ -0,0 +1,10 @@ +; Control.ok_no_invariant (ok_while) CHC, mathematical Int (uint param >= 0, no overflow guards) semantics +(set-logic HORN) +(declare-fun Inv (Int Int) Bool) +(assert (forall ((n Int)) (=> (<= 0 n) (Inv n 0)))) +(assert (forall ((n Int) (i Int)) + (=> (and (Inv n i) (< i n) ) (Inv n (+ i 1))))) +(assert (forall ((n Int) (i Int)) + (=> (and (Inv n i) (not (< i n)) (not (= i n))) false))) +(check-sat) +(get-model) diff --git a/Verify/Infer/chc/okwhile_int.spacer.out b/Verify/Infer/chc/okwhile_int.spacer.out new file mode 100644 index 00000000..1442c652 --- /dev/null +++ b/Verify/Infer/chc/okwhile_int.spacer.out @@ -0,0 +1,5 @@ +sat +( + (define-fun Inv ((x!0 Int) (x!1 Int)) Bool + (not (<= (+ x!0 (* (- 1) x!1)) (- 1)))) +) diff --git a/Verify/Infer/chc/okwhile_u256.smt2 b/Verify/Infer/chc/okwhile_u256.smt2 new file mode 100644 index 00000000..4967d69e --- /dev/null +++ b/Verify/Infer/chc/okwhile_u256.smt2 @@ -0,0 +1,10 @@ +; Control.ok_no_invariant (ok_while) CHC, uint256 checked-arithmetic semantics +(set-logic HORN) +(declare-fun Inv (Int Int) Bool) +(assert (forall ((n Int)) (=> (and (<= 0 n) (< n 115792089237316195423570985008687907853269984665640564039457584007913129639936)) (Inv n 0)))) +(assert (forall ((n Int) (i Int)) + (=> (and (Inv n i) (< i n) (and (<= 0 (+ i 1)) (< (+ i 1) 115792089237316195423570985008687907853269984665640564039457584007913129639936))) (Inv n (+ i 1))))) +(assert (forall ((n Int) (i Int)) + (=> (and (Inv n i) (not (< i n)) (not (= i n))) false))) +(check-sat) +(get-model) diff --git a/Verify/Infer/chc/okwhile_u256.spacer.out b/Verify/Infer/chc/okwhile_u256.spacer.out new file mode 100644 index 00000000..1442c652 --- /dev/null +++ b/Verify/Infer/chc/okwhile_u256.spacer.out @@ -0,0 +1,5 @@ +sat +( + (define-fun Inv ((x!0 Int) (x!1 Int)) Bool + (not (<= (+ x!0 (* (- 1) x!1)) (- 1)))) +) diff --git a/Verify/Infer/flex-4.35-bump.diff b/Verify/Infer/flex-4.35-bump.diff new file mode 100644 index 00000000..ed2760eb --- /dev/null +++ b/Verify/Infer/flex-4.35-bump.diff @@ -0,0 +1,216 @@ +diff --git a/lake-manifest.json b/lake-manifest.json +index 30aaa280..e05df5e1 100644 +--- a/lake-manifest.json ++++ b/lake-manifest.json +@@ -1,7 +1,17 @@ +-{"version": "1.2.0", ++{"version": "1.3.0", + "packagesDir": ".lake/packages", + "packages": +- [{"url": "https://github.com/LeanHorn/SMTLib-to-Lean.git", ++ [{"url": "https://github.com/leanprover-community/mathlib4", ++ "type": "git", ++ "subDir": null, ++ "scope": "", ++ "rev": "56a005855ea17e0b0958f73ec801ae140b0a1679", ++ "name": "mathlib", ++ "manifestFile": "lake-manifest.json", ++ "inputRev": "v4.35.0", ++ "inherited": false, ++ "configFile": "lakefile.lean"}, ++ {"url": "https://github.com/LeanHorn/SMTLib-to-Lean.git", + "type": "git", + "subDir": null, + "scope": "", +@@ -11,71 +21,51 @@ + "inputRev": "89667053aa420284b6794b6d6caabd551c1f7c79", + "inherited": false, + "configFile": "lakefile.toml"}, +- {"url": "https://github.com/ufmg-smite/lean-smt.git", ++ {"url": "https://github.com/abdoo8080/lean-cvc5.git", + "type": "git", + "subDir": null, + "scope": "", +- "rev": "79ef7b3d5e06608d031d75b6d015949b90016875", +- "name": "smt", ++ "rev": "d19a134c237ec7f0cb86c2027062eedeb577a9a9", ++ "name": "cvc5", + "manifestFile": "lake-manifest.json", +- "inputRev": "79ef7b3d5e06608d031d75b6d015949b90016875", ++ "inputRev": "d19a134c237ec7f0cb86c2027062eedeb577a9a9", + "inherited": false, + "configFile": "lakefile.lean"}, +- {"url": "https://github.com/leanprover-community/lean-auto.git", ++ {"url": "https://github.com/ufmg-smite/lean-smt.git", + "type": "git", + "subDir": null, + "scope": "", +- "rev": "92d628ba41801bd12c9d81f9be12fde97f0ad177", +- "name": "auto", ++ "rev": "cbec5bd226c79d80ce0c2d2ea28e1e6359c5f207", ++ "name": "smt", + "manifestFile": "lake-manifest.json", +- "inputRev": "92d628ba41801bd12c9d81f9be12fde97f0ad177", ++ "inputRev": "cbec5bd226c79d80ce0c2d2ea28e1e6359c5f207", + "inherited": false, + "configFile": "lakefile.lean"}, +- {"url": "https://github.com/leanprover-community/aesop", ++ {"url": "https://github.com/leanprover-community/lean-auto.git", + "type": "git", + "subDir": null, + "scope": "", +- "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", +- "name": "aesop", ++ "rev": "30f46ddb9a68d6878f5a1337eb2565ba4e70126b", ++ "name": "auto", + "manifestFile": "lake-manifest.json", +- "inputRev": "355695d523e41d0554926416cba2a2b3544fbbc9", ++ "inputRev": "v4.35.0", + "inherited": false, +- "configFile": "lakefile.toml"}, +- {"url": "https://github.com/leanprover-community/mathlib4.git", +- "type": "git", +- "subDir": null, +- "scope": "", +- "rev": "5ed2965256430c3649e86755f9576b54eca72435", +- "name": "mathlib", +- "manifestFile": "lake-manifest.json", +- "inputRev": "v4.34.0", +- "inherited": true, + "configFile": "lakefile.lean"}, +- {"url": "https://github.com/abdoo8080/lean-cvc5.git", ++ {"url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "", +- "rev": "41e47796d4d15712e6064b064ca5d251a1283955", +- "name": "cvc5", ++ "rev": "4a174c490d8707121c4a9290800489f105d85e07", ++ "name": "aesop", + "manifestFile": "lake-manifest.json", +- "inputRev": "41e47796d4d15712e6064b064ca5d251a1283955", ++ "inputRev": "v4.35.0", + "inherited": false, +- "configFile": "lakefile.lean"}, +- {"url": "https://github.com/leanprover-community/batteries", +- "type": "git", +- "subDir": null, +- "scope": "leanprover-community", +- "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", +- "name": "batteries", +- "manifestFile": "lake-manifest.json", +- "inputRev": "main", +- "inherited": true, + "configFile": "lakefile.toml"}, + {"url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", +- "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", ++ "rev": "dfa4f38190d07c37e315953e08b90fe2d95b3c24", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", +@@ -85,7 +75,7 @@ + "type": "git", + "subDir": null, + "scope": "leanprover-community", +- "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", ++ "rev": "d6b4c7be5be75ec4917c873ac50c756dc1436372", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", +@@ -95,7 +85,7 @@ + "type": "git", + "subDir": null, + "scope": "leanprover-community", +- "rev": "e928b72544873815af278d38681b31c0293588e3", ++ "rev": "a41f0e9a4dea23188ea9cc1c41ac9f8bbafe0b93", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", +@@ -105,7 +95,7 @@ + "type": "git", + "subDir": null, + "scope": "leanprover-community", +- "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", ++ "rev": "df72b022e558978a1c50264cfc4d7fec86fa8e04", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", +@@ -115,20 +105,30 @@ + "type": "git", + "subDir": null, + "scope": "leanprover-community", +- "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", ++ "rev": "dce0ad79c486cb1fb504af04f953c3466b0c6db8", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml"}, ++ {"url": "https://github.com/leanprover-community/batteries", ++ "type": "git", ++ "subDir": null, ++ "scope": "leanprover-community", ++ "rev": "66e469188fe07963e5cf666c7d4433f45b8131c5", ++ "name": "batteries", ++ "manifestFile": "lake-manifest.json", ++ "inputRev": "main", ++ "inherited": true, ++ "configFile": "lakefile.toml"}, + {"url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", +- "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", ++ "rev": "c24fe6078c630e89b489bffe59b3e20ac30d12c8", + "name": "Cli", + "manifestFile": "lake-manifest.json", +- "inputRev": "v4.34.0", ++ "inputRev": "v4.35.0", + "inherited": true, + "configFile": "lakefile.toml"}], + "name": "Flex", +diff --git a/lakefile.lean b/lakefile.lean +index 2a8d92ac..bccb3cf2 100644 +--- a/lakefile.lean ++++ b/lakefile.lean +@@ -10,21 +10,26 @@ package «Flex» where + -- mathlib as a transitive package dependency but its `Smt` import does not use it. + -- Keep these pins aligned with lean-smt's Lean v4.34.0 dependency set. + require aesop from git +- "https://github.com/leanprover-community/aesop" @ "355695d523e41d0554926416cba2a2b3544fbbc9" ++ "https://github.com/leanprover-community/aesop" @ "v4.35.0" + + require auto from git +- "https://github.com/leanprover-community/lean-auto.git" @ "92d628ba41801bd12c9d81f9be12fde97f0ad177" ++ "https://github.com/leanprover-community/lean-auto.git" @ "v4.35.0" + + require smt from git +- "https://github.com/ufmg-smite/lean-smt.git" @ "79ef7b3d5e06608d031d75b6d015949b90016875" ++ "https://github.com/ufmg-smite/lean-smt.git" @ "cbec5bd226c79d80ce0c2d2ea28e1e6359c5f207" + + -- CHC model import uses the same cvc5 parser as the SMT integration. + require cvc5 from git +- "https://github.com/abdoo8080/lean-cvc5.git" @ "41e47796d4d15712e6064b064ca5d251a1283955" ++ "https://github.com/abdoo8080/lean-cvc5.git" @ "d19a134c237ec7f0cb86c2027062eedeb577a9a9" + + require smt2lean from git + "https://github.com/LeanHorn/SMTLib-to-Lean.git" @ "89667053aa420284b6794b6d6caabd551c1f7c79" + ++-- flex-eval: pin mathlib to the v4.35.0 tag; declared last so Lake resolves it first ++-- (otherwise smt2lean's manifest drags in mathlib v4.33.0 and its deps). ++require mathlib from git ++ "https://github.com/leanprover-community/mathlib4" @ "v4.35.0" ++ + @[default_target] + lean_lib «Flex» where + +diff --git a/lean-toolchain b/lean-toolchain +index 12359f92..a6aff065 100644 +--- a/lean-toolchain ++++ b/lean-toolchain +@@ -1 +1 @@ +-leanprover/lean4:v4.34.0 ++leanprover/lean4:v4.35.0 diff --git a/Verify/Infer/gen_reconstruct.sh b/Verify/Infer/gen_reconstruct.sh new file mode 100755 index 00000000..86e0c072 --- /dev/null +++ b/Verify/Infer/gen_reconstruct.sh @@ -0,0 +1,82 @@ +#!/bin/sh +# Generates Reconstruct.lean: invariants pasted mechanically from z3 Spacer models; CHC clauses as stated in chc/*.smt2. +set -eu +cd "$(dirname "$0")" +W=115792089237316195423570985008687907853269984665640564039457584007913129639936 +out=Reconstruct.lean +{ +echo '/-! Kernel-checked initiation / preservation / use for the three loops.' +echo ' Each Inv_* below is generated by smt2lean_inv.py from the z3 Spacer model, unedited.' +echo ' Only Lean core is imported (no Flex, no Mathlib). -/' +echo 'namespace FlexEval' +echo +for v in counter_int counter_u256 okwhile_int okwhile_u256 drain_int drain_u256; do + python3 smt2lean_inv.py chc/$v.spacer.out Inv_$v; echo +done +cat < 0 → Inv_drain_int n (a - 1) (b + 1) := by + intros; simp only [Inv_drain_int] at *; omega +theorem drain_int_use : ∀ n a b : Int, Inv_drain_int n a b → ¬ (a > 0) → b = n := by + intros; simp only [Inv_drain_int] at *; omega + +theorem drain_u256_init : ∀ n : Int, 0 ≤ n → n < $W → Inv_drain_u256 n n 0 := by + intros; simp only [Inv_drain_u256]; omega +theorem drain_u256_pres : ∀ n a b : Int, Inv_drain_u256 n a b → a > 0 → + 0 ≤ a - 1 → a - 1 < $W → 0 ≤ b + 1 → b + 1 < $W → Inv_drain_u256 n (a - 1) (b + 1) := by + intros; simp only [Inv_drain_u256] at *; omega +theorem drain_u256_use : ∀ n a b : Int, Inv_drain_u256 n a b → ¬ (a > 0) → b = n := by + intros; simp only [Inv_drain_u256] at *; omega + +end FlexEval +EOF +for v in counter_int counter_u256 okwhile_int okwhile_u256 drain_int drain_u256; do + for k in init pres use; do echo "#print axioms FlexEval.${v}_$k"; done +done +} > $out +echo generated $out diff --git a/Verify/Infer/reconstruct-4.35.axioms.txt b/Verify/Infer/reconstruct-4.35.axioms.txt new file mode 100644 index 00000000..5b420058 --- /dev/null +++ b/Verify/Infer/reconstruct-4.35.axioms.txt @@ -0,0 +1,18 @@ +'FlexEval.counter_int_init' depends on axioms: [propext, Classical.choice, Quot.sound] +'FlexEval.counter_int_pres' depends on axioms: [propext, Classical.choice, Quot.sound] +'FlexEval.counter_int_use' depends on axioms: [propext, Classical.choice, Quot.sound] +'FlexEval.counter_u256_init' depends on axioms: [propext, Classical.choice, Quot.sound] +'FlexEval.counter_u256_pres' depends on axioms: [propext, Classical.choice, Quot.sound] +'FlexEval.counter_u256_use' depends on axioms: [propext, Classical.choice, Quot.sound] +'FlexEval.okwhile_int_init' depends on axioms: [propext, Quot.sound] +'FlexEval.okwhile_int_pres' depends on axioms: [propext, Quot.sound] +'FlexEval.okwhile_int_use' depends on axioms: [propext, Quot.sound] +'FlexEval.okwhile_u256_init' depends on axioms: [propext, Quot.sound] +'FlexEval.okwhile_u256_pres' depends on axioms: [propext, Quot.sound] +'FlexEval.okwhile_u256_use' depends on axioms: [propext, Quot.sound] +'FlexEval.drain_int_init' depends on axioms: [propext, Classical.choice, Quot.sound] +'FlexEval.drain_int_pres' depends on axioms: [propext, Classical.choice, Quot.sound] +'FlexEval.drain_int_use' depends on axioms: [propext, Quot.sound] +'FlexEval.drain_u256_init' depends on axioms: [propext, Classical.choice, Quot.sound] +'FlexEval.drain_u256_pres' depends on axioms: [propext, Classical.choice, Quot.sound] +'FlexEval.drain_u256_use' depends on axioms: [propext, Quot.sound] diff --git a/Verify/Infer/smt2lean_inv.py b/Verify/Infer/smt2lean_inv.py new file mode 100644 index 00000000..d3c26837 --- /dev/null +++ b/Verify/Infer/smt2lean_inv.py @@ -0,0 +1,59 @@ +#!/usr/bin/env python3 +"""Mechanical translation of a z3 Spacer model (define-fun Inv ...) into a Lean 4 def. +No simplification or editing: each SMT-LIB operator maps 1:1 to a Lean operator, let stays let.""" +import sys, re + +def tokenize(s): + return re.findall(r'\(|\)|[^\s()]+', s) + +def parse(toks, i=0): + if toks[i] == '(': + out = []; i += 1 + while toks[i] != ')': + x, i = parse(toks, i); out.append(x) + return out, i + 1 + return toks[i], i + 1 + +def ident(x): + return x.replace('!', '_') + +def is_bool(v): + return isinstance(v, list) and v[0] in ('not', 'and', 'or', '=>', '<=', '>=', '<', '>', '=') + +def lean(e): + if isinstance(e, str): + if re.fullmatch(r'\d+', e): return '(' + e + ' : Int)' + if e == 'true': return 'True' + if e == 'false': return 'False' + return ident(e) + op, *args = e + if op == 'let': + binds, body = args + s = lean(body) + for name, val in reversed(binds): + ty = 'Prop' if is_bool(val) else 'Int' + s = '(let ' + ident(name) + ' : ' + ty + ' := ' + lean(val) + '; ' + s + ')' + return s + a = [lean(x) for x in args] + if op == 'not': return '(¬ ' + a[0] + ')' + if op == 'and': return '(' + ' ∧ '.join(a) + ')' if a else 'True' + if op == 'or': return '(' + ' ∨ '.join(a) + ')' if a else 'False' + if op == '=>': return '(' + a[0] + ' → ' + a[1] + ')' + if op == '-' and len(a) == 1: return '(-' + a[0] + ')' + if op in ('+', '-', '*'): return '(' + (' ' + op + ' ').join(a) + ')' + if op in ('<=', '>=', '<', '>'): + m = {'<=': '≤', '>=': '≥', '<': '<', '>': '>'}[op] + return '(' + a[0] + ' ' + m + ' ' + a[1] + ')' + if op == '=': return '(' + a[0] + ' = ' + a[1] + ')' + if op == 'ite': return '(if ' + a[0] + ' then ' + a[1] + ' else ' + a[2] + ')' + raise SystemExit('unsupported operator: ' + op) + +text = open(sys.argv[1]).read() +name = sys.argv[2] +toks = tokenize(text[text.index('(define-fun'):]) +d, _ = parse(toks) +_, fname, params, ret, body = d +binders = ' '.join('(' + ident(p) + ' : Int)' for p, _t in params) +print('/-- Verbatim from ' + sys.argv[1] + ' (z3 Spacer model for ' + fname + '). -/') +print('def ' + name + ' ' + binders + ' : Prop :=') +print(' ' + lean(body)) diff --git a/Verify/Infer/spacerpath-4.35.out b/Verify/Infer/spacerpath-4.35.out new file mode 100644 index 00000000..ca95dd61 --- /dev/null +++ b/Verify/Infer/spacerpath-4.35.out @@ -0,0 +1,21 @@ +spacer: instantiated invariants + inv := fun (a a_1 a_2 a_3 a_4 : Int) => + ¬a + a_3 + -1 * a_4 ≤ -1 ∧ ¬1 ≤ a + a_3 + -1 * a_4 ∧ ¬a + a_1 + -1 * a_4 ≤ -1 ∧ ¬1 ≤ a_1 + -1 * a_2 + -1 * a_3 + a_4 +spacer: instantiated invariants + inv := fun (a a_1 a_2 a_3 a_4 : Int) => + ¬a + a_3 + -1 * a_4 ≤ -1 ∧ ¬a + a_1 + -1 * a_4 ≤ -1 ∧ ¬1 ≤ a + a_3 + -1 * a_4 ∧ ¬1 ≤ a_1 + -1 * a_2 + -1 * a_3 + a_4 +spacer: instantiated invariants + inv := fun (a a_1 : Int) => ¬a + -1 * a_1 ≤ -1 +spacer: instantiated invariants + inv := fun (a a_1 : Int) => ¬a + -1 * a_1 ≤ -1 +spacer: instantiated invariants + inv := fun (a a_1 a_2 : Int) => ¬a + -1 * a_1 + -1 * a_2 ≤ -1 ∧ ¬a + -1 * a_2 ≤ -1 ∧ ¬1 ≤ a + -1 * a_1 + -1 * a_2 +spacer: instantiated invariants + inv := fun (a a_1 a_2 : Int) => ¬a + -1 * a_1 + -1 * a_2 ≤ -1 ∧ ¬a + -1 * a_2 ≤ -1 ∧ ¬1 ≤ a + -1 * a_1 + -1 * a_2 +'FlexEval.SpacerPath.counter_int' depends on axioms: [propext, Classical.choice, Quot.sound] +'FlexEval.SpacerPath.counter_u256' depends on axioms: [propext, Classical.choice, Quot.sound] +'FlexEval.SpacerPath.okwhile_int' depends on axioms: [propext, Classical.choice, Quot.sound] +'FlexEval.SpacerPath.okwhile_u256' depends on axioms: [propext, Classical.choice, Quot.sound] +'FlexEval.SpacerPath.drain_int' depends on axioms: [propext, Classical.choice, Quot.sound] +'FlexEval.SpacerPath.drain_u256' depends on axioms: [propext, Classical.choice, Quot.sound] +wall=3.52 s maxrss=1950308 KB diff --git a/Verify/LoomAxioms.lean b/Verify/LoomAxioms.lean new file mode 100644 index 00000000..e8e76d60 --- /dev/null +++ b/Verify/LoomAxioms.lean @@ -0,0 +1,39 @@ +import Verify.CounterBump +import Verify.Fuel + +/-! Axioms of the Loom pieces SolidCore's verification builds on, and of Counter's `bump`. Each +shows only `propext`, `Classical.choice` and `Quot.sound`. -/ + +#print axioms MAlgExceptErr +#print axioms MAlgExceptErrProp +#print axioms MAlgExceptErr.lift_eq +#print axioms triple_bounded +#print axioms triple_while +#print axioms bounded_eq_of_variant +#print axioms TotalCorrectness.repeat_inv +#print axioms PartialCorrectness.repeat_inv +#print axioms triple_forIn_list +#print axioms StateT.wp_get +#print axioms StateT.wp_set +#print axioms ExceptT.wp_throw +#print axioms SolidCore.Verify.wp_eq_loom +#print axioms SolidCore.Verify.wp_get +#print axioms SolidCore.Verify.wp_set +#print axioms SolidCore.Verify.wp_throw +#print axioms SolidCore.Verify.triple_whileM +#print axioms SolidCore.Verify.triple_of_wp +#print axioms SolidCore.Verify.Triple.finishes +#print axioms SolidCore.Verify.tripleSome_of_wp +#print axioms SolidCore.Verify.Triple.some +#print axioms SolidCore.Verify.satisfies_of_triple +#print axioms SolidCore.Verify.CounterBump.body_step +#print axioms SolidCore.Verify.CounterBump.bump_spec +#print axioms SolidCore.Verify.runAny_isSome_iff +#print axioms SolidCore.Verify.runAny_spec +#print axioms SolidCore.Verify.runAny_of_run +#print axioms SolidCore.Verify.tripleAny_of_wp +#print axioms SolidCore.Verify.TripleAny.some +#print axioms SolidCore.Verify.implementsAny_of_some +#print axioms SolidCore.Verify.tripleAny_of_some +#print axioms SolidCore.Verify.triple_of_within +#print axioms SolidCore.Verify.Triple.any diff --git a/Verify/LoomImports.lean b/Verify/LoomImports.lean new file mode 100644 index 00000000..a42e32ae --- /dev/null +++ b/Verify/LoomImports.lean @@ -0,0 +1,16 @@ +import Verify.CounterBump +import Verify.Fuel + +/-! The certified Loom path does not reach Loom's SMT layer (lean-auto, z3, cvc5), its +VC tactic layer or `Verify.Finite` (which uses `native_decide`): elaboration fails +if any of these modules is in this file's import closure. -/ + +open Lean Elab Command in +run_cmd do + let forbidden := [`Loom.SMT, `Auto, `Loom.TacticAsync, `Loom.Meta, + `Loom.MonadAlgebras.WP.Tactic, `Verify.Finite, `Verify.Tactic] + let mods := (← getEnv).header.moduleNames + for f in forbidden do + if mods.any (fun m => m == f || f.isPrefixOf m) then + throwError m!"certified Loom path imports {f}" + logInfo m!"import closure: {mods.size} modules, none forbidden" diff --git a/Verify/Obligation.lean b/Verify/Obligation.lean new file mode 100644 index 00000000..a7eaeb99 --- /dev/null +++ b/Verify/Obligation.lean @@ -0,0 +1,7 @@ +import Verify.Obligation.Smt +import Verify.Obligation.Vc +import Verify.Obligation.Model + +/-! The obligations `solar-verify --emit-lean` exports: the SMT-LIB fragment it writes with its +meaning (`Smt`), its scripts and obligations (`Vc`), and models of its answers (`Model`). An +exported module imports this one. -/ diff --git a/Verify/Obligation/Model.lean b/Verify/Obligation/Model.lean new file mode 100644 index 00000000..7289c40d --- /dev/null +++ b/Verify/Obligation/Model.lean @@ -0,0 +1,67 @@ +import Verify.Obligation.Smt +/-! +Interpretations from finite models: a value for each constant, and for each function a table +of argument values with a default. Tests use them to evaluate exported terms in the kernel, and +they can replay a solver's counterexample. Nothing an obligation means depends on this file. +-/ +namespace SolarVerify.Model +open SolarVerify.Smt + +/-- An Int value. -/ +def int (i : Int) : Val := ⟨.int, show Srt.Den .int from i⟩ + +/-- A Bool value. -/ +def bool (b : Bool) : Val := ⟨.bool, show Srt.Den .bool from b⟩ + +/-- A bitvector value of width `w` and value `n mod 2^w`. -/ +def bv (w n : Nat) : Val := ⟨.bv w, show Srt.Den (.bv w) from BitVec.ofNat w n⟩ + +/-- A record value. -/ +def tup (fields : List Val) : Val := ⟨.tup (sortsOf fields), pack fields⟩ + +/-- A value at sort `s`, or the sort's default when it has another sort. -/ +def valAt (s : Srt) (v : Val) : s.Den := (v.as s).getD s.default + +/-- Whether two values are equal (arrays never compare equal here). -/ +def same (a b : Val) : Bool := + match b.as a.1 with + | some x => match a with + | ⟨.array _ _, _⟩ => false + | ⟨s, y⟩ => firstOrderEq s y x + | none => false +where + /-- Equality of first-order values, which the kernel reduces. -/ + firstOrderEq : (s : Srt) → s.Den → s.Den → Bool + | .bool, a, b => @decide _ (Bool.decEq a b) + | .int, a, b => @decide _ (Int.decEq a b) + | .bv w, a, b => @decide _ ((inferInstance : DecidableEq (BitVec w)) a b) + | .array _ _, _, _ => false + | .tup fs, a, b => tupEq fs a b + tupEq : (ss : List Srt) → Srt.DenList ss → Srt.DenList ss → Bool + | [], _, _ => true + | s :: ss, (a, as), (b, bs) => firstOrderEq s a b && tupEq ss as bs + +/-- An array of sort `(Array idx elem)`: `entries` over the default `d`, the first entry for a +key winning. -/ +def array (idx elem : Srt) (d : Val) (entries : List (Val × Val)) : Val := + ⟨.array idx elem, fun k => + match entries.find? (fun e => same e.1 ⟨idx, k⟩) with + | some e => valAt elem e.2 + | none => valAt elem d⟩ + +/-- A function: the value of the first row whose arguments equal the call's, else `d`. -/ +def table (d : Val) (rows : List (List Val × Val)) (args : List Val) : Val := + match rows.find? (fun r => r.1.length == args.length && (r.1.zip args).all (fun p => same p.1 p.2)) with + | some r => r.2 + | none => d + +/-- The interpretation giving symbol `f` the function `fns[f]`, and quotients and remainders by +zero the value 0. -/ +def env (fns : List (List Val → Val)) : Env where + fn f args ret xs := match fns[f]? with + | some g => valAt ret (g (Srt.unpack args xs)) + | none => ret.default + divZero _ := 0 + modZero _ := 0 + +end SolarVerify.Model diff --git a/Verify/Obligation/Smt.lean b/Verify/Obligation/Smt.lean new file mode 100644 index 00000000..d6af72f1 --- /dev/null +++ b/Verify/Obligation/Smt.lean @@ -0,0 +1,470 @@ +/- +The SMT-LIB fragment solar-verify writes, as a deep embedding with its denotation. + +This file is the meaning of every verification condition `solar-verify --emit-lean` exports: +see docs/VERIFY_LEAN.md. Format version 1. + +Sorts are SMT-LIB's `Bool`, `Int`, `(_ BitVec w)` and `(Array I E)`, and records: solar-verify +declares each struct as a datatype with one constructor and no recursion, which the export +writes as the product of its field sorts. Terms are untyped: `Term.eval` infers each sort and +returns `none` on an ill-sorted term. +An environment interprets every declared function symbol (constants are 0-ary symbols) and the +values SMT-LIB leaves unspecified: integer `div` and `mod` by zero. + +Evaluation reduces in the kernel except at quantifiers and equality of arrays, which decide with +classical logic, so `decide` in the kernel evaluates any term free of them. +-/ +namespace SolarVerify.Smt + +/-- A sort. A record is the product of its field sorts. -/ +inductive Srt where + | bool + | int + | bv (w : Nat) + | array (idx elem : Srt) + | tup (fields : List Srt) + deriving Repr, Inhabited + +mutual +/-- Decidable equality of sorts, written out so that the kernel reduces it. -/ +def Srt.decEq : (a b : Srt) → Decidable (a = b) + | .bool, .bool => isTrue rfl + | .int, .int => isTrue rfl + | .bv w, .bv v => + if h : w = v then isTrue (h ▸ rfl) else isFalse (fun e => by injection e; contradiction) + | .array i e, .array j f => + match Srt.decEq i j, Srt.decEq e f with + | isTrue h1, isTrue h2 => isTrue (h1 ▸ h2 ▸ rfl) + | isFalse h, _ => isFalse (fun x => by injection x; contradiction) + | _, isFalse h => isFalse (fun x => by injection x; contradiction) + | .tup fs, .tup gs => + match Srt.decEqList fs gs with + | isTrue h => isTrue (h ▸ rfl) + | isFalse h => isFalse (fun x => by injection x; contradiction) + | .bool, .int | .bool, .bv _ | .bool, .array _ _ | .bool, .tup _ + | .int, .bool | .int, .bv _ | .int, .array _ _ | .int, .tup _ + | .bv _, .bool | .bv _, .int | .bv _, .array _ _ | .bv _, .tup _ + | .array _ _, .bool | .array _ _, .int | .array _ _, .bv _ | .array _ _, .tup _ + | .tup _, .bool | .tup _, .int | .tup _, .bv _ | .tup _, .array _ _ => + isFalse (fun h => by cases h) +def Srt.decEqList : (a b : List Srt) → Decidable (a = b) + | [], [] => isTrue rfl + | x :: xs, y :: ys => + match Srt.decEq x y, Srt.decEqList xs ys with + | isTrue h1, isTrue h2 => isTrue (h1 ▸ h2 ▸ rfl) + | isFalse h, _ => isFalse (fun e => by injection e; contradiction) + | _, isFalse h => isFalse (fun e => by injection e; contradiction) + | [], _ :: _ => isFalse (fun h => by cases h) + | _ :: _, [] => isFalse (fun h => by cases h) +end + +instance : DecidableEq Srt := Srt.decEq + +mutual +/-- The values of a sort. An array is a total function, as in SMT-LIB's theory of arrays. -/ +def Srt.Den : Srt → Type + | .bool => Bool + | .int => Int + | .bv w => BitVec w + | .array i e => Srt.Den i → Srt.Den e + | .tup fs => Srt.DenList fs +/-- The values of a list of sorts, one each. -/ +def Srt.DenList : List Srt → Type + | [] => Unit + | s :: ss => Srt.Den s × Srt.DenList ss +end + +mutual +/-- A value of every sort, for building interpretations. -/ +def Srt.default : (s : Srt) → s.Den + | .bool => (false : Bool) + | .int => (0 : Int) + | .bv w => (0 : BitVec w) + | .array _ e => fun _ => Srt.default e + | .tup fs => Srt.defaultList fs +/-- A value of every list of sorts. -/ +def Srt.defaultList : (ss : List Srt) → Srt.DenList ss + | [] => () + | s :: ss => (Srt.default s, Srt.defaultList ss) +end + +/-- A value with its sort. -/ +abbrev Val := (s : Srt) × s.Den + +mutual +/-- SMT-LIB equality of two values of one sort: structural on records, extensional (classical) +on arrays. -/ +noncomputable def Srt.beq : (s : Srt) → s.Den → s.Den → Bool + | .bool, a, b => @decide _ (Bool.decEq a b) + | .int, a, b => @decide _ (Int.decEq a b) + | .bv w, a, b => @decide _ ((inferInstance : DecidableEq (BitVec w)) a b) + | .array i e, a, b => + @decide (∀ k : Srt.Den i, Srt.beq e (a k) (b k) = true) (Classical.propDecidable _) + | .tup fs, a, b => Srt.beqList fs a b +noncomputable def Srt.beqList : (ss : List Srt) → Srt.DenList ss → Srt.DenList ss → Bool + | [], _, _ => true + | s :: ss, (a, as), (b, bs) => Srt.beq s a b && Srt.beqList ss as bs +end + +/-- A value's view at a sort it may have. -/ +def Val.as (v : Val) (s : Srt) : Option s.Den := + if h : v.1 = s then some (h ▸ v.2) else none + +/-- A list of values as the values of a list of sorts. -/ +def Val.asList : List Val → (ss : List Srt) → Option (Srt.DenList ss) + | [], [] => some () + | v :: vs, s :: ss => do + let x ← v.as s + let xs ← Val.asList vs ss + pure (x, xs) + | _, _ => none + +/-- The values of a record, with their sorts. -/ +def Srt.unpack : (ss : List Srt) → Srt.DenList ss → List Val + | [], () => [] + | s :: ss, (x, xs) => ⟨s, x⟩ :: Srt.unpack ss xs + +/-- Field `i` of a record. -/ +def Srt.field : (ss : List Srt) → Srt.DenList ss → Nat → Option Val + | [], _, _ => none + | s :: _, (x, _), 0 => some ⟨s, x⟩ + | _ :: ss, (_, xs), n + 1 => Srt.field ss xs n + +/-- The bitvector a value holds, with its width. -/ +def Val.bv? : Val → Option ((w : Nat) × BitVec w) + | ⟨.bv w, x⟩ => some ⟨w, x⟩ + | _ => none + +/-- The Bool a value holds. -/ +def boolOf (o : Option Val) : Option Bool := o.bind (fun v => v.as .bool) + +/-- The built-in operators, by their SMT-LIB names. The n-ary and chainable ones take as many +arguments as SMT-LIB allows. -/ +inductive Op where + -- Core. + | not | and | or | xor | implies | eq | distinct | ite + -- Ints. `sub` with one argument is negation, as SMT-LIB's `-`. + | add | sub | mul | div | mod | abs | lt | le | gt | ge + -- Arrays. + | select | store + -- Conversions. + | bv2nat | int2bv (w : Nat) + -- Bitvectors. + | bvadd | bvsub | bvmul | bvudiv | bvurem | bvsdiv | bvsrem | bvsmod | bvneg + | bvand | bvor | bvxor | bvnot | bvshl | bvlshr | bvashr + | bvult | bvule | bvugt | bvuge | bvslt | bvsle | bvsgt | bvsge + | concat | extract (hi lo : Nat) | zeroExtend (n : Nat) | signExtend (n : Nat) + deriving Repr, DecidableEq, Inhabited + +/-- A term. Function symbols are numbered by their declaration in the script; bound variables +are de Bruijn indices, 0 the last binder of the innermost quantifier. -/ +inductive Term where + | bool (b : Bool) + | int (i : Int) + /-- The bitvector literal of width `w` and value `n mod 2^w`. -/ + | bv (w n : Nat) + /-- Declared function symbol `f` applied to its arguments (none for a constant). -/ + | fn (f : Nat) (args : List Term) + /-- Bound variable `i`. -/ + | var (i : Nat) + | app (op : Op) (args : List Term) + /-- `((as const (Array idx E)) v)`. -/ + | constArray (idx : Srt) (v : Term) + /-- The constructor of a record. -/ + | mk (fields : List Term) + /-- Field `i` of a record. -/ + | proj (i : Nat) (t : Term) + | «forall» (binders : List Srt) (body : Term) + | «exists» (binders : List Srt) (body : Term) + deriving Repr, Inhabited + +/-- A declared function symbol: its name (for people), argument sorts and result sort. -/ +structure Decl where + name : String + args : List Srt + ret : Srt + deriving Repr, Inhabited + +/-- An interpretation: a function for every symbol number at every signature (a term uses only +the one its declaration gives), and integer `div` and `mod` by zero, which SMT-LIB leaves +unspecified. -/ +structure Env where + fn : Nat → (args : List Srt) → (ret : Srt) → Srt.DenList args → ret.Den + divZero : Int → Int + modZero : Int → Int + +/-- Bound values, the innermost first. -/ +abbrev Locals := List Val + +section ops + +/-- SMT-LIB `div`: the Euclidean quotient. -/ +def intDiv (env : Env) (a b : Int) : Int := if b = 0 then env.divZero a else a.ediv b + +/-- SMT-LIB `mod`: the Euclidean remainder, in `[0, |b|)`. -/ +def intMod (env : Env) (a b : Int) : Int := if b = 0 then env.modZero a else a.emod b + +/-- A relation over consecutive arguments, as `(< a b c)` means `a < b < c`. -/ +def chain {α} (r : α → α → Bool) : α → List α → Bool + | a, b :: rest => r a b && chain r b rest + | _, [] => true + +/-- A relation over every pair of positions. -/ +def pairwise {α} (r : α → α → Bool) : List α → Bool + | [] => true + | a :: rest => rest.all (r a) && pairwise r rest + +/-- The Ints of a list of values. -/ +def ints : List Val → Option (List Int) + | [] => some [] + | v :: vs => do let x ← v.as .int; let xs ← ints vs; pure (x :: xs) + +/-- The Bools of a list of values. -/ +def bools : List Val → Option (List Bool) + | [] => some [] + | v :: vs => do let x ← v.as .bool; let xs ← bools vs; pure (x :: xs) + +/-- Values of one sort: the first one's. -/ +def sameSort (s : Srt) : List Val → Option (List s.Den) + | [] => some [] + | v :: vs => do let x ← v.as s; let xs ← sameSort s vs; pure (x :: xs) + +/-- Bitvectors of one width, the width of the first. -/ +def bvs : List Val → Option ((w : Nat) × List (BitVec w)) + | [] => none + | v :: vs => do + let ⟨w, x⟩ ← v.bv? + let xs ← sameSort (.bv w) vs + pure ⟨w, x :: xs⟩ + +/-- A left fold over at least two arguments. -/ +def foldl2 {α} (f : α → α → α) : List α → Option α + | a :: b :: rest => some (rest.foldl f (f a b)) + | _ => none + +/-- `=>` over at least two arguments, associating to the right. -/ +def impliesChain (bs : List Bool) : Option Bool := + match bs.reverse with + | last :: init@(_ :: _) => some (init.foldl (fun acc a => !a || acc) last) + | _ => none + +/-- An Int relation, chained over at least two arguments. -/ +def intRel (r : Int → Int → Bool) (args : List Val) : Option Val := do + let xs ← ints args + match xs with + | a :: rest@(_ :: _) => some ⟨.bool, chain r a rest⟩ + | _ => none + +/-- A bitvector relation of two arguments. -/ +def bvRel (r : (w : Nat) → BitVec w → BitVec w → Bool) (args : List Val) : Option Val := do + let ⟨w, xs⟩ ← bvs args + match xs with + | [a, b] => some ⟨.bool, r w a b⟩ + | _ => none + +/-- A left-associative bitvector operation of at least two arguments. -/ +def bvFold (f : (w : Nat) → BitVec w → BitVec w → BitVec w) (args : List Val) : Option Val := do + let ⟨w, xs⟩ ← bvs args + let r ← foldl2 (f w) xs + pure ⟨.bv w, r⟩ + +/-- A bitvector operation of two arguments. -/ +def bvBin (f : (w : Nat) → BitVec w → BitVec w → BitVec w) (args : List Val) : Option Val := do + let ⟨w, xs⟩ ← bvs args + match xs with + | [a, b] => some ⟨.bv w, f w a b⟩ + | _ => none + +/-- A bitvector operation of one argument. -/ +def bvUn (f : (w : Nat) → BitVec w → BitVec w) (args : List Val) : Option Val := do + let ⟨w, xs⟩ ← bvs args + match xs with + | [a] => some ⟨.bv w, f w a⟩ + | _ => none + +/-- The value of an operator on the values of its arguments, or `none` when they do not have +the sorts and number it takes. Bitvector division and remainder by zero are as SMT-LIB 2.6 +defines them. -/ +noncomputable def Op.apply (env : Env) : Op → List Val → Option Val + | .not, args => do + let bs ← bools args + match bs with | [a] => some ⟨.bool, !a⟩ | _ => none + | .and, args => do let bs ← bools args; pure ⟨.bool, bs.all id⟩ + | .or, args => do let bs ← bools args; pure ⟨.bool, bs.any id⟩ + | .xor, args => do let bs ← bools args; let r ← foldl2 Bool.xor bs; pure ⟨.bool, r⟩ + | .implies, args => do let bs ← bools args; let r ← impliesChain bs; pure ⟨.bool, r⟩ + | .eq, args => + match args with + | a :: rest@(_ :: _) => do + let xs ← sameSort a.1 rest + pure ⟨.bool, chain (Srt.beq a.1) a.2 xs⟩ + | _ => none + | .distinct, args => + match args with + | a :: rest@(_ :: _) => do + let xs ← sameSort a.1 rest + pure ⟨.bool, pairwise (fun x y => !Srt.beq a.1 x y) (a.2 :: xs)⟩ + | _ => none + | .ite, args => + match args with + | [c, t, e] => do + let b ← boolOf (some c) + let e' ← e.as t.1 + pure (if b then t else ⟨t.1, e'⟩) + | _ => none + | .add, args => do let xs ← ints args; let r ← foldl2 (· + ·) xs; pure ⟨.int, r⟩ + | .sub, args => do + let xs ← ints args + match xs with + | [a] => some ⟨.int, -a⟩ + | _ => do let r ← foldl2 (· - ·) xs; pure ⟨.int, r⟩ + | .mul, args => do let xs ← ints args; let r ← foldl2 (· * ·) xs; pure ⟨.int, r⟩ + | .div, args => do let xs ← ints args; let r ← foldl2 (intDiv env) xs; pure ⟨.int, r⟩ + | .mod, args => do + let xs ← ints args + match xs with | [a, b] => some ⟨.int, intMod env a b⟩ | _ => none + | .abs, args => do + let xs ← ints args + match xs with | [a] => some ⟨.int, (a.natAbs : Int)⟩ | _ => none + | .lt, args => intRel (fun a b => decide (a < b)) args + | .le, args => intRel (fun a b => decide (a ≤ b)) args + | .gt, args => intRel (fun a b => decide (b < a)) args + | .ge, args => intRel (fun a b => decide (b ≤ a)) args + | .select, args => + match args with + | [⟨.array i e, f⟩, k] => do let k' ← k.as i; pure ⟨e, f k'⟩ + | _ => none + | .store, args => + match args with + | [⟨.array i e, f⟩, k, v] => do + let k' ← k.as i + let v' ← v.as e + pure ⟨.array i e, fun j => if Srt.beq i j k' then v' else f j⟩ + | _ => none + | .bv2nat, args => + match args with + | [⟨.bv _, x⟩] => some ⟨.int, (x.toNat : Int)⟩ + | _ => none + | .int2bv w, args => do + let xs ← ints args + match xs with | [a] => some ⟨.bv w, BitVec.ofInt w a⟩ | _ => none + | .bvadd, args => bvFold (fun _ a b => a + b) args + | .bvsub, args => bvBin (fun _ a b => a - b) args + | .bvmul, args => bvFold (fun _ a b => a * b) args + | .bvudiv, args => bvBin (fun _ a b => BitVec.smtUDiv a b) args + | .bvurem, args => bvBin (fun _ a b => BitVec.umod a b) args + | .bvsdiv, args => bvBin (fun _ a b => BitVec.smtSDiv a b) args + | .bvsrem, args => bvBin (fun _ a b => BitVec.srem a b) args + | .bvsmod, args => bvBin (fun _ a b => BitVec.smod a b) args + | .bvneg, args => bvUn (fun _ a => -a) args + | .bvand, args => bvFold (fun _ a b => a &&& b) args + | .bvor, args => bvFold (fun _ a b => a ||| b) args + | .bvxor, args => bvFold (fun _ a b => a ^^^ b) args + | .bvnot, args => bvUn (fun _ a => ~~~a) args + | .bvshl, args => bvBin (fun _ a b => a <<< b.toNat) args + | .bvlshr, args => bvBin (fun _ a b => a >>> b.toNat) args + | .bvashr, args => bvBin (fun _ a b => a.sshiftRight b.toNat) args + | .bvult, args => bvRel (fun _ a b => BitVec.ult a b) args + | .bvule, args => bvRel (fun _ a b => BitVec.ule a b) args + | .bvugt, args => bvRel (fun _ a b => BitVec.ult b a) args + | .bvuge, args => bvRel (fun _ a b => BitVec.ule b a) args + | .bvslt, args => bvRel (fun _ a b => BitVec.slt a b) args + | .bvsle, args => bvRel (fun _ a b => BitVec.sle a b) args + | .bvsgt, args => bvRel (fun _ a b => BitVec.slt b a) args + | .bvsge, args => bvRel (fun _ a b => BitVec.sle b a) args + | .concat, args => + match args with + | [⟨.bv w, a⟩, ⟨.bv v, b⟩] => some ⟨.bv (w + v), BitVec.append (n := w) (m := v) a b⟩ + | _ => none + | .extract hi lo, args => + match args with + | [⟨.bv w, a⟩] => + if lo ≤ hi ∧ hi < w then some ⟨.bv (hi - lo + 1), a.extractLsb' lo (hi - lo + 1)⟩ + else none + | _ => none + | .zeroExtend n, args => + match args with + | [⟨.bv w, a⟩] => some ⟨.bv (w + n), a.setWidth (w + n)⟩ + | _ => none + | .signExtend n, args => + match args with + | [⟨.bv w, a⟩] => some ⟨.bv (w + n), a.signExtend (w + n)⟩ + | _ => none + +end ops + +/-- The sorts of a list of values. -/ +def sortsOf : List Val → List Srt + | [] => [] + | v :: vs => v.1 :: sortsOf vs + +/-- A record value from its fields. -/ +def pack : (vs : List Val) → Srt.DenList (sortsOf vs) + | [] => () + | v :: vs => (v.2, pack vs) + +/-- Bound values after binding `xs`, of sorts `ss`: the last binder is innermost. -/ +def bindAll (ss : List Srt) (xs : Srt.DenList ss) (locals : Locals) : Locals := + (Srt.unpack ss xs).reverse ++ locals + +mutual +/-- The value of a term under an interpretation of the declared symbols `decls` and values of +its bound variables, or `none` when the term or any part of it is ill-sorted. A quantifier is +`none` unless its body is a formula at every value of its binders. -/ +noncomputable def Term.eval (env : Env) (decls : List Decl) (locals : Locals) : Term → Option Val + | .bool b => some ⟨.bool, b⟩ + | .int i => some ⟨.int, i⟩ + | .bv w n => some ⟨.bv w, BitVec.ofNat w n⟩ + | .fn f args => do + let d ← decls[f]? + let vs ← Term.evalList env decls locals args + let xs ← Val.asList vs d.args + pure ⟨d.ret, env.fn f d.args d.ret xs⟩ + | .var i => locals[i]? + | .app op args => do + let vs ← Term.evalList env decls locals args + op.apply env vs + | .constArray idx v => do + let x ← Term.eval env decls locals v + pure ⟨.array idx x.1, fun _ => x.2⟩ + | .mk fields => do + let vs ← Term.evalList env decls locals fields + pure ⟨.tup (sortsOf vs), pack vs⟩ + | .proj i t => do + let v ← Term.eval env decls locals t + match v with + | ⟨.tup ss, x⟩ => Srt.field ss x i + | _ => none + | .forall ss body => + @ite _ (∀ xs : Srt.DenList ss, (boolOf (Term.eval env decls (bindAll ss xs locals) body)).isSome) + (Classical.propDecidable _) + (some ⟨.bool, @decide (∀ xs : Srt.DenList ss, + boolOf (Term.eval env decls (bindAll ss xs locals) body) = some true) + (Classical.propDecidable _)⟩) + none + | .exists ss body => + @ite _ (∀ xs : Srt.DenList ss, (boolOf (Term.eval env decls (bindAll ss xs locals) body)).isSome) + (Classical.propDecidable _) + (some ⟨.bool, @decide (∃ xs : Srt.DenList ss, + boolOf (Term.eval env decls (bindAll ss xs locals) body) = some true) + (Classical.propDecidable _)⟩) + none +/-- The values of a list of terms. -/ +noncomputable def Term.evalList (env : Env) (decls : List Decl) (locals : Locals) : + List Term → Option (List Val) + | [] => some [] + | t :: ts => do + let v ← Term.eval env decls locals t + let vs ← Term.evalList env decls locals ts + pure (v :: vs) +end + +/-- A closed formula holds: it is well-sorted and evaluates to true. -/ +def Holds (env : Env) (decls : List Decl) (t : Term) : Prop := + boolOf (Term.eval env decls [] t) = some true + +/-- The Bool a closed formula evaluates to, for tests that evaluate in the kernel. -/ +noncomputable def Term.evalBool (env : Env) (decls : List Decl) (t : Term) : Option Bool := + boolOf (Term.eval env decls [] t) + +end SolarVerify.Smt diff --git a/Verify/Obligation/Vc.lean b/Verify/Obligation/Vc.lean new file mode 100644 index 00000000..1af20145 --- /dev/null +++ b/Verify/Obligation/Vc.lean @@ -0,0 +1,38 @@ +import Verify.Obligation.Smt +/-! +Verification conditions as solar-verify exports them: a script of declarations and assertions, +as the solver's assertion stack held them, and obligations that each ask the solver to show a +goal under a guard and the first assertions of the script. See docs/VERIFY_LEAN.md. +-/ +namespace SolarVerify.Vc +open SolarVerify.Smt + +/-- The version of the export format this library reads. -/ +def formatVersion : Nat := 1 + +/-- The declarations and assertions in scope in the solver, in the order solar-verify sent them. +A `define-fun` is a declaration and an assertion that it equals its body at every argument. -/ +structure Script where + decls : List Decl + asserts : List Term + deriving Repr, Inhabited + +/-- One query: the goal follows from the first `upto` assertions of the script and the guard. +solar-verify asks the solver whether `(and asserts guard (not goal))` is unsatisfiable. -/ +structure Obligation where + script : Script + upto : Nat + guard : Term + goal : Term + deriving Repr, Inhabited + +/-- The obligation as one closed formula, `(=> (and a_0 ... a_{upto-1} guard) goal)`. -/ +def Obligation.formula (o : Obligation) : Term := + .app .implies [.app .and (o.script.asserts.take o.upto ++ [o.guard]), o.goal] + +/-- The obligation holds: its formula is well-sorted and true under every interpretation of the +declared symbols. Exactly when the query solar-verify sends is unsatisfiable. -/ +def Obligation.Valid (o : Obligation) : Prop := + ∀ env : Env, Holds env o.script.decls o.formula + +end SolarVerify.Vc diff --git a/Verify/Reconstruct/.gitignore b/Verify/Reconstruct/.gitignore new file mode 100644 index 00000000..bfb30ec8 --- /dev/null +++ b/Verify/Reconstruct/.gitignore @@ -0,0 +1 @@ +/.lake diff --git a/Verify/Reconstruct/Tactic.lean b/Verify/Reconstruct/Tactic.lean new file mode 100644 index 00000000..24d75859 --- /dev/null +++ b/Verify/Reconstruct/Tactic.lean @@ -0,0 +1,42 @@ +import Verify.Discharge +import Smt + +/-! +`vc_smt` proves an exported obligation `Obligation.Valid ob` from a cvc5 proof: + +1. `vc_valid_prep` (SolarVerify.Discharge) reduces it to a shallow goal `False` over Int, Bool and + functions; +2. `vc_smt_norm` substitutes away the definitions `x = t` of local symbols and turns Booleans, + conditions of `if` included, into propositions, so that a quantifier the export evaluates + classically (`qdec (∀ x, …)`) reaches cvc5 as a quantified formula rather than an opaque Bool; +3. lean-smt's `smt` asks cvc5 for a refutation of the hypotheses and reconstructs its proof + (CPC rules) as a Lean proof term, step by step. cvc5 gets 60 seconds; `unknown` fails the proof. + +The kernel checks the term; cvc5 and lean-smt's tactic code are not trusted. A step lean-smt cannot +reconstruct becomes a hole (`sorryAx`), which reconstruct.sh rejects, so the proof fails closed. +-/ + +namespace SolarVerify.Reconstruct + +/-- An `if` at any instance is the classical one, whose condition `simp` can rewrite without a +`Decidable` instance for the result (such as a condition with a quantifier). -/ +theorem ite_eq_qite {α : Type} (c : Prop) [h : Decidable c] (a b : α) : + @ite α c h a b = SolarVerify.Discharge.qite c a b := by + unfold SolarVerify.Discharge.qite; congr + +end SolarVerify.Reconstruct + +/-- Substitutes local definitions and turns Booleans into propositions: see the module comment. -/ +macro "vc_smt_norm" : tactic => `(tactic| ( + try subst_vars + try simp -failIfUnchanged only [SolarVerify.Reconstruct.ite_eq_qite] at * + try simp -failIfUnchanged only [Bool.and_eq_true, Bool.or_eq_true, Bool.not_eq_true', + Bool.not_eq_eq_eq_not, Bool.not_true, Bool.not_false, Bool.and_true, Bool.true_and, + Bool.and_false, Bool.false_and, Bool.or_true, Bool.true_or, Bool.or_false, Bool.false_or, + SolarVerify.Discharge.decide_any_eq_true, SolarVerify.Discharge.qdec_eq_true, + decide_eq_true_eq, decide_eq_false_iff_not, Bool.decide_and, Bool.decide_or, + decide_not, Bool.eq_false_iff, ne_eq, SolarVerify.Discharge.true_eq_iff, + SolarVerify.Discharge.false_eq_iff] at * + try simp -failIfUnchanged only [SolarVerify.Discharge.qite] at *)) + +macro "vc_smt" : tactic => `(tactic| (vc_valid_prep <;> (intros; vc_smt_norm; smt (timeout := .some 60) [*]))) diff --git a/Verify/Reconstruct/lake-manifest.json b/Verify/Reconstruct/lake-manifest.json new file mode 100644 index 00000000..51c8f38d --- /dev/null +++ b/Verify/Reconstruct/lake-manifest.json @@ -0,0 +1,46 @@ +{"version": "1.3.0", + "packagesDir": ".lake/packages", + "packages": + [{"url": "https://github.com/ufmg-smite/lean-smt.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "6b26285ece45e38fc0d21809b944522233039829", + "name": "smt", + "manifestFile": "lake-manifest.json", + "inputRev": "6b26285ece45e38fc0d21809b944522233039829", + "inherited": false, + "configFile": "lakefile.lean"}, + {"url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "", + "rev": "dce0ad79c486cb1fb504af04f953c3466b0c6db8", + "name": "quote4", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.35.0", + "inherited": true, + "configFile": "lakefile.toml"}, + {"url": "https://github.com/abdoo8080/lean-cvc5.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d19a134c237ec7f0cb86c2027062eedeb577a9a9", + "name": "cvc5", + "manifestFile": "lake-manifest.json", + "inputRev": "d19a134", + "inherited": true, + "configFile": "lakefile.lean"}, + {"url": "https://github.com/leanprover-community/lean-auto.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "30f46ddb9a68d6878f5a1337eb2565ba4e70126b", + "name": "auto", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.35.0", + "inherited": true, + "configFile": "lakefile.lean"}], + "name": "verify_reconstruct", + "lakeDir": ".lake", + "fixedToolchain": false} diff --git a/Verify/Reconstruct/lakefile.lean b/Verify/Reconstruct/lakefile.lean new file mode 100644 index 00000000..85fbdd48 --- /dev/null +++ b/Verify/Reconstruct/lakefile.lean @@ -0,0 +1,16 @@ +import Lake +open Lake DSL + +-- cvc5 proof reconstruction for exported VCs (`vc_smt`, Tactic.lean), a package of its own so +-- that building solidity-lean fetches no solver. It builds the obligation and discharge +-- modules from this repository's sources (srcDir "../..") rather than requiring the root +-- package, whose Mathlib and EVM dependencies it does not need. +require smt from git "https://github.com/ufmg-smite/lean-smt.git" @ "6b26285ece45e38fc0d21809b944522233039829" + +package verify_reconstruct where + leanOptions := #[⟨`maxHeartbeats, (200000 : Nat)⟩, ⟨`backward.do.legacy, false⟩] + +@[default_target] +lean_lib VerifyReconstruct where + srcDir := "../.." + roots := #[`Verify.Obligation, `Verify.Discharge, `Verify.Reconstruct.Tactic] diff --git a/Verify/Reconstruct/lean-toolchain b/Verify/Reconstruct/lean-toolchain new file mode 100644 index 00000000..a6aff065 --- /dev/null +++ b/Verify/Reconstruct/lean-toolchain @@ -0,0 +1 @@ +leanprover/lean4:v4.35.0 diff --git a/Verify/Run.lean b/Verify/Run.lean new file mode 100644 index 00000000..8f2c485a --- /dev/null +++ b/Verify/Run.lean @@ -0,0 +1,132 @@ +import Verify.Abi + +/-! +# Running a call from a given storage + +The wide refinement proofs run SolidCore on calls from empty storage (`Wide.run_eq`). A +specification over a contract whose constructor leaves storage, such as c4's packed +`uint8 w = 7`, runs from that storage instead: on `callAt sel ws s`, the call of selector +`sel` on the free argument words `ws` from the storage `s`, which `Wide.run_eq_at` rewrites +to the ABI dispatcher of the core contract on the deployed state with `s` written over its +storage, for `src_symex` to evaluate. `callAt`, `deployedAt` and `run_eq_at` live in +`SolidCore.Refinement.Wide`, which the refinement proofs from a given storage share. + +`implements_of_run` turns one theorem per function on free words into `Implements` on +`Abi.fullScope`. `vcs_of_fullScope` states the verification conditions on `Abi.fullScope` +call by call, with the argument words and the initial storage known, the form `sc_vcgen` +proves. +-/ + +namespace SolidCore.Verify + +open EthLib.Base SolidCore.Refinement SolidCore.Refinement.Abi SolidCore.Refinement.Wide +open SolidCore.Refinement.Evm.Wide SolidCore.Solidity SolidCore.Solidity.Source + +/-- One theorem per function, on free argument words that meet `ok`, gives `Implements` on +the calls of `Abi.fullScope` whose argument words meet `ok`. -/ +theorem implements_of_run {fuel : Nat} {c : TypeCheck.CheckedContract} {fns : List Fn} + {s : List (Nat × Nat)} {n : Nat} {ok : List Nat → Prop} {model : List Nat → SolM (List Nat)} + (hn : ∀ fn ∈ fns, fn.params.length = n) + (h : ∀ fn ∈ fns, ∀ ws : List U256, ws.length = n → ok (ws.map BitVec.toNat) → + Source.run fuel c (callAt fn.sel ws s) = + some (observe (slotValue s) (model (ws.map BitVec.toNat) (slotValue s)))) : + Implements fuel c (fun call => fullScope fns s call ∧ ok (argWords n call)) (argWords n) + model := by + rintro _ ⟨⟨fn, hfn, args, hlen, hargs, rfl⟩, hok⟩ + rw [hn fn hfn] at hlen + have hw : argWords n ({ calldata := Abi.calldata fn.sel args, callvalue := 0, storage := s } : + Call) = args := hlen ▸ argWords_calldata _ args hargs 0 s + have hws := map_ofNat_toNat args hargs + rw [hw] at hok ⊢ + have := h fn hfn (args.map (BitVec.ofNat 256)) (by simpa using hlen) (by rw [hws]; exact hok) + rw [hws, ← callAt_of_args _ _ hargs] at this + exact this + +/-- `implements_of_run` with no condition on the argument words. -/ +theorem implements_of_run' {fuel : Nat} {c : TypeCheck.CheckedContract} {fns : List Fn} + {s : List (Nat × Nat)} {n : Nat} {model : List Nat → SolM (List Nat)} + (hn : ∀ fn ∈ fns, fn.params.length = n) + (h : ∀ fn ∈ fns, ∀ ws : List U256, ws.length = n → + Source.run fuel c (callAt fn.sel ws s) = + some (observe (slotValue s) (model (ws.map BitVec.toNat) (slotValue s)))) : + Implements fuel c (fullScope fns s) (argWords n) model := fun call hs => + implements_of_run (ok := fun _ => True) hn (fun fn hfn ws hl _ => h fn hfn ws hl) call + ⟨hs, trivial⟩ + +/-- `Implements` on a scope holds on every smaller one. -/ +theorem Implements.mono {fuel : Nat} {c : TypeCheck.CheckedContract} {scope scope' : Call → Prop} + {args : Call → List Nat} {model : List Nat → SolM (List Nat)} + (h : Implements fuel c scope args model) (hs : ∀ call, scope' call → scope call) : + Implements fuel c scope' args model := fun call hc => h call (hs call hc) + +/-- The verification conditions on `Abi.fullScope`, call by call: for each function and each +list of argument words, with the call, its argument words and its initial storage known. -/ +theorem vcs_of_fullScope {fns : List Fn} {s : List (Nat × Nat)} {n : Nat} + {model : List Nat → SolM (List Nat)} {pre : Call → Prop} {post : Call → Observable → Prop} + (hn : ∀ fn ∈ fns, fn.params.length = n) + (h : ∀ fn ∈ fns, ∀ call args, + call = ({ calldata := Abi.calldata fn.sel args, callvalue := 0, storage := s } : Call) → + argWords n call = args → args.length = n → (∀ a ∈ args, a < 2 ^ 256) → + initStorage call = slotValue s → pre call → + wp (model args) + (fun out _ s' => post call { success := true, output := out, logs := [], storage := s' }) + (fun e => post call { success := false, output := e, logs := [], storage := slotValue s }) + (slotValue s)) : + ∀ call, fullScope fns s call → pre call → vc model (argWords n) post call := by + rintro _ ⟨fn, hfn, args, hlen, hargs, rfl⟩ hpre + rw [hn fn hfn] at hlen + have hw : argWords n ({ calldata := Abi.calldata fn.sel args, callvalue := 0, storage := s } : + Call) = args := hlen ▸ argWords_calldata _ args hargs 0 s + have := h fn hfn _ args rfl hw hlen hargs rfl hpre + simp only [vc, hw] + exact this + +/-- The verification conditions on a smaller scope follow from those on a larger one. -/ +theorem vcs_mono {scope scope' pre : Call → Prop} {model : List Nat → SolM (List Nat)} + {args : Call → List Nat} {post : Call → Observable → Prop} + (h : ∀ call, scope call → pre call → vc model args post call) + (hs : ∀ call, scope' call → scope call) : + ∀ call, scope' call → pre call → vc model args post call := fun call hc hp => + h call (hs call hc) hp + +/-- A slot of a storage map after the entries `σ` are written over it, as the last write of the +slot or the map's own entry. -/ +theorem getElem?_foldl_insertLoop (σ : List (Nat × Nat)) (m0 : StorageMap) (q : Nat) : + (σ.foldl (fun acc kv => acc.insertLoop kv.1 kv.2) m0)[q]? = + σ.foldl (fun acc kv => if Shared.norm kv.1 = q then some (Shared.norm kv.2) else acc) + m0[q]? := by + induction σ generalizing m0 with + | nil => rfl + | cons kv σ ih => + simp only [List.foldl_cons] + rw [ih] + simp only [StorageMap.insertLoop, Std.HashMap.getElem?_insert, beq_iff_eq] + +/-- The last write of a slot among `σ`, as a word, is `slotValue`'s fold. -/ +theorem getD_foldl (σ : List (Nat × Nat)) (k : Nat) (a : Option Nat) (b : Nat) (h : a.getD 0 = b) : + (σ.foldl (fun acc kv => if Shared.norm kv.1 = k % 2 ^ 256 then some (Shared.norm kv.2) else acc) + a).getD 0 = + σ.foldl (fun acc kv => if kv.1 % 2 ^ 256 = k % 2 ^ 256 then kv.2 % 2 ^ 256 else acc) b := by + induction σ generalizing a b with + | nil => simpa using h + | cons kv σ ih => + simp only [List.foldl_cons] + apply ih + simp only [Shared.norm, Shared.wordModulus, EvmYul.UInt256.size, Nat.reducePow] + split <;> simp_all + +/-- A slot of the storage a call writes over an empty deployed storage reads as `slotValue`. -/ +theorem getD_storage {m0 : StorageMap} (h0 : ∀ q : Nat, m0[q]? = none) (σ : List (Nat × Nat)) + (k : Nat) : + ((σ.foldl (fun acc kv => acc.insertLoop kv.1 kv.2) m0)[k % 2 ^ 256]?).getD 0 = + slotValue σ k := by + rw [getElem?_foldl_insertLoop, h0] + exact getD_foldl σ k none 0 rfl + +/-- A constructor that leaves no storage leaves exactly the empty list of entries. -/ +theorem deployedAt_of_deployed {fuel : Nat} {c : TypeCheck.CheckedContract} {d : Source.State} + (hd : Deployed fuel c d) : DeployedAt fuel c d [] := + ⟨hd.cons, by + exact List.isEmpty_iff.mp (by rw [Std.HashMap.isEmpty_toList]; exact hd.storage), hd.events⟩ + +end SolidCore.Verify diff --git a/Verify/Spec/Contract.lean b/Verify/Spec/Contract.lean new file mode 100644 index 00000000..9eb6515d --- /dev/null +++ b/Verify/Spec/Contract.lean @@ -0,0 +1,186 @@ +import Verify.Spec.Semantics + +/-! +# A function's spec over a call and its observable + +`Pre` and `Post` are a function's spec as predicates over a `SolarTV.Call` and the +`SolarTV.Observable` it finishes with, given the call's environment (`Ctx`), the ghost state before +and after it and `__time` before it. `Holds` says that every function's spec holds of a program in +a semantics. Because SolidCore (`SolidCore.Refinement.solidCore`) and EthLib +(`SolidCore.Refinement.ethLib`) are both `SolarTV.Sem`s over the same calls and observables, the +same `Holds` states the spec of the source and of the bytecode, and a refinement between them +carries one to the other (`Holds.of_stage`). + +The meaning follows solar-verify's (crates/verify/README.md, "Semantics"): + +* the requires and the contract invariants are assumed of the pre-state, with `__time` the time + before the call, at most the block's timestamp; +* a successful call returns ABI-clean words of the return types, and the ensures and the + invariants hold of the post-state, in which `__time` is the block's timestamp; +* a reverted call owes nothing, since it has no effect (the semantics' failure convention); +* from a pre-state meeting the succeeds-if conditions (and the requires), the call succeeds. +-/ + +namespace SolidCore.Spec + +open SolarTV + +/-- The 32-byte big-endian words of a byte list (a short last word is dropped). -/ +def words (bs : List Nat) : List Nat := + (List.range (bs.length / 32)).map fun i => bytesWord ((bs.drop (32 * i)).take 32) + +/-- Decode words as values of the types, or `none` when there are too few or one is not clean. -/ +def decodeWords : List Ty → List Nat → Option (List Int) + | [], _ => some [] + | _ :: _, [] => none + | t :: ts, w :: ws => do + let v ← t.ofWord w + let vs ← decodeWords ts ws + pure (v :: vs) + +/-- The selector of a call: its first four bytes. -/ +def selectorOf (call : Call) : Nat := bytesWord ((call.calldata.data.toList.map (·.toNat)).take 4) + +/-- The call is to `fs`, with arguments `args`: the selector matches and the argument words are +clean for the parameter types. -/ +def Decodes (fs : FnSpec) (call : Call) (args : List Int) : Prop := + 4 ≤ call.calldata.size ∧ selectorOf call = fs.selector ∧ + decodeWords fs.params (words ((call.calldata.data.toList.map (·.toNat)).drop 4)) = some args + +/-- The environment of a spec expression on a call. -/ +def mkEnv (ctx : Ctx) (args rets : List Int) (pre post : State) : Env := + { args, rets, pre, post, ctx, vars := [], inOld := false } + +/-- The spec of a contract's functions, with `fuel` the bound on nested spec function calls. -/ +structure Bundle where + spec : ContractSpec + fuel : Nat + +/-- A formula of the bundle holds in an environment. -/ +def Bundle.sat (b : Bundle) (t : Term) (e : Env) : Prop := eval b.spec.fns b.fuel t e ≠ 0 + +/-- Every formula of a list holds. -/ +def Bundle.satAll (b : Bundle) (ts : List Term) (e : Env) : Prop := ∀ t ∈ ts, b.sat t e + +/-- The precondition of `fs` on `call` from the state `pre`: the arguments decode, `pre` is the +call's storage, `__time` is at most the block's timestamp, and the requires and invariants hold. -/ +def Pre (b : Bundle) (fs : FnSpec) (ctx : Ctx) (pre : State) (call : Call) (args : List Int) : + Prop := + Decodes fs call args ∧ pre.storage = slotValue call.storage ∧ pre.time ≤ ctx.timestamp ∧ + b.satAll fs.requires (mkEnv ctx args [] pre pre) ∧ + b.satAll b.spec.invariants (mkEnv ctx args [] pre pre) + +/-- The postcondition of `fs` on `call` from `pre`, finishing with `obs` and the ghost state +`ghost'`: a success returns clean words meeting the ensures and leaves a state meeting the +invariants; when `fs` has succeeds-if conditions, from a pre-state meeting them the call +succeeds. A function without any makes no claim that it succeeds, as in solar-verify, whose +export then writes `succeedsIf := []`. -/ +def Post (b : Bundle) (fs : FnSpec) (ctx : Ctx) (pre : State) (ghost' : Ghost) (obs : Observable) + (args : List Int) : Prop := + let post : State := { storage := obs.storage, ghost := ghost', time := ctx.timestamp } + (obs.success = true → ∃ rets, decodeWords fs.rets (words obs.output) = some rets ∧ + b.satAll fs.ensures (mkEnv ctx args rets pre post) ∧ + b.satAll b.spec.invariants (mkEnv ctx args rets post post)) ∧ + (fs.succeedsIf ≠ [] → b.satAll fs.succeedsIf (mkEnv ctx args [] pre pre) → obs.success = true) + +/-- The ghost state after a call, from the call and the ghost state before it. -/ +abbrev GhostStep := Call → Ghost → Ghost + +/-- `fs`'s spec holds of `p` in `S` on `scope`: every call of the scope to `fs` from a pre-state +meeting `Pre` finishes, with an observable meeting `Post`. -/ +def HoldsFn (S : Sem) (p : S.Prog) (scope : Call → Prop) (b : Bundle) (ctxOf : Call → Ctx) + (step : GhostStep) (fs : FnSpec) : Prop := + ∀ call, scope call → ∀ (args : List Int) (pre : State), Pre b fs (ctxOf call) pre call args → + ∃ obs, S.run p call = some obs ∧ Post b fs (ctxOf call) pre (step call pre.ghost) obs args + +/-- Every function's spec holds of `p`. -/ +def Holds (S : Sem) (p : S.Prog) (scope : Call → Prop) (b : Bundle) (ctxOf : Call → Ctx) + (step : GhostStep) : Prop := + ∀ fs ∈ b.spec.specs, HoldsFn S p scope b ctxOf step fs + +/-- A refinement carries a spec from source to target: a stage from `S` to `T` preserves every +observable `p` finishes with, and `Post` speaks only of the observable. -/ +theorem HoldsFn.of_stage {S T : Sem} {p : S.Prog} {q : T.Prog} {scope : Call → Prop} + {b : Bundle} {ctxOf : Call → Ctx} {step : GhostStep} {fs : FnSpec} + (h : HoldsFn S p scope b ctxOf step fs) (st : Stage S T p q scope) : + HoldsFn T q scope b ctxOf step fs := by + intro call hs args pre hpre + obtain ⟨obs, hrun, hpost⟩ := h call hs args pre hpre + exact ⟨obs, st call hs obs hrun, hpost⟩ + +theorem Holds.of_stage {S T : Sem} {p : S.Prog} {q : T.Prog} {scope : Call → Prop} + {b : Bundle} {ctxOf : Call → Ctx} {step : GhostStep} + (h : Holds S p scope b ctxOf step) (st : Stage S T p q scope) : + Holds T q scope b ctxOf step := + fun fs hfs => (h fs hfs).of_stage st + +/-- A spec holds on any narrower scope. -/ +theorem HoldsFn.mono {S : Sem} {p : S.Prog} {scope narrower : Call → Prop} {b : Bundle} + {ctxOf : Call → Ctx} {step : GhostStep} {fs : FnSpec} (h : HoldsFn S p scope b ctxOf step fs) + (hn : ∀ call, narrower call → scope call) : HoldsFn S p narrower b ctxOf step fs := + fun call hc => h call (hn call hc) + +/-! ## Checked obligations -/ + +/-- Every spec function call of the bundle resolves and nests within its fuel, and every spec +function's body does too. Computable: the kernel checks it of an exported bundle by `decide`. -/ +def Bundle.WF (b : Bundle) : Bool := + (b.spec.specs.all fun fs => + Term.ClosedList b.spec.fns b.fuel fs.requires && + Term.ClosedList b.spec.fns b.fuel fs.ensures && + Term.ClosedList b.spec.fns b.fuel fs.succeedsIf) && + Term.ClosedList b.spec.fns b.fuel b.spec.invariants + +/-- Every opaque spec function's body takes values in its return type's range, at every depth +up to the fuel and in every environment: the range solar-verify assumes of an opaque +application, so that its proofs, which hold for every function in that range, hold for this one. -/ +def OpaqueInRange (b : Bundle) : Prop := + ∀ f ∈ b.spec.fns, f.isOpaque = true → ∀ k ≤ b.fuel, ∀ e, f.ret.InRange (eval b.spec.fns k f.body e) + +theorem opaqueInRange_of_none {b : Bundle} (h : b.spec.fns.all (fun f => !f.isOpaque) = true) : + OpaqueInRange b := by + intro f hf ho + have := List.all_eq_true.mp h f hf + simp [ho] at this + +/-! ## Ghost-free specs -/ + +mutual +/-- One level of `Term.GhostFree`: `t` reads no ghost variable, and `k` holds of the bodies of the +spec functions it calls. -/ +def Term.ghostFreeWith (fns : List SpecFn) (k : Term → Bool) : Term → Bool + | .ghost _ _ => false + | .load p off _ _ => Place.ghostFreeWith fns k p && Term.ghostFreeWith fns k off + | .len p => Place.ghostFreeWith fns k p + | .old t | .un _ t | .shl t _ | .shr t _ | .all _ _ t | .ex _ _ t => Term.ghostFreeWith fns k t + | .bin _ a b => Term.ghostFreeWith fns k a && Term.ghostFreeWith fns k b + | .ite c a b => Term.ghostFreeWith fns k c && Term.ghostFreeWith fns k a && Term.ghostFreeWith fns k b + | .call f args => + Term.ghostFreeListWith fns k args && + match fns.find? (·.name == f) with + | some sf => k sf.body + | none => true + | .lit _ | .arg _ | .ret _ | .var _ | .env _ => true + +def Term.ghostFreeListWith (fns : List SpecFn) (k : Term → Bool) : List Term → Bool + | [] => true + | t :: ts => Term.ghostFreeWith fns k t && Term.ghostFreeListWith fns k ts + +def Place.ghostFreeWith (fns : List SpecFn) (k : Term → Bool) : Place → Bool + | .slot _ => true + | .offset b i | .entry b i | .elem b i _ | .packedElem b i _ => + Place.ghostFreeWith fns k b && Term.ghostFreeWith fns k i +end + +/-- `t` reads no ghost variable, through spec function calls nested at most `fuel` deep. -/ +def Term.GhostFree (fns : List SpecFn) : Nat → Term → Bool + | 0 => Term.ghostFreeWith fns fun _ => true + | n + 1 => Term.ghostFreeWith fns (Term.GhostFree fns n) + +/-- Two environments that differ only in their ghost states. -/ +def Env.ghostEquiv (e e' : Env) : Prop := + e.args = e'.args ∧ e.rets = e'.rets ∧ e.ctx = e'.ctx ∧ e.vars = e'.vars ∧ e.inOld = e'.inOld ∧ + e.pre.storage = e'.pre.storage ∧ e.pre.time = e'.pre.time ∧ + e.post.storage = e'.post.storage ∧ e.post.time = e'.post.time + +end SolidCore.Spec diff --git a/Verify/Spec/Ghost.lean b/Verify/Spec/Ghost.lean new file mode 100644 index 00000000..7402319f --- /dev/null +++ b/Verify/Spec/Ghost.lean @@ -0,0 +1,635 @@ +/-! +# Ghost erasure + +solar-verify proves a contract together with its ghost code: `@custom:ghost x = e` updates, +`@custom:assert` and `@custom:assume`, and the lemmas `@custom:use` applies. The bytecode runs +without any of it: NatSpec is a comment to the compiler. A proof with ghost code is a proof of the +deployed program only if erasing the ghost code leaves every real execution as it was. +solar-verify checks the discipline of Filliâtre, Gondelman and Paskevich, "The Spirit of Ghost +Code" (CAV 2014), before it verifies anything (crates/verify/src/ghost.rs, README "Ghost code"): + +1. ghost code writes only ghost variables (it may read real ones); +2. ghost code never reverts, and no ghost condition decides a real write; +3. ghost code terminates; +4. real code never reads a ghost variable. + +This module proves that the discipline suffices, for a core statement language with that shape: +assignments, `require`, sequencing, conditionals and loops over real and ghost variables of one +store, ghost updates, `assert` and `assume`. `WF` is rules 1, 2 and 4 as a boolean check on the +syntax, as ghost.rs grades variables; rule 3 is `GhostTotal`, that every piece of ghost code +finishes from every state (solar-verify proves it through `@custom:decreases` variants and its +syntactic rules; `ghostTotal_of_straight` proves it here for ghost code without loops or assumes). + +* `sound`: every instrumented execution that does not fail an assertion is, on the real + variables, an execution of the erased program. +* `complete`: every execution of the erased program is, on the real variables, an instrumented + execution from any ghost state, or one that fails an assertion. +* `spec_of_erased`: a property proved of every instrumented execution, with no failing + assertion, holds of every execution of the erased program, with some ghost state. + +What this module leaves to solar-verify's encoding (crates/verify/src/vc.rs, a named hypothesis of +the final theorem, `SolidCore.Spec.TrustedBase`): that its model of a Solidity function is the +instrumented program of this language whose erasure is the function SolidCore runs. +-/ + +namespace SolidCore.Spec.Ghost + +/-- One store of real and ghost variables. -/ +abbrev Store := String → Int + +/-- Expressions over the store. -/ +inductive Exp where + | lit (v : Int) + | var (x : String) + | un (f : Int → Int) (a : Exp) + | bin (f : Int → Int → Int) (a b : Exp) + +/-- An expression's value. -/ +def Exp.eval (σ : Store) : Exp → Int + | .lit v => v + | .var x => σ x + | .un f a => f (a.eval σ) + | .bin f a b => f (a.eval σ) (b.eval σ) + +/-- The variables an expression reads. -/ +def Exp.vars : Exp → List String + | .lit _ => [] + | .var x => [x] + | .un _ a => a.vars + | .bin _ a b => a.vars ++ b.vars + +/-- Statements: real code (`assign`, `require`), ghost code (`ghost`, `assert`, `assume`), and the +control flow both share. -/ +inductive Stmt where + | skip + | assign (x : String) (e : Exp) + | require (e : Exp) + | seq (s t : Stmt) + | ite (c : Exp) (s t : Stmt) + | loop (c : Exp) (body : Stmt) + /-- `@custom:ghost x = e`. -/ + | ghost (x : String) (e : Exp) + /-- `@custom:assert e`: proved, so a failure is a failed proof. -/ + | assert (e : Exp) + /-- `@custom:assume e` (and a lemma's ensures, or a trusted contract): an execution where it + does not hold does not exist. -/ + | assume (e : Exp) + +/-- What a statement finishes with: normally, by reverting (which undoes everything, so no +store), or by failing an assertion. -/ +inductive Out where + | ok (σ : Store) + | rev + | fail + +/-- Update a variable. -/ +def Store.set (σ : Store) (x : String) (v : Int) : Store := fun y => if y = x then v else σ y + +/-- Big-step semantics. A loop that does not terminate, and an `assume` that does not hold, have +no execution. -/ +inductive Exec : Stmt → Store → Out → Prop where + | skip : Exec .skip σ (.ok σ) + | assign : Exec (.assign x e) σ (.ok (σ.set x (e.eval σ))) + | requireOk : e.eval σ ≠ 0 → Exec (.require e) σ (.ok σ) + | requireRev : e.eval σ = 0 → Exec (.require e) σ .rev + | seqOk : Exec s σ (.ok σ') → Exec t σ' o → Exec (.seq s t) σ o + | seqRev : Exec s σ .rev → Exec (.seq s t) σ .rev + | seqFail : Exec s σ .fail → Exec (.seq s t) σ .fail + | iteT : c.eval σ ≠ 0 → Exec s σ o → Exec (.ite c s t) σ o + | iteF : c.eval σ = 0 → Exec t σ o → Exec (.ite c s t) σ o + | loopDone : c.eval σ = 0 → Exec (.loop c b) σ (.ok σ) + | loopOk : c.eval σ ≠ 0 → Exec b σ (.ok σ') → Exec (.loop c b) σ' o → Exec (.loop c b) σ o + | loopRev : c.eval σ ≠ 0 → Exec b σ .rev → Exec (.loop c b) σ .rev + | loopFail : c.eval σ ≠ 0 → Exec b σ .fail → Exec (.loop c b) σ .fail + | ghost : Exec (.ghost x e) σ (.ok (σ.set x (e.eval σ))) + | assertOk : e.eval σ ≠ 0 → Exec (.assert e) σ (.ok σ) + | assertFail : e.eval σ = 0 → Exec (.assert e) σ .fail + | assume : e.eval σ ≠ 0 → Exec (.assume e) σ (.ok σ) + +section +variable (isGhost : String → Bool) + +/-- The expression reads no ghost variable. -/ +def Exp.real (e : Exp) : Bool := e.vars.all fun x => !isGhost x + +/-- Ghost code: statements made only of ghost updates of ghost variables, assertions and +assumptions, under any control flow. -/ +def Stmt.ghostCode : Stmt → Bool + | .skip | .assert _ | .assume _ => true + | .ghost x _ => isGhost x + | .assign _ _ | .require _ => false + | .seq s t | .ite _ s t => s.ghostCode && t.ghostCode + | .loop _ b => b.ghostCode + +/-- Erase the ghost code. -/ +def Stmt.erase : Stmt → Stmt + | s@(.seq a b) => if s.ghostCode isGhost then .skip else .seq (a.erase) (b.erase) + | s@(.ite c a b) => if s.ghostCode isGhost then .skip else .ite c (a.erase) (b.erase) + | s@(.loop c b) => if s.ghostCode isGhost then .skip else .loop c (b.erase) + | s => if s.ghostCode isGhost then .skip else s + +/-- The discipline, as a check on the syntax: real assignments write real variables from real +values (rules 1 and 4), `require` and every real condition read only real variables (rules 2 +and 4), and ghost updates write ghost variables (rule 1). Ghost code has no `require` and no real +assignment by `ghostCode` (rule 2). -/ +def Stmt.WF : Stmt → Bool + | .skip | .assert _ | .assume _ => true + | .ghost x _ => isGhost x + | .assign x e => !isGhost x && e.real isGhost + | .require e => e.real isGhost + | .seq s t => s.WF && t.WF + | s@(.ite c a b) => s.ghostCode isGhost || (c.real isGhost && a.WF && b.WF) + | s@(.loop c b) => s.ghostCode isGhost || (c.real isGhost && b.WF) + +/-- Two stores agree on the real variables. -/ +def Agree (σ τ : Store) : Prop := ∀ x, isGhost x = false → σ x = τ x + +/-- Two outcomes agree on the real variables. -/ +def OutAgree : Out → Out → Prop + | .ok σ, .ok τ => Agree isGhost σ τ + | .rev, .rev => True + | .fail, .fail => True + | _, _ => False + +/-- Rule 3: every piece of ghost code finishes from every state (perhaps failing an assertion). -/ +def GhostTotal : Stmt → Prop + | s@(.seq a b) | s@(.ite _ a b) => + (s.ghostCode isGhost = true → ∀ σ, ∃ o, Exec s σ o) ∧ GhostTotal a ∧ GhostTotal b + | s@(.loop _ b) => (s.ghostCode isGhost = true → ∀ σ, ∃ o, Exec s σ o) ∧ GhostTotal b + | s => s.ghostCode isGhost = true → ∀ σ, ∃ o, Exec s σ o +end + +/-! ## Lemmas -/ + +variable {isGhost : String → Bool} + +theorem Agree.refl (σ : Store) : Agree isGhost σ σ := fun _ _ => rfl + +theorem Agree.symm {σ τ : Store} (h : Agree isGhost σ τ) : Agree isGhost τ σ := + fun x hx => (h x hx).symm + +theorem Agree.trans {σ τ υ : Store} (h : Agree isGhost σ τ) (h' : Agree isGhost τ υ) : + Agree isGhost σ υ := fun x hx => (h x hx).trans (h' x hx) + +theorem Agree.set {σ τ : Store} (h : Agree isGhost σ τ) (x : String) (v : Int) : + Agree isGhost (σ.set x v) (τ.set x v) := by + intro y hy + simp only [Store.set] + split + · rfl + · exact h y hy + +theorem Agree.set_ghost {σ : Store} {x : String} (hx : isGhost x = true) (v : Int) : + Agree isGhost (σ.set x v) σ := by + intro y hy + simp only [Store.set] + split + · subst_vars; simp_all + · rfl + +theorem Exp.eval_agree {σ τ : Store} (h : Agree isGhost σ τ) : + ∀ e : Exp, e.real isGhost = true → e.eval σ = e.eval τ + | .lit _, _ => rfl + | .var x, he => by + simp [Exp.real, Exp.vars] at he + exact h x he + | .un f a, he => by + simp only [Exp.real, Exp.vars] at he + simp only [Exp.eval, Exp.eval_agree h a he] + | .bin f a b, he => by + simp only [Exp.real, Exp.vars, List.all_append, Bool.and_eq_true] at he + simp only [Exp.eval, Exp.eval_agree h a he.1, Exp.eval_agree h b he.2] + +/-- Ghost code changes no real variable and never reverts. -/ +theorem ghostCode_exec {s : Stmt} {σ : Store} {o : Out} (hx : Exec s σ o) + (hg : s.ghostCode isGhost = true) : + o = .fail ∨ ∃ σ', o = .ok σ' ∧ Agree isGhost σ' σ := by + induction hx with + | skip => exact .inr ⟨_, rfl, Agree.refl _⟩ + | assign => simp [Stmt.ghostCode] at hg + | requireOk => simp [Stmt.ghostCode] at hg + | requireRev => simp [Stmt.ghostCode] at hg + | seqOk _ _ ih1 ih2 => + simp only [Stmt.ghostCode, Bool.and_eq_true] at hg + rcases ih1 hg.1 with h | ⟨σ1, h1, a1⟩ + · cases h + · cases h1 + rcases ih2 hg.2 with h | ⟨σ2, h2, a2⟩ + · exact .inl h + · exact .inr ⟨σ2, h2, a2.trans a1⟩ + | seqRev _ ih => + simp only [Stmt.ghostCode, Bool.and_eq_true] at hg + rcases ih hg.1 with h | ⟨_, h, _⟩ <;> cases h + | seqFail => exact .inl rfl + | iteT _ _ ih => + simp only [Stmt.ghostCode, Bool.and_eq_true] at hg + exact ih hg.1 + | iteF _ _ ih => + simp only [Stmt.ghostCode, Bool.and_eq_true] at hg + exact ih hg.2 + | loopDone => exact .inr ⟨_, rfl, Agree.refl _⟩ + | loopOk _ _ _ ih1 ih2 => + rcases ih1 hg with h | ⟨σ1, h1, a1⟩ + · cases h + · cases h1 + rcases ih2 hg with h | ⟨σ2, h2, a2⟩ + · exact .inl h + · exact .inr ⟨σ2, h2, a2.trans a1⟩ + | loopRev _ _ ih => + rcases ih hg with h | ⟨_, h, _⟩ <;> cases h + | loopFail => exact .inl rfl + | ghost => exact .inr ⟨_, rfl, Agree.set_ghost (by simpa [Stmt.ghostCode] using hg) _⟩ + | assertOk => exact .inr ⟨_, rfl, Agree.refl _⟩ + | assertFail => exact .inl rfl + | assume => exact .inr ⟨_, rfl, Agree.refl _⟩ + +theorem erase_of_ghostCode {s : Stmt} (hg : s.ghostCode isGhost = true) : + s.erase isGhost = .skip := by + cases s <;> simp_all [Stmt.erase] + +theorem erase_of_not_ghostCode {s : Stmt} (hg : s.ghostCode isGhost = false) : + s.erase isGhost = match s with + | .seq a b => .seq (a.erase isGhost) (b.erase isGhost) + | .ite c a b => .ite c (a.erase isGhost) (b.erase isGhost) + | .loop c b => .loop c (b.erase isGhost) + | s => s := by + cases s <;> simp_all [Stmt.erase] + +/-! ## Soundness: instrumented executions are executions of the erased program -/ + +/-- **Soundness of erasure.** An instrumented execution of a well-formed program that does not +fail an assertion is, from any store agreeing on the real variables, an execution of the erased +program agreeing on the real variables. -/ +theorem sound {s : Stmt} {σ : Store} {o : Out} (hx : Exec s σ o) (hwf : s.WF isGhost = true) + (hnf : o ≠ .fail) : ∀ τ, Agree isGhost σ τ → + ∃ o', Exec (s.erase isGhost) τ o' ∧ OutAgree isGhost o o' := by + induction hx with + | skip => intro τ h; exact ⟨.ok τ, by simp [Stmt.erase, Stmt.ghostCode]; exact .skip, h⟩ + | @assign x e σ => + intro τ h + simp only [Stmt.WF, Bool.and_eq_true, Bool.not_eq_true'] at hwf + have he : (Stmt.assign x e).erase isGhost = .assign x e := by simp [Stmt.erase, Stmt.ghostCode] + rw [he] + refine ⟨_, .assign, ?_⟩ + show Agree isGhost _ _ + rw [Exp.eval_agree h e hwf.2] + exact h.set x _ + | @requireOk e σ hc => + intro τ h + simp only [Stmt.WF] at hwf + have he : (Stmt.require e).erase isGhost = .require e := by simp [Stmt.erase, Stmt.ghostCode] + rw [he] + exact ⟨.ok τ, .requireOk (by rwa [← Exp.eval_agree h e hwf]), h⟩ + | @requireRev e σ hc => + intro τ h + simp only [Stmt.WF] at hwf + have he : (Stmt.require e).erase isGhost = .require e := by simp [Stmt.erase, Stmt.ghostCode] + rw [he] + exact ⟨_, .requireRev (by rwa [← Exp.eval_agree h e hwf]), trivial⟩ + | @seqOk a σ σ1 b o h1 h2 ih1 ih2 => + intro τ h + simp only [Stmt.WF, Bool.and_eq_true] at hwf + cases hg : (Stmt.seq a b).ghostCode isGhost + · rw [erase_of_not_ghostCode hg] + obtain ⟨o1, e1, a1⟩ := ih1 hwf.1 (by simp) τ h + cases o1 with + | ok τ1 => + obtain ⟨o2, e2, a2⟩ := ih2 hwf.2 hnf τ1 a1 + exact ⟨o2, .seqOk e1 e2, a2⟩ + | rev => exact absurd a1 (by simp [OutAgree]) + | fail => exact absurd a1 (by simp [OutAgree]) + · rw [erase_of_ghostCode hg] + rcases ghostCode_exec (.seqOk h1 h2) hg with hf | ⟨σ', ho, ha⟩ + · exact absurd hf hnf + · subst ho; exact ⟨.ok τ, .skip, ha.trans h⟩ + | @seqRev a σ b h1 ih => + intro τ h + simp only [Stmt.WF, Bool.and_eq_true] at hwf + cases hg : (Stmt.seq a b).ghostCode isGhost + · rw [erase_of_not_ghostCode hg] + obtain ⟨o1, e1, a1⟩ := ih hwf.1 (by simp) τ h + cases o1 with + | rev => exact ⟨_, .seqRev e1, trivial⟩ + | ok _ => exact absurd a1 (by simp [OutAgree]) + | fail => exact absurd a1 (by simp [OutAgree]) + · rcases ghostCode_exec (.seqRev (t := b) h1) hg with hf | ⟨σ', ho, _⟩ + · cases hf + · cases ho + | seqFail => exact absurd rfl hnf + | @iteT a σ o c b hc h1 ih => + intro τ h + cases hg : (Stmt.ite c a b).ghostCode isGhost + · rw [erase_of_not_ghostCode hg] + simp only [Stmt.WF, hg, Bool.false_or, Bool.and_eq_true] at hwf + obtain ⟨o1, e1, a1⟩ := ih hwf.1.2 hnf τ h + exact ⟨o1, .iteT (by rwa [← Exp.eval_agree h c hwf.1.1]) e1, a1⟩ + · rw [erase_of_ghostCode hg] + rcases ghostCode_exec (.iteT (t := b) hc h1) hg with hf | ⟨σ', ho, ha⟩ + · exact absurd hf hnf + · subst ho; exact ⟨.ok τ, .skip, ha.trans h⟩ + | @iteF b σ o c a hc h1 ih => + intro τ h + cases hg : (Stmt.ite c a b).ghostCode isGhost + · rw [erase_of_not_ghostCode hg] + simp only [Stmt.WF, hg, Bool.false_or, Bool.and_eq_true] at hwf + obtain ⟨o1, e1, a1⟩ := ih hwf.2 hnf τ h + exact ⟨o1, .iteF (by rwa [← Exp.eval_agree h c hwf.1.1]) e1, a1⟩ + · rw [erase_of_ghostCode hg] + rcases ghostCode_exec (.iteF (s := a) hc h1) hg with hf | ⟨σ', ho, ha⟩ + · exact absurd hf hnf + · subst ho; exact ⟨.ok τ, .skip, ha.trans h⟩ + | @loopDone c b σ hc => + intro τ h + cases hg : (Stmt.loop c b).ghostCode isGhost + · rw [erase_of_not_ghostCode hg] + simp only [Stmt.WF, hg, Bool.false_or, Bool.and_eq_true] at hwf + exact ⟨.ok τ, .loopDone (by rwa [← Exp.eval_agree h c hwf.1]), h⟩ + · rw [erase_of_ghostCode hg]; exact ⟨.ok τ, .skip, h⟩ + | @loopOk b σ σ1 c o hc h1 h2 ih1 ih2 => + intro τ h + cases hg : (Stmt.loop c b).ghostCode isGhost + · have hwf' := hwf + rw [erase_of_not_ghostCode hg] at ih2 ⊢ + simp only [Stmt.WF, hg, Bool.false_or, Bool.and_eq_true] at hwf + obtain ⟨o1, e1, a1⟩ := ih1 hwf.2 (by simp) τ h + cases o1 with + | ok τ1 => + obtain ⟨o2, e2, a2⟩ := ih2 hwf' hnf τ1 a1 + exact ⟨o2, .loopOk (by rwa [← Exp.eval_agree h c hwf.1]) e1 e2, a2⟩ + | rev => exact absurd a1 (by simp [OutAgree]) + | fail => exact absurd a1 (by simp [OutAgree]) + · rw [erase_of_ghostCode hg] + rcases ghostCode_exec (.loopOk hc h1 h2) hg with hf | ⟨σ', ho, ha⟩ + · exact absurd hf hnf + · subst ho; exact ⟨.ok τ, .skip, ha.trans h⟩ + | @loopRev b σ c hc h1 ih => + intro τ h + cases hg : (Stmt.loop c b).ghostCode isGhost + · rw [erase_of_not_ghostCode hg] + simp only [Stmt.WF, hg, Bool.false_or, Bool.and_eq_true] at hwf + obtain ⟨o1, e1, a1⟩ := ih hwf.2 (by simp) τ h + cases o1 with + | rev => exact ⟨_, .loopRev (by rwa [← Exp.eval_agree h c hwf.1]) e1, trivial⟩ + | ok _ => exact absurd a1 (by simp [OutAgree]) + | fail => exact absurd a1 (by simp [OutAgree]) + · rcases ghostCode_exec (.loopRev hc h1) hg with hf | ⟨σ', ho, _⟩ + · cases hf + · cases ho + | loopFail => exact absurd rfl hnf + | @ghost x e σ => + intro τ h + simp only [Stmt.WF] at hwf + have hg : (Stmt.ghost x e).ghostCode isGhost = true := by simpa [Stmt.ghostCode] using hwf + rw [erase_of_ghostCode hg] + exact ⟨.ok τ, .skip, (Agree.set_ghost hwf _).trans h⟩ + | assertOk => + intro τ h; exact ⟨.ok τ, by simp [Stmt.erase, Stmt.ghostCode]; exact .skip, h⟩ + | assertFail => exact absurd rfl hnf + | assume => + intro τ h; exact ⟨.ok τ, by simp [Stmt.erase, Stmt.ghostCode]; exact .skip, h⟩ + +/-! ## Completeness: every execution of the erased program is matched -/ + +theorem ghostTotal_here {s : Stmt} (ht : GhostTotal isGhost s) (hg : s.ghostCode isGhost = true) : + ∀ σ, ∃ o, Exec s σ o := by + cases s <;> simp only [GhostTotal] at ht + all_goals first | exact ht hg | exact ht.1 hg + +/-- **Completeness of erasure.** Every execution of the erased program of a well-formed program +whose ghost code terminates is matched, from any store agreeing on the real variables (any ghost +state), by an instrumented execution that agrees with it on the real variables or fails an +assertion. -/ +theorem complete : ∀ {s : Stmt}, s.WF isGhost = true → GhostTotal isGhost s → + ∀ {τ : Store} {o : Out}, Exec (s.erase isGhost) τ o → ∀ σ, Agree isGhost σ τ → + ∃ o', Exec s σ o' ∧ (o' = .fail ∨ OutAgree isGhost o' o) := by + intro s + induction s with + | skip => + intro _ _ τ o hx σ h + simp only [Stmt.erase, Stmt.ghostCode, ite_true] at hx + cases hx + exact ⟨_, .skip, .inr h⟩ + | assign x e => + intro hwf _ τ o hx σ h + simp only [Stmt.WF, Bool.and_eq_true, Bool.not_eq_true'] at hwf + simp only [Stmt.erase, Stmt.ghostCode] at hx + cases hx + refine ⟨_, .assign, .inr ?_⟩ + show Agree isGhost _ _ + rw [Exp.eval_agree h e hwf.2] + exact h.set x _ + | require e => + intro hwf _ τ o hx σ h + simp only [Stmt.WF] at hwf + simp only [Stmt.erase, Stmt.ghostCode] at hx + cases hx with + | requireOk hc => exact ⟨_, .requireOk (by rwa [Exp.eval_agree h e hwf]), .inr h⟩ + | requireRev hc => exact ⟨_, .requireRev (by rwa [Exp.eval_agree h e hwf]), .inr trivial⟩ + | seq a b iha ihb => + intro hwf ht τ o hx σ h + cases hg : (Stmt.seq a b).ghostCode isGhost + · rw [erase_of_not_ghostCode hg] at hx + simp only [Stmt.WF, Bool.and_eq_true] at hwf + simp only [GhostTotal] at ht + cases hx with + | seqOk h1 h2 => + obtain ⟨o1, e1, a1⟩ := iha hwf.1 ht.2.1 h1 σ h + rcases a1 with rfl | a1 + · exact ⟨_, .seqFail e1, .inl rfl⟩ + · cases o1 with + | ok σ1 => + obtain ⟨o2, e2, a2⟩ := ihb hwf.2 ht.2.2 h2 σ1 a1 + exact ⟨o2, .seqOk e1 e2, a2⟩ + | _ => simp [OutAgree] at a1 + | seqRev h1 => + obtain ⟨o1, e1, a1⟩ := iha hwf.1 ht.2.1 h1 σ h + rcases a1 with rfl | a1 + · exact ⟨_, .seqFail e1, .inl rfl⟩ + · cases o1 with + | rev => exact ⟨_, .seqRev e1, .inr trivial⟩ + | _ => simp [OutAgree] at a1 + | seqFail h1 => + obtain ⟨o1, e1, a1⟩ := iha hwf.1 ht.2.1 h1 σ h + rcases a1 with rfl | a1 + · exact ⟨_, .seqFail e1, .inl rfl⟩ + · cases o1 with + | fail => exact ⟨_, .seqFail e1, .inl rfl⟩ + | _ => simp [OutAgree] at a1 + · rw [erase_of_ghostCode hg] at hx + cases hx + obtain ⟨o', e'⟩ := ghostTotal_here ht hg σ + rcases ghostCode_exec e' hg with rfl | ⟨σ', rfl, a'⟩ + · exact ⟨_, e', .inl rfl⟩ + · exact ⟨_, e', .inr (a'.trans h)⟩ + | ite c a b iha ihb => + intro hwf ht τ o hx σ h + cases hg : (Stmt.ite c a b).ghostCode isGhost + · rw [erase_of_not_ghostCode hg] at hx + simp only [Stmt.WF, hg, Bool.false_or, Bool.and_eq_true] at hwf + simp only [GhostTotal] at ht + cases hx with + | iteT hc h1 => + obtain ⟨o1, e1, a1⟩ := iha hwf.1.2 ht.2.1 h1 σ h + exact ⟨o1, .iteT (by rwa [Exp.eval_agree h c hwf.1.1]) e1, a1⟩ + | iteF hc h1 => + obtain ⟨o1, e1, a1⟩ := ihb hwf.2 ht.2.2 h1 σ h + exact ⟨o1, .iteF (by rwa [Exp.eval_agree h c hwf.1.1]) e1, a1⟩ + · rw [erase_of_ghostCode hg] at hx + cases hx + obtain ⟨o', e'⟩ := ghostTotal_here ht hg σ + rcases ghostCode_exec e' hg with rfl | ⟨σ', rfl, a'⟩ + · exact ⟨_, e', .inl rfl⟩ + · exact ⟨_, e', .inr (a'.trans h)⟩ + | loop c b ihb => + intro hwf ht τ o hx σ h + cases hg : (Stmt.loop c b).ghostCode isGhost + · have he : (Stmt.loop c b).erase isGhost = .loop c (b.erase isGhost) := by + simp [Stmt.erase, hg] + rw [he] at hx + simp only [Stmt.WF, hg, Bool.false_or, Bool.and_eq_true] at hwf + simp only [GhostTotal] at ht + generalize hl : Stmt.loop c (b.erase isGhost) = l at hx + induction hx generalizing σ with + | loopDone hc => + cases hl + exact ⟨_, .loopDone (by rwa [Exp.eval_agree h c hwf.1]), .inr h⟩ + | loopOk hc h1 _ _ ih2 => + cases hl + obtain ⟨o1, e1, a1⟩ := ihb hwf.2 ht.2 h1 σ h + rcases a1 with rfl | a1 + · exact ⟨_, .loopFail (by rwa [Exp.eval_agree h c hwf.1]) e1, .inl rfl⟩ + · cases o1 with + | ok σ1 => + obtain ⟨o2, e2, a2⟩ := ih2 σ1 a1 rfl + exact ⟨o2, .loopOk (by rwa [Exp.eval_agree h c hwf.1]) e1 e2, a2⟩ + | _ => simp [OutAgree] at a1 + | loopRev hc h1 => + cases hl + obtain ⟨o1, e1, a1⟩ := ihb hwf.2 ht.2 h1 σ h + rcases a1 with rfl | a1 + · exact ⟨_, .loopFail (by rwa [Exp.eval_agree h c hwf.1]) e1, .inl rfl⟩ + · cases o1 with + | rev => exact ⟨_, .loopRev (by rwa [Exp.eval_agree h c hwf.1]) e1, .inr trivial⟩ + | _ => simp [OutAgree] at a1 + | loopFail hc h1 => + cases hl + obtain ⟨o1, e1, a1⟩ := ihb hwf.2 ht.2 h1 σ h + rcases a1 with rfl | a1 + · exact ⟨_, .loopFail (by rwa [Exp.eval_agree h c hwf.1]) e1, .inl rfl⟩ + · cases o1 with + | fail => exact ⟨_, .loopFail (by rwa [Exp.eval_agree h c hwf.1]) e1, .inl rfl⟩ + | _ => simp [OutAgree] at a1 + | _ => cases hl + · rw [erase_of_ghostCode hg] at hx + cases hx + obtain ⟨o', e'⟩ := ghostTotal_here ht hg σ + rcases ghostCode_exec e' hg with rfl | ⟨σ', rfl, a'⟩ + · exact ⟨_, e', .inl rfl⟩ + · exact ⟨_, e', .inr (a'.trans h)⟩ + | ghost x e => + intro hwf ht τ o hx σ h + have hg : (Stmt.ghost x e).ghostCode isGhost = true := by simpa [Stmt.WF, Stmt.ghostCode] using hwf + rw [erase_of_ghostCode hg] at hx + cases hx + exact ⟨_, .ghost, .inr ((Agree.set_ghost (by simpa [Stmt.WF] using hwf) _).trans h)⟩ + | assert e => + intro _ _ τ o hx σ h + simp only [Stmt.erase, Stmt.ghostCode, ite_true] at hx + cases hx + by_cases hc : e.eval σ = 0 + · exact ⟨_, .assertFail hc, .inl rfl⟩ + · exact ⟨_, .assertOk hc, .inr h⟩ + | assume e => + intro _ ht τ o hx σ h + simp only [Stmt.erase, Stmt.ghostCode, ite_true] at hx + cases hx + obtain ⟨o', e'⟩ := ht (by simp [Stmt.ghostCode]) σ + cases e' + exact ⟨_, .assume ‹_›, .inr h⟩ + +/-! ## A spec proved with ghost code holds of the erased program -/ + +/-- **A spec proved with ghost code holds of the erased program.** If every instrumented +execution of a well-formed program whose ghost code terminates passes its assertions and ends in +an outcome meeting `Q`, then every execution of the erased program, from any store, ends in an +outcome that agrees on the real variables with one meeting `Q`: one started from that store with +any ghost state. When `Q` reads only real variables it holds of the erased outcome itself +(`spec_of_erased_real`). -/ +theorem spec_of_erased {s : Stmt} {Q : Store → Out → Prop} (hwf : s.WF isGhost = true) + (ht : GhostTotal isGhost s) + (hproof : ∀ σ o, Exec s σ o → o ≠ .fail ∧ Q σ o) : + ∀ τ o, Exec (s.erase isGhost) τ o → ∀ σ, Agree isGhost σ τ → + ∃ o', Exec s σ o' ∧ Q σ o' ∧ OutAgree isGhost o' o := by + intro τ o hx σ h + obtain ⟨o', e', a'⟩ := complete hwf ht hx σ h + obtain ⟨hnf, hq⟩ := hproof σ o' e' + rcases a' with rfl | a' + · exact absurd rfl hnf + · exact ⟨o', e', hq, a'⟩ + +/-- `Q` reads only the real variables of the outcome. -/ +def RealOnly (isGhost : String → Bool) (Q : Out → Prop) : Prop := + ∀ o o', OutAgree isGhost o o' → Q o → Q o' + +/-- A real postcondition proved with ghost code holds of every execution of the erased program. -/ +theorem spec_of_erased_real {s : Stmt} {Q : Out → Prop} (hwf : s.WF isGhost = true) + (ht : GhostTotal isGhost s) (hq : RealOnly isGhost Q) + (hproof : ∀ σ o, Exec s σ o → o ≠ .fail ∧ Q o) : + ∀ τ o, Exec (s.erase isGhost) τ o → Q o := by + intro τ o hx + obtain ⟨o', _, hq', a'⟩ := spec_of_erased (Q := fun _ o => Q o) hwf ht hproof τ o hx τ + (Agree.refl τ) + exact hq o' o a' hq' + +/-! ## Ghost code without loops or assumptions terminates -/ + +/-- Ghost code made of ghost updates and assertions, under sequencing and conditionals. -/ +def Stmt.straight : Stmt → Bool + | .skip | .assert _ | .ghost _ _ | .assign _ _ | .require _ => true + | .seq a b | .ite _ a b => a.straight && b.straight + | .loop _ _ | .assume _ => false + +theorem total_of_straight : ∀ {s : Stmt}, s.straight = true → ∀ σ, ∃ o, Exec s σ o + | .skip, _, σ => ⟨_, .skip⟩ + | .assign _ _, _, σ => ⟨_, .assign⟩ + | .ghost _ _, _, σ => ⟨_, .ghost⟩ + | .require e, _, σ => by + by_cases hc : e.eval σ = 0 + · exact ⟨_, .requireRev hc⟩ + · exact ⟨_, .requireOk hc⟩ + | .assert e, _, σ => by + by_cases hc : e.eval σ = 0 + · exact ⟨_, .assertFail hc⟩ + · exact ⟨_, .assertOk hc⟩ + | .seq a b, hs, σ => by + simp only [Stmt.straight, Bool.and_eq_true] at hs + obtain ⟨o1, e1⟩ := total_of_straight hs.1 σ + cases o1 with + | ok σ1 => + obtain ⟨o2, e2⟩ := total_of_straight hs.2 σ1 + exact ⟨_, .seqOk e1 e2⟩ + | rev => exact ⟨_, .seqRev e1⟩ + | fail => exact ⟨_, .seqFail e1⟩ + | .ite c a b, hs, σ => by + simp only [Stmt.straight, Bool.and_eq_true] at hs + by_cases hc : c.eval σ = 0 + · obtain ⟨o, e⟩ := total_of_straight hs.2 σ + exact ⟨_, .iteF hc e⟩ + · obtain ⟨o, e⟩ := total_of_straight hs.1 σ + exact ⟨_, .iteT hc e⟩ + +/-- **Rule 3 for straight-line ghost code**: a program whose statements have no loop and no +assumption meets `GhostTotal`. -/ +theorem ghostTotal_of_straight : ∀ {s : Stmt}, s.straight = true → GhostTotal isGhost s + | .skip, _ | .assert _, _ | .ghost _ _, _ | .assign _ _, _ | .require _, _ => + fun _ => total_of_straight (by simp [Stmt.straight]) + | .seq a b, hs => by + simp only [Stmt.straight, Bool.and_eq_true] at hs + exact ⟨fun _ => total_of_straight (by simp [Stmt.straight, hs]), + ghostTotal_of_straight hs.1, ghostTotal_of_straight hs.2⟩ + | .ite c a b, hs => by + simp only [Stmt.straight, Bool.and_eq_true] at hs + exact ⟨fun _ => total_of_straight (by simp [Stmt.straight, hs]), + ghostTotal_of_straight hs.1, ghostTotal_of_straight hs.2⟩ + +end SolidCore.Spec.Ghost diff --git a/Verify/Spec/GhostFree.lean b/Verify/Spec/GhostFree.lean new file mode 100644 index 00000000..62bdae71 --- /dev/null +++ b/Verify/Spec/GhostFree.lean @@ -0,0 +1,168 @@ +import Verify.Spec.Contract + +/-! +# Ghost-free specs ignore ghosts + +A term that reads no ghost variable, through the spec functions it calls (`Term.GhostFree`), has the +same value in two environments that differ only in their ghost states (`Env.ghostEquiv`). So a +ghost-free spec clause cannot tell a run with ghost code apart from its erasure, which only changes +ghost state (`Ghost.sound`). +-/ + +namespace SolidCore.Spec + +namespace Env.ghostEquiv + +theorem refl (e : Env) : e.ghostEquiv e := by + simp [Env.ghostEquiv] + +theorem symm {e e' : Env} (h : e.ghostEquiv e') : e'.ghostEquiv e := by + obtain ⟨h1, h2, h3, h4, h5, h6, h7, h8, h9⟩ := h + exact ⟨h1.symm, h2.symm, h3.symm, h4.symm, h5.symm, h6.symm, h7.symm, h8.symm, h9.symm⟩ + +theorem storage {e e' : Env} (h : e.ghostEquiv e') : e.cur.storage = e'.cur.storage := by + obtain ⟨-, -, -, -, h5, h6, -, h8, -⟩ := h + simp only [Env.cur, h5]; split <;> assumption + +theorem time {e e' : Env} (h : e.ghostEquiv e') : e.cur.time = e'.cur.time := by + obtain ⟨-, -, -, -, h5, -, h7, -, h9⟩ := h + simp only [Env.cur, h5]; split <;> assumption + +theorem bind {e e' : Env} (h : e.ghostEquiv e') (x : String) (v : Int) : + (e.bind x v).ghostEquiv (e'.bind x v) := by + obtain ⟨h1, h2, h3, h4, h5, h6, h7, h8, h9⟩ := h + exact ⟨h1, h2, h3, by simp [Env.bind, h4], h5, h6, h7, h8, h9⟩ + +theorem old {e e' : Env} (h : e.ghostEquiv e') : + ({ e with inOld := true } : Env).ghostEquiv { e' with inOld := true } := by + obtain ⟨h1, h2, h3, h4, h5, h6, h7, h8, h9⟩ := h + exact ⟨h1, h2, h3, h4, rfl, h6, h7, h8, h9⟩ + +theorem withVars {e e' : Env} (h : e.ghostEquiv e') (vs : List (String × Int)) : + ({ e with vars := vs } : Env).ghostEquiv { e' with vars := vs } := by + obtain ⟨h1, h2, h3, h4, h5, h6, h7, h8, h9⟩ := h + exact ⟨h1, h2, h3, rfl, h5, h6, h7, h8, h9⟩ + +end Env.ghostEquiv + +/-- What `k` promises of the spec function bodies at one fuel level: they ignore ghosts when +evaluated with one less fuel. -/ +def BodiesIgnoreGhosts (fns : List SpecFn) (fuel : Nat) (k : Term → Bool) : Prop := + ∀ body, k body = true → ∀ fuel', fuel = fuel' + 1 → + ∀ e e', e.ghostEquiv e' → eval fns fuel' body e = eval fns fuel' body e' + +mutual +theorem eval_ghostEquiv_with {fns : List SpecFn} {fuel : Nat} {k : Term → Bool} + (hk : BodiesIgnoreGhosts fns fuel k) : + ∀ (t : Term), Term.ghostFreeWith fns k t = true → + ∀ e e', e.ghostEquiv e' → eval fns fuel t e = eval fns fuel t e' + | .lit _, _, e, e', h => by simp only [eval] + | .arg _, _, e, e', h => by simp only [eval, h.1] + | .ret _, _, e, e', h => by simp only [eval, h.2.1] + | .var _, _, e, e', h => by simp only [eval, h.2.2.2.1] + | .env v, _, e, e', h => by + cases v <;> simp only [eval, h.2.2.1, h.time] + | .load p off size ty, hg, e, e', h => by + simp only [Term.ghostFreeWith, Bool.and_eq_true] at hg + simp only [eval, h.storage, slotOf_ghostEquiv_with hk p hg.1 e e' h, + eval_ghostEquiv_with hk off hg.2 e e' h] + | .len p, hg, e, e', h => by + simp only [Term.ghostFreeWith] at hg + simp only [eval, h.storage, slotOf_ghostEquiv_with hk p hg e e' h] + | .ghost _ _, hg, _, _, _ => by simp [Term.ghostFreeWith] at hg + | .old t, hg, e, e', h => by + simp only [Term.ghostFreeWith] at hg + simp only [eval]; exact eval_ghostEquiv_with hk t hg _ _ h.old + | .un op t, hg, e, e', h => by + simp only [Term.ghostFreeWith] at hg + cases op <;> simp only [eval, eval_ghostEquiv_with hk t hg e e' h] + | .bin op a b, hg, e, e', h => by + simp only [Term.ghostFreeWith, Bool.and_eq_true] at hg + simp only [eval, eval_ghostEquiv_with hk a hg.1 e e' h, eval_ghostEquiv_with hk b hg.2 e e' h] + | .shl t _, hg, e, e', h => by + simp only [Term.ghostFreeWith] at hg + simp only [eval, eval_ghostEquiv_with hk t hg e e' h] + | .shr t _, hg, e, e', h => by + simp only [Term.ghostFreeWith] at hg + simp only [eval, eval_ghostEquiv_with hk t hg e e' h] + | .ite c a b, hg, e, e', h => by + simp only [Term.ghostFreeWith, Bool.and_eq_true] at hg + simp only [eval, eval_ghostEquiv_with hk c hg.1.1 e e' h, eval_ghostEquiv_with hk a hg.1.2 e e' h, + eval_ghostEquiv_with hk b hg.2 e e' h] + | .all x _ body, hg, e, e', h => by + simp only [Term.ghostFreeWith] at hg + have hb : ∀ v, eval fns fuel body (e.bind x v) = eval fns fuel body (e'.bind x v) := + fun v => eval_ghostEquiv_with hk body hg _ _ (h.bind x v) + simp only [eval, hb] + | .ex x _ body, hg, e, e', h => by + simp only [Term.ghostFreeWith] at hg + have hb : ∀ v, eval fns fuel body (e.bind x v) = eval fns fuel body (e'.bind x v) := + fun v => eval_ghostEquiv_with hk body hg _ _ (h.bind x v) + simp only [eval, hb] + | .call f args, hg, e, e', h => by + simp only [Term.ghostFreeWith, Bool.and_eq_true] at hg + have ha := evalList_ghostEquiv_with hk args hg.1 e e' h + obtain ⟨-, hb⟩ := hg + cases fuel with + | zero => rw [eval.eq_def, eval.eq_def] + | succ fuel' => + cases hf : fns.find? (·.name == f) with + | none => rw [eval.eq_def, eval.eq_def]; simp only [hf] + | some sf => + rw [hf] at hb + rw [eval.eq_def, eval.eq_def]; simp only [hf, ha] + exact hk sf.body hb fuel' rfl _ _ (h.withVars _) +termination_by t => sizeOf t + +theorem evalList_ghostEquiv_with {fns : List SpecFn} {fuel : Nat} {k : Term → Bool} + (hk : BodiesIgnoreGhosts fns fuel k) : + ∀ (ts : List Term), Term.ghostFreeListWith fns k ts = true → + ∀ e e', e.ghostEquiv e' → evalList fns fuel ts e = evalList fns fuel ts e' + | [], _, e, e', _ => by simp only [evalList] + | t :: ts, hg, e, e', h => by + simp only [Term.ghostFreeListWith, Bool.and_eq_true] at hg + simp only [evalList, eval_ghostEquiv_with hk t hg.1 e e' h, + evalList_ghostEquiv_with hk ts hg.2 e e' h] +termination_by ts => sizeOf ts + +theorem slotOf_ghostEquiv_with {fns : List SpecFn} {fuel : Nat} {k : Term → Bool} + (hk : BodiesIgnoreGhosts fns fuel k) : + ∀ (p : Place), Place.ghostFreeWith fns k p = true → + ∀ e e', e.ghostEquiv e' → slotOf fns fuel p e = slotOf fns fuel p e' + | .slot _, _, e, e', _ => by simp only [slotOf] + | .offset b i, hg, e, e', h => by + simp only [Place.ghostFreeWith, Bool.and_eq_true] at hg + simp only [slotOf, slotOf_ghostEquiv_with hk b hg.1 e e' h, eval_ghostEquiv_with hk i hg.2 e e' h] + | .entry b i, hg, e, e', h => by + simp only [Place.ghostFreeWith, Bool.and_eq_true] at hg + simp only [slotOf, slotOf_ghostEquiv_with hk b hg.1 e e' h, eval_ghostEquiv_with hk i hg.2 e e' h] + | .elem b i _, hg, e, e', h => by + simp only [Place.ghostFreeWith, Bool.and_eq_true] at hg + simp only [slotOf, slotOf_ghostEquiv_with hk b hg.1 e e' h, eval_ghostEquiv_with hk i hg.2 e e' h] + | .packedElem b i _, hg, e, e', h => by + simp only [Place.ghostFreeWith, Bool.and_eq_true] at hg + simp only [slotOf, slotOf_ghostEquiv_with hk b hg.1 e e' h, eval_ghostEquiv_with hk i hg.2 e e' h] +termination_by p => sizeOf p +end + +/-- A ghost-free term has the same value in two environments that differ only in their ghost +states: a spec that reads no ghost cannot tell ghost code apart from its erasure. -/ +theorem eval_ghostEquiv {fns : List SpecFn} : + ∀ (fuel : Nat) {t : Term}, Term.GhostFree fns fuel t = true → + ∀ {e e' : Env}, e.ghostEquiv e' → eval fns fuel t e = eval fns fuel t e' + | 0, t, hg, e, e', h => by + refine eval_ghostEquiv_with ?_ t hg e e' h + intro _ _ fuel' h0; cases h0 + | n + 1, t, hg, e, e', h => by + refine eval_ghostEquiv_with ?_ t hg e e' h + intro body hb fuel' hf _ _ h' + cases hf + exact eval_ghostEquiv n hb h' + +/-- A ghost-free clause holds in one environment exactly when it holds in another that differs only +in its ghost state. -/ +theorem Bundle.sat_ghostEquiv (b : Bundle) {t : Term} (hg : Term.GhostFree b.spec.fns b.fuel t = true) + {e e' : Env} (h : e.ghostEquiv e') : b.sat t e ↔ b.sat t e' := by + simp only [Bundle.sat, eval_ghostEquiv b.fuel hg h] + +end SolidCore.Spec diff --git a/Verify/Spec/README.md b/Verify/Spec/README.md new file mode 100644 index 00000000..684b13db --- /dev/null +++ b/Verify/Spec/README.md @@ -0,0 +1,91 @@ +# The meaning of solar-verify's specs + +This directory gives the annotations `solar-verify` checks a meaning in Lean, over the calls and +observables SolidCore and EthLib share (`SolarTV.Sem`), so a spec `solar-verify` accepts becomes a +Lean proposition about the contract and, through the certified translation, about solar's bytecode. + +## Files + +- `Syntax.lean`: the spec language after `solar-verify`'s front end. Terms are integers (math-int + semantics: no wrapping until a value is stored), with arguments, named returns, storage loads at + a slot, byte offset and width with their type, `old(..)`, ghosts, `msg.sender`, `msg.value`, + `block.timestamp` (`__time`), `==>` and `<==>`, bounded `forall` and `exists`, and calls of spec + functions, opaque (`@custom:opaque`) or inlined by unfolding. A `Manifest` binds a spec to its + source's sha256, the compiler and the runtime bytecode's sha256. +- `Semantics.lean`: `eval`, total on fuel; mapping and array slots by keccak. +- `Contract.lean`: `Pre` and `Post` of a function spec at a call (selector, ABI decoding, + requires, and the contract and struct invariants) and `Holds S p scope b ctxOf`: every call in + scope that meets its function's `Pre` ends in an observable meeting its `Post` (a revert is + allowed only where the spec does not say the call succeeds). `Holds.of_stage` moves it along a + refinement stage, so a spec proved of SolidCore holds of the bytecode. +- `Ghost.lean`: ghost erasure. For a core language with assignments, requires, branches, loops, + ghost statements, asserts and assumes, erasing well-formed ghost code changes no real state and + no outcome when the ghost code terminates (`sound`, `complete`), so a spec over real state + proved of the program with ghosts holds of the erased program (`spec_of_erased_real`). + Straight-line ghost code always terminates (`ghostTotal_of_straight`). +- `GhostFree.lean`: a ghost-free term has the same value in environments that differ only in + their ghost states (`eval_ghostEquiv`, `Bundle.sat_ghostEquiv`). +- `TrustedBase.lean`: each item of the "Trusted base" in solar-verify's README as a named + hypothesis, never an axiom, and `spec_of_verdict`, which takes the verdict itself as one. +- `TrustedBase/Hypotheses.lean`: each of those hypotheses stated precisely (`Hyps`, + `Hyps.toAssumptions`, `spec_of_verdict_hyps`), with a witness that it is satisfiable, where cheap one + that it is not trivially true, and its discharge for code without the feature (table below). + `TrustedBase/Instances.lean`: c4's and Counter's discharged. `TrustedBase/Axioms.lean`: their + `#print axioms`. +- `Export/`: specs generated by `solar-verify --emit-lean-spec` from `scripts/refinement/spec`. +- `Solar/C4.lean`: the c4 spec proved of SolidCore (`holds_source`), of solar's bytecode for the + deployed storage (`holds_bytecode`) and for any storage given the solar-tv stage + (`holds_bytecode_at`), bound to the manifest (`certified`); the wrong spec fails on a concrete + call (`wrong_fails`). +- `Axioms.lean`: `#print axioms` for the theorems above: `propext`, `Classical.choice` and + `Quot.sound` only. + +## Trusted base as hypotheses + +| README item | Lean | +| --- | --- | +| 1. Parser, VC encoding and solvers | `Verdict`, the hypothesis of `spec_of_verdict` | +| 2. `@custom:assume`, `@custom:trusted`, interface ensures | `Assumptions.assumptionsHold` | +| 3. No `delegatecall` into the contract | `Assumptions.noDelegatecall` | +| 4. keccak256 injective, images in `[2^128, 2^256)` | `Assumptions.keccakSeparated`, per call: injectivity cannot hold of all inputs | +| 5. Assembly slots disjoint, assembly memory-safe | `Assumptions.asmSlotsDisjoint`, `Assumptions.asmMemorySafe` | +| 6. `Math.mulDiv` summarized as OpenZeppelin's | `Assumptions.mulDiv` | +| 7. View and pure calls answer as functions of what they read | `Assumptions.viewCalls` | +| Opaque spec functions return values of their type | `OpaqueInRange` | + +Stated precisely in `TrustedBase/Hypotheses.lean`: + +| Item | Statement | Satisfiable / not trivial | Discharged | +| --- | --- | --- | --- | +| 2. `@custom:assume` | `Core.AssumesHold s σ`: no assume cuts off an execution of the core program from `σ` | `assumesHold_assumeX` / `not_assumesHold_assumeX` | no assume: `assumesHold_of_noAssume` | +| 2. `@custom:trusted`, internal | `Core.MeetsContract s req ens` | `meetsContract_assign` / `not_meetsContract_assign` | no trusted function | +| 2. `@custom:trusted`, external | `TrustedHold`: `Holds` of the trusted functions' specs | | `trustedHold_nil`, `trustedHold_of_holds` | +| 2. Interface ensures | `InterfaceEnsures ens tr` over a transcript's call exchanges; `ens := ifaceEnsOf iface ctx st` builds it from an exported interface spec (`Interface.lean`) | `interfaceEnsures_one` / `not_interfaceEnsures_zero` | no call returns: `interfaceEnsures_of_default` | +| 3. No `delegatecall` into the contract | `NoForeignWrites` within a call; `Reach` from deployment across calls | `Reach.refl` | `noForeignWrites_of_default` | +| 4. keccak256 | `KeccakSeparated S` of the call's preimages | `keccakSeparated_mapping` (six real mapping slots, kernel-evaluated) / `not_keccakSeparated_univ` | nothing hashed: `keccakSeparated_empty` | +| 5. Assembly | `AsmFree u`, stronger: SolidCore rejects assembly | `asmFree_example` / `not_asmFree_example` | by `decide`: `asmFree_c4`, `asmFree_counter` | +| 6. `Math.mulDiv` | `MulDivSummary impl`: agrees with `ozMulDiv` (`ozMulDiv_spec`: floor of the exact quotient) | `mulDivSummary_oz` / `not_mulDivSummary_unchecked` | no `Math.mulDiv` | +| 7. View calls | `ViewDeterministic self tr`: same target and calldata, from worlds agreeing on balances, code and the caller's storage, answer alike whatever the gas | `viewDeterministic_twice` / `not_viewDeterministic` | `viewDeterministic_of_default` | + +`Hyps.satisfiable`: the whole structure holds on every call of some instance. Open: a call's keccak256 +preimages and its transcript are supplied with `Hyps`, not yet derived from SolidCore's run +(`transcriptWith` computes a transcript from an interaction tree, but `Source.run` folds its tree +without exposing it, and SolidCore hashes inside its interpreter); `MulDivSummary` is not yet +instantiated with SolidCore's internal-call semantics. + +c4 needs none of them: `Assumptions.none_on`, and its spec has no opaque functions. + +## Checking the exports + +`scripts/refinement/spec/check.sh` regenerates the exports with `solar-verify` and fails if they +differ, checks that the annotated source is the corpus source with comments, and that the +manifest's bytecode sha256 is the runtime bytecode's. + +## Not done yet + +- Loop invariants have syntax but no meaning yet; they wait on Loom's loop rules in + `vendor/loom`. Ghost erasure is proved for the core language, not yet tied to SolidCore + statements. +- A spec holds per call; invariants are not yet chained along a sequence of calls. +- `holds_bytecode_at` takes the solar-tv c4 stage as a hypothesis, because the pinned solar-tv + c4 milestone proofs do not build here. diff --git a/Verify/Spec/Semantics.lean b/Verify/Spec/Semantics.lean new file mode 100644 index 00000000..928ef038 --- /dev/null +++ b/Verify/Spec/Semantics.lean @@ -0,0 +1,263 @@ +import Verify.Spec.Syntax + +/-! +# solar-verify's spec language: meaning + +The meaning of a spec over a call and what it observes (`SolarTV.Call`, `SolarTV.Observable`), +the interface SolidCore, solar's IRs and EthLib share, so that the same predicate holds of the +source and of the bytecode a refinement relates it to. + +* `eval`: a spec expression's value, an `Int`, from the call's arguments and return values, the + pre- and post-state (storage, ghost state, `__time`) and the call's environment. Arithmetic is + on mathematical integers; division and remainder truncate toward zero; `&`, `|`, `^` work on the + 256-bit two's complement words of their operands; `<<` by a literal wraps modulo `2 ^ 256`. These + are solar-verify's own spec encodings (`src/vc.rs`, `arith` in spec mode). Where solar-verify + leaves a value unconstrained (division by zero, a negative exponent), any value here is sound + for its proofs, and this one picks Lean's. +* Quantifiers range over the binder's type, as solar-verify's `quant` does. They make `eval` + noncomputable: a formula's meaning is a proposition. +* A spec function call evaluates the function's body with its parameters bound to the + arguments' values. Calls nest at most `fuel` deep: `Term.Closed` checks that the exported fuel + suffices, so the out-of-fuel case (`0`) is never reached in an exported spec. An opaque + function means its body too; solar-verify proves facts about it for every interpretation in its + return type's range, which includes this one exactly when `OpaqueInRange` holds. +* `Pre` and `Post` state a function's spec: the call selects the function and its arguments + decode (ABI-clean words of their types), and from a pre-state meeting the requires and the + contract invariants, a successful call returns clean words meeting the ensures and leaves a + state meeting the invariants, and one meeting the succeeds-if conditions succeeds. +* `Holds S p scope cs ctxOf step`: every function's spec holds of program `p` in semantics `S` on + `scope`, with ghost state updated by `step`. A ghost-free spec does not depend on `step` + (`Holds.ghostFree`). +-/ + +namespace SolidCore.Spec + +open SolarTV + +/-- Storage: slot to word. -/ +abbrev Storage := Nat → Nat + +/-- Ghost state: each ghost variable, as a function of its mapping keys (none for a scalar). -/ +abbrev Ghost := String → List Int → Int + +/-- The ghost state at deployment: every ghost zero. -/ +def Ghost.zero : Ghost := fun _ _ => 0 + +/-- `2 ^ 256`. -/ +abbrev wordMod : Nat := 2 ^ 256 + +/-- The 256-bit word of an integer (two's complement for negative ones). -/ +def toWord (v : Int) : Nat := (v % (wordMod : Int)).toNat + +/-- The 32 big-endian bytes of a word. -/ +def wordBytes (v : Nat) : List Nat := (List.range 32).reverse.map fun i => v / 256 ^ i % 256 + +/-- The big-endian word of a byte list. -/ +def bytesWord (bs : List Nat) : Nat := bs.foldl (fun acc b => acc * 256 + b) 0 + +/-- Keccak-256 of a byte list, as a word: the definition SolidCore and EthLib both use. -/ +def keccakWord (bs : List Nat) : Nat := bytesWord (EvmYul.SpongeHash.Keccak256.keccak256Bytes bs) + +/-! ## Types -/ + +/-- The values of a type. -/ +def Ty.InRange : Ty → Int → Prop + | .uint b, v => 0 ≤ v ∧ v < 2 ^ b + | .int b, v => -(2 ^ (b - 1)) ≤ v ∧ v < 2 ^ (b - 1) + | .bool, v => v = 0 ∨ v = 1 + | .address, v => 0 ≤ v ∧ v < 2 ^ 160 + | .fixedBytes n, v => 0 ≤ v ∧ v < 2 ^ (8 * n) + | .enum c, v => 0 ≤ v ∧ v < c + | .math, _ => True + +instance (t : Ty) (v : Int) : Decidable (t.InRange v) := by + cases t <;> unfold Ty.InRange <;> infer_instance + +/-- A value of type `t` from the `8 * bits` low bits of a storage word, as Solidity reads it. -/ +def Ty.ofBits : Ty → Nat → Int + | .int b, raw => if 2 ^ (b - 1) ≤ raw then (raw : Int) - 2 ^ b else raw + | .bool, raw => if raw = 0 then 0 else 1 + | _, raw => raw + +/-- A value of type `t` from an ABI word, or `none` when the word is not clean for `t` (Solidity's +decoder reverts on it). `bytesN` is left-aligned. -/ +def Ty.ofWord : Ty → Nat → Option Int + | .uint b, w => if w < 2 ^ b then some w else none + | .int b, w => + if w < 2 ^ (b - 1) then some w + else if wordMod - 2 ^ (b - 1) ≤ w ∧ w < wordMod then some ((w : Int) - wordMod) + else none + | .bool, w => if w ≤ 1 then some w else none + | .address, w => if w < 2 ^ 160 then some w else none + | .fixedBytes n, w => + if w < wordMod ∧ w % 2 ^ (8 * (32 - n)) = 0 then some (w / 2 ^ (8 * (32 - n)) : Nat) else none + | .enum c, w => if w < c then some w else none + | .math, _ => none + +/-! ## States and environments -/ + +/-- What a spec reads of a state: storage, ghost state and `__time`. -/ +structure State where + storage : Storage + ghost : Ghost + time : Int + +/-- The call's environment. -/ +structure Ctx where + sender : Int + value : Int + timestamp : Int + self : Int + +/-- Everything a spec expression reads. `inOld` is set inside `old(..)`. -/ +structure Env where + args : List Int + rets : List Int + pre : State + post : State + ctx : Ctx + vars : List (String × Int) + inOld : Bool + +/-- The state a read sees. -/ +def Env.cur (e : Env) : State := if e.inOld then e.pre else e.post + +/-- Bind a variable. -/ +def Env.bind (e : Env) (x : String) (v : Int) : Env := { e with vars := (x, v) :: e.vars } + +/-- A truth value as `0` or `1`. -/ +noncomputable def ofProp (p : Prop) : Int := by + classical exact if p then 1 else 0 + +/-- Binary operators on values. -/ +noncomputable def BinOp.apply : BinOp → Int → Int → Int + | .add, a, b => a + b + | .sub, a, b => a - b + | .mul, a, b => a * b + | .div, a, b => a.tdiv b + | .mod, a, b => a.tmod b + | .pow, a, b => a ^ b.toNat + | .band, a, b => (toWord a &&& toWord b : Nat) + | .bor, a, b => (toWord a ||| toWord b : Nat) + | .bxor, a, b => (toWord a ^^^ toWord b : Nat) + | .eq, a, b => ofProp (a = b) + | .ne, a, b => ofProp (a ≠ b) + | .lt, a, b => ofProp (a < b) + | .le, a, b => ofProp (a ≤ b) + | .gt, a, b => ofProp (a > b) + | .ge, a, b => ofProp (a ≥ b) + | .and, a, b => ofProp (a ≠ 0 ∧ b ≠ 0) + | .or, a, b => ofProp (a ≠ 0 ∨ b ≠ 0) + | .implies, a, b => ofProp (a ≠ 0 → b ≠ 0) + +/-! ## Evaluation -/ + +mutual +/-- The value of a spec expression, with spec function calls nested at most `fuel` deep. -/ +noncomputable def eval (fns : List SpecFn) (fuel : Nat) : Term → Env → Int + | .lit v, _ => v + | .arg i, e => e.args.getD i 0 + | .ret i, e => e.rets.getD i 0 + | .var x, e => (e.vars.lookup x).getD 0 + | .env .sender, e => e.ctx.sender + | .env .value, e => e.ctx.value + | .env .timestamp, e => e.ctx.timestamp + | .env .self, e => e.ctx.self + | .env .time, e => e.cur.time + | .load p off size ty, e => + ty.ofBits (e.cur.storage (slotOf fns fuel p e) / 2 ^ (8 * toWord (eval fns fuel off e)) % + 2 ^ (8 * size)) + | .len p, e => e.cur.storage (slotOf fns fuel p e) + | .ghost x ks, e => e.cur.ghost x (evalList fns fuel ks e) + | .old t, e => eval fns fuel t { e with inOld := true } + | .un .neg t, e => -eval fns fuel t e + | .un .not t, e => ofProp (eval fns fuel t e = 0) + | .bin op a b, e => op.apply (eval fns fuel a e) (eval fns fuel b e) + | .shl t k, e => (eval fns fuel t e * 2 ^ k) % (wordMod : Int) + | .shr t k, e => eval fns fuel t e / 2 ^ k + | .ite c a b, e => if eval fns fuel c e ≠ 0 then eval fns fuel a e else eval fns fuel b e + | .all x ty body, e => ofProp (∀ v, ty.InRange v → eval fns fuel body (e.bind x v) ≠ 0) + | .ex x ty body, e => ofProp (∃ v, ty.InRange v ∧ eval fns fuel body (e.bind x v) ≠ 0) + | .call f args, e => + match fuel, fns.find? (·.name == f) with + | fuel' + 1, some sf => + eval fns fuel' sf.body { e with vars := (sf.params.map Prod.fst).zip (evalList fns (fuel' + 1) args e) } + | _, _ => 0 +termination_by t => (fuel, sizeOf t) + +/-- The values of a list of spec expressions. -/ +noncomputable def evalList (fns : List SpecFn) (fuel : Nat) : List Term → Env → List Int + | [], _ => [] + | t :: ts, e => eval fns fuel t e :: evalList fns fuel ts e +termination_by ts => (fuel, sizeOf ts) + +/-- The slot of a place. -/ +noncomputable def slotOf (fns : List SpecFn) (fuel : Nat) : Place → Env → Nat + | .slot n, _ => n % wordMod + | .offset b k, e => (slotOf fns fuel b e + toWord (eval fns fuel k e)) % wordMod + | .entry b k, e => keccakWord (wordBytes (toWord (eval fns fuel k e)) ++ wordBytes (slotOf fns fuel b e)) + | .elem b i n, e => + (keccakWord (wordBytes (slotOf fns fuel b e)) + toWord (eval fns fuel i e) * n) % wordMod + | .packedElem b i n, e => + (keccakWord (wordBytes (slotOf fns fuel b e)) + toWord (eval fns fuel i e) / n) % wordMod +termination_by p => (fuel, sizeOf p) +end + +/-- A formula holds: its value is nonzero. -/ +def Holds' (fns : List SpecFn) (fuel : Nat) (t : Term) (e : Env) : Prop := eval fns fuel t e ≠ 0 + + +/-! ## Evaluation lemmas -/ + +@[simp] theorem ofProp_ne_zero (p : Prop) : ofProp p ≠ 0 ↔ p := by + unfold ofProp; split <;> simp_all + +@[simp] theorem ofProp_eq_zero (p : Prop) : ofProp p = 0 ↔ ¬p := by + unfold ofProp; split <;> simp_all + +@[simp] theorem toWord_natCast {n : Nat} (h : n < 2 ^ 256) : toWord (n : Int) = n := by + have h' : (n : Int) < ((wordMod : Nat) : Int) := by exact_mod_cast h + unfold toWord + rw [Int.emod_eq_of_lt (by omega) h'] + simp + +/-! ## Well-formedness, checked by the kernel on every exported spec -/ + +mutual +/-- One level of `Term.Closed`: every call in `t` names a function of `fns` with as many arguments +as it has parameters, and `k` holds of the body it unfolds. Structural, so the kernel evaluates it. -/ +def Term.closedWith (fns : List SpecFn) (k : Term → Bool) : Term → Bool + | .load p off _ _ => Place.closedWith fns k p && Term.closedWith fns k off + | .len p => Place.closedWith fns k p + | .ghost _ ks => Term.closedListWith fns k ks + | .old t | .un _ t | .shl t _ | .shr t _ | .all _ _ t | .ex _ _ t => Term.closedWith fns k t + | .bin _ a b => Term.closedWith fns k a && Term.closedWith fns k b + | .ite c a b => Term.closedWith fns k c && Term.closedWith fns k a && Term.closedWith fns k b + | .call f args => + Term.closedListWith fns k args && + match fns.find? (·.name == f) with + | some sf => sf.params.length == args.length && k sf.body + | none => false + | .lit _ | .arg _ | .ret _ | .var _ | .env _ => true + +def Term.closedListWith (fns : List SpecFn) (k : Term → Bool) : List Term → Bool + | [] => true + | t :: ts => Term.closedWith fns k t && Term.closedListWith fns k ts + +def Place.closedWith (fns : List SpecFn) (k : Term → Bool) : Place → Bool + | .slot _ => true + | .offset b i | .entry b i | .elem b i _ | .packedElem b i _ => + Place.closedWith fns k b && Term.closedWith fns k i +end + +/-- Every spec function call in `t` resolves, with as many arguments as parameters, and calls nest +at most `fuel` deep, counting the bodies they unfold: `eval fns fuel t` never runs out of fuel. -/ +def Term.Closed (fns : List SpecFn) : Nat → Term → Bool + | 0 => Term.closedWith fns fun _ => false + | n + 1 => Term.closedWith fns (Term.Closed fns n) + +/-- `Term.Closed` of every term of a list. -/ +def Term.ClosedList (fns : List SpecFn) (fuel : Nat) (ts : List Term) : Bool := + ts.all (Term.Closed fns fuel) + +end SolidCore.Spec diff --git a/Verify/Spec/Syntax.lean b/Verify/Spec/Syntax.lean new file mode 100644 index 00000000..94974e99 --- /dev/null +++ b/Verify/Spec/Syntax.lean @@ -0,0 +1,162 @@ +import SolarTV.Sem +import EvmYul.SpongeHash.Keccak256 + +/-! +# solar-verify's spec language: syntax + +solar-verify (paradigmxyz/solar, crates/verify) reads specs from NatSpec tags: +`@custom:requires`, `@custom:ensures`, `@custom:succeeds-if`, `@custom:invariant` on a contract +or a struct, `@custom:ghost` declarations and updates, and spec functions, plain or +`@custom:opaque`. Its exporter (`solar-verify --emit-lean`) writes each contract's specs in the +syntax below, and `SolidCore.Spec.Semantics` gives them their meaning over the calls and +observables of SolidCore and EthLib (`SolarTV.Call`, `SolarTV.Observable`). + +Spec expressions are Solidity expressions over mathematical integers, as solar-verify encodes them +(`src/vc.rs`, `arith` with `spec` set): one sort, `Int`, with booleans as `0` and `1`. A spec +reads the contract's storage through `Place`s the exporter resolves from the storage layout +(state variables, mapping entries, array elements, struct fields), so its meaning is over the raw +slots the bytecode reads and writes, not over solar-verify's per-variable model of them. + +Every form the exporter does not translate is an export error, never a dropped spec. +-/ + +namespace SolidCore.Spec + +/-- The value types a spec reads, binds and returns. -/ +inductive Ty where + /-- `uintN`, `bits` a multiple of 8 up to 256. -/ + | uint (bits : Nat) + /-- `intN`, two's complement. -/ + | int (bits : Nat) + | bool + | address + /-- `bytesN`, read as the unsigned integer of its `n` bytes. -/ + | fixedBytes (n : Nat) + /-- An enum with `count` members, read as its index. -/ + | enum (count : Nat) + /-- A mathematical integer: the type of a `mathint` or `integer` quantifier binder. -/ + | math + deriving Repr, DecidableEq, Inhabited + +/-- Environment values of a call. `time` is solar-verify's `__time`, the latest +`block.timestamp` the contract has seen. -/ +inductive EnvVar where + | sender | value | timestamp | self | time + deriving Repr, DecidableEq, Inhabited + +/-- Unary operators. -/ +inductive UnOp where + | neg | not + deriving Repr, DecidableEq, Inhabited + +/-- Binary operators. The logical operators take and give `0` and `1`. -/ +inductive BinOp where + | add | sub | mul | div | mod | pow + | band | bor | bxor + | eq | ne | lt | le | gt | ge + | and | or | implies + deriving Repr, DecidableEq, Inhabited + +mutual +/-- A spec expression. -/ +inductive Term where + | lit (v : Int) + /-- The `i`th parameter of the function, as the call passed it. -/ + | arg (i : Nat) + /-- The `i`th return value (`result` is `ret 0`; named returns are their index). -/ + | ret (i : Nat) + /-- A variable bound by a quantifier or a spec function's parameter. -/ + | var (name : String) + | env (v : EnvVar) + /-- The value of type `ty` stored at `place`, `size` bytes from byte `offset` of its slot + (counted from the least significant byte; computed for packed array elements). -/ + | load (place : Place) (offset : Term) (size : Nat) (ty : Ty) + /-- The length of the dynamic storage array at `place`: the word in its slot. -/ + | len (place : Place) + /-- A ghost variable; `keys` index a ghost mapping. Ghost state starts at zero. -/ + | ghost (name : String) (keys : List Term) + /-- `old(e)`: `e` in the pre-state (storage, ghost state and `__time` of the call's start). -/ + | old (e : Term) + | un (op : UnOp) (e : Term) + | bin (op : BinOp) (a b : Term) + /-- `e << k` by a literal `k`: wraps modulo `2 ^ 256`, as solar-verify's specs do. -/ + | shl (e : Term) (k : Nat) + /-- `e >> k` by a literal `k`: the floor of `e / 2 ^ k`. Shifts by a computed amount are export + errors, since solar-verify encodes them through a table that differs from `2 ^ k` past 255. -/ + | shr (e : Term) (k : Nat) + /-- `c ? a : b`. -/ + | ite (c a b : Term) + /-- `forall T x :: body` (one binder; the exporter nests several). -/ + | all (x : String) (ty : Ty) (body : Term) + /-- `exists T x :: body`. -/ + | ex (x : String) (ty : Ty) (body : Term) + /-- A call of the spec function `fn`. -/ + | call (fn : String) (args : List Term) + deriving Repr, Inhabited + +/-- A storage location, resolved from the storage layout. -/ +inductive Place where + /-- A slot fixed by the layout. -/ + | slot (n : Nat) + /-- `k` slots after `base`: a struct field, or an element of a fixed-size array. -/ + | offset (base : Place) (k : Term) + /-- The entry of the mapping at `base` for the value-typed key `key`: + `keccak256(key ++ slot(base))`, both as 32-byte words. -/ + | entry (base : Place) (key : Term) + /-- Element `index` of the dynamic array at `base`, whose elements take `slots` slots each: + `keccak256(slot(base)) + index * slots`. -/ + | elem (base : Place) (index : Term) (slots : Nat) + /-- The slot holding packed element `index` of the dynamic array at `base`, `perSlot` elements to + a slot: `keccak256(slot(base)) + index / perSlot`. Its byte offset is the reader's. -/ + | packedElem (base : Place) (index : Term) (perSlot : Nat) + deriving Repr, Inhabited +end + +/-- A spec function: a single-`return` pure or view function solar-verify unfolds in specs. +An `isOpaque` one is uninterpreted in solar-verify's proofs except where revealed; its meaning +here is its body, and `ret` is the range solar-verify assumes of its result +(`Semantics.OpaqueInRange`). -/ +structure SpecFn where + name : String + params : List (String × Ty) + ret : Ty + body : Term + isOpaque : Bool + deriving Repr, Inhabited + +/-- One function's spec. -/ +structure FnSpec where + /-- `Contract.name`. -/ + name : String + /-- The 4-byte ABI selector. -/ + selector : Nat + params : List Ty + rets : List Ty + payable : Bool + requires : List Term + ensures : List Term + succeedsIf : List Term + deriving Repr, Inhabited + +/-- A contract's specs. `invariants` are the contract's `@custom:invariant`s and, expanded +by the exporter over every stored value of the struct, its structs' invariants. -/ +structure ContractSpec where + name : String + fns : List SpecFn + invariants : List Term + ghosts : List String + specs : List FnSpec + deriving Repr, Inhabited + +/-- What a spec was exported from: the source and its sha256, the compiler that built the +bytecode, its options, and the runtime bytecode's sha256. `solar-verify --emit-lean` writes it; +a theorem about the spec is about these bytes only. -/ +structure Manifest where + source : String + sourceSha256 : String + compiler : String + options : List String + bytecodeSha256 : String + deriving Repr, Inhabited, DecidableEq + +end SolidCore.Spec diff --git a/Verify/Spec/TrustedBase.lean b/Verify/Spec/TrustedBase.lean new file mode 100644 index 00000000..b268b771 --- /dev/null +++ b/Verify/Spec/TrustedBase.lean @@ -0,0 +1,103 @@ +import Verify.Spec.Contract +import Verify.Spec.Ghost + +/-! +# solar-verify's trusted base, as named hypotheses + +solar-verify's ✔ is a claim of its own (crates/verify/README.md, "Trusted base"), checked by +Rust code and SMT solvers rather than by Lean's kernel. This module states that claim as one +proposition about the spec's meaning (`Verdict`), with every assumption of its model a separate, +named field of `Assumptions`, so that a theorem that rests on it says so in its statement and +never through an axiom. `spec_of_verdict` is the final theorem: the verdict on the source +semantics, and a kernel-checked refinement from the source to the bytecode, give the spec of the +bytecode on the calls where the assumptions hold. A spec proved of SolidCore in Lean instead +(`SolidCore.Spec.Solar.C4`) needs none of this. + +The items, in the README's order, and where each one is in the statement: + +1. "The parser, the encoding in `src/vc.rs` and `src/vc/yul.rs`, and the solvers": `Verdict` + itself. This includes that solar-verify's model of a function with its ghost code is a program + whose erasure is the function SolidCore runs; erasure itself is proved, not trusted + (`SolidCore.Spec.Ghost.spec_of_erased`), on a core language with solar-verify's discipline. +2. "`@custom:assume`, `@custom:trusted` and interface ensures": `Assumptions.assumptionsHold`. +3. "No `delegatecall` into the contract": `Assumptions.noDelegatecall`. It matters across calls: + the storage a call starts from is the one the previous call left. +4. "`keccak256` is injective and its results lie in `[2^128, 2^256)`": `Assumptions.keccakSeparated`, + per call. Stated for all inputs it is false (keccak256 maps unboundedly many inputs to 2^256 + words, and some 64-byte input almost surely hashes below 2^128), and a false hypothesis would + make every theorem that takes it vacuous; per call it says only that the hashes this call + computes are separated, which is what the encoding uses. +5. "Raw storage slots that assembly reaches are disjoint from the declared state variables, and + assembly is memory-safe": `Assumptions.asmSlotsDisjoint`, `Assumptions.asmMemorySafe`. +6. "A library named `Math` with a `mulDiv` ... is summarized as OpenZeppelin's": `Assumptions.mulDiv`. +7. "A high-level call to a view or pure function answers as a function of its target, its + arguments and the state it can read": `Assumptions.viewCalls`. + +Two more obligations come from giving specs a meaning, and are checked rather than trusted: every +spec function call resolves and nests within the exported fuel (`Bundle.WF`, by the kernel's +evaluation), and an opaque spec function's body stays in its return type's range, the range +solar-verify assumes of it (`OpaqueInRange`, proved per contract). +-/ + +namespace SolidCore.Spec + +open SolarTV + +/-- The per-call and global assumptions of solar-verify's model (items 2 to 7 above). Each is a +proposition supplied by whoever states the theorem; `Assumptions.none` assumes nothing. -/ +structure Assumptions where + /-- Item 2: on this call, every `@custom:assume` holds where it is assumed, every + `@custom:trusted` function meets its contract, and every external callee meets its interface's + ensures. -/ + assumptionsHold : Call → Prop + /-- Item 3: no account changes the contract's storage except through its own functions. -/ + noDelegatecall : Prop + /-- Item 4, per call: the keccak256 images this call computes are distinct for distinct + preimages and at least `2 ^ 128`. -/ + keccakSeparated : Call → Prop + /-- Item 5: on this call, the raw slots inline assembly reaches are none of the declared + variables' slots. -/ + asmSlotsDisjoint : Call → Prop + /-- Item 5: on this call, inline assembly is memory-safe. -/ + asmMemorySafe : Call → Prop + /-- Item 6: a library `Math.mulDiv` without specs computes OpenZeppelin's `Math.mulDiv`. -/ + mulDiv : Prop + /-- Item 7: view and pure calls answer as a function of their target, arguments and the state + they can read. -/ + viewCalls : Prop + +/-- Every assumption, on one call. -/ +def Assumptions.On (A : Assumptions) (call : Call) : Prop := + A.assumptionsHold call ∧ A.noDelegatecall ∧ A.keccakSeparated call ∧ A.asmSlotsDisjoint call ∧ + A.asmMemorySafe call ∧ A.mulDiv ∧ A.viewCalls + +/-- No assumption at all: the case of a contract without assumes, trusted functions, external +calls, mappings, assembly or `Math.mulDiv`, or of a spec proved in Lean. -/ +def Assumptions.none : Assumptions := + ⟨fun _ => True, True, fun _ => True, fun _ => True, fun _ => True, True, True⟩ + +theorem Assumptions.none_on (call : Call) : Assumptions.none.On call := by + simp [Assumptions.On, Assumptions.none] + +/-- Item 1, **solar-verify's verdict**: its ✔ on every function of the bundle means the spec +holds of the source program `p` in `S` on the calls of the scope where the assumptions hold. This +is the trusted claim; nothing in Lean proves it. -/ +def Verdict (S : Sem) (p : S.Prog) (scope : Call → Prop) (b : Bundle) (ctxOf : Call → Ctx) + (step : GhostStep) (A : Assumptions) : Prop := + Holds S p (fun call => scope call ∧ A.On call) b ctxOf step + +/-! ## The final theorem -/ + +/-- **The spec of the bytecode, from solar-verify's verdict.** A kernel-checked stage from the +source semantics `S` to the target `T` (for SolidCore and EthLib, a certified translation of the +contract to its bytecode), and solar-verify's verdict on the source (trusted, item 1), give the +spec of the target on every call of the scope where the assumptions (items 2 to 7) hold. The +bundle's well-formedness and the opaque functions' ranges are hypotheses checked per contract. -/ +theorem spec_of_verdict {S T : Sem} {p : S.Prog} {q : T.Prog} {scope : Call → Prop} {b : Bundle} + {ctxOf : Call → Ctx} {step : GhostStep} {A : Assumptions} + (_wf : b.WF = true) (_opaque : OpaqueInRange b) + (verdict : Verdict S p scope b ctxOf step A) (stage : Stage S T p q scope) : + Holds T q (fun call => scope call ∧ A.On call) b ctxOf step := + verdict.of_stage (Stage.mono stage fun _ h => h.1) + +end SolidCore.Spec diff --git a/Verify/Spec/TrustedBase/Axioms.lean b/Verify/Spec/TrustedBase/Axioms.lean new file mode 100644 index 00000000..19979aac --- /dev/null +++ b/Verify/Spec/TrustedBase/Axioms.lean @@ -0,0 +1,45 @@ +import Verify.Spec.TrustedBase.Instances +import Verify.Spec.TrustedBase.Interface + +/-! The axioms of the trusted base's theorems: `propext`, `Classical.choice` and `Quot.sound` at most, +and no `sorry`, `native_decide` (`Lean.ofReduceBool`) or `bv_decide`. -/ + +open SolidCore.Spec.TrustedBase in +section +#print axioms keccakSeparated_empty +#print axioms keccakSeparated_mapping +#print axioms not_keccakSeparated_univ +#print axioms Core.exec_dropAssumes +#print axioms Core.assumesHold_of_noAssume +#print axioms Core.spec_of_assumes +#print axioms Core.assumesHold_assumeX +#print axioms Core.not_assumesHold_assumeX +#print axioms Core.meetsContract_assign +#print axioms Core.not_meetsContract_assign +#print axioms trustedHold_nil +#print axioms trustedHold_of_holds +#print axioms follows_transcriptWith +#print axioms defaultCalls_transcriptWith +#print axioms interfaceEnsures_of_default +#print axioms interfaceEnsures_of_default' +#print axioms interfaceEnsures_one +#print axioms not_interfaceEnsures_zero +#print axioms viewDeterministic_of_default +#print axioms noForeignWrites_of_default +#print axioms viewDeterministic_twice +#print axioms not_viewDeterministic +#print axioms Reach.trans +#print axioms asmFree_example +#print axioms not_asmFree_example +#print axioms mulDivSummary_oz +#print axioms not_mulDivSummary_unchecked +#print axioms ozMulDiv_spec +#print axioms Hyps.plain_on +#print axioms Hyps.satisfiable +#print axioms spec_of_verdict_hyps +#print axioms Instances.asmFree_c4 +#print axioms Instances.asmFree_counter +#print axioms Instances.c4_on +#print axioms Instances.counter_on +#print axioms Instances.counter_spec_of_verdict +end diff --git a/Verify/Spec/TrustedBase/Hypotheses.lean b/Verify/Spec/TrustedBase/Hypotheses.lean new file mode 100644 index 00000000..bdb70556 --- /dev/null +++ b/Verify/Spec/TrustedBase/Hypotheses.lean @@ -0,0 +1,657 @@ +import Verify.Spec.TrustedBase +import EvmInteraction.Simulation.Interaction +import SolidCore.Solidity.Ast + +/-! +# solar-verify's trusted base, item by item, as precise hypotheses + +`SolidCore.Spec.TrustedBase.Assumptions` names each item of solar-verify's trusted base +(crates/verify/README.md, "Trusted base") as a field, but leaves each field an arbitrary +proposition. This module gives each item a precise statement over the objects the composition +already has: `SolarTV.Call`/`Observable` and a `Sem`, the transcripts of query/answer exchanges +SolidCore's interaction trees make with the outside world (`EvmCompiler.Simulation.Interaction`), +the core language of ghost code (`SolidCore.Spec.Ghost`) and the Solidity AST. `Hyps` collects +them, `Hyps.toAssumptions` instantiates `Assumptions` with them, and `spec_of_verdict_hyps` is +`spec_of_verdict` with the precise hypotheses. + +For each item: the statement, a witness that it is satisfiable (not `False` in disguise), where +it is cheap a witness that it is not trivially `True` either, and the discharge for code that does +not use the feature. + +| README item | Here | Discharged when | +|---|---|---| +| keccak256 injective, results in `[2^128, 2^256)` | `KeccakSeparated` of the call's preimages | no preimages (`keccakSeparated_empty`); checked by the kernel on concrete ones (`keccakSeparated_mapping`) | +| `@custom:assume` | `AssumesHold` | the body has no assume (`assumesHold_of_noAssume`) | +| `@custom:trusted` (internal) | `MeetsContract` | no trusted function | +| `@custom:trusted` (external) | `TrustedHold` | no trusted function (`trustedHold_nil`), or the spec proved (`trustedHold_of_holds`) | +| interface ensures | `InterfaceEnsures` | every external call fails, e.g. SolidCore's fail-open answers (`DefaultCalls`) | +| no delegatecall into the contract | `NoForeignWrites` within a call, `Reach` across calls | `DefaultCalls` | +| assembly slots disjoint, memory-safe | `AsmFree` (stronger) | the source has no assembly (`AsmFree` by `decide`) | +| `Math.mulDiv` summary | `MulDivSummary` | no `Math.mulDiv` | +| view calls deterministic | `ViewDeterministic` | `DefaultCalls` | + +Two items are stated against data the theorem's user supplies rather than derived from SolidCore's +run, and the gap is named where they are: the keccak256 preimages a call hashes +(`Hyps.keccakInputs`) and the transcript of a call (`Hyps.transcript`; `transcriptWith` computes it +from an interaction tree and an answerer, but `Source.run` does not yet expose its tree). Item 1 +(the parser, the VC encoding and the solvers) stays `Verdict` itself. +-/ + +namespace SolidCore.Spec.TrustedBase + +open SolarTV SolidCore.Spec + +/-! ## keccak256 -/ + +/-- A set of keccak256 preimages (byte lists), as a predicate. -/ +abbrev Preimages := List Nat → Prop + +/-- **keccak256 is separated on `S`**: injective on `S`, and every image at least `2 ^ 128`, so +no image is a small constant slot. Stated for every input it is false (`not_keccakSeparated_univ`); +solar-verify's encoding uses it only on the preimages a call hashes. -/ +def KeccakSeparated (S : Preimages) : Prop := + (∀ x y, S x → S y → keccakWord x = keccakWord y → x = y) ∧ ∀ x, S x → 2 ^ 128 ≤ keccakWord x + +theorem KeccakSeparated.mono {S T : Preimages} (h : KeccakSeparated T) (hST : ∀ x, S x → T x) : + KeccakSeparated S := + ⟨fun x y hx hy he => h.1 x y (hST x hx) (hST y hy) he, fun x hx => h.2 x (hST x hx)⟩ + +/-- A call that hashes nothing needs nothing of keccak256. -/ +theorem keccakSeparated_empty : KeccakSeparated (fun _ => False) := + ⟨fun _ _ h => h.elim, fun _ h => h.elim⟩ + +/-- Injectivity on a list from distinct images. -/ +theorem inj_of_nodup_map {α β : Type} {f : α → β} : + ∀ {l : List α}, (l.map f).Nodup → ∀ x ∈ l, ∀ y ∈ l, f x = f y → x = y + | [], _, _, hx, _, _, _ => by simp at hx + | a :: l, h, x, hx, y, hy, he => by + simp only [List.map_cons, List.nodup_cons, List.mem_map] at h + simp only [List.mem_cons] at hx hy + rcases hx with rfl | hx <;> rcases hy with rfl | hy + · rfl + · exact absurd ⟨y, hy, he.symm⟩ h.1 + · exact absurd ⟨x, hx, he⟩ h.1 + · exact inj_of_nodup_map h.2 x hx y hy he + +/-- Separation on a list, from its images: distinct and each at least `2 ^ 128`. -/ +theorem keccakSeparated_of_images {L : List (List Nat)} {H : List Nat} + (hH : L.map keccakWord = H) (hnd : H.Nodup) (hge : ∀ v ∈ H, 2 ^ 128 ≤ v) : + KeccakSeparated (· ∈ L) := + ⟨fun x y hx hy he => inj_of_nodup_map (hH ▸ hnd) x hx y hy he, + fun _ hx => hge _ (hH ▸ List.mem_map_of_mem hx)⟩ + +/-- The preimage of the slot of `m[k]` for a mapping `m` at slot `s`: `k` then `s`, as words. -/ +def mappingPreimage (k s : Nat) : List Nat := wordBytes k ++ wordBytes s + +/-- The slots of `m[0]`, `m[1]` and `m[0x2000]` (`msg.sender` for `callerAddress`) for mappings at slots 0 +and 1. -/ +def mappingPreimages : List (List Nat) := + [mappingPreimage 0 0, mappingPreimage 1 0, mappingPreimage 0x2000 0, mappingPreimage 0 1, + mappingPreimage 1 1, mappingPreimage 0x2000 1] + +/-! Their keccak256 images, each by the kernel's evaluation of the sponge (one per declaration, +so that the kernel's caches stay small). -/ + +set_option maxRecDepth 100000 in +theorem image0 : keccakWord (mappingPreimage 0 0) = + 0xad3228b676f7d3cd4284a5443f17f1962b36e491b30a40b2405849e597ba5fb5 := by + decide +kernel + +set_option maxRecDepth 100000 in +theorem image1 : keccakWord (mappingPreimage 1 0) = + 0xada5013122d395ba3c54772283fb069b10426056ef8ca54750cb9bb552a59e7d := by + decide +kernel + +set_option maxRecDepth 100000 in +theorem image2 : keccakWord (mappingPreimage 0x2000 0) = + 0x7a590e257d634ba5db8688524231d50b5351ea3cd1a840d196ed0e2098593fd8 := by + decide +kernel + +set_option maxRecDepth 100000 in +theorem image3 : keccakWord (mappingPreimage 0 1) = + 0xa6eef7e35abe7026729641147f7915573c7e97b47efa546f5f6e3230263bcb49 := by + decide +kernel + +set_option maxRecDepth 100000 in +theorem image4 : keccakWord (mappingPreimage 1 1) = + 0xcc69885fda6bcc1a4ace058b4a62bf5e179ea78fd58a1ccd71c22cc9b688792f := by + decide +kernel + +set_option maxRecDepth 100000 in +theorem image5 : keccakWord (mappingPreimage 0x2000 1) = + 0x38da9dc9759c46bd12ce677a753bb966a85f8995667f5aade8c3f5d0f1de587a := by + decide +kernel + +theorem mappingPreimages_images : + mappingPreimages.map keccakWord = + [0xad3228b676f7d3cd4284a5443f17f1962b36e491b30a40b2405849e597ba5fb5, + 0xada5013122d395ba3c54772283fb069b10426056ef8ca54750cb9bb552a59e7d, + 0x7a590e257d634ba5db8688524231d50b5351ea3cd1a840d196ed0e2098593fd8, + 0xa6eef7e35abe7026729641147f7915573c7e97b47efa546f5f6e3230263bcb49, + 0xcc69885fda6bcc1a4ace058b4a62bf5e179ea78fd58a1ccd71c22cc9b688792f, + 0x38da9dc9759c46bd12ce677a753bb966a85f8995667f5aade8c3f5d0f1de587a] := by + simp only [mappingPreimages, List.map_cons, List.map_nil, image0, image1, image2, image3, image4, + image5] + +/-- **Satisfiable on real preimages**: keccak256 is separated on `mappingPreimages`. -/ +theorem keccakSeparated_mapping : KeccakSeparated (· ∈ mappingPreimages) := + keccakSeparated_of_images mappingPreimages_images (by decide) (by decide) + +set_option maxRecDepth 100000 in +theorem not_keccakSeparated_univ : ¬ KeccakSeparated (fun _ => True) := by + intro h + have := h.1 [0] [256] trivial trivial (by decide +kernel) + simp at this + +/-! ## `@custom:assume` and `@custom:trusted`, on the core language of ghost code -/ + +namespace Core +open SolidCore.Spec.Ghost + +/-- The program with every `assume` replaced by `skip`. -/ +def dropAssumes : Ghost.Stmt → Ghost.Stmt + | .assume _ => .skip + | .seq s t => .seq (dropAssumes s) (dropAssumes t) + | .ite c s t => .ite c (dropAssumes s) (dropAssumes t) + | .loop c b => .loop c (dropAssumes b) + | s => s + +/-- The program has no `assume`. -/ +def noAssume : Ghost.Stmt → Bool + | .assume _ => false + | .seq s t => noAssume s && noAssume t + | .ite _ s t => noAssume s && noAssume t + | .loop _ b => noAssume b + | _ => true + +/-- **Every `@custom:assume` holds where it is reached** from `σ`: every execution of the program +without its assumes is one of the program, so no assume cuts an execution off. -/ +def AssumesHold (s : Ghost.Stmt) (σ : Store) : Prop := + ∀ o, Exec (dropAssumes s) σ o → Exec s σ o + +/-- Dropping assumes only adds executions. -/ +theorem exec_dropAssumes {s : Ghost.Stmt} {σ : Store} {o : Out} (h : Exec s σ o) : + Exec (dropAssumes s) σ o := by + induction h with + | skip => exact .skip + | assign => exact .assign + | requireOk h => exact .requireOk h + | requireRev h => exact .requireRev h + | seqOk _ _ ih1 ih2 => exact .seqOk ih1 ih2 + | seqRev _ ih => exact .seqRev ih + | seqFail _ ih => exact .seqFail ih + | iteT hc _ ih => exact .iteT hc ih + | iteF hc _ ih => exact .iteF hc ih + | loopDone hc => exact .loopDone hc + | loopOk hc _ _ ih1 ih2 => exact .loopOk hc ih1 ih2 + | loopRev hc _ ih => exact .loopRev hc ih + | loopFail hc _ ih => exact .loopFail hc ih + | ghost => exact .ghost + | assertOk h => exact .assertOk h + | assertFail h => exact .assertFail h + | assume _ => exact .skip + +theorem dropAssumes_of_noAssume : ∀ {s : Ghost.Stmt}, noAssume s = true → dropAssumes s = s + | .skip, _ | .assign _ _, _ | .require _, _ | .ghost _ _, _ | .assert _, _ => rfl + | .assume _, h => by simp [noAssume] at h + | .seq s t, h => by + simp only [noAssume, Bool.and_eq_true] at h + simp [dropAssumes, dropAssumes_of_noAssume h.1, dropAssumes_of_noAssume h.2] + | .ite c s t, h => by + simp only [noAssume, Bool.and_eq_true] at h + simp [dropAssumes, dropAssumes_of_noAssume h.1, dropAssumes_of_noAssume h.2] + | .loop c b, h => by + simp only [noAssume] at h + simp [dropAssumes, dropAssumes_of_noAssume h] + +/-- **Discharged without assumes.** -/ +theorem assumesHold_of_noAssume {s : Ghost.Stmt} (h : noAssume s = true) (σ : Store) : + AssumesHold s σ := by + intro o ho + rwa [dropAssumes_of_noAssume h] at ho + +/-- What a proof of `s` gives the program without its assumes, where they hold. -/ +theorem spec_of_assumes {s : Ghost.Stmt} {σ : Store} {Q : Out → Prop} + (hs : ∀ o, Exec s σ o → Q o) (ha : AssumesHold s σ) : ∀ o, Exec (dropAssumes s) σ o → Q o := + fun o ho => hs o (ha o ho) + +/-- `@custom:assume x`. -/ +def assumeX : Ghost.Stmt := .assume (.var "x") + +/-- **Satisfiable**: `assume x` holds from a store where `x = 1`. -/ +theorem assumesHold_assumeX : AssumesHold assumeX (fun _ => 1) := by + intro o ho + cases ho + exact .assume (by simp [Exp.eval]) + +/-- **Not trivial**: it fails from a store where `x = 0`. -/ +theorem not_assumesHold_assumeX : ¬ AssumesHold assumeX (fun _ => 0) := by + intro h + have := h _ (Exec.skip (σ := fun _ => 0)) + cases this with + | assume hx => exact hx (by simp [Exp.eval]) + +/-- **A `@custom:trusted` internal function meets its contract**: from every store meeting `req`, +every execution of its body `s` meets `ens`. -/ +def MeetsContract (s : Ghost.Stmt) (req : Store → Prop) (ens : Store → Out → Prop) : Prop := + ∀ σ, req σ → ∀ o, Exec s σ o → ens σ o + +/-- **Satisfiable**: `r = 1` ensures `r == 1`. -/ +theorem meetsContract_assign : + MeetsContract (.assign "r" (.lit 1)) (fun _ => True) + (fun _ o => ∃ σ', o = .ok σ' ∧ σ' "r" = 1) := by + intro σ _ o ho + cases ho + exact ⟨_, rfl, by simp [Store.set, Exp.eval]⟩ + +/-- **Not trivial**: `r = 0` does not. -/ +theorem not_meetsContract_assign : + ¬ MeetsContract (.assign "r" (.lit 0)) (fun _ => True) + (fun _ o => ∃ σ', o = .ok σ' ∧ σ' "r" = 1) := by + intro h + obtain ⟨σ', h1, h2⟩ := h (fun _ => 0) trivial _ .assign + cases h1 + simp [Store.set, Exp.eval] at h2 + +end Core + +/-! ## `@custom:trusted` external and public functions, on calls -/ + +/-- The bundle restricted to the functions named. -/ +def Bundle.only (b : Bundle) (names : List String) : Bundle := + { b with spec := { b.spec with specs := b.spec.specs.filter (fun fs => names.contains fs.name) } } + +/-- **The `@custom:trusted` external functions `names` meet their specs** on `p` in `S`: their +bodies are not verified, so their specs are assumed. -/ +def TrustedHold (S : Sem) (p : S.Prog) (scope : Call → Prop) (b : Bundle) (ctxOf : Call → Ctx) + (step : GhostStep) (names : List String) : Prop := + Holds S p scope (Bundle.only b names) ctxOf step + +/-- **Discharged without trusted functions.** -/ +theorem trustedHold_nil {S : Sem} {p : S.Prog} {scope : Call → Prop} {b : Bundle} + {ctxOf : Call → Ctx} {step : GhostStep} : TrustedHold S p scope b ctxOf step [] := by + intro fs hfs + simp [Bundle.only] at hfs + +/-- **Discharged by a proof**: a spec proved of every function, in Lean or otherwise, holds of the +trusted ones. -/ +theorem trustedHold_of_holds {S : Sem} {p : S.Prog} {scope : Call → Prop} {b : Bundle} + {ctxOf : Call → Ctx} {step : GhostStep} (names : List String) + (h : Holds S p scope b ctxOf step) : TrustedHold S p scope b ctxOf step names := by + intro fs hfs + simp only [Bundle.only, List.mem_filter] at hfs + exact h fs hfs.1 + +/-! ## External calls: interface ensures, view calls and writes by others + +SolidCore runs a function as an interaction tree whose external calls are `Query.external` nodes, +answered by an answerer; a run's transcript is the list of its exchanges. These items are +properties of a transcript's call exchanges: the world the call was made in, the request and the +response (whose `postWorld` the caller adopts). +-/ + +open EvmCompiler.Simulation + +/-- The call exchanges of a transcript: world, request, response. -/ +def callsOf : Interaction.Transcript → List (OpenWorld × CallRequest × CallResponse) + | [] => [] + | ⟨.external w (.call r), a⟩ :: tr => (w, r, a) :: callsOf tr + | _ :: tr => callsOf tr + +/-- The transcript of an interaction tree answered by `ans`. -/ +def transcriptWith {ε α : Type} (ans : (q : Query) → Answer q) : + Interaction ε α → Interaction.Transcript + | .done _ => [] + | .request q k => ⟨q, ans q⟩ :: transcriptWith ans (k (ans q)) + +/-- The transcript is a branch of the tree. -/ +theorem follows_transcriptWith {ε α : Type} (ans : (q : Query) → Answer q) : + ∀ t : Interaction ε α, Interaction.Follows t (transcriptWith ans t) + | .done _ => .nil _ + | .request q k => .request (follows_transcriptWith ans (k (ans q))) + +/-- **Interface ensures**: every external call that returns meets `ens`, the interface's ensures +on the request (target and calldata) and the returned data. -/ +def InterfaceEnsures (ens : CallRequest → CallResponse → Prop) (tr : Interaction.Transcript) : + Prop := + ∀ c ∈ callsOf tr, c.2.2.success = true → ens c.2.1 c.2.2 + +/-- What a view call may read, as solar-verify's README puts it: the balance and code of every +account, and the storage of the calling contract `self`. -/ +def ReadAgree (self : InteractionAddress) (w w' : OpenWorld) : Prop := + (∀ a, (w.accounts.find? a).map (fun acc => (acc.balance, acc.codeBytes)) = + (w'.accounts.find? a).map (fun acc => (acc.balance, acc.codeBytes))) ∧ + ∀ k, (w.accounts.find? self).map (fun acc => acc.storage.find? k) = + (w'.accounts.find? self).map (fun acc => acc.storage.find? k) + +/-- **View calls are deterministic**: two static calls to the same target with the same calldata, +from worlds that agree on what a view call may read, answer alike, whatever gas each carried. -/ +def ViewDeterministic (self : InteractionAddress) (tr : Interaction.Transcript) : Prop := + ∀ c₁ ∈ callsOf tr, ∀ c₂ ∈ callsOf tr, c₁.2.1.kind = .staticcall → c₂.2.1.kind = .staticcall → + c₁.2.1.recipient = c₂.2.1.recipient → c₁.2.1.calldata = c₂.2.1.calldata → + ReadAgree self c₁.1 c₂.1 → + c₁.2.2.success = c₂.2.2.success ∧ c₁.2.2.returnData = c₂.2.2.returnData + +/-- `self`'s storage in a world, as a slot function (absent slots and accounts read zero). -/ +def selfSlots (self : InteractionAddress) (w : OpenWorld) : Nat → Nat := fun k => + (((w.accounts.find? self).bind fun acc => acc.storage.find? (EvmYul.UInt256.ofNat k)).map + EvmYul.UInt256.toNat).getD 0 + +/-- Storage `σ'` is reachable from `σ` through the contract's own functions: by successful calls of +`p` in `S`, each from the storage the previous one left. -/ +inductive Reach (S : Sem) (p : S.Prog) : (Nat → Nat) → (Nat → Nat) → Prop + | refl (σ : Nat → Nat) : Reach S p σ σ + | step {σ σ' : Nat → Nat} (call : Call) (obs : Observable) : + slotValue call.storage = σ → S.run p call = some obs → obs.success = true → + Reach S p obs.storage σ' → Reach S p σ σ' + +theorem Reach.trans {S : Sem} {p : S.Prog} {σ σ' σ'' : Nat → Nat} (h : Reach S p σ σ') + (h' : Reach S p σ' σ'') : Reach S p σ σ'' := by + induction h with + | refl => exact h' + | step call obs hs hr hok _ ih => exact .step call obs hs hr hok (ih h') + +/-- **No delegatecall into the contract**, within a call: across each external call, `self`'s +storage changes only by reentrant calls of its own functions. Across transactions the same +relation, `Reach S p deployed (slotValue call.storage)`, restricts the calls a theorem covers to +those from a storage the contract's functions reach from deployment (`Hyps.reachable`). -/ +def NoForeignWrites (S : Sem) (p : S.Prog) (self : InteractionAddress) + (tr : Interaction.Transcript) : Prop := + ∀ c ∈ callsOf tr, Reach S p (selfSlots self c.1) (selfSlots self c.2.2.postWorld) + +/-- The default, fail-open response to a call from `w`: failure, no data, the world unchanged. -/ +def defaultResponse (w : OpenWorld) : CallResponse := + CallResponse.mk false default w (EvmYul.UInt256.ofNat 0) + +/-- Every external call of the transcript got the default, fail-open answer: failure, no data, +the world unchanged. SolidCore's `contextAnswer` gives it to every call that is not a precompile's. -/ +def DefaultCalls (tr : Interaction.Transcript) : Prop := + ∀ c ∈ callsOf tr, c.2.2 = defaultResponse c.1 + +/-- An answerer that gives every external call the default answer. -/ +def DefaultOnCalls (ans : (q : Query) → Answer q) : Prop := + ∀ w r, ans (.external w (.call r)) = Query.defaultAnswer (.external w (.call r)) + +theorem defaultCalls_cons_call {w : OpenWorld} {r : CallRequest} {a : CallResponse} + {tr : Interaction.Transcript} + (ha : a = defaultResponse w) (h : DefaultCalls tr) : + DefaultCalls (⟨.external w (.call r), a⟩ :: tr) := by + intro c hc + simp only [callsOf, List.mem_cons] at hc + rcases hc with rfl | hc + · exact ha + · exact h c hc + +/-- An answerer defaulting on calls yields a transcript with default calls, on every tree. -/ +theorem defaultCalls_transcriptWith {ε α : Type} {ans : (q : Query) → Answer q} + (hans : DefaultOnCalls ans) : ∀ t : Interaction ε α, DefaultCalls (transcriptWith ans t) + | .done _ => fun _ h => by simp [transcriptWith, callsOf] at h + | .request q k => by + have ih := defaultCalls_transcriptWith hans (k (ans q)) + match q with + | .external w (.call r) => + exact defaultCalls_cons_call ((hans w r).trans rfl) ih + | .external w (.create r) => + intro c hc + exact ih c (by simpa [transcriptWith, callsOf] using hc) + | .resource r => + intro c hc + exact ih c (by simpa [transcriptWith, callsOf] using hc) + +/-- **Interface ensures, discharged** where no external call returns. -/ +theorem interfaceEnsures_of_default {ens : CallRequest → CallResponse → Prop} + {tr : Interaction.Transcript} (h : DefaultCalls tr) : InterfaceEnsures ens tr := by + intro c hc hs + rw [h c hc] at hs + cases hs + +/-- **View calls, discharged** where every call gets the default answer. -/ +theorem viewDeterministic_of_default {self : InteractionAddress} {tr : Interaction.Transcript} + (h : DefaultCalls tr) : ViewDeterministic self tr := by + intro c₁ h₁ c₂ h₂ _ _ _ _ _ + rw [h c₁ h₁, h c₂ h₂] + exact ⟨rfl, rfl⟩ + +/-- **Writes by others, discharged** where every call gets the default answer. -/ +theorem noForeignWrites_of_default {S : Sem} {p : S.Prog} {self : InteractionAddress} + {tr : Interaction.Transcript} (h : DefaultCalls tr) : NoForeignWrites S p self tr := by + intro c hc + rw [h c hc] + exact .refl _ + +/-- A static call to target 1 with empty calldata, from the default world. -/ +def staticReq : CallRequest := + { kind := .staticcall, requestedGas := EvmYul.UInt256.ofNat 0, caller := default, + recipient := default, codeAddress := default, transferValue := EvmYul.UInt256.ofNat 0, + apparentValue := EvmYul.UInt256.ofNat 0, calldata := .empty, permission := false } + +/-- The same static call, answered with `ok` and the data `d`. -/ +def staticEx (ok : Bool) (d : ByteArray) : Interaction.Exchange := + ⟨.external default (.call staticReq), + (CallResponse.mk ok d default (EvmYul.UInt256.ofNat 0) : CallResponse)⟩ + +/-- **Satisfiable with calls that return**: the same view call twice, answered alike. -/ +theorem viewDeterministic_twice (self : InteractionAddress) (d : ByteArray) : + ViewDeterministic self [staticEx true d, staticEx true d] := by + intro c₁ h₁ c₂ h₂ _ _ _ _ _ + simp only [callsOf, staticEx, List.mem_cons, List.not_mem_nil, or_false] at h₁ h₂ + rcases h₁ with rfl | rfl <;> rcases h₂ with rfl | rfl <;> exact ⟨rfl, rfl⟩ + +theorem readAgree_refl (self : InteractionAddress) (w : OpenWorld) : ReadAgree self w w := + ⟨fun _ => rfl, fun _ => rfl⟩ + +/-- **Not trivial**: the same view call answered once with success and once without breaks it. -/ +theorem not_viewDeterministic (self : InteractionAddress) : + ¬ ViewDeterministic self [staticEx true .empty, staticEx false .empty] := by + intro h + have := h (default, staticReq, CallResponse.mk true .empty default (EvmYul.UInt256.ofNat 0)) + (by simp [callsOf, staticEx]) (default, staticReq, CallResponse.mk false .empty default + (EvmYul.UInt256.ofNat 0)) (by simp [callsOf, staticEx]) rfl rfl rfl rfl (readAgree_refl _ _) + simp at this + +/-! ## Inline assembly -/ + +open SolidCore.Solidity in +mutual +/-- The statement contains inline assembly. -/ +def stmtHasAsm : Solidity.Stmt → Bool + | .inlineAssembly _ => true + | .block ss => stmtsHaveAsm ss + | .ifElse _ s none => stmtHasAsm s + | .ifElse _ s (some t) => stmtHasAsm s || stmtHasAsm t + | .whileLoop _ s => stmtHasAsm s + | .doWhile s _ => stmtHasAsm s + | .forLoop none _ _ s => stmtHasAsm s + | .forLoop (some i) _ _ s => stmtHasAsm i || stmtHasAsm s + | .tryCatch _ cs => clausesHaveAsm cs + | .tryCatchReturns _ _ s cs => stmtHasAsm s || clausesHaveAsm cs + | .unchecked s => stmtHasAsm s + | .empty | .varDecl _ _ | .expr _ | .emitEvent _ | .revertCall _ | .returnValues _ | .break + | .continue | .modifierPlaceholder => false + +def stmtsHaveAsm : List Solidity.Stmt → Bool + | [] => false + | s :: ss => stmtHasAsm s || stmtsHaveAsm ss + +def clausesHaveAsm : List Solidity.CatchClause → Bool + | [] => false + | .clause _ _ s :: cs => stmtHasAsm s || clausesHaveAsm cs +end + +/-- A body that may be absent contains inline assembly. -/ +def bodyHasAsm : Option Solidity.Stmt → Bool + | none => false + | some s => stmtHasAsm s + +/-- A contract item contains inline assembly. -/ +def itemHasAsm : Solidity.ContractItem → Bool + | .function f => bodyHasAsm f.body + | .modifierDecl m => bodyHasAsm m.body + | _ => false + +/-- A source item contains inline assembly. -/ +def sourceItemHasAsm : Solidity.SourceItem → Bool + | .contract c => c.items.any itemHasAsm + | .freeFunction f => bodyHasAsm f.body + | _ => false + +/-- **No inline assembly** anywhere in the source unit. SolidCore's type checker rejects inline +assembly, and its AST keeps a block as an unparsed string, so the composition can rely only on +this, which is stronger than README item 5 (raw slots that assembly reaches are disjoint from the +declared variables, and assembly is memory-safe) and implies it: with no assembly there is no +raw slot and no assembly memory access. Contracts with assembly fail closed, at type checking. -/ +def AsmFree (u : Solidity.SourceUnit) : Prop := u.items.any sourceItemHasAsm = false + +instance (u : Solidity.SourceUnit) : Decidable (AsmFree u) := by unfold AsmFree; infer_instance + +/-- A source unit with one contract and one function with body `body`. -/ +def exampleFn (body : Solidity.Stmt) : Solidity.SourceUnit := + Solidity.SourceUnit.mk [.contract (Solidity.ContractDecl.mk .contract "C" false none [] + [.function { body := some body }])] + +/-- **Satisfiable**: a contract with one empty function. -/ +theorem asmFree_example : AsmFree (exampleFn .empty) := by decide + +/-- **Not trivial**: a function whose body is an assembly block. -/ +theorem not_asmFree_example : + ¬ AsmFree (exampleFn (.block [.inlineAssembly "sstore(0, 1)"])) := by + decide + +/-! ## `Math.mulDiv` -/ + +/-- OpenZeppelin's `Math.mulDiv(x, y, d)` on words: `⌊x * y / d⌋`, or a revert (`none`) when `d` is +zero or the quotient does not fit a word. -/ +def ozMulDiv (x y d : Nat) : Option Nat := + if d = 0 ∨ 2 ^ 256 ≤ x * y / d then none else some (x * y / d) + +/-- **`Math.mulDiv` is OpenZeppelin's**: the library function, as a function of its word arguments +to its result or a revert (`impl`), agrees with `ozMulDiv` on every word. -/ +def MulDivSummary (impl : Nat → Nat → Nat → Option Nat) : Prop := + ∀ x y d, x < 2 ^ 256 → y < 2 ^ 256 → d < 2 ^ 256 → impl x y d = ozMulDiv x y d + +/-- **Satisfiable**: by the summary itself. -/ +theorem mulDivSummary_oz : MulDivSummary ozMulDiv := fun _ _ _ _ _ _ => rfl + +/-- **Not trivial**: plain `x * y / d` without the overflow check is not the summary +(`2^255 * 4 / 2` overflows a word). -/ +theorem not_mulDivSummary_unchecked : + ¬ MulDivSummary (fun x y d => if d = 0 then none else some (x * y / d)) := by + intro h + have := h (2 ^ 255) 4 2 (by decide) (by decide) (by decide) + simp [ozMulDiv] at this + +/-- The summary's full-precision meaning: what it returns is the floor of the exact quotient. -/ +theorem ozMulDiv_spec {x y d r : Nat} (h : ozMulDiv x y d = some r) : + 0 < d ∧ r * d ≤ x * y ∧ x * y < (r + 1) * d ∧ r < 2 ^ 256 := by + unfold ozMulDiv at h + split at h + · cases h + · rename_i hn + cases h + have hd : 0 < d := Nat.pos_of_ne_zero (fun h0 => hn (Or.inl h0)) + refine ⟨hd, Nat.div_mul_le_self _ _, ?_, Nat.lt_of_not_le (fun h' => hn (Or.inr h'))⟩ + rw [Nat.mul_comm _ d] + exact Nat.lt_mul_div_succ _ hd + +/-! ## All of it -/ + +/-- The data the precise trusted base is stated over, for a source program `p` in `S`: + +* `keccakInputs call`: the keccak256 preimages the call hashes. Supplied, not derived: SolidCore + hashes inside its interpreter, not through a query, so its runs do not yet expose them. +* `transcript call`: the call's exchanges with the outside world. Supplied: `transcriptWith` + computes it from an interaction tree and an answerer, but `Source.run` does not expose its tree. +* `self`: the contract's address in those worlds; `deployed`: its storage after deployment. +* `ifaceEns`: the external interfaces' ensures, on a request and its response. +* `assumeSites call`: each body with `@custom:assume`s the call runs, with the store it starts + from; `trustedBodies`: each `@custom:trusted` internal function's body, requires and ensures; + `trustedNames`: the `@custom:trusted` external functions. +* `source`: the Solidity source unit SolidCore checked; `mulDiv`: the contract's `Math.mulDiv`, + if it has one. -/ +structure Hyps (S : Sem) (p : S.Prog) where + keccakInputs : Call → Preimages + transcript : Call → Interaction.Transcript + self : InteractionAddress + deployed : Nat → Nat + ifaceEns : CallRequest → CallResponse → Prop + assumeSites : Call → List (Ghost.Stmt × Ghost.Store) + trustedBodies : List (Ghost.Stmt × (Ghost.Store → Prop) × (Ghost.Store → Ghost.Out → Prop)) + trustedNames : List String + source : Solidity.SourceUnit + mulDiv : Option (Nat → Nat → Nat → Option Nat) + +namespace Hyps + +variable {S : Sem} {p : S.Prog} (H : Hyps S p) + +/-- The contract's `Math.mulDiv` is OpenZeppelin's, if it has one. -/ +def MulDivOk : Prop := ∀ f, H.mulDiv = some f → MulDivSummary f + +/-- **The trusted base, precisely**, as `Assumptions` for `spec_of_verdict`: item 2 is +`AssumesHold` at every assume site, `MeetsContract` of every trusted internal body, `TrustedHold` +of the trusted external functions and `InterfaceEnsures`; item 3 `NoForeignWrites` of every call; +item 4 `KeccakSeparated` of the call's preimages; item 5 `AsmFree`; item 6 `MulDivSummary`; item 7 +`ViewDeterministic` of every call. -/ +def toAssumptions (scope : Call → Prop) (b : Bundle) (ctxOf : Call → Ctx) (step : GhostStep) : + Assumptions where + assumptionsHold call := + (∀ x ∈ H.assumeSites call, Core.AssumesHold x.1 x.2) ∧ + (∀ t ∈ H.trustedBodies, Core.MeetsContract t.1 t.2.1 t.2.2) ∧ + TrustedHold S p scope b ctxOf step H.trustedNames ∧ + InterfaceEnsures H.ifaceEns (H.transcript call) + noDelegatecall := ∀ call, NoForeignWrites S p H.self (H.transcript call) + keccakSeparated call := KeccakSeparated (H.keccakInputs call) + asmSlotsDisjoint _ := AsmFree H.source + asmMemorySafe _ := AsmFree H.source + mulDiv := H.MulDivOk + viewCalls := ∀ call, ViewDeterministic H.self (H.transcript call) + +/-- The calls from a storage the contract's own functions reach from deployment: item 3 across +transactions. -/ +def reachable (call : Call) : Prop := Reach S p H.deployed (slotValue call.storage) + +/-- The plain instance: nothing hashed, every external call answered by default, no assumes, no +trusted functions, an assembly-free source `u`, no `Math.mulDiv`. -/ +def plain (S : Sem) (p : S.Prog) (u : Solidity.SourceUnit) (deployed : Nat → Nat) + (transcript : Call → Interaction.Transcript) : Hyps S p := + { keccakInputs := fun _ _ => False, transcript, self := default, deployed, + ifaceEns := fun _ _ => False, assumeSites := fun _ => [], trustedBodies := [], + trustedNames := [], source := u, mulDiv := none } + +/-- **Discharged for a contract with no hashing, no external call that returns, no assume, no +trusted function, no assembly and no `Math.mulDiv`**: every hypothesis holds on every call. The +interface ensures are `False` here, so this holds only because no call returns. -/ +theorem plain_on {S : Sem} {p : S.Prog} {u : Solidity.SourceUnit} {deployed : Nat → Nat} + {transcript : Call → Interaction.Transcript} (hu : AsmFree u) + (ht : ∀ call, DefaultCalls (transcript call)) (scope : Call → Prop) (b : Bundle) + (ctxOf : Call → Ctx) (step : GhostStep) (call : Call) : + ((plain S p u deployed transcript).toAssumptions scope b ctxOf step).On call := by + refine ⟨⟨fun _ h => by simp [plain] at h, fun _ h => by simp [plain] at h, trustedHold_nil, + interfaceEnsures_of_default (ht call)⟩, fun c => noForeignWrites_of_default (ht c), + keccakSeparated_empty, hu, hu, fun _ h => by simp [plain] at h, + fun c => viewDeterministic_of_default (ht c)⟩ + +/-- The empty transcript, of a call that makes no query. -/ +theorem defaultCalls_nil : DefaultCalls [] := fun _ h => by simp [callsOf] at h + +/-- **The whole structure is satisfiable**: on every call, in every semantics. -/ +theorem satisfiable (S : Sem) (p : S.Prog) (scope : Call → Prop) (b : Bundle) + (ctxOf : Call → Ctx) (step : GhostStep) : + ∃ H : Hyps S p, ∀ call, (H.toAssumptions scope b ctxOf step).On call := + ⟨plain S p {} (fun _ => 0) (fun _ => []), + plain_on (by decide) (fun _ => defaultCalls_nil) scope b ctxOf step⟩ + +end Hyps + +/-- **The spec of the bytecode from solar-verify's verdict, under the precise trusted base**: as +`spec_of_verdict`, on the calls of the scope where every hypothesis of `H` holds. -/ +theorem spec_of_verdict_hyps {S T : Sem} {p : S.Prog} {q : T.Prog} {scope : Call → Prop} + {b : Bundle} {ctxOf : Call → Ctx} {step : GhostStep} (H : Hyps S p) + (hwf : b.WF = true) (hopaque : OpaqueInRange b) + (verdict : Verdict S p scope b ctxOf step (H.toAssumptions scope b ctxOf step)) + (stage : Stage S T p q scope) : + Holds T q (fun call => scope call ∧ (H.toAssumptions scope b ctxOf step).On call) b ctxOf + step := + spec_of_verdict hwf hopaque verdict stage + +end SolidCore.Spec.TrustedBase diff --git a/Verify/Spec/TrustedBase/Instances.lean b/Verify/Spec/TrustedBase/Instances.lean new file mode 100644 index 00000000..9b40d92e --- /dev/null +++ b/Verify/Spec/TrustedBase/Instances.lean @@ -0,0 +1,60 @@ +import Verify.Spec.TrustedBase.Hypotheses +import SolidCore.Refinement.Source.C4 +import SolidCore.Refinement.Solar.Counter.Source + +/-! +# The trusted base for c4 and Counter + +c4 (`scripts/refinement/corpus/c4.sol`, the source of the spec corpus's `c4.sol`) and Counter +(`scripts/refinement/counter/counter.sol`) have no inline assembly, no `@custom:assume`, no +`@custom:trusted` function and no `Math.mulDiv`, hash nothing and call nothing. Their trusted base: + +* inline assembly: `AsmFree` of the source units SolidCore checks, by the kernel (`asmFree_c4`, + `asmFree_counter`); +* assume, trusted, `Math.mulDiv`: none to assume (`Hyps.plain`); +* keccak256 and external calls: given that a call hashes nothing and makes no external call, every + hypothesis holds (`c4_on`, `counter_on`). That premise is not yet proved of SolidCore's run: + its interpreter hashes internally and `Source.run` folds its interaction tree without exposing + the transcript. For c4 the spec is in any case proved in Lean of SolidCore and of the bytecode + (`SolidCore.Spec.Solar.C4.holds_bytecode`), without the trusted base. +-/ + +namespace SolidCore.Spec.TrustedBase.Instances + +open SolarTV SolidCore.Spec SolidCore.Spec.TrustedBase + +/-- c4's source has no inline assembly. -/ +theorem asmFree_c4 : AsmFree SolidCore.Refinement.Source.C4.importedSourceUnit := by decide + +/-- Counter's source has no inline assembly. -/ +theorem asmFree_counter : AsmFree SolidCore.Refinement.Source.Counter.importedSourceUnit := by + decide + +/-- **c4's trusted base, discharged** on every call, for any source semantics and program: no +hashing, no external call (the empty transcript), its assembly-free source. -/ +theorem c4_on (S : Sem) (p : S.Prog) (deployed : Nat → Nat) (scope : Call → Prop) (b : Bundle) + (ctxOf : Call → Ctx) (step : GhostStep) (call : Call) : + ((Hyps.plain S p SolidCore.Refinement.Source.C4.importedSourceUnit deployed + (fun _ => [])).toAssumptions scope b ctxOf step).On call := + Hyps.plain_on asmFree_c4 (fun _ => Hyps.defaultCalls_nil) scope b ctxOf step call + +/-- **Counter's trusted base, discharged**, as c4's. -/ +theorem counter_on (S : Sem) (p : S.Prog) (deployed : Nat → Nat) (scope : Call → Prop) + (b : Bundle) (ctxOf : Call → Ctx) (step : GhostStep) (call : Call) : + ((Hyps.plain S p SolidCore.Refinement.Source.Counter.importedSourceUnit deployed + (fun _ => [])).toAssumptions scope b ctxOf step).On call := + Hyps.plain_on asmFree_counter (fun _ => Hyps.defaultCalls_nil) scope b ctxOf step call + +/-- **The spec of the bytecode from solar-verify's verdict on Counter, with the trusted base +discharged**: the verdict and a stage give the spec on the whole scope. -/ +theorem counter_spec_of_verdict {S T : Sem} {p : S.Prog} {q : T.Prog} {scope : Call → Prop} + {b : Bundle} {ctxOf : Call → Ctx} {step : GhostStep} (deployed : Nat → Nat) + (hwf : b.WF = true) (hopaque : OpaqueInRange b) + (verdict : Verdict S p scope b ctxOf step + ((Hyps.plain S p SolidCore.Refinement.Source.Counter.importedSourceUnit deployed + (fun _ => [])).toAssumptions scope b ctxOf step)) + (stage : Stage S T p q scope) : Holds T q scope b ctxOf step := + fun fs hfs => (spec_of_verdict_hyps _ hwf hopaque verdict stage fs hfs).mono fun call h => + ⟨h, counter_on S p deployed scope b ctxOf step call⟩ + +end SolidCore.Spec.TrustedBase.Instances diff --git a/Verify/Spec/TrustedBase/Interface.lean b/Verify/Spec/TrustedBase/Interface.lean new file mode 100644 index 00000000..b94fa88e --- /dev/null +++ b/Verify/Spec/TrustedBase/Interface.lean @@ -0,0 +1,98 @@ +import Verify.Spec.TrustedBase.Hypotheses + +/-! +# Interface ensures from an exported interface spec + +`InterfaceEnsures ens tr` (`Hypotheses.lean`) takes the interfaces' ensures as a predicate on a +request and its response. `ifaceEnsOf` builds that predicate from an interface's exported spec (a +`Bundle` whose `FnSpec`s are the interface's functions), with the meaning `Post` gives a function's +ensures: when the calldata selects a function of the interface (its selector, then clean argument +words of its parameter types) and the call returns clean words of its return types, its ensures +hold of those arguments and results. solar-verify trusts exactly this of every interface call that +returns; `--spec-check` samples it where the implementation is in the file. + +`ctx` is the callee's environment and `st` the state its storage and ghost reads see: an interface's +ensures speak of its arguments and results, which these do not affect. +-/ + +namespace SolidCore.Spec.TrustedBase + +open SolarTV SolidCore.Spec EvmCompiler.Simulation + +/-- A byte array's bytes, as numbers. -/ +def bytesOf (b : ByteArray) : List Nat := b.data.toList.map (·.toNat) + +/-- **The ensures of interface `iface` on one call** (see the module doc). -/ +def ifaceEnsOf (iface : Bundle) (ctx : Ctx) (st : State) (r : CallRequest) (a : CallResponse) : + Prop := + ∀ fs ∈ iface.spec.specs, ∀ args rets, + 4 ≤ (bytesOf r.calldata).length → + bytesWord ((bytesOf r.calldata).take 4) = fs.selector → + decodeWords fs.params (words ((bytesOf r.calldata).drop 4)) = some args → + decodeWords fs.rets (words (bytesOf a.returnData)) = some rets → + iface.satAll fs.ensures (mkEnv ctx args rets st st) + +/-- A call that fails owes no ensures, so `InterfaceEnsures` constrains only returning calls. -/ +theorem interfaceEnsures_of_default' {iface : Bundle} {ctx : Ctx} {st : State} + {tr : Interaction.Transcript} (h : DefaultCalls tr) : + InterfaceEnsures (ifaceEnsOf iface ctx st) tr := + interfaceEnsures_of_default h + +/-! ## Witnesses: an interface `one() returns (uint256)` that ensures `result == 1` -/ + +/-- `function one() external returns (uint256)`, selector `0x12345678`, ensuring `result == 1`. -/ +def oneFn : FnSpec := + { name := "one", selector := 0x12345678, params := [], rets := [.uint 256], payable := false, + requires := [], ensures := [.bin .eq (.ret 0) (.lit 1)], succeedsIf := [] } + +/-- The interface with `one`. -/ +def oneIface : Bundle := + { spec := { name := "IOne", fns := [], invariants := [], ghosts := [], specs := [oneFn] }, + fuel := 1 } + +/-- The calldata of `one()`. -/ +def oneCalldata : ByteArray := ⟨#[0x12, 0x34, 0x56, 0x78]⟩ + +/-- The 32-byte big-endian word `v < 256`. -/ +def smallWord (v : UInt8) : ByteArray := ⟨(List.replicate 31 (0 : UInt8) ++ [v]).toArray⟩ + +/-- A call of `one()` that returns the word `v`. -/ +def oneEx (v : UInt8) : Interaction.Exchange := + ⟨.external default (.call { staticReq with calldata := oneCalldata }), + (CallResponse.mk true (smallWord v) default (EvmYul.UInt256.ofNat 0) : CallResponse)⟩ + +theorem oneCalldata_facts : + 4 ≤ (bytesOf oneCalldata).length ∧ + bytesWord ((bytesOf oneCalldata).take 4) = 0x12345678 ∧ + decodeWords [] (words ((bytesOf oneCalldata).drop 4)) = some [] := by + decide + +theorem decode_smallWord1 : decodeWords [.uint 256] (words (bytesOf (smallWord 1))) = some [1] := by + decide + +theorem decode_smallWord0 : decodeWords [.uint 256] (words (bytesOf (smallWord 0))) = some [0] := by + decide + +/-- **Satisfiable with a call that returns**: `one()` returning 1 meets the interface's ensures. -/ +theorem interfaceEnsures_one (ctx : Ctx) (st : State) : + InterfaceEnsures (ifaceEnsOf oneIface ctx st) [oneEx 1] := by + intro c hc _ fs hfs args rets _ _ hargs hrets + simp only [callsOf, oneEx, List.mem_cons, List.not_mem_nil, or_false] at hc + subst hc + simp only [oneIface, List.mem_cons, List.not_mem_nil, or_false] at hfs + subst hfs + rw [show (oneFn.rets) = [.uint 256] from rfl, decode_smallWord1] at hrets + cases hrets + simp [Bundle.satAll, Bundle.sat, oneFn, eval, mkEnv, BinOp.apply, ofProp] + +/-- **Not trivial**: `one()` returning 0 breaks it. -/ +theorem not_interfaceEnsures_zero (ctx : Ctx) (st : State) : + ¬ InterfaceEnsures (ifaceEnsOf oneIface ctx st) [oneEx 0] := by + intro h + obtain ⟨h4, hsel, hargs⟩ := oneCalldata_facts + have := h (default, { staticReq with calldata := oneCalldata }, + CallResponse.mk true (smallWord 0) default (EvmYul.UInt256.ofNat 0)) (by simp [callsOf, oneEx]) + rfl oneFn (by simp [oneIface]) [] [0] h4 hsel hargs decode_smallWord0 + simp [Bundle.satAll, Bundle.sat, oneFn, eval, mkEnv, BinOp.apply, ofProp] at this + +end SolidCore.Spec.TrustedBase diff --git a/Verify/Tactic.lean b/Verify/Tactic.lean new file mode 100644 index 00000000..b55c491f --- /dev/null +++ b/Verify/Tactic.lean @@ -0,0 +1,110 @@ +import Verify.Run +import Verify.Finite + +/-! +# One tactic for the verification conditions + +`sc_vcgen [defs]` proves the verification conditions of a model on `Abi.fullScope`, the goal +`∀ call, scope call → pre call → vc model (argWords n) post call`, where `defs` are the +definitions to unfold: the scope, the function list, the model, the postcondition and +whatever they mention. It + +1. reduces the scope to `Abi.fullScope` (`vcs_of_fullScope`), one goal per function and + list of argument words, with the call's argument words and initial storage known; +2. introduces the argument words (up to four) and their bounds; +3. computes Loom's weakest precondition of the model with `wp_bind`, `wp_pure` and the + rules of `Verify.Basic` and `Verify.Finite` (`wp_sload`, `wp_sstore`, `wp_revert`, + `wp_ite`, `wp_ofPure`); +4. closes what is left, a goal on words, with a fixed cascade (`sc_close`): split the + `if`s, the conjunctions and the quantifiers, then `simp_all`, `omega`, `bv_omega` and + `decide`. It never calls `bv_decide` or `native_decide`, so its proofs rest on the + kernel alone. + +A scope that is a subset of `Abi.fullScope`, such as the finite `· ∈ Abi.calls fns [s]`, +goes through `vcs_mono` first. +-/ + +namespace SolidCore.Verify + +open Lean Elab Tactic + +/-- The bitwise `&&&`, `|||` and `^^^` terms on `Nat` in `e` that mention no bound variable. -/ +partial def bitTerms (e : Expr) (acc : Array Expr := #[]) : Array Expr := + let acc := + if (e.isAppOfArity ``HXor.hXor 6 || e.isAppOfArity ``HOr.hOr 6 || e.isAppOfArity ``HAnd.hAnd 6) && + !e.hasLooseBVars && e.appFn!.appFn!.appFn!.appFn!.appFn!.appArg! == mkConst ``Nat && + !acc.contains e then acc.push e + else acc + match e with + | .app f a => bitTerms a (bitTerms f acc) + | .lam _ t b _ | .forallE _ t b _ => bitTerms b (bitTerms t acc) + | .letE _ t v b _ => bitTerms b (bitTerms v (bitTerms t acc)) + | .mdata _ b | .proj _ _ b => bitTerms b acc + | _ => acc + +/-- For each bitwise term on `Nat` in the goal, adds the bound `t < 2 ^ n` at the least byte +width `n` its operands fit, as `omega` shows, so that `omega`, which treats the term as an +atom, knows it. -/ +elab "sc_bounds" : tactic => do + let ty ← instantiateMVars (← (← getMainGoal).getType) + for e in bitTerms ty do + let stx ← (← getMainGoal).withContext do Term.exprToSyntax e + for n in (List.range 32).map (8 * · + 8) do + let ok ← try + evalTactic (← `(tactic| have : $stx < 2 ^ $(quote n) := by + first + | exact Nat.xor_lt_two_pow (by omega) (by omega) + | exact Nat.or_lt_two_pow (by omega) (by omega) + | exact Nat.lt_of_le_of_lt Nat.and_le_left (by omega))) + pure true + catch _ => pure false + if ok then break + +/-- The closing cascade on a goal on words. -/ +macro "sc_arith" : tactic => `(tactic| first + | done + | trivial + | rfl + | (simp_all; done) + | omega + | (sc_bounds; omega) + | (congr 1 <;> (sc_bounds; omega)) + | (simp only [Nat.reducePow] at *; sc_bounds; omega) + | bv_omega + | decide + | (simp_all <;> (sc_bounds; omega))) + +/-- Splits a goal on words into its cases and closes each with `sc_arith`. -/ +macro "sc_close" : tactic => `(tactic| ( + try split_ifs + all_goals try dsimp only + all_goals repeat' (first | apply And.intro | intro) + all_goals try split_ifs + all_goals repeat' (first | apply And.intro | intro) + all_goals sc_arith)) + +/-- The verification conditions of a model on `Abi.fullScope` (see the module docs). -/ +syntax "sc_vcgen" (" [" term,* "]")? : tactic + +macro_rules + | `(tactic| sc_vcgen) => `(tactic| sc_vcgen []) + | `(tactic| sc_vcgen [$ts,*]) => do + let ts : Array (TSyntax `Lean.Parser.Tactic.simpLemma) ← + ts.getElems.mapM fun t => `(Lean.Parser.Tactic.simpLemma| $t:term) + `(tactic| set_option linter.unusedSimpArgs false in ( + try simp only [$ts,*] + refine vcs_of_fullScope (by simp [$ts,*]) ?_ + intro fn hfn call args hcall hw hlen hargs hinit hpre + simp only [$ts,*, List.mem_cons, List.not_mem_nil, or_false] at hfn + try casesm* _ ∨ _ + all_goals subst fn + all_goals rcases args with _ | ⟨a1, _ | ⟨a2, _ | ⟨a3, _ | ⟨a4, _⟩⟩⟩⟩ + all_goals try (simp at hlen; done) + all_goals try simp only [List.mem_cons, List.not_mem_nil, or_false, forall_eq_or_imp, + forall_eq, imp_false, not_false_eq_true, implies_true, and_true, IsEmpty.forall_iff] at hargs + all_goals simp only [$ts,*, hw, wp_bind, wp_pure, wp_sload, wp_sstore, wp_revert, wp_ite, + wp_ofPure, List.getD_cons_zero, List.getD_cons_succ, ite_apply, dite_apply, SolidCore.Refinement.slotValue, + List.foldl_cons, List.foldl_nil] + all_goals sc_close)) + +end SolidCore.Verify diff --git a/Verify/VC.lean b/Verify/VC.lean new file mode 100644 index 00000000..46dbad2a --- /dev/null +++ b/Verify/VC.lean @@ -0,0 +1,56 @@ +import Verify.VC.Term +import Verify.VC.Check +import Verify.VC.Model +import Verify.VC.Obligations + +/-! +# solar-verify's verification conditions, checked in Lean + +solar-verify (paradigmxyz/solar, `crates/verify`) proves a Solidity function by sending SMT-LIB to a +solver; its README lists the encoding in `src/vc.rs` as part of its trusted base. This library takes +that encoding out of it, one step at a time: + +* `Term`: the SMT-LIB fragment solar-verify emits, its meaning, and `Valid`, what a verdict of + solar-verify claims of a script (every obligation has no model). +* `Check`: `checkScript`, decided by the kernel, and `checkScript_sound`: a script's obligations, + normalized (definitions inlined, names renamed, conjunctions flattened, range facts derived), give + the obligations of the Lean side. +* `Model`: the generic source stage's tree of a function as a model in `SolM`, the monad of the + Loom generator `SolidCore.Verify` (`Basic`), and `implements_tree`, proved once from `source_run`, + so that Loom's weakest precondition of the model gives a `Triple` against SolidCore's + `Source.run` through `triple_of_wp`. +* `Obligations`: `triple_of_binds` and `triple_of_checked`, the generic theorem from a function the + stage erases to its obligations: valid Lean obligations (or solar-verify's verdict and + `checkScript`) and a binding of the erased tree to them (`Binds`, about the tree alone) give the + function's triple against SolidCore on the stage's scope. `Contracts.Counter.VC.Generic` derives + the counter milestone's `inc_triple` from it. +* `Contracts/*/VC/Export`: solar-verify's transcripts of `scripts/verify/Counter.sol`, `CounterMilestone.sol` + and `Token.sol` (`solar-verify --dry-run --dump-lean`), and `Contracts/*/VC/Bind`, which checks that each + script prints back to its transcript byte for byte. +* `Contracts.Token.VC.Burn` (its own root, since it imports this one): `Token`'s `burn` end to end. The kernel computes + that `Token` deploys with only `owner` in storage and that the stage erases `burn` to `burnTree`; + `burn_triple` is its ensures clause as a `Triple` against SolidCore, and `burn_obligation` is + solar-verify's obligation for it, normalized by `checkScript` and instantiated at the assignment a + successful call gives. `KernelIdx` makes `Std.HashMap`, the storage of SolidCore's state, reduce in + the kernel (`mkIdx_eq`), which the constructor run needs. +* `Contracts.Token.VC.Transfer`: `Token.transfer`'s three ensures clauses on distinct addresses as a `Triple` + against SolidCore (`transfer_triple`), each read off solar-verify's checked obligation through the + binding `trStore_eval`: SolidCore's storage after the call, read through `balanceOf`'s layout, is + solar-verify's array term at the assignment the call binds. Injectivity of the mapping slot on + address keys (`HashInj`) is a hypothesis of the theorem. `Contracts.Token.VC.Mutants`: for a one-line source + mutant and a one-line spec mutant of `Token.sol`, exported by the same solar-verify, `checkScript` + rejects the obligations `transfer`'s clauses need. +* `Contracts.Counter.VC.Inc`: the certified counter milestone's `inc` (`scripts/refinement/counter/counter.sol`, + annotated in `scripts/verify/CounterMilestone.sol`). `inc_triple`: on the stage's scope `inc` + succeeds exactly when `x + d < 2 ^ 256`, then slot 0 holds `x + d` and every other slot is unchanged. + solar-verify's obligation for its clause is valid by its own encoding (`x + d = x + d` once its + definition is inlined), so the theorem takes no verdict: `inc_check` ties solar-verify's script to the + Lean obligation and `inc_binding` ties solar-verify's encoded effect and guard to what SolidCore runs. + `Contracts.Counter.VC.Mutants`: `checkScript` rejects a one-line source mutant and a one-line spec + mutant. + +Nothing here uses `native_decide`, `bv_decide` or `ofReduceBool`, or imports +`SolidCore.Verify.Finite`. `Bind`'s check runs Lean's evaluator (`#guard`), not the kernel: it +checks that the generated module is the transcript, as `scripts/verify/check.sh` checks that the +transcript is solar-verify's. +-/ diff --git a/Verify/VC/Check.lean b/Verify/VC/Check.lean new file mode 100644 index 00000000..31993a04 --- /dev/null +++ b/Verify/VC/Check.lean @@ -0,0 +1,818 @@ +import Verify.VC.Term + +/-! +# Checking solar-verify's obligations against the Lean generator's + +`checkOb e (hs, φ)` decides, by evaluation, that an obligation `e` solar-verify sent the solver (the +facts one `check-sat` reads) implies the obligation `hs ⟹ φ` the Lean generator computes: +`checkOb_sound` shows that if `e` has no model then every assignment that makes `hs` hold makes `φ` +hold. The check normalizes `e` and compares it with the Lean obligation by syntax: + +1. `inline`: a fact `(= x t)`, where `x` is a constant that `t` does not mention, of `t`'s sort, is a + definition (solar-verify names its intermediate terms so): `x` is replaced by `t` in the other + facts and the fact dropped. An obligation without a model keeps none (`inline_sound`). +2. `rename`: solar-verify's constants are `name@N` and its bound variables `name!N`; each is + renamed to `name` (`strip`), provided no renaming makes a bound variable meet another name in its + scope (`renameOk`). +3. The last fact must be `(not φ')` with `φ'` equal to `φ`. Every other fact, its conjunctions + flattened, must be one of `hs`, a range fact `0 ≤ t` or `t ≤ M` that `hs` imply (`inRange`: + through `select`, `store` and `ite`), or a range fact `0 ≤ x` or `x ≤ M` (`0 ≤ M`) of a constant the + Lean obligation does not mention, which 0 satisfies. + +Each step is proved once, so the check is sound whatever the terms are; a step that does not +apply leaves the obligation unmatched, and the check fails. +-/ + +namespace SolidCore.Verify.VC + +/-! ## Variables -/ + +mutual +/-- Every name a term mentions, free or bound, of any sort. -/ +def Tm.vars : Tm → List String + | .num _ | .tt | .ff => [] + | .ivar x | .bvar x | .avar x => [x] + | .app _ args => Tm.varsList args + | .all x body => x :: Tm.vars body +def Tm.varsList : List Tm → List String + | [] => [] + | t :: ts => Tm.vars t ++ Tm.varsList ts +end + +/-- Two assignments agree on a name, in every sort. -/ +def Env.Agree (σ τ : Env) (x : String) : Prop := σ.i x = τ.i x ∧ σ.b x = τ.b x ∧ σ.a x = τ.a x + +theorem Env.Agree.setI {σ τ : Env} {x : String} (h : σ.Agree τ x) (y : String) (n : Int) : + (σ.setI y n).Agree (τ.setI y n) x := by + obtain ⟨h1, h2, h3⟩ := h + refine ⟨?_, h2, h3⟩ + by_cases hx : x = y <;> simp [Env.setI, hx, h1] + +mutual +theorem Tm.eval_congr : ∀ (t : Tm) {σ τ : Env}, (∀ x ∈ t.vars, σ.Agree τ x) → t.eval σ = t.eval τ + | .num _, _, _, _ => rfl + | .tt, _, _, _ => rfl + | .ff, _, _, _ => rfl + | .ivar x, _, _, h => by simp [Tm.eval, (h x (by simp [Tm.vars])).1] + | .bvar x, _, _, h => by simp [Tm.eval, (h x (by simp [Tm.vars])).2.1] + | .avar x, _, _, h => by simp [Tm.eval, (h x (by simp [Tm.vars])).2.2] + | .app f args, σ, τ, h => by + simp only [Tm.eval] + rw [Tm.evalList_congr args (by simpa [Tm.vars] using h)] + | .all x body, σ, τ, h => by + simp only [Tm.eval] + have : ∀ n : Int, Tm.eval (σ.setI x n) body = Tm.eval (τ.setI x n) body := fun n => + Tm.eval_congr body fun y hy => Env.Agree.setI (h y (by simp [Tm.vars, hy])) x n + simp only [this] +theorem Tm.evalList_congr : ∀ (ts : List Tm) {σ τ : Env}, (∀ x ∈ Tm.varsList ts, σ.Agree τ x) → + Tm.evalList σ ts = Tm.evalList τ ts + | [], _, _, _ => rfl + | t :: ts, σ, τ, h => by + simp only [Tm.evalList] + rw [Tm.eval_congr t (fun x hx => h x (by simp [Tm.varsList, hx])), + Tm.evalList_congr ts (fun x hx => h x (by simp [Tm.varsList, hx]))] +end + +/-! ## Sorts of values -/ + +/-- The sort of a value. -/ +def Value.sortOf : Value → Srt + | .int _ => .int + | .prop _ => .bool + | .arr _ => .arr + +/-- Values whose sorts are the ones the list gives, where it gives one. -/ +def SortsAgree : List (Option Srt) → List Value → Prop + | [], [] => True + | o :: os, v :: vs => (∀ s, o = some s → v.sortOf = s) ∧ SortsAgree os vs + | _, _ => False + +theorem applyOp_sortOf (f : String) : ∀ (os : List (Option Srt)) (vs : List Value), + SortsAgree os vs → ∀ {s : Srt}, sortOp f os = some s → (applyOp f vs).sortOf = s := by + intro os vs h s hs + unfold sortOp at hs + split at hs + all_goals first + | (simp at hs; done) + | (rcases vs with _ | ⟨v1, _ | ⟨v2, _ | ⟨v3, _ | ⟨v4, vs⟩⟩⟩⟩ <;> + simp_all [SortsAgree, applyOp, Value.sortOf] <;> done) + | skip + all_goals + split at hs <;> simp at hs + subst_vars + rcases vs with _ | ⟨c, _ | ⟨v1, _ | ⟨v2, _ | ⟨v3, vs⟩⟩⟩⟩ <;> simp [SortsAgree] at h + obtain ⟨-, h1, h2⟩ := h + cases v1 <;> cases v2 <;> simp [Value.sortOf, applyOp] at h1 h2 ⊢ <;> (try subst h1) <;> simp_all + +mutual +theorem Tm.eval_sortOf : ∀ (t : Tm) (σ : Env) {s : Srt}, t.sort? = some s → (t.eval σ).sortOf = s + | .num _, _, s, h => by simp_all [Tm.sort?, Tm.eval, Value.sortOf] + | .tt, _, s, h => by simp_all [Tm.sort?, Tm.eval, Value.sortOf] + | .ff, _, s, h => by simp_all [Tm.sort?, Tm.eval, Value.sortOf] + | .ivar _, _, s, h => by simp_all [Tm.sort?, Tm.eval, Value.sortOf] + | .bvar _, _, s, h => by simp_all [Tm.sort?, Tm.eval, Value.sortOf] + | .avar _, _, s, h => by simp_all [Tm.sort?, Tm.eval, Value.sortOf] + | .all _ _, _, s, h => by + simp only [Tm.sort?] at h + split at h <;> simp at h + subst h; simp [Tm.eval, Value.sortOf] + | .app f args, σ, s, h => by + simp only [Tm.sort?] at h + simp only [Tm.eval] + exact applyOp_sortOf f _ _ (Tm.evalList_sortOf args σ) h +theorem Tm.evalList_sortOf : ∀ (ts : List Tm) (σ : Env), SortsAgree (Tm.sortList ts) (Tm.evalList σ ts) + | [], _ => trivial + | t :: ts, σ => ⟨fun _ h => Tm.eval_sortOf t σ h, Tm.evalList_sortOf ts σ⟩ +end + +/-! ## Substitution -/ + +mutual +/-- The names a term binds. -/ +def Tm.binders : Tm → List String + | .app _ args => Tm.bindersList args + | .all x body => x :: Tm.binders body + | _ => [] +def Tm.bindersList : List Tm → List String + | [] => [] + | t :: ts => Tm.binders t ++ Tm.bindersList ts +end + +/-- Whether `t` is the constant of sort `s` named `x`. -/ +def Tm.isVar : Tm → Srt → String → Bool + | .ivar y, .int, x => y == x + | .bvar y, .bool, x => y == x + | .avar y, .arr, x => y == x + | _, _, _ => false + +mutual +/-- Replace the constant of sort \`s\` named \`x\` by \`u\`. A bound variable of the same name shadows +it. -/ +def Tm.subst : Tm → Srt → String → Tm → Tm + | .num n, _, _, _ => .num n + | .tt, _, _, _ => .tt + | .ff, _, _, _ => .ff + | .ivar y, s, x, u => if (Tm.ivar y).isVar s x then u else .ivar y + | .bvar y, s, x, u => if (Tm.bvar y).isVar s x then u else .bvar y + | .avar y, s, x, u => if (Tm.avar y).isVar s x then u else .avar y + | .app f args, s, x, u => .app f (Tm.substList args s x u) + | .all y body, s, x, u => if s = .int ∧ y = x then .all y body else .all y (Tm.subst body s x u) +def Tm.substList : List Tm → Srt → String → Tm → List Tm + | [], _, _, _ => [] + | t :: ts, s, x, u => Tm.subst t s x u :: Tm.substList ts s x u +end + +/-- The assignment with the constant of sort `s` named `x` set to the value `v`. -/ +def Env.set (σ : Env) : Srt → String → Value → Env + | .int, x, v => σ.setI x v.toInt + | .bool, x, v => σ.setB x v.toProp + | .arr, x, v => σ.setA x v.toArr + +theorem Env.setI_setI (σ : Env) (x : String) (m n : Int) : (σ.setI x m).setI x n = σ.setI x n := by + cases σ; simp only [Env.setI, Env.mk.injEq, and_true]; funext y; split <;> rfl + +theorem Env.set_setI_comm (σ : Env) (s : Srt) (x y : String) (v : Value) (n : Int) + (h : ¬ (s = .int ∧ y = x)) : (σ.setI y n).set s x v = (σ.set s x v).setI y n := by + cases σ + cases s <;> simp only [Env.set, Env.setI, Env.setB, Env.setA, Env.mk.injEq, and_true] + funext z + have : y ≠ x := fun e => h ⟨rfl, e⟩ + by_cases hz : z = x + · subst hz; simp [this.symm] + · simp [hz] + +theorem Value.eq_refl : ∀ v : Value, v.eq v + | .int _ => rfl + | .prop _ => Iff.rfl + | .arr _ => rfl + +theorem Value.sortOf_int {v : Value} (h : v.sortOf = .int) : v = .int v.toInt := by + cases v <;> simp_all [Value.sortOf, Value.toInt] +theorem Value.sortOf_bool {v : Value} (h : v.sortOf = .bool) : v = .prop v.toProp := by + cases v <;> simp_all [Value.sortOf, Value.toProp] +theorem Value.sortOf_arr {v : Value} (h : v.sortOf = .arr) : v = .arr v.toArr := by + cases v <;> simp_all [Value.sortOf, Value.toArr] + +/-- The constant of sort `s` named `x` reads the value of sort `s` set at it. -/ +theorem Env.set_var (σ : Env) (s : Srt) (x : String) (v : Value) (hv : v.sortOf = s) (y : Tm) + (hy : y.isVar s x = true) : y.eval (σ.set s x v) = v := by + cases y <;> cases s <;> simp [Tm.isVar] at hy <;> subst hy <;> + simp [Tm.eval, Env.set, Env.setI, Env.setB, Env.setA] + · exact (Value.sortOf_int hv).symm + · exact (Value.sortOf_bool hv).symm + · exact (Value.sortOf_arr hv).symm + +theorem Env.set_other (σ : Env) (s : Srt) (x : String) (v : Value) : + ∀ y : Tm, (y matches .ivar _ | .bvar _ | .avar _) → y.isVar s x = false → + y.eval (σ.set s x v) = y.eval σ := by + intro y hy hn + cases y <;> simp at hy <;> cases s <;> + simp_all [Tm.isVar, Tm.eval, Env.set, Env.setI, Env.setB, Env.setA] + +mutual +theorem Tm.eval_subst (s : Srt) (x : String) (u : Tm) (hu : u.sort? = some s) : + ∀ (A : Tm) (σ : Env), (∀ y ∈ A.binders, y ∉ u.vars) → + (A.subst s x u).eval σ = A.eval (σ.set s x (u.eval σ)) + | .num _, σ, _ => rfl + | .tt, σ, _ => rfl + | .ff, σ, _ => rfl + | .ivar y, σ, _ => by + simp only [Tm.subst] + split + · rename_i h; exact (Env.set_var σ s x _ (Tm.eval_sortOf u σ hu) _ h).symm + · rename_i h; exact (Env.set_other σ s x _ _ rfl (by simpa using h)).symm + | .bvar y, σ, _ => by + simp only [Tm.subst] + split + · rename_i h; exact (Env.set_var σ s x _ (Tm.eval_sortOf u σ hu) _ h).symm + · rename_i h; exact (Env.set_other σ s x _ _ rfl (by simpa using h)).symm + | .avar y, σ, _ => by + simp only [Tm.subst] + split + · rename_i h; exact (Env.set_var σ s x _ (Tm.eval_sortOf u σ hu) _ h).symm + · rename_i h; exact (Env.set_other σ s x _ _ rfl (by simpa using h)).symm + | .app f args, σ, hb => by + simp only [Tm.subst, Tm.eval] + rw [Tm.evalList_subst s x u hu args σ (by simpa [Tm.binders] using hb)] + | .all y body, σ, hb => by + simp only [Tm.subst] + split + · rename_i h + obtain ⟨rfl, rfl⟩ := h + simp only [Tm.eval, Env.set, Env.setI_setI] + · rename_i h + simp only [Tm.eval] + have hy : y ∉ u.vars := hb y (by simp [Tm.binders]) + have key : ∀ n : Int, (body.subst s x u).eval (σ.setI y n) = + body.eval ((σ.set s x (u.eval σ)).setI y n) := by + intro n + rw [Tm.eval_subst s x u hu body (σ.setI y n) (fun z hz => hb z (by simp [Tm.binders, hz]))] + have : u.eval (σ.setI y n) = u.eval σ := Tm.eval_congr u fun z hz => by + have : z ≠ y := fun e => hy (e ▸ hz) + exact ⟨by simp [Env.setI, this], rfl, rfl⟩ + rw [this, Env.set_setI_comm σ s x y _ n h] + simp only [key] +theorem Tm.evalList_subst (s : Srt) (x : String) (u : Tm) (hu : u.sort? = some s) : + ∀ (ts : List Tm) (σ : Env), (∀ y ∈ Tm.bindersList ts, y ∉ u.vars) → + Tm.evalList σ (Tm.substList ts s x u) = Tm.evalList (σ.set s x (u.eval σ)) ts + | [], _, _ => rfl + | t :: ts, σ, hb => by + simp only [Tm.substList, Tm.evalList] + rw [Tm.eval_subst s x u hu t σ (fun y hy => hb y (by simp [Tm.bindersList, hy])), + Tm.evalList_subst s x u hu ts σ (fun y hy => hb y (by simp [Tm.bindersList, hy]))] +end + +/-! ## Inlining definitions -/ + +/-- A definition `(= x u)`: a constant `x` that `u` does not mention, of `u`'s sort. -/ +def defOf? : Tm → Option (Srt × String × Tm) + | .app "=" [.ivar x, u] => if u.sort? = some .int ∧ x ∉ u.vars then some (.int, x, u) else none + | .app "=" [.bvar x, u] => if u.sort? = some .bool ∧ x ∉ u.vars then some (.bool, x, u) else none + | .app "=" [.avar x, u] => if u.sort? = some .arr ∧ x ∉ u.vars then some (.arr, x, u) else none + | _ => none + +/-- The definition's variable, as a term. -/ +def varOf : Srt → String → Tm + | .int, x => .ivar x + | .bool, x => .bvar x + | .arr, x => .avar x + +theorem defOf?_spec {t : Tm} {s : Srt} {x : String} {u : Tm} (h : defOf? t = some (s, x, u)) : + u.sort? = some s ∧ x ∉ u.vars ∧ ∀ σ, t.eval σ = .prop (((varOf s x).eval σ).eq (u.eval σ)) := by + unfold defOf? at h + split at h <;> (try simp at h) + all_goals + obtain ⟨⟨hs1, hs2⟩, rfl, rfl, rfl⟩ := h + exact ⟨hs1, hs2, fun σ => by simp [Tm.eval, applyOp, Tm.evalList, varOf]⟩ + +theorem varOf_isVar (s : Srt) (x : String) : (varOf s x).isVar s x = true := by + cases s <;> simp [varOf, Tm.isVar] + +/-- Whether the facts have a model. -/ +def Sat (σ : Env) (fs : List Tm) : Prop := ∀ t ∈ fs, t.Holds σ + +/-- A definition holds where its variable is set to its term's value. -/ +theorem def_holds {t : Tm} {s : Srt} {x : String} {u : Tm} (h : defOf? t = some (s, x, u)) + (σ : Env) : t.Holds (σ.set s x (u.eval σ)) := by + obtain ⟨hu, hx, he⟩ := defOf?_spec h + have hv : u.eval (σ.set s x (u.eval σ)) = u.eval σ := Tm.eval_congr u fun z hz => by + have : z ≠ x := fun e => hx (e ▸ hz) + cases s <;> refine ⟨?_, ?_, ?_⟩ <;> simp [Env.set, Env.setI, Env.setB, Env.setA, this] + have hvar : (varOf s x).eval (σ.set s x (u.eval σ)) = u.eval σ := + Env.set_var σ s x (u.eval σ) (Tm.eval_sortOf u σ hu) (varOf s x) (varOf_isVar s x) + simp only [Tm.Holds, he, hvar, hv, Value.toProp] + exact Value.eq_refl _ + +/-- Inline the definitions among `rest`, with `done` the facts already seen (newest first), with +`fuel` steps. -/ +def inlineFuel : Nat → List Tm → List Tm → List Tm + | 0, done, rest => done.reverse ++ rest + | _ + 1, done, [] => done.reverse + | n + 1, done, f :: rest => + match defOf? f with + | some (s, x, u) => + if (done ++ rest).all (fun t => t.binders.all (fun y => !u.vars.contains y)) then + inlineFuel n (done.map (·.subst s x u)) (rest.map (·.subst s x u)) + else inlineFuel n (f :: done) rest + | none => inlineFuel n (f :: done) rest + +def inline (fs : List Tm) : List Tm := inlineFuel fs.length [] fs + +theorem shift {t f : Tm} {done rest : List Tm} (ht : t ∈ done ∨ t ∈ f :: rest) : + t ∈ f :: done ∨ t ∈ rest := by + rcases ht with ht | ht + · exact Or.inl (List.mem_cons_of_mem _ ht) + · rcases List.mem_cons.mp ht with h | h + · exact Or.inl (List.mem_cons.mpr (Or.inl h)) + · exact Or.inr h + +theorem inlineFuel_sound : ∀ (n : Nat) (done rest : List Tm), + (∀ σ, ¬ ∀ t, t ∈ done ∨ t ∈ rest → t.Holds σ) → ∀ σ, ¬ Sat σ (inlineFuel n done rest) + | 0, done, rest, h, σ, hs => h σ fun t ht => hs t (by + simp only [inlineFuel, List.mem_append, List.mem_reverse]; exact ht) + | _ + 1, done, [], h, σ, hs => h σ fun t ht => hs t (by simp [inlineFuel]; simpa using ht) + | n + 1, done, f :: rest, h, σ, hs => by + simp only [inlineFuel] at hs + split at hs + · rename_i s x u hd + split at hs + · rename_i hcap + refine inlineFuel_sound n _ _ ?_ σ hs + intro τ hτ + have hu := (defOf?_spec hd).1 + have hcap' : ∀ t ∈ done ++ rest, ∀ y ∈ t.binders, y ∉ u.vars := by + intro t ht y hy hyu + have := List.all_eq_true.mp hcap t ht + have := List.all_eq_true.mp this y hy + simp [hyu] at this + apply h (τ.set s x (u.eval τ)) + intro t ht + rcases ht with ht | ht + · have := hτ (t.subst s x u) (Or.inl (List.mem_map.mpr ⟨t, ht, rfl⟩)) + simp only [Tm.Holds] at this ⊢ + rwa [Tm.eval_subst s x u hu t τ (hcap' t (by simp [ht]))] at this + · rcases List.mem_cons.mp ht with rfl | ht + · exact def_holds hd τ + · have := hτ (t.subst s x u) (Or.inr (List.mem_map.mpr ⟨t, ht, rfl⟩)) + simp only [Tm.Holds] at this ⊢ + rwa [Tm.eval_subst s x u hu t τ (hcap' t (by simp [ht]))] at this + · exact inlineFuel_sound n (f :: done) rest + (fun τ hτ => h τ fun t ht => hτ t (shift ht)) σ hs + · exact inlineFuel_sound n (f :: done) rest + (fun τ hτ => h τ fun t ht => hτ t (shift ht)) σ hs + +theorem inline_sound {fs : List Tm} (h : ∀ σ, ¬ Sat σ fs) : ∀ σ, ¬ Sat σ (inline fs) := + inlineFuel_sound _ [] fs (fun σ hσ => h σ fun t ht => hσ t (Or.inr ht)) + +/-! ## Renaming solar-verify's names -/ + +/-- `name@N` and `name!N` to `name`. -/ +def strip (x : String) : String := String.ofList (x.toList.takeWhile fun c => c ≠ '@' ∧ c ≠ '!') + +mutual +def Tm.rename : Tm → Tm + | .num n => .num n + | .tt => .tt + | .ff => .ff + | .ivar x => .ivar (strip x) + | .bvar x => .bvar (strip x) + | .avar x => .avar (strip x) + | .app f args => .app f (Tm.renameList args) + | .all x body => .all (strip x) (Tm.rename body) +def Tm.renameList : List Tm → List Tm + | [] => [] + | t :: ts => Tm.rename t :: Tm.renameList ts +end + +mutual +/-- No renaming makes a bound variable meet another name in its scope. -/ +def Tm.renameOk : Tm → Bool + | .app _ args => Tm.renameOkList args + | .all x body => body.vars.all (fun y => y == x || strip y != strip x) && Tm.renameOk body + | _ => true +def Tm.renameOkList : List Tm → Bool + | [] => true + | t :: ts => Tm.renameOk t && Tm.renameOkList ts +end + +/-- `σ` reads each name as `τ` reads its renaming. -/ +def Env.Renamed (σ τ : Env) (y : String) : Prop := + σ.i y = τ.i (strip y) ∧ σ.b y = τ.b (strip y) ∧ σ.a y = τ.a (strip y) + +mutual +theorem Tm.eval_rename : ∀ (t : Tm) {σ τ : Env}, t.renameOk = true → + (∀ y ∈ t.vars, σ.Renamed τ y) → t.eval σ = t.rename.eval τ + | .num _, _, _, _, _ => rfl + | .tt, _, _, _, _ => rfl + | .ff, _, _, _, _ => rfl + | .ivar x, _, _, _, h => by simp [Tm.rename, Tm.eval, (h x (by simp [Tm.vars])).1] + | .bvar x, _, _, _, h => by simp [Tm.rename, Tm.eval, (h x (by simp [Tm.vars])).2.1] + | .avar x, _, _, _, h => by simp [Tm.rename, Tm.eval, (h x (by simp [Tm.vars])).2.2] + | .app f args, σ, τ, ho, h => by + simp only [Tm.rename, Tm.eval] + rw [Tm.evalList_rename args (by simpa [Tm.renameOk] using ho) (by simpa [Tm.vars] using h)] + | .all x body, σ, τ, ho, h => by + simp only [Tm.renameOk, Bool.and_eq_true, List.all_eq_true] at ho + simp only [Tm.rename, Tm.eval] + have key : ∀ n : Int, body.eval (σ.setI x n) = body.rename.eval (τ.setI (strip x) n) := by + intro n + apply Tm.eval_rename body ho.2 + intro y hy + obtain ⟨h1, h2, h3⟩ := h y (by simp [Tm.vars, hy]) + refine ⟨?_, h2, h3⟩ + by_cases hyx : y = x + · subst hyx; simp [Env.setI] + · have := ho.1 y hy + have hs : strip y ≠ strip x := by simpa [hyx] using this + simp [Env.setI, hyx, hs, h1] + simp only [key] +theorem Tm.evalList_rename : ∀ (ts : List Tm) {σ τ : Env}, Tm.renameOkList ts = true → + (∀ y ∈ Tm.varsList ts, σ.Renamed τ y) → Tm.evalList σ ts = Tm.evalList τ (Tm.renameList ts) + | [], _, _, _, _ => rfl + | t :: ts, σ, τ, ho, h => by + simp only [Tm.renameOkList, Bool.and_eq_true] at ho + simp only [Tm.renameList, Tm.evalList] + rw [Tm.eval_rename t ho.1 (fun y hy => h y (by simp [Tm.varsList, hy])), + Tm.evalList_rename ts ho.2 (fun y hy => h y (by simp [Tm.varsList, hy]))] +end + +theorem rename_sound {fs : List Tm} (hok : fs.all Tm.renameOk = true) (h : ∀ σ, ¬ Sat σ fs) : + ∀ τ, ¬ Sat τ (fs.map Tm.rename) := by + intro τ hτ + let σ : Env := ⟨fun y => τ.i (strip y), fun y => τ.b (strip y), fun y => τ.a (strip y)⟩ + apply h σ + intro t ht + have := hτ t.rename (List.mem_map.mpr ⟨t, ht, rfl⟩) + simp only [Tm.Holds] at this ⊢ + rwa [Tm.eval_rename t (List.all_eq_true.mp hok t ht) (fun y _ => ⟨rfl, rfl, rfl⟩)] + +/-! ## Flattening conjunctions -/ + +mutual +def flatten : Tm → List Tm + | .tt => [] + | .app "and" args => flattenList args + | t => [t] +def flattenList : List Tm → List Tm + | [] => [] + | t :: ts => flatten t ++ flattenList ts +end + +mutual +theorem flatten_holds : ∀ (t : Tm) (σ : Env), (∀ c ∈ flatten t, c.Holds σ) → t.Holds σ + | .tt, _, _ => by simp [Tm.Holds, Tm.eval, Value.toProp] + | .app f args, σ, h => by + by_cases hf : f = "and" + · subst hf + simp only [flatten] at h + have := flattenList_holds args σ h + simp only [Tm.Holds, Tm.eval, applyOp, Value.toProp, Tm.evalList_eq] + intro v hv + obtain ⟨t, ht, rfl⟩ := List.mem_map.mp hv + exact this t ht + · have : flatten (.app f args) = [.app f args] := by + unfold flatten; split <;> simp_all + exact h _ (by simp [this]) + | .num n, _, h => h _ (by simp [flatten]) + | .ff, _, h => h _ (by simp [flatten]) + | .ivar x, _, h => h _ (by simp [flatten]) + | .bvar x, _, h => h _ (by simp [flatten]) + | .avar x, _, h => h _ (by simp [flatten]) + | .all x b, _, h => h _ (by simp [flatten]) +theorem flattenList_holds : ∀ (ts : List Tm) (σ : Env), (∀ c ∈ flattenList ts, c.Holds σ) → + ∀ t ∈ ts, t.Holds σ + | [], _, _ => by simp + | t :: ts, σ, h => by + simp only [flattenList, List.mem_append] at h + intro u hu + cases hu with + | head => exact flatten_holds t σ fun c hc => h c (Or.inl hc) + | tail _ hu => exact flattenList_holds ts σ (fun c hc => h c (Or.inr hc)) u hu +end + +theorem mem_flattenList {t c : Tm} : ∀ {ts : List Tm}, t ∈ ts → c ∈ flatten t → c ∈ flattenList ts + | _ :: _, .head _, hc => by simp only [flattenList, List.mem_append]; exact Or.inl hc + | _ :: _, .tail _ ht, hc => by + simp only [flattenList, List.mem_append]; exact Or.inr (mem_flattenList ht hc) + +/-! ## Range facts -/ + +/-- The fact that the elements of the array `m` lie in `[0, M]`, as the Lean generator states it of +the arrays of its storage: `(forall ((k Int)) (and (<= 0 (select m k)) (<= (select m k) M)))`. -/ +def arrFact (k m : String) (M : Nat) : Tm := + .all k (.app "and" [.app "<=" [.num 0, .app "select" [.avar m, .ivar k]], + .app "<=" [.app "select" [.avar m, .ivar k], .num M]]) + +/-- An array fact of `m` among `hs` bounds its elements by at most `M`. -/ +def arrBound (hs : List Tm) (m : String) (M : Nat) : Bool := + hs.any fun h => match h with + | .all k (.app "and" [.app "<=" [.num 0, .app "select" [.avar m', .ivar k']], + .app "<=" [.app "select" [.avar m'', .ivar k''], .num M']]) => + m' == m && m'' == m && k' == k && k'' == k && decide (M' ≤ M) + | _ => false + +theorem arrBound_sound {hs : List Tm} {m : String} {M : Nat} (h : arrBound hs m M = true) + {σ : Env} (hh : ∀ x ∈ hs, x.Holds σ) (n : Int) : 0 ≤ σ.a m n ∧ σ.a m n ≤ M := by + obtain ⟨f, hf, hm⟩ := List.any_eq_true.mp h + split at hm + · rename_i k m' k' m'' k'' M' + simp only [Bool.and_eq_true, beq_iff_eq, decide_eq_true_eq] at hm + obtain ⟨⟨⟨⟨rfl, rfl⟩, rfl⟩, rfl⟩, hM⟩ := hm + have := hh _ hf + simp only [Tm.Holds, Tm.eval, Value.toProp] at this + have := this n + simp [Tm.eval, Tm.evalList, applyOp, Value.toProp, Value.toInt, Value.toArr, Env.setI] at this + exact ⟨this.1, Int.le_trans this.2 (by exact_mod_cast hM)⟩ + · simp at hm + +/-- `hs` imply `0 ≤ t`, with `fuel` steps: a fact of `hs`, or through an `ite`, a `select` of a +`store` and a `select` of an array whose elements `hs` bound. -/ +def lowerOk (hs : List Tm) : Nat → Tm → Bool + | 0, t => hs.any (·.beq (.app "<=" [.num 0, t])) + | n + 1, t => hs.any (·.beq (.app "<=" [.num 0, t])) || match t with + | .app "ite" [_, a, b] => lowerOk hs n a && lowerOk hs n b + | .app "select" [.app "store" [a, _, v], j] => lowerOk hs n v && lowerOk hs n (.app "select" [a, j]) + | .app "select" [.avar m, _] => hs.any fun h => match h with + | .all k (.app "and" [.app "<=" [.num 0, .app "select" [.avar m', .ivar k']], _]) => + m' == m && k' == k + | _ => false + | _ => false + +/-- `hs` imply `t ≤ M`, as `lowerOk` does `0 ≤ t`. -/ +def upperOk (hs : List Tm) (M : Nat) : Nat → Tm → Bool + | 0, t => hs.any fun h => match h with + | .app "<=" [t', .num M'] => t'.beq t && decide (M' ≤ M) + | _ => false + | n + 1, t => (hs.any fun h => match h with + | .app "<=" [t', .num M'] => t'.beq t && decide (M' ≤ M) + | _ => false) || match t with + | .app "ite" [_, a, b] => upperOk hs M n a && upperOk hs M n b + | .app "select" [.app "store" [a, _, v], j] => + upperOk hs M n v && upperOk hs M n (.app "select" [a, j]) + | .app "select" [.avar m, _] => arrBound hs m M + | _ => false + +theorem holds_le (σ : Env) (a b : Tm) : + (Tm.app "<=" [a, b]).Holds σ ↔ (a.eval σ).toInt ≤ (b.eval σ).toInt := by + simp [Tm.Holds, Tm.eval, Tm.evalList, applyOp, Value.toProp] + +theorem eval_select (σ : Env) (a j : Tm) : + (Tm.app "select" [a, j]).eval σ = .int ((a.eval σ).toArr (j.eval σ).toInt) := by + simp [Tm.eval, Tm.evalList, applyOp] + +theorem eval_store_select (σ : Env) (a i v j : Tm) : + ((Tm.app "select" [.app "store" [a, i, v], j]).eval σ).toInt = + if (j.eval σ).toInt = (i.eval σ).toInt then (v.eval σ).toInt + else ((Tm.app "select" [a, j]).eval σ).toInt := by + simp only [Tm.eval, Tm.evalList, applyOp, Value.toInt] + rfl + +open Classical in +theorem eval_ite_int (σ : Env) (c a b : Tm) : + ((Tm.app "ite" [c, a, b]).eval σ).toInt = ((Tm.app "ite" [c, a, b]).eval σ).toInt := rfl + +/-- The integer an `ite` takes is one of its branches', whatever their sorts. -/ +theorem ite_toInt (σ : Env) (c a b : Tm) : + ((Tm.app "ite" [c, a, b]).eval σ).toInt = (a.eval σ).toInt ∨ + ((Tm.app "ite" [c, a, b]).eval σ).toInt = (b.eval σ).toInt ∨ + ((Tm.app "ite" [c, a, b]).eval σ).toInt = 0 := by + simp only [Tm.eval, Tm.evalList] + cases a.eval σ <;> cases b.eval σ + all_goals first + | (simp [applyOp, Value.toInt]; done) + | (simp only [applyOp, Value.toInt]; split <;> simp) + +theorem lowerOk_sound (hs : List Tm) {σ : Env} (hh : ∀ x ∈ hs, x.Holds σ) : + ∀ n t, lowerOk hs n t = true → 0 ≤ (t.eval σ).toInt := by + have mem : ∀ t, (hs.any (·.beq (.app "<=" [.num 0, t]))) = true → 0 ≤ (t.eval σ).toInt := by + intro t h + obtain ⟨f, hf, he⟩ := List.any_eq_true.mp h + have := hh f hf + rw [Tm.eq_of_beq he, holds_le] at this + simpa [Tm.eval, Value.toInt] using this + intro n + induction n with + | zero => exact fun t h => mem t h + | succ n ih => + intro t h + simp only [lowerOk, Bool.or_eq_true] at h + rcases h with h | h + · exact mem t h + · split at h + · rename_i c a b + simp only [Bool.and_eq_true] at h + rcases ite_toInt σ c a b with e | e | e <;> rw [e] + · exact ih a h.1 + · exact ih b h.2 + · exact Int.le_refl 0 + · rename_i a i v j + simp only [Bool.and_eq_true] at h + rw [eval_store_select] + split + · exact ih v h.1 + · exact ih _ h.2 + · rename_i m j + obtain ⟨f, hf, hm⟩ := List.any_eq_true.mp h + split at hm + · rename_i k m' k' rest + simp only [Bool.and_eq_true, beq_iff_eq] at hm + obtain ⟨rfl, rfl⟩ := hm + have := hh _ hf + simp only [Tm.Holds, Tm.eval, Value.toProp] at this + have := this (j.eval σ).toInt + simp [Tm.eval, Tm.evalList, applyOp, Value.toProp, Value.toInt, Value.toArr, Env.setI] at this + rw [eval_select] + simpa [Value.toInt, Tm.eval, Value.toArr] using this.1 + · simp at hm + · simp at h + +theorem upperOk_sound (hs : List Tm) (M : Nat) {σ : Env} (hh : ∀ x ∈ hs, x.Holds σ) : + ∀ n t, upperOk hs M n t = true → (t.eval σ).toInt ≤ M := by + have mem : ∀ t, (hs.any fun h => match h with + | .app "<=" [t', .num M'] => t'.beq t && decide (M' ≤ M) + | _ => false) = true → (t.eval σ).toInt ≤ M := by + intro t h + obtain ⟨f, hf, he⟩ := List.any_eq_true.mp h + split at he + · rename_i t' M' + simp only [Bool.and_eq_true, decide_eq_true_eq] at he + have := hh _ hf + rw [Tm.eq_of_beq he.1, holds_le] at this + simp only [Tm.eval, Value.toInt] at this + exact Int.le_trans this (by exact_mod_cast he.2) + · simp at he + intro n + induction n with + | zero => exact fun t h => mem t h + | succ n ih => + intro t h + simp only [upperOk, Bool.or_eq_true] at h + rcases h with h | h + · exact mem t h + · split at h + · rename_i c a b + simp only [Bool.and_eq_true] at h + rcases ite_toInt σ c a b with e | e | e <;> rw [e] + · exact ih a h.1 + · exact ih b h.2 + · exact Int.natCast_nonneg M + · rename_i a i v j + simp only [Bool.and_eq_true] at h + rw [eval_store_select] + split + · exact ih v h.1 + · exact ih _ h.2 + · rename_i m j + rw [eval_select] + exact (arrBound_sound h hh _).2 + · simp at h + +/-! ## The check of one obligation -/ + +/-- A range fact of a constant the Lean obligation does not mention, which 0 satisfies. -/ +def defaultOk (V : List String) : Tm → Bool + | .app "<=" [.num 0, .ivar x] => !V.contains x + | .app "<=" [.ivar x, .num _] => !V.contains x + | _ => false + +/-- A fact of solar-verify's obligation that the Lean obligation's facts `hs` give. -/ +def hypOk (hs : List Tm) (V : List String) (h : Tm) : Bool := + hs.any (·.beq h) || defaultOk V h || match h with + | .app "<=" [.num 0, t] => lowerOk hs 64 t + | .app "<=" [t, .num M] => upperOk hs M 64 t + | _ => false + +/-- The names the Lean obligation mentions. -/ +def leanVars (hs : List Tm) (φ : Tm) : List String := Tm.varsList hs ++ φ.vars + +/-- solar-verify's obligation `e` gives the Lean obligation `hs ⟹ φ`. -/ +def checkOb (e hs : List Tm) (φ : Tm) : Bool := + let e1 := inline e + e1.all Tm.renameOk && + match (e1.map Tm.rename).reverse with + | .app "not" [φ'] :: rhyps => φ'.beq φ && (flattenList rhyps).all (hypOk hs (leanVars hs φ)) + | _ => false + +/-- The assignment that reads as `σ` the names of `V`, and every other name as 0. -/ +def Env.restrict (σ : Env) (V : List String) : Env := + ⟨fun x => if x ∈ V then σ.i x else 0, fun x => if x ∈ V then σ.b x else False, + fun x => if x ∈ V then σ.a x else fun _ => 0⟩ + +theorem Env.restrict_agree (σ : Env) {V : List String} {x : String} (h : x ∈ V) : + (σ.restrict V).Agree σ x := by + simp [Env.restrict, Env.Agree, h] + +theorem mem_varsList {t : Tm} : ∀ {ts : List Tm}, t ∈ ts → ∀ x ∈ t.vars, x ∈ Tm.varsList ts + | _ :: _, .head _, x, hx => by simp only [Tm.varsList, List.mem_append]; exact Or.inl hx + | _ :: _, .tail _ ht, x, hx => by + simp only [Tm.varsList, List.mem_append]; exact Or.inr (mem_varsList ht x hx) + +theorem holds_restrict {σ : Env} {V : List String} {t : Tm} (h : ∀ x ∈ t.vars, x ∈ V) : + t.Holds (σ.restrict V) ↔ t.Holds σ := by + simp only [Tm.Holds] + rw [Tm.eval_congr t fun x hx => Env.restrict_agree σ (h x hx)] + +theorem hypOk_sound {hs : List Tm} {φ : Tm} {σ : Env} (hh : ∀ x ∈ hs, x.Holds σ) {h : Tm} + (ok : hypOk hs (leanVars hs φ) h = true) : h.Holds (σ.restrict (leanVars hs φ)) := by + have hV : ∀ x ∈ hs, ∀ y ∈ x.vars, y ∈ leanVars hs φ := fun x hx y hy => by + simp only [leanVars, List.mem_append]; exact Or.inl (mem_varsList hx y hy) + have hh' : ∀ x ∈ hs, x.Holds (σ.restrict (leanVars hs φ)) := fun x hx => + (holds_restrict (hV x hx)).mpr (hh x hx) + simp only [hypOk, Bool.or_eq_true] at ok + rcases ok with (ok | ok) | ok + · obtain ⟨f, hf, he⟩ := List.any_eq_true.mp ok + rw [← Tm.eq_of_beq he]; exact hh' f hf + · unfold defaultOk at ok + split at ok + · rename_i x + simp only [Bool.not_eq_true', List.contains_eq_mem, decide_eq_false_iff_not] at ok + rw [holds_le]; simp [Tm.eval, Env.restrict, ok, Value.toInt] + · rename_i x M + simp only [Bool.not_eq_true', List.contains_eq_mem, decide_eq_false_iff_not] at ok + rw [holds_le]; simp [Tm.eval, Env.restrict, ok, Value.toInt] + · simp at ok + · split at ok + · rename_i t + rw [holds_le] + simpa [Tm.eval, Value.toInt] using lowerOk_sound hs hh' 64 t ok + · rename_i t M _ + rw [holds_le] + simpa [Tm.eval, Value.toInt] using upperOk_sound hs M hh' 64 t ok + · simp at ok + +theorem checkOb_sound {e hs : List Tm} {φ : Tm} (h : checkOb e hs φ = true) + (hv : ∀ σ, ¬ Sat σ e) (σ : Env) (hh : ∀ x ∈ hs, x.Holds σ) : φ.Holds σ := by + simp only [checkOb, Bool.and_eq_true] at h + obtain ⟨hok, h⟩ := h + have h2 := rename_sound hok (inline_sound hv) + split at h + · rename_i φ' rhyps hr + simp only [Bool.and_eq_true, List.all_eq_true] at h + obtain ⟨hφ, hyps⟩ := h + have he := Tm.eq_of_beq hφ + subst he + have hφV : ∀ x ∈ φ'.vars, x ∈ leanVars hs φ' := fun x hx => by + simp only [leanVars, List.mem_append]; exact Or.inr hx + apply Classical.byContradiction + intro hn + apply h2 (σ.restrict (leanVars hs φ')) + intro t ht + have ht' : t ∈ (Tm.app "not" [φ'] :: rhyps).reverse := by + rw [← hr, List.reverse_reverse]; exact ht + rw [List.mem_reverse] at ht' + rcases List.mem_cons.mp ht' with rfl | ht' + · simp only [Tm.Holds, Tm.eval, Tm.evalList, applyOp, Value.toProp] + intro hp + exact hn ((holds_restrict hφV).mp hp) + · exact flatten_holds t _ fun c hc => + hypOk_sound hh (hyps c (mem_flattenList ht' hc)) + · simp at h + +/-! ## The check of a script -/ + +/-- Every Lean obligation `(hs, φ)` is given by one of the script's obligations. -/ +def checkScript (cs : List Cmd) (obs : List (List Tm × Tm)) : Bool := + let es := (obligations cs).filter (fun e => !isProbe e) + obs.all fun o => es.any fun e => checkOb e o.1 o.2 + +/-- What the Lean obligations claim: each one's facts imply its goal. -/ +def ObsValid (obs : List (List Tm × Tm)) : Prop := + ∀ o ∈ obs, ∀ σ : Env, (∀ x ∈ o.1, x.Holds σ) → o.2.Holds σ + +theorem checkScript_sound {cs : List Cmd} {obs : List (List Tm × Tm)} + (h : checkScript cs obs = true) (hv : Valid cs) : ObsValid obs := by + intro o ho σ hh + have := List.all_eq_true.mp h o ho + obtain ⟨e, he, hc⟩ := List.any_eq_true.mp this + rw [List.mem_filter] at he + have hp : isProbe e = false := by simpa using he.2 + exact checkOb_sound hc (fun τ hτ => hv e he.1 hp τ hτ) σ hh + +/-! ## One function's obligations -/ + +/-- The commands of the function `name` (`Contract.fn`): those after its `; ===== name` line, up to +the next function's. -/ +def fnSlice (cs : List Cmd) (name : String) : List Cmd := + let isMark : Cmd → String → Bool := fun c n => match c with + | .raw l => l == "; ===== " ++ n + | _ => false + let isAny : Cmd → Bool := fun c => match c with + | .raw l => l.startsWith "; ===== " + | _ => false + ((cs.dropWhile (fun c => !isMark c name)).drop 1).takeWhile (fun c => !isAny c) + +/-- An obligation of solar-verify's, normalized as `checkOb` normalizes it: its facts, flattened, +and its goal. -/ +def normOb (e : List Tm) : Option (List Tm × Tm) := + let e1 := inline e + if e1.all Tm.renameOk then + match (e1.map Tm.rename).reverse with + | .app "not" [φ] :: rhyps => some (flattenList rhyps, φ) + | _ => none + else none + +/-- The obligations of the function `name`, normalized, without the probe. -/ +def fnObs (cs : List Cmd) (name : String) : List (List Tm × Tm) := + ((obligations (fnSlice cs name)).filter (fun e => !isProbe e)).filterMap normOb + +end SolidCore.Verify.VC diff --git a/Verify/VC/KernelIdx.lean b/Verify/VC/KernelIdx.lean new file mode 100644 index 00000000..6dc459db --- /dev/null +++ b/Verify/VC/KernelIdx.lean @@ -0,0 +1,59 @@ +import Std + +/-! +# Hash map buckets the kernel can compute + +`Std.HashMap` picks a key's bucket with `mkIdx`, a `USize` computation. The width of `USize` is +`System.Platform.numBits`, which the kernel cannot reduce, so no lookup or insert, and nothing that +runs the constructor of a contract that writes storage, reduces by conversion alone. `mkIdxK` +computes the same index on `Nat` for every table below `2 ^ 32` buckets, where the mask fits either +platform's word, and falls back to `mkIdx` otherwise. `mkIdx_eq` proves the two equal, so +`kernel_rfl … using mkIdx_eq` evaluates hash maps in the kernel without assuming a platform. +-/ + +namespace SolidCore.Verify.VC + +open Std.DHashMap.Internal + +/-- Either platform's `USize` holds every `Nat` below `2 ^ 32`. -/ +theorem usize_size_ge : 2 ^ 32 ≤ USize.size := by + rcases USize.size_eq with h | h <;> rw [h] <;> decide + +/-- `mkIdx` on `Nat` below `2 ^ 32` buckets, where its mask does not depend on the word width. -/ +def mkIdxK (sz : Nat) (h : 0 < sz) (hash : UInt64) : { u : USize // u.toNat < sz } := + if hs : sz < 2 ^ 32 then + ⟨USize.ofNatLT ((scrambleHash hash).toNat &&& (sz - 1)) + (Nat.lt_of_le_of_lt Nat.and_le_right (by have := usize_size_ge; omega)), + by + show (scrambleHash hash).toNat &&& (sz - 1) < sz + exact Nat.lt_of_le_of_lt Nat.and_le_right (by omega)⟩ + else mkIdx sz h hash + +/-- `mkIdxK` is `mkIdx`, whatever `System.Platform.numBits` is. -/ +theorem mkIdx_eq : @mkIdx = @mkIdxK := by + funext sz h hash + unfold mkIdxK + split + · next hs => + apply Subtype.ext + apply USize.toNat_inj.mp + have hsz := usize_size_ge + unfold mkIdx + simp only [USize.toNat_and, USize.toNat_ofNatLT, UInt64.toNat_toUSize] + rw [USize.toNat_sub_of_le, USize.toNat_ofNat_of_lt' (by omega)] + · simp only [USize.toNat_one] + have hm : sz - 1 < 2 ^ System.Platform.numBits := by + have : USize.size = 2 ^ System.Platform.numBits := rfl + omega + apply Nat.eq_of_testBit_eq + intro i + simp only [Nat.testBit_and, Nat.testBit_mod_two_pow] + by_cases hi : i < System.Platform.numBits + · simp [hi] + · have : sz - 1 < 2 ^ i := + Nat.lt_of_lt_of_le hm (Nat.pow_le_pow_right (by decide) (by omega)) + simp [hi, Nat.testBit_lt_two_pow this] + · simp [USize.le_iff_toNat_le, USize.toNat_ofNat_of_lt' (show sz < USize.size by omega)]; omega + · rfl + +end SolidCore.Verify.VC diff --git a/Verify/VC/Model.lean b/Verify/VC/Model.lean new file mode 100644 index 00000000..6a347bf2 --- /dev/null +++ b/Verify/VC/Model.lean @@ -0,0 +1,127 @@ +import Verify.Abi +import SolidCore.Refinement.Generic.SourceRun + +/-! +# The generic source stage's trees as Loom models + +The generic source stage (`SolidCore.Refinement.Generic`) erases a SolidCore function of its +fragment to a `Tree` (`eraseFn`) and proves that SolidCore runs every call of it as the tree +(`source_run`). `treeModel T` reads the tree as a model in `SolM`, the monad of +`SolidCore.Verify`'s Loom generator: it reads the storage, branches where the tree branches, and +ends as the tree's leaf does, writing the leaf's storage and returning its output, or reverting +with it. `implements_tree` is `Implements` for every function the stage erases, proved once from +`source_run`: so Loom's weakest precondition of `treeModel T` (`vc`, computed by `wp_bind`, `wp_ite` +and the rules below) gives a `Triple` against `Source.run` through `triple_of_wp`, with no proof +per contract of how SolidCore runs it. + +The scope is the stage's: every call of the function on any argument words below `2 ^ 256`, with +no value, from any storage that writes every slot the constructor wrote (`Covers`). A model emits +no logs (`observe`), so the tree must have none (`noLogs`). +-/ + +namespace SolidCore.Verify.VC + +open SolidCore.Verify SolidCore.Refinement SolidCore.Refinement.Abi SolidCore.Refinement.Generic +open SolidCore.Solidity + +/-- Read the whole storage. -/ +def getStore : SolM Storage := fun s => .ok (s, s) + +/-- Replace the whole storage. -/ +def setStore (s' : Storage) : SolM Unit := fun _ => .ok ((), s') + +@[simp] theorem wp_getStore (post : Storage → Assn) : + wp getStore post = fun herr s => post s herr s := by + rw [wp_eq]; rfl + +@[simp] theorem wp_setStore (s' : Storage) (post : Unit → Assn) : + wp (setStore s') post = fun herr _ => post () herr s' := by + rw [wp_eq]; rfl + +/-- The words of a call on the argument words `args` from the storage `s`, with SolidCore's slot +hash. -/ +def valOf (args : List Nat) (s : Storage) : Val := ⟨args, s, solHash⟩ + +/-- A tree that emits no log. -/ +def noLogs : Tree → Bool + | .halt _ _ _ ls => ls.isEmpty + | .ite _ t e => noLogs t && noLogs e + +/-- The tree as a model: branch on the words of the call, end as the leaf does. -/ +def treeModel : Tree → List Nat → SolM (List Nat) + | .halt ok out ws _, args => do + let s ← getStore + if ok then do + setStore (Writes.store (valOf args s) ws) + pure (out.map (OByte.eval (valOf args s))) + else revert (out.map (OByte.eval (valOf args s))) + | .ite c t e, args => do + let s ← getStore + if c.eval (valOf args s) = 0 then treeModel e args else treeModel t args + +/-- What a tree's result is as a model's outcome. -/ +def resOutcome (R : Res) : Except Revert (List Nat × Storage) := + if R.success then .ok (R.output, R.store) else .error R.output + +theorem treeModel_run (args : List Nat) (s : Storage) : + ∀ T : Tree, treeModel T args s = resOutcome (T.eval (valOf args s)) + | .halt ok out ws ls => by + cases ok <;> rfl + | .ite c t e => by + show (if c.eval (valOf args s) = 0 then treeModel e args else treeModel t args) s = _ + simp only [Tree.eval] + split + · exact treeModel_run args s e + · exact treeModel_run args s t + +theorem eval_logs (ρ : Val) : ∀ T : Tree, noLogs T = true → (T.eval ρ).logs = [] + | .halt ok out ws ls, h => by + simp only [noLogs, List.isEmpty_iff] at h + subst h; cases ok <;> rfl + | .ite c t e, h => by + simp only [noLogs, Bool.and_eq_true] at h + simp only [Tree.eval] + split + · exact eval_logs ρ e h.2 + · exact eval_logs ρ t h.1 + +theorem observe_resOutcome (s : Storage) (R : Res) (hs : R.success = false → R.store = s) + (hl : R.logs = []) : observe s (resOutcome R) = R.obs := by + unfold resOutcome observe Res.obs + cases h : R.success + · simp [hs h, hl] + · simp [hl] + +theorem eval_store_fail (ρ : Val) : ∀ T : Tree, (T.eval ρ).success = false → + (T.eval ρ).store = ρ.store + | .halt ok out ws ls, h => by cases ok <;> simp_all [Tree.eval] + | .ite c t e, h => by + simp only [Tree.eval] at h ⊢ + split at h <;> rename_i hc <;> simp only [hc, ite_true, ite_false] <;> + first | exact eval_store_fail ρ e h | exact eval_store_fail ρ t h + +/-- The stage's scope of one function: every call of it on argument words below `2 ^ 256`, with no +value, from any storage that writes every slot the constructor wrote. -/ +def stageScope (fn : Fn) (s : List (Nat × Nat)) (call : Call) : Prop := + ∃ σ, Covers s σ ∧ fullScope [fn] σ call + +/-- Every function the generic source stage erases is implemented by its tree's model. -/ +theorem implements_tree {fuel : Nat} {c : TypeCheck.CheckedContract} {d : Source.State} + {s : List (Nat × Nat)} (hd : Wide.DeployedAt fuel c d s) {fn : Fn} {f : Source.FunctionDef} + (hsel : fn.sel < 2 ^ 32) (hfind : c.core.findFunctionBySelector? fn.sel = some f) + (hlen : f.params.length = fn.params.length) {T : Tree} + (hT : eraseFn (envOf c.core) fuel f = some T) (hlogs : noLogs T = true) : + Implements fuel c (stageScope fn s) (argWords fn.params.length) (treeModel T) := by + rintro _ ⟨σ, hcov, fn', hfn', args, hl, hargs, rfl⟩ + simp only [List.mem_singleton] at hfn' + subst hfn' + have hw : argWords fn'.params.length + ({ calldata := Abi.calldata fn'.sel args, callvalue := 0, storage := σ } : Call) = args := + hl ▸ argWords_calldata _ args hargs 0 σ + rw [hw, source_run hd hcov hsel hfind hT args (hl.trans hlen.symm) hargs] + simp only [initStorage] + rw [treeModel_run] + exact congrArg some (observe_resOutcome _ _ (eval_store_fail _ T) + (eval_logs _ T hlogs)).symm + +end SolidCore.Verify.VC diff --git a/Verify/VC/Obligations.lean b/Verify/VC/Obligations.lean new file mode 100644 index 00000000..333416d4 --- /dev/null +++ b/Verify/VC/Obligations.lean @@ -0,0 +1,92 @@ +import Verify.VC.Model +import Verify.VC.Check + +/-! +# From an erased function to solar-verify's obligations, once for every function + +The generic source stage erases a function of its fragment to a `Tree` (`eraseFn`), and +`source_run` proves that SolidCore runs every call of it as the tree. solar-verify's verdict on a +script is `Valid`, and `checkScript` ties the script's obligations to Lean obligations +(`checkScript_sound`). What is left per function is the binding: the Lean obligations, at the +assignment of solar-verify's names a call binds, say what the tree's result is. + +* `ObsAt obs σ`: every Lean obligation of `obs` holds at the assignment `σ`. +* `Binds fn T obs env P`: on every call's argument words `args` (as many as `fn` takes, each + below `2 ^ 256`) and every storage `s` of words, the obligations at `env args s` give `P args s` + of the tree's observable. This is the one proof a function needs, and it is about the tree and + the obligations alone: no SolidCore run, no fuel, no ABI. +* `triple_of_binds`: for every function the stage erases, its obligations' validity and the + binding give the triple `{True} c {treePost fn P}` against SolidCore on the stage's scope + (`stageScope`). Unlike `implements_tree`, the tree may emit logs: the observable is the tree's, + logs included. +* `triple_of_checked`: the same from solar-verify's script, its verdict `Valid cs` and the + kernel's `checkScript cs obs = true`. + +A verdict is a hypothesis (`Valid cs`): solar-verify's solver is not trusted, so the theorem says +what holds if its verdict is right, and `checkScript` makes sure the verdict is about the +obligations the binding uses. An obligation that is valid by solar-verify's own encoding needs no +verdict: `triple_of_binds` takes `ObsValid obs` proved in Lean. +-/ + +namespace SolidCore.Verify.VC + +open SolidCore.Verify SolidCore.Refinement SolidCore.Refinement.Abi SolidCore.Refinement.Generic +open SolidCore.Solidity + +/-- Every Lean obligation of `obs` holds at the assignment `σ`. -/ +def ObsAt (obs : List (List Tm × Tm)) (σ : Env) : Prop := + ∀ o ∈ obs, (∀ x ∈ o.1, x.Holds σ) → o.2.Holds σ + +theorem ObsValid.at {obs : List (List Tm × Tm)} (h : ObsValid obs) (σ : Env) : ObsAt obs σ := + fun o ho hh => h o ho σ hh + +/-- The binding of a function's tree to Lean obligations: on every call's argument words and +storage of words, the obligations at the assignment `env args s` give `P` of the tree's +observable. -/ +def Binds (fn : Fn) (T : Tree) (obs : List (List Tm × Tm)) (env : List Nat → Storage → Env) + (P : List Nat → Storage → Observable → Prop) : Prop := + ∀ (args : List Nat) (s : Storage), args.length = fn.params.length → (∀ a ∈ args, a < 2 ^ 256) → + (∀ k, s k < 2 ^ 256) → ObsAt obs (env args s) → P args s (T.eval (valOf args s)).obs + +/-- `P` of a call: of its argument words, its initial storage and its observable. -/ +def treePost (fn : Fn) (P : List Nat → Storage → Observable → Prop) (call : Call) + (o : Observable) : Prop := + P (argWords fn.params.length call) (initStorage call) o + +/-- **Every function the generic source stage erases meets the triple its binding gives**, from +valid Lean obligations. -/ +theorem triple_of_binds {fuel : Nat} {c : TypeCheck.CheckedContract} {d : Source.State} + {s : List (Nat × Nat)} (hd : Wide.DeployedAt fuel c d s) {fn : Fn} {f : Source.FunctionDef} + (hsel : fn.sel < 2 ^ 32) (hfind : c.core.findFunctionBySelector? fn.sel = some f) + (hlen : f.params.length = fn.params.length) {T : Tree} + (hT : eraseFn (envOf c.core) fuel f = some T) {obs : List (List Tm × Tm)} + {env : List Nat → Storage → Env} {P : List Nat → Storage → Observable → Prop} + (hobs : ObsValid obs) (hbind : Binds fn T obs env P) : + Triple fuel c (stageScope fn s) (fun _ => True) (treePost fn P) := by + rintro _ ⟨σ, hcov, fn', hfn', args, hl, hargs, rfl⟩ - + simp only [List.mem_singleton] at hfn' + subst hfn' + have hrun := source_run hd hcov hsel hfind hT args (hl.trans hlen.symm) hargs + refine ⟨by simp [hrun], fun o ho => ?_⟩ + rw [hrun] at ho + cases ho + have hw : argWords fn'.params.length + ({ calldata := Abi.calldata fn'.sel args, callvalue := 0, storage := σ } : Call) = args := + hl ▸ argWords_calldata _ args hargs 0 σ + unfold treePost + rw [hw] + exact hbind args (slotValue σ) hl hargs (fun k => Generic.slotValue_lt σ k) (hobs.at _) + +/-- **The same from solar-verify's script**: its verdict and the kernel's check that its +obligations are the Lean ones. -/ +theorem triple_of_checked {fuel : Nat} {c : TypeCheck.CheckedContract} {d : Source.State} + {s : List (Nat × Nat)} (hd : Wide.DeployedAt fuel c d s) {fn : Fn} {f : Source.FunctionDef} + (hsel : fn.sel < 2 ^ 32) (hfind : c.core.findFunctionBySelector? fn.sel = some f) + (hlen : f.params.length = fn.params.length) {T : Tree} + (hT : eraseFn (envOf c.core) fuel f = some T) {cs : List Cmd} {obs : List (List Tm × Tm)} + {env : List Nat → Storage → Env} {P : List Nat → Storage → Observable → Prop} + (hcheck : checkScript cs obs = true) (hv : Valid cs) (hbind : Binds fn T obs env P) : + Triple fuel c (stageScope fn s) (fun _ => True) (treePost fn P) := + triple_of_binds hd hsel hfind hlen hT (checkScript_sound hcheck hv) hbind + +end SolidCore.Verify.VC diff --git a/Verify/VC/Term.lean b/Verify/VC/Term.lean new file mode 100644 index 00000000..a355ebe3 --- /dev/null +++ b/Verify/VC/Term.lean @@ -0,0 +1,318 @@ +/-! +# SMT-LIB terms of solar-verify's verification conditions + +solar-verify proves a function by sending SMT-LIB to a solver: constants with their sorts, the +facts it assumes, and for each obligation a `check-sat` of the guard of the paths that return +normally and the negation of what they must show. `Tm` is the fragment of SMT-LIB terms it emits +over integers, booleans and arrays from integers to integers, and `Cmd` its commands. Every +constant carries its sort (`Tm.ivar`, `Tm.bvar`, `Tm.avar`), as its `declare-const` gives it, +so an assignment of the constants (`Env`) is well sorted by construction. + +`Tm.eval` is the meaning SMT-LIB gives the theory of integers with arrays, with one model of what +SMT-LIB leaves open: `div` and `mod` by zero are 0. An obligation that holds in every model holds in +this one. A term the fragment does not cover (an unknown operator, a wrong arity or sort) means the +default value of its sort: the checks of `Check` compare terms by their syntax, so such a term can +only make a check fail. + +`Tm.print` prints a term as solar-verify does, so that a script's print can be compared with the +bytes solar-verify sent the solver. +-/ + +namespace SolidCore.Verify.VC + +/-- The sorts of the fragment. -/ +inductive Srt where + | int | bool | arr + deriving DecidableEq, Repr + +/-- A term. Numerals are naturals; a negative integer is `(- n)`. -/ +inductive Tm where + | num (n : Nat) + | tt + | ff + | ivar (x : String) + | bvar (x : String) + | avar (x : String) + | app (f : String) (args : List Tm) + /-- `(forall ((x Int)) body)`. -/ + | all (x : String) (body : Tm) + deriving Repr, Inhabited + +/-! ## Equality of terms, by structural recursion (the kernel evaluates it) -/ + +mutual +def Tm.beq : Tm → Tm → Bool + | .num a, .num b => a == b + | .tt, .tt => true + | .ff, .ff => true + | .ivar a, .ivar b => a == b + | .bvar a, .bvar b => a == b + | .avar a, .avar b => a == b + | .app f as, .app g bs => f == g && Tm.beqList as bs + | .all x a, .all y b => x == y && Tm.beq a b + | _, _ => false +def Tm.beqList : List Tm → List Tm → Bool + | [], [] => true + | a :: as, b :: bs => Tm.beq a b && Tm.beqList as bs + | _, _ => false +end + +mutual +theorem Tm.eq_of_beq : ∀ {a b : Tm}, Tm.beq a b = true → a = b + | .num a, .num b, h => by simp [Tm.beq] at h; rw [h] + | .tt, .tt, _ => rfl + | .ff, .ff, _ => rfl + | .ivar a, .ivar b, h => by simp [Tm.beq] at h; rw [h] + | .bvar a, .bvar b, h => by simp [Tm.beq] at h; rw [h] + | .avar a, .avar b, h => by simp [Tm.beq] at h; rw [h] + | .app f as, .app g bs, h => by + simp only [Tm.beq, Bool.and_eq_true, beq_iff_eq] at h + rw [h.1, Tm.eq_of_beqList h.2] + | .all x a, .all y b, h => by + simp only [Tm.beq, Bool.and_eq_true, beq_iff_eq] at h + rw [h.1, Tm.eq_of_beq h.2] + | .num _, .tt, h | .num _, .ff, h | .num _, .ivar _, h | .num _, .bvar _, h + | .num _, .avar _, h | .num _, .app _ _, h | .num _, .all _ _, h => by simp [Tm.beq] at h + | .tt, .num _, h | .tt, .ff, h | .tt, .ivar _, h | .tt, .bvar _, h + | .tt, .avar _, h | .tt, .app _ _, h | .tt, .all _ _, h => by simp [Tm.beq] at h + | .ff, .num _, h | .ff, .tt, h | .ff, .ivar _, h | .ff, .bvar _, h + | .ff, .avar _, h | .ff, .app _ _, h | .ff, .all _ _, h => by simp [Tm.beq] at h + | .ivar _, .num _, h | .ivar _, .tt, h | .ivar _, .ff, h | .ivar _, .bvar _, h + | .ivar _, .avar _, h | .ivar _, .app _ _, h | .ivar _, .all _ _, h => by simp [Tm.beq] at h + | .bvar _, .num _, h | .bvar _, .tt, h | .bvar _, .ff, h | .bvar _, .ivar _, h + | .bvar _, .avar _, h | .bvar _, .app _ _, h | .bvar _, .all _ _, h => by simp [Tm.beq] at h + | .avar _, .num _, h | .avar _, .tt, h | .avar _, .ff, h | .avar _, .ivar _, h + | .avar _, .bvar _, h | .avar _, .app _ _, h | .avar _, .all _ _, h => by simp [Tm.beq] at h + | .app _ _, .num _, h | .app _ _, .tt, h | .app _ _, .ff, h | .app _ _, .ivar _, h + | .app _ _, .bvar _, h | .app _ _, .avar _, h | .app _ _, .all _ _, h => by simp [Tm.beq] at h + | .all _ _, .num _, h | .all _ _, .tt, h | .all _ _, .ff, h | .all _ _, .ivar _, h + | .all _ _, .bvar _, h | .all _ _, .avar _, h | .all _ _, .app _ _, h => by simp [Tm.beq] at h +theorem Tm.eq_of_beqList : ∀ {as bs : List Tm}, Tm.beqList as bs = true → as = bs + | [], [], _ => rfl + | a :: as, b :: bs, h => by + simp only [Tm.beqList, Bool.and_eq_true] at h + rw [Tm.eq_of_beq h.1, Tm.eq_of_beqList h.2] + | [], _ :: _, h | _ :: _, [], h => by simp [Tm.beqList] at h +end + +instance : BEq Tm := ⟨Tm.beq⟩ + +/-! ## Values and assignments -/ + +/-- A value of one of the sorts. A boolean is a proposition: a quantifier's value need not be +decidable. -/ +inductive Value where + | int (n : Int) + | prop (p : Prop) + | arr (f : Int → Int) + +def Value.toInt : Value → Int + | .int n => n + | _ => 0 + +def Value.toProp : Value → Prop + | .prop p => p + | _ => False + +def Value.toArr : Value → (Int → Int) + | .arr f => f + | _ => fun _ => 0 + +/-- Whether a value has a sort. -/ +def Value.Sorted : Value → Srt → Prop + | .int _, .int => True + | .prop _, .bool => True + | .arr _, .arr => True + | _, _ => False + +/-- An assignment of the constants and bound variables, one function per sort. -/ +structure Env where + i : String → Int + b : String → Prop + a : String → (Int → Int) + +def Env.setI (σ : Env) (x : String) (n : Int) : Env := + { σ with i := fun y => if y = x then n else σ.i y } +def Env.setB (σ : Env) (x : String) (p : Prop) : Env := + { σ with b := fun y => if y = x then p else σ.b y } +def Env.setA (σ : Env) (x : String) (f : Int → Int) : Env := + { σ with a := fun y => if y = x then f else σ.a y } + +open Classical in +/-- Equality of two values of one sort. -/ +noncomputable def Value.eq : Value → Value → Prop + | .int a, .int b => a = b + | .prop a, .prop b => (a ↔ b) + | .arr a, .arr b => a = b + | _, _ => False + +open Classical in +/-- The meaning of an operator applied to the values of its arguments. -/ +noncomputable def applyOp : String → List Value → Value + | "+", [a, b] => .int (a.toInt + b.toInt) + | "-", [a] => .int (-a.toInt) + | "-", [a, b] => .int (a.toInt - b.toInt) + | "*", [a, b] => .int (a.toInt * b.toInt) + | "div", [a, b] => .int (if b.toInt = 0 then 0 else a.toInt / b.toInt) + | "mod", [a, b] => .int (if b.toInt = 0 then 0 else a.toInt % b.toInt) + | "<=", [a, b] => .prop (a.toInt ≤ b.toInt) + | "<", [a, b] => .prop (a.toInt < b.toInt) + | ">=", [a, b] => .prop (a.toInt ≥ b.toInt) + | ">", [a, b] => .prop (a.toInt > b.toInt) + | "=", [a, b] => .prop (a.eq b) + | "not", [a] => .prop (¬ a.toProp) + | "=>", [a, b] => .prop (a.toProp → b.toProp) + | "and", as => .prop (∀ v ∈ as, v.toProp) + | "or", as => .prop (∃ v ∈ as, v.toProp) + | "ite", [c, .int a, .int b] => .int (if c.toProp then a else b) + | "ite", [c, .prop a, .prop b] => .prop (if c.toProp then a else b) + | "ite", [c, .arr a, .arr b] => .arr (if c.toProp then a else b) + | "select", [a, i] => .int (a.toArr i.toInt) + | "store", [a, i, v] => .arr (fun j => if j = i.toInt then v.toInt else a.toArr j) + | _, _ => .int 0 + +mutual +noncomputable def Tm.eval (σ : Env) : Tm → Value + | .num n => .int n + | .tt => .prop True + | .ff => .prop False + | .ivar x => .int (σ.i x) + | .bvar x => .prop (σ.b x) + | .avar x => .arr (σ.a x) + | .app f args => applyOp f (Tm.evalList σ args) + | .all x body => .prop (∀ n : Int, (Tm.eval (σ.setI x n) body).toProp) +noncomputable def Tm.evalList (σ : Env) : List Tm → List Value + | [] => [] + | t :: ts => Tm.eval σ t :: Tm.evalList σ ts +end + +theorem Tm.evalList_eq (σ : Env) : ∀ ts : List Tm, Tm.evalList σ ts = ts.map (Tm.eval σ) + | [] => rfl + | t :: ts => by rw [Tm.evalList, Tm.evalList_eq σ ts]; rfl + +/-- A term holds. -/ +def Tm.Holds (σ : Env) (t : Tm) : Prop := (t.eval σ).toProp + +/-! ## Sorts of terms -/ + +/-- The sort of a term, when the fragment gives it one. -/ +def sortOp : String → List (Option Srt) → Option Srt + | "+", [some .int, some .int] => some .int + | "-", [some .int] => some .int + | "-", [some .int, some .int] => some .int + | "*", [some .int, some .int] => some .int + | "div", [some .int, some .int] => some .int + | "mod", [some .int, some .int] => some .int + | "<=", [some .int, some .int] => some .bool + | "<", [some .int, some .int] => some .bool + | ">=", [some .int, some .int] => some .bool + | ">", [some .int, some .int] => some .bool + | "=", [some a, some b] => if a = b then some .bool else none + | "not", [some .bool] => some .bool + | "=>", [some .bool, some .bool] => some .bool + | "and", ss => if ss.all (· == some .bool) then some .bool else none + | "or", ss => if ss.all (· == some .bool) then some .bool else none + | "ite", [some .bool, some a, some b] => if a = b then some a else none + | "select", [some .arr, some .int] => some .int + | "store", [some .arr, some .int, some .int] => some .arr + | _, _ => none + +mutual +def Tm.sort? : Tm → Option Srt + | .num _ => some .int + | .tt => some .bool + | .ff => some .bool + | .ivar _ => some .int + | .bvar _ => some .bool + | .avar _ => some .arr + | .app f args => sortOp f (Tm.sortList args) + | .all _ body => if Tm.sort? body = some .bool then some .bool else none +def Tm.sortList : List Tm → List (Option Srt) + | [] => [] + | t :: ts => Tm.sort? t :: Tm.sortList ts +end + +/-! ## Printing, as solar-verify prints SMT-LIB -/ + +mutual +def Tm.print : Tm → String + | .num n => toString n + | .tt => "true" + | .ff => "false" + | .ivar x => "|" ++ x ++ "|" + | .bvar x => "|" ++ x ++ "|" + | .avar x => "|" ++ x ++ "|" + | .app f args => "(" ++ f ++ Tm.printArgs args ++ ")" + | .all x body => "(forall ((|" ++ x ++ "| Int)) " ++ Tm.print body ++ ")" +def Tm.printArgs : List Tm → String + | [] => "" + | t :: ts => " " ++ Tm.print t ++ Tm.printArgs ts +end + +def Srt.print : Srt → String + | .int => "Int" + | .bool => "Bool" + | .arr => "(Array Int Int)" + +/-! ## Scripts -/ + +/-- A command of a script. `raw` is a line the checks do not read (a comment, `(push 1)` around a +function); `elem x lo hi` is solar-verify's `;@elem` hint that the elements of the array `x` lie +in `[lo, hi]`, which the checks do not take as a fact. -/ +inductive Cmd where + | decl (x : String) (s : Srt) + | assert (t : Tm) + | push + | pop + | checkSat + | elem (x : String) (lo hi : Nat) + | raw (line : String) + deriving Repr, Inhabited + +def Cmd.print : Cmd → String + | .decl x s => "(declare-const |" ++ x ++ "| " ++ s.print ++ ")" + | .assert t => "(assert " ++ t.print ++ ")" + | .push => "(push 1)" + | .pop => "(pop 1)" + | .checkSat => "(check-sat)" + | .elem x lo hi => ";@elem |" ++ x ++ "| " ++ toString lo ++ " " ++ toString hi + | .raw l => l + +/-- A script's print: one command per line, each line ending in a newline. -/ +def printScript (cs : List Cmd) : String := + String.join (cs.map fun c => c.print ++ "\n") + +/-! ## Obligations + +At each `check-sat` the solver is asked whether the facts asserted so far, in every open `push`, +have a model. solar-verify asks it of the obligations it owes, which hold when there is none, and +of one probe per function, `(assert (not false))` after the guard, which asks whether some path +returns at all and owes nothing. -/ + +/-- The facts asserted when the commands `cs` have run from the stack `stk` (innermost frame +first), and at each `check-sat` the facts it reads, in order. -/ +def obligationsFrom : List (List Tm) → List Cmd → List (List Tm) + | _, [] => [] + | stk, .assert t :: cs => + match stk with + | [] => obligationsFrom [[t]] cs + | f :: rest => obligationsFrom ((t :: f) :: rest) cs + | stk, .push :: cs => obligationsFrom ([] :: stk) cs + | stk, .pop :: cs => obligationsFrom (stk.drop 1) cs + | stk, .checkSat :: cs => stk.flatten.reverse :: obligationsFrom stk cs + | stk, _ :: cs => obligationsFrom stk cs + +/-- The facts each `check-sat` of a script reads, oldest first. -/ +def obligations (cs : List Cmd) : List (List Tm) := obligationsFrom [[]] cs + +/-- A `check-sat` that only probes whether a path returns: its last fact is `(not false)`. -/ +def isProbe (fs : List Tm) : Bool := + match fs.getLast? with + | some (.app "not" [.ff]) => true + | _ => false + +/-- What solar-verify's verdict claims of a script: every obligation's facts have no model. -/ +def Valid (cs : List Cmd) : Prop := + ∀ fs ∈ obligations cs, isProbe fs = false → ∀ σ : Env, ¬ ∀ t ∈ fs, t.Holds σ + +end SolidCore.Verify.VC diff --git a/Verify/W1.lean b/Verify/W1.lean new file mode 100644 index 00000000..e9a27566 --- /dev/null +++ b/Verify/W1.lean @@ -0,0 +1,98 @@ +import Verify.Tactic +import SolidCore.Refinement.Corpus.W1 + +/-! +# w1: `f(uint256 x)` returns `x + 1`, or panics on overflow + +The specification of `Main.f` in `scripts/refinement/corpus/w1.sol`, proved against SolidCore +with the Loom VC generator of `Verify.Basic`: on every call of `f` with any argument word +`x < 2 ^ 256`, from the deployed (empty) storage, the call returns the word `x + 1` when it +fits in 256 bits and otherwise reverts with `Panic(0x11)`; storage stays empty. + +`model` is the function as a `SolM` program; `implements` ties it to SolidCore by symbolic +evaluation of the interpreter (`wide_symex`), and `spec` follows from Loom's weakest +precondition of the model, which `simp` computes and `omega` discharges. +-/ + +namespace SolidCore.Verify.W1 + +open EthLib.Base SolidCore.Refinement SolidCore.Refinement.Abi SolidCore.Refinement.Wide +open SolidCore.Refinement.Evm.Wide SolidCore.Solidity SolidCore.Solidity.Source +open SolidCore.Refinement.Corpus.W1 + +/-- `f` as a Loom program over the storage. -/ +def model (ws : List Nat) : SolM (List Nat) := + if ws.getD 0 0 + 1 < 2 ^ 256 then pure (word (ws.getD 0 0 + 1)) else revert (panic 0x11) + +/-- The calls of the specification: `f` on any word, from the deployed storage. -/ +def scope : Call → Prop := fullScope fns [] + +/-- No precondition beyond the scope. -/ +def pre : Call → Prop := fun _ => True + +/-- `f(x)` returns `x + 1` when it fits, else reverts with `Panic(0x11)`, and leaves +storage empty. -/ +def post (call : Call) (obs : Observable) : Prop := + let x := (argWords 1 call).getD 0 0 + (if x + 1 < 2 ^ 256 then obs.success = true ∧ obs.output = word (x + 1) + else obs.success = false ∧ obs.output = panic 0x11) ∧ + obs.logs = [] ∧ ∀ slot, obs.storage slot = 0 + +end SolidCore.Verify.W1 + + +namespace SolidCore.Verify.W1 + +open EthLib.Base SolidCore.Refinement SolidCore.Refinement.Abi SolidCore.Refinement.Wide +open SolidCore.Refinement.Evm.Wide SolidCore.Solidity SolidCore.Solidity.Source +open SolidCore.Refinement.Corpus.W1 + +set_option maxHeartbeats 0 in +set_option maxRecDepth 100000 in +/-- SolidCore runs `f` on any argument word as `model` does. -/ +theorem run_f {c : TypeCheck.CheckedContract} (hcore : c.core = coreLit) {d : Source.State} + (hd : Deployed fuel c d) (w : U256) : + Source.run fuel c (callOf Bytecode.W1.Main.fSelector [w]) = + some (Verify.observe (fun _ => 0) (model [w.toNat] (fun _ => 0))) := by + rw [run_eq hd] + have hs := hd.storage + have hev := hd.events + simp only [hcore, List.map_cons, List.map_nil] + wide_symex [coreLit, fuel, ctxOf, hcore, Bytecode.W1.Main.fSelector] + all_goals + have hw := w.isLt + simp only [model, List.getD_cons_zero] + split + all_goals try omega + all_goals + try rw [Nat.mod_eq_of_lt (by omega)] + simp [Source.observe, Verify.observe, revert, pure, StateT.pure, Except.pure, panic, word, + State.logEntries, State.loadSlot, StorageMap.lookup?, getElem?_of_isEmpty hs, + slotValue, callOf] + +/-- `model` implements SolidCore's `Main` on every call of the scope. -/ +theorem implements {c : TypeCheck.CheckedContract} (hcore : c.core = coreLit) {d : Source.State} + (hd : Deployed fuel c d) : Implements fuel c scope (argWords 1) model := + implements_of_run' (by simp [fns]) fun fn hfn ws hl => by + simp only [fns, List.mem_cons, List.not_mem_nil, or_false] at hfn + subst hfn + rcases ws with _ | ⟨w, _ | _⟩ <;> simp at hl + exact run_f hcore hd w + +/-- The verification conditions of `f`, by Loom's weakest preconditions. -/ +theorem vcs : ∀ call, scope call → pre call → vc model (argWords 1) post call := by + sc_vcgen [scope, fns, model, post] + +/-- **The specification of `w1`'s `f`**, as a triple against SolidCore. -/ +theorem spec : ∃ c, contract? = .ok c ∧ Triple fuel c scope pre post := by + obtain ⟨c, hc⟩ := contract_ok + obtain ⟨hk, _, hemp⟩ := shape_of hc + obtain ⟨d, hd⟩ := deployed_of hemp + exact ⟨c, hc, triple_of_wp (implements hk hd) vcs⟩ + +/-- The specification of `w1`'s `f` as `Satisfies` on SolidCore. -/ +theorem satisfies : ∃ c, contract? = .ok c ∧ Satisfies (solidCore fuel) c scope pre post := by + obtain ⟨c, hc, h⟩ := spec + exact ⟨c, hc, satisfies_of_triple h⟩ + +end SolidCore.Verify.W1 diff --git a/Verify/W4.lean b/Verify/W4.lean new file mode 100644 index 00000000..e35de352 --- /dev/null +++ b/Verify/W4.lean @@ -0,0 +1,173 @@ +import Verify.Tactic +import SolidCore.Refinement.Corpus.W4 + +/-! +# w4: `set(uint256 v)` stores `v` in slot 0 + +The specification of `Main.set` in `scripts/refinement/corpus/w4.sol`, proved against +SolidCore with the Loom VC generator of `Verify.Basic`: on every call of `set` with any +argument word `v < 2 ^ 256`, from the deployed (empty) storage, the call succeeds with empty +output and no logs, and afterwards slot 0 holds `v` and every other slot 0. + +`model` is the function as a `SolM` program (one `sstore`); `implements` ties it to +SolidCore by symbolic evaluation of the interpreter (`wide_symex`), and `spec` follows +from Loom's weakest precondition of the model. + +`specAt` widens it to any initial storage: on every call of `set` with no value from any +storage `σ` (`scopeAt`), slot 0 ends holding `v` and every other slot of `σ` is kept +(`postAt`). +-/ + +namespace SolidCore.Verify.W4 + +open EthLib.Base SolidCore.Refinement SolidCore.Refinement.Abi SolidCore.Refinement.Wide +open SolidCore.Refinement.Evm.Wide SolidCore.Solidity SolidCore.Solidity.Source +open SolidCore.Refinement.Corpus.W4 + +/-- `set` as a Loom program over the storage. -/ +def model (ws : List Nat) : SolM (List Nat) := do + sstore 0 (ws.getD 0 0) + pure [] + +/-- The calls of the specification: `set` on any word, from the deployed storage. -/ +def scope : Call → Prop := fullScope fns [] + +/-- No precondition beyond the scope. -/ +def pre : Call → Prop := fun _ => True + +/-- `set(v)` succeeds with no output and no logs, and leaves `v` in slot 0 and 0 elsewhere. -/ +def post (call : Call) (obs : Observable) : Prop := + let v := (argWords 1 call).getD 0 0 + obs.success = true ∧ obs.output = [] ∧ obs.logs = [] ∧ + ∀ slot, obs.storage slot = if slot % 2 ^ 256 = 0 then v else 0 + +set_option maxHeartbeats 0 in +set_option maxRecDepth 100000 in +/-- SolidCore runs `set` on any argument word as `model` does. -/ +theorem run_set {c : TypeCheck.CheckedContract} (hcore : c.core = coreLit) {d : Source.State} + (hd : Deployed fuel c d) (w : U256) : + Source.run fuel c (callOf Bytecode.W4.Main.setSelector [w]) = + some (Verify.observe (fun _ => 0) (model [w.toNat] (fun _ => 0))) := by + rw [run_eq hd] + have hs := hd.storage + have hev := hd.events + simp only [hcore, List.map_cons, List.map_nil] + wide_symex [coreLit, fuel, ctxOf, hcore, Bytecode.W4.Main.setSelector] + have hw := w.isLt + simp only [Source.observe, Verify.observe, model, sstore, bind, StateT.bind, pure, StateT.pure, + Except.bind, Except.pure, Observable.mk.injEq] + refine ⟨trivial, trivial, by simp [State.logEntries], ?_⟩ + funext slot + simp only [ite_true, State.loadSlot, StorageMap.lookup?, Std.HashMap.get?_eq_getElem?, + Std.HashMap.getElem?_insert, getElem?_of_isEmpty hs, Shared.norm, Shared.wordModulus] + rw [show EvmYul.UInt256.size = 2 ^ 256 from rfl] + generalize slot % 115792089237316195423570985008687907853269984665640564039457584007913129639936 = k + by_cases h : k = 0 + · subst h; simp; exact (Nat.mod_eq_of_lt hw).symm + · have h' : ¬0 = k := fun e => h e.symm + simp [h, h'] + +/-- `model` implements SolidCore's `Main` on every call of the scope. -/ +theorem implements {c : TypeCheck.CheckedContract} (hcore : c.core = coreLit) {d : Source.State} + (hd : Deployed fuel c d) : Implements fuel c scope (argWords 1) model := + implements_of_run' (by simp [fns]) fun fn hfn ws hl => by + simp only [fns, List.mem_cons, List.not_mem_nil, or_false] at hfn + subst hfn + rcases ws with _ | ⟨w, _ | _⟩ <;> simp at hl + exact run_set hcore hd w + +/-- The verification conditions of `set`, by Loom's weakest preconditions. -/ +theorem vcs : ∀ call, scope call → pre call → vc model (argWords 1) post call := by + sc_vcgen [scope, fns, model, post] + +/-- **The specification of `w4`'s `set`**, as a triple against SolidCore. -/ +theorem spec : ∃ c, contract? = .ok c ∧ Triple fuel c scope pre post := by + obtain ⟨c, hc⟩ := contract_ok + obtain ⟨hk, _, hemp⟩ := shape_of hc + obtain ⟨d, hd⟩ := deployed_of hemp + exact ⟨c, hc, triple_of_wp (implements hk hd) vcs⟩ + +/-- The specification of `w4`'s `set` as `Satisfies` on SolidCore. -/ +theorem satisfies : ∃ c, contract? = .ok c ∧ Satisfies (solidCore fuel) c scope pre post := by + obtain ⟨c, hc, h⟩ := spec + exact ⟨c, hc, satisfies_of_triple h⟩ + + +/-! ## From any storage + +`specAt` states the same on `scopeAt`, every call of `set` with no value from any storage `σ`, +whose postcondition `postAt` keeps every slot of `σ` but slot 0: `run_set_at` runs SolidCore +from `σ` written over the deployed storage (`run_eq_at`), and `vcsAt` is `sc_vcgen` for each +`σ`. -/ + +/-- The calls of `set` on any word, with no value, from any storage. -/ +def scopeAt : Call → Prop := fun call => ∃ σ, fullScope fns σ call + +/-- `set(v)` succeeds with no output and no logs, and leaves `v` in slot 0 and every other +slot of the call's storage as it was. -/ +def postAt (call : Call) (obs : Observable) : Prop := + let v := (argWords 1 call).getD 0 0 + obs.success = true ∧ obs.output = [] ∧ obs.logs = [] ∧ + ∀ slot, obs.storage slot = if slot % 2 ^ 256 = 0 then v else slotValue call.storage slot + +set_option maxHeartbeats 0 in +set_option maxRecDepth 100000 in +/-- SolidCore runs `set` on any argument word from any storage `σ` as `model` does. -/ +theorem run_set_at {c : TypeCheck.CheckedContract} (hcore : c.core = coreLit) {d : Source.State} + (hd : DeployedAt fuel c d []) (w : U256) (σ : List (Nat × Nat)) : + Source.run fuel c (callAt Bytecode.W4.Main.setSelector [w] σ) = + some (Verify.observe (slotValue σ) (model [w.toNat] (slotValue σ))) := by + rw [run_eq_at hd] + have hev := hd.events + have h0 : ∀ q : Nat, d.storage[q]? = none := fun q => hd.getElem?_eq_none (by simp) + have hget := getD_storage h0 σ + generalize σ.foldl (fun acc kv => StorageMap.insertLoop acc kv.1 kv.2) d.storage = m at hget + simp only [hcore, List.map_cons, List.map_nil] + wide_symex [coreLit, fuel, ctxOf, hcore, Bytecode.W4.Main.setSelector] + have hw := w.isLt + simp only [Source.observe, Verify.observe, model, sstore, bind, StateT.bind, pure, StateT.pure, + Except.bind, Except.pure, Observable.mk.injEq] + refine ⟨trivial, trivial, by simp [State.logEntries], ?_⟩ + funext slot + have hs := hget slot + simp only [Nat.reducePow] at hs + simp only [ite_true, State.loadSlot, StorageMap.lookup?, Std.HashMap.get?_eq_getElem?, + Std.HashMap.getElem?_insert, Shared.norm, Shared.wordModulus, EvmYul.UInt256.size, + List.getD_cons_zero, Nat.zero_mod, beq_iff_eq] + generalize slot % 115792089237316195423570985008687907853269984665640564039457584007913129639936 = k at hs ⊢ + by_cases h : k = 0 + · subst h; simp [Nat.mod_eq_of_lt hw] + · have h' : ¬0 = k := fun e => h e.symm + simp only [h, h', ↓reduceIte, ← hs] + cases m[k]? <;> rfl + +/-- `model` implements SolidCore's `Main` on every call of `scopeAt`. -/ +theorem implementsAt {c : TypeCheck.CheckedContract} (hcore : c.core = coreLit) {d : Source.State} + (hd : DeployedAt fuel c d []) : Implements fuel c scopeAt (argWords 1) model := by + rintro call ⟨σ, hs⟩ + refine implements_of_run' (s := σ) (by simp [fns]) (fun fn hfn ws hl => ?_) call hs + simp only [fns, List.mem_cons, List.not_mem_nil, or_false] at hfn + subst hfn + rcases ws with _ | ⟨w, _ | _⟩ <;> simp at hl + exact run_set_at hcore hd w σ + +/-- The verification conditions of `set` from any storage, by Loom's weakest preconditions. -/ +theorem vcsAt : ∀ call, scopeAt call → pre call → vc model (argWords 1) postAt call := by + rintro call ⟨σ, hs⟩ hp + have h : ∀ call, fullScope fns σ call → pre call → vc model (argWords 1) postAt call := by + sc_vcgen [fns, model, postAt] + exact h call hs hp + +/-- **The specification of `w4`'s `set` from any storage**, as a triple against SolidCore. -/ +theorem specAt : ∃ c, contract? = .ok c ∧ Triple fuel c scopeAt pre postAt := by + obtain ⟨c, hc⟩ := contract_ok + obtain ⟨hk, _, hemp⟩ := shape_of hc + obtain ⟨d, hd⟩ := deployed_of hemp + exact ⟨c, hc, triple_of_wp (implementsAt hk (deployedAt_of_deployed hd)) vcsAt⟩ + +/-- The specification from any storage as `Satisfies` on SolidCore. -/ +theorem satisfiesAt : ∃ c, contract? = .ok c ∧ Satisfies (solidCore fuel) c scopeAt pre postAt := by + obtain ⟨c, hc, h⟩ := specAt + exact ⟨c, hc, satisfies_of_triple h⟩ + +end SolidCore.Verify.W4 diff --git a/Verify/W5.lean b/Verify/W5.lean new file mode 100644 index 00000000..8a065c5f --- /dev/null +++ b/Verify/W5.lean @@ -0,0 +1,173 @@ +import Verify.Tactic +import SolidCore.Refinement.Corpus.W5 + +/-! +# w5: `f(uint256 a, uint256 b)` returns `a + b`, or panics on overflow + +The specification of `Main.f` in `scripts/refinement/corpus/w5.sol` (compiled by solar with +`-Ogas`), proved against SolidCore with the Loom VC generator of `Verify.Basic`: on every call +of `f` with any argument words `a b < 2 ^ 256`, from the deployed (empty) storage, the call +returns the word `a + b` when it fits in 256 bits and otherwise reverts with `Panic(0x11)`; +it emits no logs and storage stays empty. + +`model` is the function as a `SolM` program; `implements` ties it to SolidCore by symbolic +evaluation of the interpreter (`wide_symex`), and `vcs` follows from Loom's weakest +precondition of the model by `sc_vcgen`. Nothing here, nor in `Corpus.W5`, uses +`native_decide` or `bv_decide`: the kernel checks `Corpus.W5.shape_eq` by evaluation. +-/ + +namespace SolidCore.Verify.W5 + +open EthLib.Base SolidCore.Refinement SolidCore.Refinement.Abi SolidCore.Refinement.Wide +open SolidCore.Refinement.Evm.Wide SolidCore.Solidity SolidCore.Solidity.Source +open SolidCore.Refinement.Corpus.W5 + +/-- `f` as a Loom program over the storage. -/ +def model (ws : List Nat) : SolM (List Nat) := + if ws.getD 0 0 + ws.getD 1 0 < 2 ^ 256 then pure (word (ws.getD 0 0 + ws.getD 1 0)) + else revert (panic 0x11) + +/-- The calls of the specification: `f` on any two words, from the deployed storage. -/ +def scope : Call → Prop := fullScope fns [] + +/-- No precondition beyond the scope. -/ +def pre : Call → Prop := fun _ => True + +/-- `f(a, b)` returns `a + b` when it fits, else reverts with `Panic(0x11)`; it emits no +logs and leaves storage empty. -/ +def post (call : Call) (obs : Observable) : Prop := + let a := (argWords 2 call).getD 0 0 + let b := (argWords 2 call).getD 1 0 + (if a + b < 2 ^ 256 then obs.success = true ∧ obs.output = word (a + b) + else obs.success = false ∧ obs.output = panic 0x11) ∧ + obs.logs = [] ∧ ∀ slot, obs.storage slot = 0 + +set_option maxHeartbeats 0 in +set_option maxRecDepth 100000 in +/-- SolidCore runs `f` on any argument words as `model` does. -/ +theorem run_f {c : TypeCheck.CheckedContract} (hcore : c.core = coreLit) {d : Source.State} + (hd : Deployed fuel c d) (w1 w2 : U256) : + Source.run fuel c (callOf Bytecode.W5.Main.fSelector [w1, w2]) = + some (Verify.observe (fun _ => 0) (model [w1.toNat, w2.toNat] (fun _ => 0))) := by + rw [run_eq hd] + have hs := hd.storage + have hev := hd.events + simp only [hcore, List.map_cons, List.map_nil] + wide_symex [coreLit, fuel, ctxOf, hcore, Bytecode.W5.Main.fSelector] + all_goals + have hw1 := w1.isLt + have hw2 := w2.isLt + simp only [model, List.getD_cons_zero, List.getD_cons_succ] + split + all_goals try omega + all_goals + try rw [Nat.mod_eq_of_lt (by omega)] + simp [Source.observe, Verify.observe, revert, pure, StateT.pure, Except.pure, panic, word, + State.logEntries, State.loadSlot, StorageMap.lookup?, getElem?_of_isEmpty hs, + slotValue, callOf] + +/-- `model` implements SolidCore's `Main` on every call of the scope. -/ +theorem implements {c : TypeCheck.CheckedContract} (hcore : c.core = coreLit) {d : Source.State} + (hd : Deployed fuel c d) : Implements fuel c scope (argWords 2) model := + implements_of_run' (by simp [fns]) fun fn hfn ws hl => by + simp only [fns, List.mem_cons, List.not_mem_nil, or_false] at hfn + subst hfn + rcases ws with _ | ⟨w1, _ | ⟨w2, _ | _⟩⟩ <;> simp at hl + exact run_f hcore hd w1 w2 + +/-- The verification conditions of `f`, by Loom's weakest preconditions. -/ +theorem vcs : ∀ call, scope call → pre call → vc model (argWords 2) post call := by + sc_vcgen [scope, fns, model, post] + +/-- **The specification of `w5`'s `f`**, as a triple against SolidCore. -/ +theorem spec : ∃ c, contract? = .ok c ∧ Triple fuel c scope pre post := by + obtain ⟨c, hc⟩ := contract_ok + obtain ⟨hk, _, hemp⟩ := shape_of hc + obtain ⟨d, hd⟩ := deployed_of hemp + exact ⟨c, hc, triple_of_wp (implements hk hd) vcs⟩ + +/-- The specification of `w5`'s `f` as `Satisfies` on SolidCore. -/ +theorem satisfies : ∃ c, contract? = .ok c ∧ Satisfies (solidCore fuel) c scope pre post := by + obtain ⟨c, hc, h⟩ := spec + exact ⟨c, hc, satisfies_of_triple h⟩ + + +/-! ## From any storage + +`specAt` states the same on `scopeAt`, every call of `f` with no value from any storage `σ`, +whose postcondition `postAt` keeps `σ`: `run_f_at` runs SolidCore from `σ` written over the +deployed storage (`run_eq_at`), and `vcsAt` is `sc_vcgen` for each `σ`. -/ + +/-- The calls of `f` on any two words, with no value, from any storage. -/ +def scopeAt : Call → Prop := fun call => ∃ σ, fullScope fns σ call + +/-- `f(a, b)` returns `a + b` when it fits, else reverts with `Panic(0x11)`; it emits no +logs and leaves the call's storage as it was. -/ +def postAt (call : Call) (obs : Observable) : Prop := + let a := (argWords 2 call).getD 0 0 + let b := (argWords 2 call).getD 1 0 + (if a + b < 2 ^ 256 then obs.success = true ∧ obs.output = word (a + b) + else obs.success = false ∧ obs.output = panic 0x11) ∧ + obs.logs = [] ∧ ∀ slot, obs.storage slot = slotValue call.storage slot + +set_option maxHeartbeats 0 in +set_option maxRecDepth 100000 in +/-- SolidCore runs `f` on any argument words from any storage `σ` as `model` does. -/ +theorem run_f_at {c : TypeCheck.CheckedContract} (hcore : c.core = coreLit) {d : Source.State} + (hd : DeployedAt fuel c d []) (w1 w2 : U256) (σ : List (Nat × Nat)) : + Source.run fuel c (callAt Bytecode.W5.Main.fSelector [w1, w2] σ) = + some (Verify.observe (slotValue σ) (model [w1.toNat, w2.toNat] (slotValue σ))) := by + rw [run_eq_at hd] + have hev := hd.events + have h0 : ∀ q : Nat, d.storage[q]? = none := fun q => hd.getElem?_eq_none (by simp) + have hget := getD_storage h0 σ + generalize σ.foldl (fun acc kv => StorageMap.insertLoop acc kv.1 kv.2) d.storage = m at hget + simp only [hcore, List.map_cons, List.map_nil] + wide_symex [coreLit, fuel, ctxOf, hcore, Bytecode.W5.Main.fSelector] + all_goals + have hw1 := w1.isLt + have hw2 := w2.isLt + simp only [model, List.getD_cons_zero, List.getD_cons_succ] + split + all_goals try omega + all_goals + try rw [Nat.mod_eq_of_lt (by omega)] + simp [Source.observe, Verify.observe, revert, pure, StateT.pure, Except.pure, panic, word, + State.logEntries, State.loadSlot, StorageMap.lookup?, callAt] + funext slot + have hs := hget slot + simp only [Nat.reducePow] at hs + simp only [Shared.norm, Shared.wordModulus, EvmYul.UInt256.size] + rw [← hs] + split <;> (rename_i h; simp [h]) + +/-- `model` implements SolidCore's `Main` on every call of `scopeAt`. -/ +theorem implementsAt {c : TypeCheck.CheckedContract} (hcore : c.core = coreLit) {d : Source.State} + (hd : DeployedAt fuel c d []) : Implements fuel c scopeAt (argWords 2) model := by + rintro call ⟨σ, hs⟩ + refine implements_of_run' (s := σ) (by simp [fns]) (fun fn hfn ws hl => ?_) call hs + simp only [fns, List.mem_cons, List.not_mem_nil, or_false] at hfn + subst hfn + rcases ws with _ | ⟨w1, _ | ⟨w2, _ | _⟩⟩ <;> simp at hl + exact run_f_at hcore hd w1 w2 σ + +/-- The verification conditions of `f` from any storage, by Loom's weakest preconditions. -/ +theorem vcsAt : ∀ call, scopeAt call → pre call → vc model (argWords 2) postAt call := by + rintro call ⟨σ, hs⟩ hp + have h : ∀ call, fullScope fns σ call → pre call → vc model (argWords 2) postAt call := by + sc_vcgen [fns, model, postAt] + exact h call hs hp + +/-- **The specification of `w5`'s `f` from any storage**, as a triple against SolidCore. -/ +theorem specAt : ∃ c, contract? = .ok c ∧ Triple fuel c scopeAt pre postAt := by + obtain ⟨c, hc⟩ := contract_ok + obtain ⟨hk, _, hemp⟩ := shape_of hc + obtain ⟨d, hd⟩ := deployed_of hemp + exact ⟨c, hc, triple_of_wp (implementsAt hk (deployedAt_of_deployed hd)) vcsAt⟩ + +/-- The specification from any storage as `Satisfies` on SolidCore. -/ +theorem satisfiesAt : ∃ c, contract? = .ok c ∧ Satisfies (solidCore fuel) c scopeAt pre postAt := by + obtain ⟨c, hc, h⟩ := specAt + exact ⟨c, hc, satisfies_of_triple h⟩ + +end SolidCore.Verify.W5 diff --git a/lakefile.lean b/lakefile.lean index 8d441779..c4c88958 100644 --- a/lakefile.lean +++ b/lakefile.lean @@ -115,11 +115,19 @@ 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. -/ +/-- Loom's monad algebras and weakest preconditions, ported to Lean 4.35 (Loom/README.md). Only +the ported modules are kept; every one builds. -/ lean_lib Loom where - srcDir := "vendor/loom" - globs := #[.submodules `Loom] + roots := #[`Loom] + globs := #[.andSubmodules `Loom] + +/-- Verification on top of SolidCore: the Loom-based VC generator and the specs it proves +(Verify/*.lean), solar-verify's spec language with ghost erasure and its trusted base +(Verify/Spec), solar-verify's VCs checked against Loom models (Verify/VC) and the composition +of a source triple with the refinement to bytecode (Verify/Final.lean). `lake build Verify` +builds the root's closure; the libraries below hold the heavier, generated-input parts. -/ +lean_lib Verify where + roots := #[`Verify] -- bank's and events' assembly stages against solar's exports (solar-tv/milestone/bank and -- solar-tv/milestone/events at 0a455fda): the generic assembler check with mapping hashes, @@ -202,62 +210,129 @@ lean_lib W1 where lean_lib counter where srcDir := "Certified" roots := #[`counter.Proofs] - globs := #[.andSubmodules `counter] + globs := #[.submodules `counter] leanOptions := solarTVOptions moreLeanArgs := #["-M", "3000"] lean_lib w4 where srcDir := "Certified" roots := #[`w4.Proofs] - globs := #[.andSubmodules `w4] + globs := #[.submodules `w4] leanOptions := solarTVOptions moreLeanArgs := #["-M", "3000"] lean_lib masks where srcDir := "Certified" roots := #[`masks.Proofs] - globs := #[.andSubmodules `masks] + globs := #[.submodules `masks] leanOptions := solarTVOptions moreLeanArgs := #["-M", "3000"] lean_lib bank where srcDir := "Certified" roots := #[`bank.Proofs] - globs := #[.andSubmodules `bank] + globs := #[.submodules `bank] leanOptions := solarTVOptions moreLeanArgs := #["-M", "3000"] lean_lib c4 where srcDir := "Certified" roots := #[`c4.Proofs] - globs := #[.andSubmodules `c4] + globs := #[.submodules `c4] leanOptions := solarTVOptions moreLeanArgs := #["-M", "3000"] lean_lib mulx where srcDir := "Certified" roots := #[`mulx.Proofs] - globs := #[.andSubmodules `mulx] + globs := #[.submodules `mulx] leanOptions := solarTVOptions moreLeanArgs := #["-M", "3000"] lean_lib events where srcDir := "Certified" roots := #[`events.Proofs] - globs := #[.andSubmodules `events] + globs := #[.submodules `events] leanOptions := solarTVOptions moreLeanArgs := #["-M", "3000"] lean_lib reader where srcDir := "Certified" roots := #[`reader.Proofs] - globs := #[.andSubmodules `reader] + globs := #[.submodules `reader] leanOptions := solarTVOptions moreLeanArgs := #["-M", "3000"] lean_lib token where srcDir := "Certified" roots := #[`token.Proofs] - globs := #[.andSubmodules `token] + globs := #[.submodules `token] leanOptions := solarTVOptions moreLeanArgs := #["-M", "3000"] + +-- solar-verify's spec language: its meaning over SolidCore's and EthLib's calls and observables, +-- ghost erasure, the trusted base as named hypotheses, and the specs solar-verify exports +-- (Verify/Spec, scripts/refinement/spec/check.sh). +lean_lib VerifySpec where + roots := #[`Verify.Spec.Syntax, `Verify.Spec.Semantics, `Verify.Spec.Contract, + `Verify.Spec.Ghost, `Verify.Spec.GhostFree, `Verify.Spec.TrustedBase, + `Verify.Spec.TrustedBase.Hypotheses, `Verify.Spec.TrustedBase.Interface] + +-- The trusted base discharged for c4 and Counter on their checked-in source ASTs, and its axiom +-- audit. Separate from VerifySpec because the ASTs import the type checker. +lean_lib VerifySpecTrustedBase where + roots := #[`Verify.Spec.TrustedBase.Instances, `Verify.Spec.TrustedBase.Axioms] + +-- c4's exported spec (solar-verify --emit-lean-spec, scripts/refinement/spec/check.sh) proved of +-- SolidCore and of solar's bytecode, and the axiom audit. Needs the generated corpus +-- (scripts/refinement/gen.sh), so it is outside the default root. +lean_lib ContractsC4Spec where + roots := #[`Contracts.C4.Spec.Export, `Contracts.C4.Spec.ExportWrong, `Contracts.C4.Spec.Bytecode, + `Contracts.C4.Spec.Axioms] + +-- solar-verify's verification conditions checked against SolidCore through the Loom generator +-- (Verify/VC.lean), the generic theorem from an erased function to its obligations +-- (Verify/VC/Obligations.lean) and its fuel uniformity (Verify/FuelStable.lean), outside the default +-- root: it builds on the generic source stage. +lean_lib VerifyVC where + roots := #[`Verify.VC, `Verify.FuelStable] + +-- solar-verify's transcripts of scripts/verify/{Counter,Token}.sol (scripts/verify/check.sh) bound +-- to their scripts, Token.burn and Token.transfer proved from the checked VCs, and the mutants. +lean_lib ContractsVC where + roots := #[`Contracts.Counter.VC.Bind, `Contracts.Token.VC.Bind, `Contracts.Token.VC.Burn, + `Contracts.Token.VC.Transfer, `Contracts.Token.VC.Mutants, `Contracts.Counter.VC.Inc, `Contracts.Counter.VC.Get, + `Contracts.Counter.VC.Mutants, `Contracts.Counter.VC.Generic] + -- The exports, sources and mutants the roots import are under the same directories. + globs := #[.submodules `Contracts.Counter.VC, .submodules `Contracts.Token.VC] + +-- Loom's axiom audit and the check that the certified Loom path stays off Loom's unported +-- layers (Verify/LoomAxioms.lean, Verify/LoomImports.lean). +lean_lib VerifyLoom where + roots := #[`Verify.LoomAxioms, `Verify.LoomImports] + +-- Counter end to end: its source triple carried through the refinement to solar's bytecode +-- (Verify.Final) and solar-verify's verdict as named hypotheses; the headline +-- (Contracts/Counter/Headline.lean) discharges the verdict for solar-verify's exported spec of +-- scripts/verify/CounterMilestone.sol and states it of solar's bytecode. +lean_lib ContractsCounter where + roots := #[`Contracts.Counter.Final, `Contracts.Counter.Verdict, `Contracts.Counter.EndToEnd, + `Contracts.Counter.Headline] + -- The spec exports and the source binding the roots import. + globs := #[.one `Contracts.Counter.Verify, .submodules `Contracts.Counter.Spec] + +/-! solar-verify's verification conditions and their kernel-checked discharge (formerly solar's +crates/verify/lean). An exported VC module imports `Verify.Obligation`; `Verify.Discharge` holds the +certificate checkers a VC is accepted by (Verify/Discharge/README.md). Lean's default options, as +solar's `solar_verify` package had. -/ +lean_lib VerifyDischarge where + roots := #[`Verify.Obligation, `Verify.Discharge] + leanOptions := #[⟨`maxHeartbeats, (200000 : Nat)⟩, ⟨`backward.do.legacy, false⟩] + +-- ArrayMax and Vault: solar-verify's exported VCs of their specs (Contracts/{ArrayMax,Vault}/Vc), +-- every required obligation proved in the kernel (Proofs/), Vault's vacuous obligations shown +-- vacuous (Contracts/Vault/Proofs/Vacuous.lean), and the axiom audits. +lean_lib ContractsArrayMaxVault where + roots := #[`Contracts.ArrayMax.Audit, `Contracts.Vault.Audit] + globs := #[.submodules `Contracts.ArrayMax, .submodules `Contracts.Vault] + leanOptions := #[⟨`maxHeartbeats, (200000 : Nat)⟩, ⟨`backward.do.legacy, false⟩] diff --git a/scripts/refinement/axiom-audit.sh b/scripts/refinement/axiom-audit.sh index c51223bc..611ac18b 100755 --- a/scripts/refinement/axiom-audit.sh +++ b/scripts/refinement/axiom-audit.sh @@ -1,13 +1,14 @@ #!/usr/bin/env bash -# The axiom pass: elaborates the five SolidCore/Refinement/Axioms files (one environment can hold +# The axiom pass: elaborates the six 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 +# SolidCoreSolarBankSource SolidCore.Refinement.Axioms.Audit \ +# ContractsCounter ContractsVC VerifyLoom VerifySpecTrustedBase set -uo pipefail cd "$(dirname "$0")/../.." logs=() closures=() -for part in Main C4 MulX W4 CounterGeneric; do +for part in Main C4 MulX W4 CounterGeneric Contracts; 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 $?" diff --git a/scripts/refinement/spec/c4.sol b/scripts/refinement/spec/c4.sol new file mode 100644 index 00000000..f45337b6 --- /dev/null +++ b/scripts/refinement/spec/c4.sol @@ -0,0 +1,11 @@ +// SPDX-License-Identifier: UNLICENSED +pragma solidity ^0.8.28; +contract Main { + uint8 v; + uint8 w = 7; + /// @custom:ensures result == old(v) + x + /// @custom:ensures v == old(v) + x + /// @custom:ensures w == (old(w) ^ x) + /// @custom:succeeds-if v + x < 256 + function add(uint8 x) external returns (uint8) { v += x; w ^= x; return v; } +} diff --git a/scripts/refinement/spec/c4_wrong.sol b/scripts/refinement/spec/c4_wrong.sol new file mode 100644 index 00000000..4a7c7294 --- /dev/null +++ b/scripts/refinement/spec/c4_wrong.sol @@ -0,0 +1,11 @@ +// SPDX-License-Identifier: UNLICENSED +pragma solidity ^0.8.28; +contract Main { + uint8 v; + uint8 w = 7; + /// @custom:ensures result == old(v) + x + 1 + /// @custom:ensures v == old(v) + x + /// @custom:ensures w == (old(w) ^ x) + /// @custom:succeeds-if v + x < 256 + function add(uint8 x) external returns (uint8) { v += x; w ^= x; return v; } +} diff --git a/scripts/refinement/spec/check.sh b/scripts/refinement/spec/check.sh new file mode 100755 index 00000000..01b435e7 --- /dev/null +++ b/scripts/refinement/spec/check.sh @@ -0,0 +1,47 @@ +#!/usr/bin/env bash +# Check the specs solar-verify exported for the spec corpus (scripts/refinement/spec). +# +# SOLAR_VERIFY=path/to/solar-verify scripts/refinement/spec/check.sh +# +# For each annotated source NAME.sol it +# 1. regenerates Contracts/C4/Spec/.lean with solar-verify --emit-lean-spec and fails if it +# differs from the checked-in file; +# 2. checks that the annotated source is the corpus source it annotates +# (scripts/refinement/corpus/c4.sol) with comments and whitespace removed, so the compiler +# sees the same program; +# 3. checks that the manifest's bytecode sha256 is the sha256 of the runtime bytecode the corpus +# refinement is about (SolidCore/Refinement/Bytecode/C4.lean). +set -euo pipefail +cd "$(dirname "${BASH_SOURCE[0]}")/../../.." + +sv="${SOLAR_VERIFY:?set SOLAR_VERIFY to a solar-verify binary with --emit-lean-spec}" +compiler="solar 0.3.0-dev+commit.9688f215" +sha="8a21bc207d9dd8be48d921a717eda3ecb7e5bfcb5397850bc3d64a29037fac47" +tmp="$(mktemp -d)" +trap 'rm -rf "$tmp"' EXIT + +for pair in c4:C4:Export c4_wrong:C4Wrong:ExportWrong; do + name="${pair%%:*}" + rest="${pair#*:}"; mod="${rest%%:*}"; file="${rest#*:}" + "$sv" "scripts/refinement/spec/$name.sol" --emit-lean-spec "$tmp/$mod.lean" \ + --lean-spec-module "SolidCore.Spec.Export.$mod" --lean-spec-compiler "$compiler" \ + --lean-spec-bytecode-sha256 "$sha" + diff -u "Contracts/C4/Spec/$file.lean" "$tmp/$mod.lean" +done + +strip() { sed -e 's|//.*$||' "$1" | tr -d ' \t\n'; } +[[ "$(strip scripts/refinement/spec/c4.sol)" == "$(strip scripts/refinement/corpus/c4.sol)" ]] || { + echo "spec/c4.sol is not corpus/c4.sol with comments" >&2 + exit 1 +} + +python3 - "$sha" <<'PY' +import hashlib, re, sys +s = open("SolidCore/Refinement/Bytecode/C4.lean").read() +h = re.search(r"def Main.runtimeNat : Nat :=\s*0x([0-9a-f]+)", s).group(1) +n = int(re.search(r"runtimeSize : Nat := (\d+)", s).group(1)) +got = hashlib.sha256(bytes.fromhex(h.rjust(2 * n, "0"))).hexdigest() +if got != sys.argv[1]: + sys.exit(f"bytecode sha256 {got} is not the manifest's {sys.argv[1]}") +PY +echo "spec exports, sources and bytecode hash check out" diff --git a/scripts/solc_ast_to_lean_source.py b/scripts/solc_ast_to_lean_source.py index 5de6c1eb..f2f6eebc 100755 --- a/scripts/solc_ast_to_lean_source.py +++ b/scripts/solc_ast_to_lean_source.py @@ -47,7 +47,9 @@ SOURCE_CHILD_FIELDS: set[tuple[str, str]] = {('ArrayTypeName', 'baseType'), ('Ar METADATA_CHILD_FIELDS: set[tuple[str, str]] = {('ContractDefinition', 'documentation'), ('EnumDefinition', 'documentation'), ('ErrorDefinition', 'documentation'), ('EventDefinition', 'documentation'), ('FunctionDefinition', 'documentation'), ('ModifierDefinition', 'documentation'), ('StructDefinition', 'documentation'), ('VariableDeclaration', 'documentation')} SOURCE_SCALAR_FIELDS: set[tuple[str, str]] = {('Assignment', 'operator'), ('BinaryOperation', 'operator'), ('ContractDefinition', 'abstract'), ('ContractDefinition', 'contractKind'), ('ContractDefinition', 'name'), ('ElementaryTypeName', 'name'), ('ElementaryTypeName', 'stateMutability'), ('EnumDefinition', 'name'), ('EnumValue', 'name'), ('ErrorDefinition', 'name'), ('EventDefinition', 'anonymous'), ('EventDefinition', 'name'), ('FunctionCall', 'names'), ('FunctionCallOptions', 'names'), ('FunctionDefinition', 'kind'), ('FunctionDefinition', 'name'), ('FunctionDefinition', 'stateMutability'), ('FunctionDefinition', 'virtual'), ('FunctionDefinition', 'visibility'), ('FunctionTypeName', 'stateMutability'), ('FunctionTypeName', 'visibility'), ('Identifier', 'name'), ('IdentifierPath', 'name'), ('Literal', 'hexValue'), ('Literal', 'kind'), ('Literal', 'subdenomination'), ('Literal', 'value'), ('MemberAccess', 'memberName'), ('ModifierDefinition', 'name'), ('ModifierDefinition', 'virtual'), ('PragmaDirective', 'literals'), ('StructDefinition', 'name'), ('TryCatchClause', 'errorName'), ('TupleExpression', 'components'), ('TupleExpression', 'isInlineArray'), ('UnaryOperation', 'operator'), ('UnaryOperation', 'prefix'), ('UserDefinedValueTypeDefinition', 'name'), ('UsingForDirective', 'functionList.operator'), ('UsingForDirective', 'global'), ('VariableDeclaration', 'constant'), ('VariableDeclaration', 'indexed'), ('VariableDeclaration', 'mutability'), ('VariableDeclaration', 'name'), ('VariableDeclaration', 'stateVariable'), ('VariableDeclaration', 'storageLocation'), ('VariableDeclaration', 'visibility'), ('VariableDeclarationStatement', 'declarations')} ANALYSIS_SCALAR_FIELDS: set[tuple[str, str]] = {('ArrayTypeName', 'typeDescriptions.typeIdentifier'), ('ArrayTypeName', 'typeDescriptions.typeString'), ('Assignment', 'isConstant'), ('Assignment', 'isLValue'), ('Assignment', 'isPure'), ('Assignment', 'lValueRequested'), ('Assignment', 'typeDescriptions.typeIdentifier'), ('Assignment', 'typeDescriptions.typeString'), ('BinaryOperation', 'commonType.typeIdentifier'), ('BinaryOperation', 'commonType.typeString'), ('BinaryOperation', 'isConstant'), ('BinaryOperation', 'isLValue'), ('BinaryOperation', 'isPure'), ('BinaryOperation', 'lValueRequested'), ('BinaryOperation', 'function'), ('BinaryOperation', 'typeDescriptions.typeIdentifier'), ('BinaryOperation', 'typeDescriptions.typeString'), ('Conditional', 'isConstant'), ('Conditional', 'isLValue'), ('Conditional', 'isPure'), ('Conditional', 'lValueRequested'), ('Conditional', 'typeDescriptions.typeIdentifier'), ('Conditional', 'typeDescriptions.typeString'), ('ContractDefinition', 'fullyImplemented'), ('ElementaryTypeName', 'typeDescriptions.typeIdentifier'), ('ElementaryTypeName', 'typeDescriptions.typeString'), ('ElementaryTypeNameExpression', 'argumentTypes.typeIdentifier'), ('ElementaryTypeNameExpression', 'argumentTypes.typeString'), ('ElementaryTypeNameExpression', 'isConstant'), ('ElementaryTypeNameExpression', 'isLValue'), ('ElementaryTypeNameExpression', 'isPure'), ('ElementaryTypeNameExpression', 'lValueRequested'), ('ElementaryTypeNameExpression', 'typeDescriptions.typeIdentifier'), ('ElementaryTypeNameExpression', 'typeDescriptions.typeString'), ('ForStatement', 'isSimpleCounterLoop'), ('FunctionCall', 'argumentTypes.typeIdentifier'), ('FunctionCall', 'argumentTypes.typeString'), ('FunctionCall', 'isConstant'), ('FunctionCall', 'isLValue'), ('FunctionCall', 'isPure'), ('FunctionCall', 'kind'), ('FunctionCall', 'lValueRequested'), ('FunctionCall', 'tryCall'), ('FunctionCall', 'typeDescriptions.typeIdentifier'), ('FunctionCall', 'typeDescriptions.typeString'), ('FunctionCallOptions', 'argumentTypes.typeIdentifier'), ('FunctionCallOptions', 'argumentTypes.typeString'), ('FunctionCallOptions', 'isConstant'), ('FunctionCallOptions', 'isLValue'), ('FunctionCallOptions', 'isPure'), ('FunctionCallOptions', 'lValueRequested'), ('FunctionCallOptions', 'typeDescriptions.typeIdentifier'), ('FunctionCallOptions', 'typeDescriptions.typeString'), ('FunctionDefinition', 'implemented'), ('FunctionTypeName', 'typeDescriptions.typeIdentifier'), ('FunctionTypeName', 'typeDescriptions.typeString'), ('Identifier', 'argumentTypes.typeIdentifier'), ('Identifier', 'argumentTypes.typeString'), ('Identifier', 'typeDescriptions.typeIdentifier'), ('Identifier', 'typeDescriptions.typeString'), ('IndexAccess', 'argumentTypes.typeIdentifier'), ('IndexAccess', 'argumentTypes.typeString'), ('IndexAccess', 'isConstant'), ('IndexAccess', 'isLValue'), ('IndexAccess', 'isPure'), ('IndexAccess', 'lValueRequested'), ('IndexAccess', 'typeDescriptions.typeIdentifier'), ('IndexAccess', 'typeDescriptions.typeString'), ('IndexRangeAccess', 'isConstant'), ('IndexRangeAccess', 'isLValue'), ('IndexRangeAccess', 'isPure'), ('IndexRangeAccess', 'lValueRequested'), ('IndexRangeAccess', 'typeDescriptions.typeIdentifier'), ('IndexRangeAccess', 'typeDescriptions.typeString'), ('Literal', 'isConstant'), ('Literal', 'isLValue'), ('Literal', 'isPure'), ('Literal', 'lValueRequested'), ('Literal', 'typeDescriptions.typeIdentifier'), ('Literal', 'typeDescriptions.typeString'), ('Mapping', 'typeDescriptions.typeIdentifier'), ('Mapping', 'typeDescriptions.typeString'), ('MemberAccess', 'argumentTypes.typeIdentifier'), ('MemberAccess', 'argumentTypes.typeString'), ('MemberAccess', 'isConstant'), ('MemberAccess', 'isLValue'), ('MemberAccess', 'isPure'), ('MemberAccess', 'lValueRequested'), ('MemberAccess', 'typeDescriptions.typeIdentifier'), ('MemberAccess', 'typeDescriptions.typeString'), ('ModifierInvocation', 'kind'), ('NewExpression', 'argumentTypes.typeIdentifier'), ('NewExpression', 'argumentTypes.typeString'), ('NewExpression', 'isConstant'), ('NewExpression', 'isLValue'), ('NewExpression', 'isPure'), ('NewExpression', 'lValueRequested'), ('NewExpression', 'typeDescriptions.typeIdentifier'), ('NewExpression', 'typeDescriptions.typeString'), ('TupleExpression', 'argumentTypes.typeIdentifier'), ('TupleExpression', 'argumentTypes.typeString'), ('TupleExpression', 'isConstant'), ('TupleExpression', 'isLValue'), ('TupleExpression', 'isPure'), ('TupleExpression', 'lValueRequested'), ('TupleExpression', 'typeDescriptions.typeIdentifier'), ('TupleExpression', 'typeDescriptions.typeString'), ('UnaryOperation', 'function'), ('UnaryOperation', 'isConstant'), ('UnaryOperation', 'isLValue'), ('UnaryOperation', 'isPure'), ('UnaryOperation', 'lValueRequested'), ('UnaryOperation', 'typeDescriptions.typeIdentifier'), ('UnaryOperation', 'typeDescriptions.typeString'), ('UserDefinedTypeName', 'typeDescriptions.typeIdentifier'), ('UserDefinedTypeName', 'typeDescriptions.typeString'), ('VariableDeclaration', 'typeDescriptions.typeIdentifier'), ('VariableDeclaration', 'typeDescriptions.typeString')} -METADATA_SCALAR_FIELDS: set[tuple[str, str]] = {('Mapping', 'keyName'), ('Mapping', 'keyNameLocation'), ('Mapping', 'valueName'), ('Mapping', 'valueNameLocation'), ('ModifierDefinition', 'baseModifiers'), ('ModifierDefinition', 'visibility'), ('SourceUnit', 'absolutePath'), ('SourceUnit', 'license'), ('StructDefinition', 'visibility'), ('StructuredDocumentation', 'text'), ('VariableDeclarationStatement', 'assignments')} +# Statement-level NatSpec (solar-verify's @custom: specs) is a comment: it does not change +# the program, so it is metadata like declaration-level documentation. +METADATA_SCALAR_FIELDS: set[tuple[str, str]] = {('Block', 'documentation'), ('Break', 'documentation'), ('Continue', 'documentation'), ('DoWhileStatement', 'documentation'), ('EmitStatement', 'documentation'), ('ExpressionStatement', 'documentation'), ('ForStatement', 'documentation'), ('IfStatement', 'documentation'), ('PlaceholderStatement', 'documentation'), ('Return', 'documentation'), ('RevertStatement', 'documentation'), ('TryStatement', 'documentation'), ('UncheckedBlock', 'documentation'), ('VariableDeclarationStatement', 'documentation'), ('WhileStatement', 'documentation'), ('Mapping', 'keyName'), ('Mapping', 'keyNameLocation'), ('Mapping', 'valueName'), ('Mapping', 'valueNameLocation'), ('ModifierDefinition', 'baseModifiers'), ('ModifierDefinition', 'visibility'), ('SourceUnit', 'absolutePath'), ('SourceUnit', 'license'), ('StructDefinition', 'visibility'), ('StructuredDocumentation', 'text'), ('VariableDeclarationStatement', 'assignments')} METADATA_SCALAR_FIELD_SUFFIXES: set[str] = {'baseFunctions', 'canonicalName', 'contractDependencies', 'errorSelector', 'eventSelector', 'functionReturnParameters', 'functionSelector', 'id', 'linearizedBaseContracts', 'memberLocation', 'nameLocation', 'nameLocations', 'overloadedDeclarations', 'referencedDeclaration', 'scope', 'src', 'usedErrors', 'usedEvents'} SOURCE_SCALAR_VALUE_DOMAINS: dict[tuple[str, str], set[Any]] = { ('Assignment', 'operator'): {'=', '+=', '-=', '*=', '/=', '%=', '&=', '|=', '^=', '<<=', '>>='}, diff --git a/scripts/verify/Counter.sol b/scripts/verify/Counter.sol new file mode 100644 index 00000000..c27e1c20 --- /dev/null +++ b/scripts/verify/Counter.sol @@ -0,0 +1,37 @@ +// SPDX-License-Identifier: MIT +pragma solidity ^0.8.20; + +/// @custom:invariant count <= limit +contract Counter { + uint256 public count; + uint256 public limit; + + /// @custom:ensures limit == _limit && count == 0 + constructor(uint256 _limit) { + limit = _limit; + } + + /// @custom:requires count < limit + /// @custom:ensures count == old(count) + 1 + function increment() external { + count += 1; + } + + /// @custom:ensures count == old(count) + n + function bump(uint256 n) external { + require(count + n <= limit, "over"); + /// @custom:invariant i <= n + /// @custom:invariant count == old(count) + i + /// @custom:decreases n - i + for (uint256 i = 0; i < n; i++) { + count++; + } + } + + /// @custom:ensures result == (a >= b ? a : b) + /// @custom:ensures result >= a && result >= b + function max(uint256 a, uint256 b) public pure returns (uint256) { + if (a >= b) return a; + return b; + } +} diff --git a/scripts/verify/CounterMilestone.sol b/scripts/verify/CounterMilestone.sol new file mode 100644 index 00000000..5a7a17e3 --- /dev/null +++ b/scripts/verify/CounterMilestone.sol @@ -0,0 +1,8 @@ +// SPDX-License-Identifier: UNLICENSED +pragma solidity ^0.8.28; +contract Counter { + uint256 x; + /// @custom:ensures x == old(x) + d + function inc(uint256 d) external { x += d; } + function get() external view returns (uint256) { return x; } +} diff --git a/scripts/verify/MANIFEST b/scripts/verify/MANIFEST new file mode 100644 index 00000000..cd74918a --- /dev/null +++ b/scripts/verify/MANIFEST @@ -0,0 +1,9 @@ +# SHA-256 of the sources and of solar-verify's transcripts (--dry-run --dump-smt). +# solar-verify: paradigmxyz/solar alpharush/verify at 4c1c187 with --dump-lean; solc 0.8.35 for the source AST. +f1c87a334b8db31fc8f80541febeaf8617318d20b685634f44e26c74146ad326 Counter.sol +45b62aa1152c4ec09e76735ac7257a06bf3e4be0f435fdacdc174f41e8c8e75c Token.sol +6db0750ba689e6aff86103e846e76739d732822f9a436efe2bc2ec69b935cb8e Counter.smt2 +59ba90cc3e7c018685d759fb6c566d82bddd147db3cc7581f835154a95b52b90 Token.smt2 +# CounterMilestone and the Counter mutants: solar-verify from paradigmxyz/solar alpharush/verify-dump-lean with the raw-section exporter change (same output for Counter and Token). +6ed83fe1a6c41fb109c6a880ed372b37ca1d895b9bde4bb5f202461289706da9 CounterMilestone.sol +1c38d99ffd21a587329c1c5ad39b97a144809a4c751d5adfb6636f665022c5e1 CounterMilestone.smt2 diff --git a/scripts/verify/Token.sol b/scripts/verify/Token.sol new file mode 100644 index 00000000..70d2f281 --- /dev/null +++ b/scripts/verify/Token.sol @@ -0,0 +1,50 @@ +// SPDX-License-Identifier: MIT +pragma solidity ^0.8.20; + +/// A minimal token. The invariant ties the ghost sum of balances to totalSupply, with +/// Certora-style ghost updates written next to every balance write. +/// @custom:ghost uint256 sumBalances +/// @custom:invariant totalSupply == sumBalances +contract Token { + mapping(address => uint256) public balanceOf; + uint256 public totalSupply; + address public owner; + + modifier onlyOwner() { + require(msg.sender == owner, "not owner"); + _; + } + + /// @custom:ensures owner == msg.sender + constructor() { + owner = msg.sender; + } + + /// @custom:ensures balanceOf[to] == old(balanceOf[to]) + amount + /// @custom:ensures totalSupply == old(totalSupply) + amount + /// @custom:ensures forall address a :: a != to ==> balanceOf[a] == old(balanceOf[a]) + function mint(address to, uint256 amount) external onlyOwner { + totalSupply += amount; + /// @custom:ghost sumBalances = sumBalances + amount + balanceOf[to] += amount; + } + + /// @custom:ensures msg.sender != to ==> balanceOf[msg.sender] == old(balanceOf[msg.sender]) - amount + /// @custom:ensures msg.sender != to ==> balanceOf[to] == old(balanceOf[to]) + amount + /// @custom:ensures forall address a :: a != msg.sender && a != to ==> balanceOf[a] == old(balanceOf[a]) + /// @custom:ensures totalSupply == old(totalSupply) + function transfer(address to, uint256 amount) external returns (bool) { + uint256 bal = balanceOf[msg.sender]; + require(bal >= amount, "insufficient"); + balanceOf[msg.sender] = bal - amount; + balanceOf[to] += amount; + return true; + } + + /// @custom:ensures balanceOf[msg.sender] == old(balanceOf[msg.sender]) - amount + function burn(uint256 amount) external { + balanceOf[msg.sender] -= amount; + /// @custom:ghost sumBalances = sumBalances - amount + totalSupply -= amount; + } +} diff --git a/scripts/verify/check.sh b/scripts/verify/check.sh new file mode 100755 index 00000000..3f344526 --- /dev/null +++ b/scripts/verify/check.sh @@ -0,0 +1,91 @@ +#!/usr/bin/env bash +# Regenerate solar-verify's exports and fail if any changed. +# +# SOLAR_VERIFY=/path/to/solar-verify scripts/verify/check.sh +# +# For each scripts/verify/NAME.sol (a copy of solar's crates/verify/examples/NAME.sol, or an +# annotated copy of a source the refinement certifies) and each mutant in scripts/verify/mutant, +# runs solar-verify --dry-run with --dump-smt and --dump-lean, compares the Lean module with its +# file under Contracts/ (out_of), and the source's and transcript's SHA-256 with the MANIFEST. +# lake build ContractsVC then checks (Contracts/NAME/VC/Bind.lean) that each script prints back to +# its transcript. It also compares solar-verify's spec exports (--emit-lean-spec) with +# Contracts/Counter/Spec/{Export,ExportWrong}.lean (spec_of). +set -euo pipefail +cd "$(dirname "${BASH_SOURCE[0]}")/../.." +: "${SOLAR_VERIFY:?set SOLAR_VERIFY to a solar-verify binary built with --dump-lean and --emit-lean-spec}" +tmp="$(mktemp -d)" +trap 'rm -rf "$tmp"' EXIT +status=0 +# Annotated copies of sources the refinement certifies: stripping the NatSpec lines must give +# the certified source back byte for byte. +if ! grep -v '^ *///' scripts/verify/CounterMilestone.sol | cmp -s - scripts/refinement/counter/counter.sol; then + echo "error: scripts/verify/CounterMilestone.sol is not scripts/refinement/counter/counter.sol plus NatSpec" >&2 + status=1 +fi +# The Lean module of each transcript. +out_of() { + case "$1" in + CounterMilestone) echo Contracts/Counter/VC/ExportMilestone.lean ;; + CounterSrcMut) echo Contracts/Counter/VC/Mutant/SrcMut.lean ;; + CounterSpecMut) echo Contracts/Counter/VC/Mutant/SpecMut.lean ;; + TokenSrcMut) echo Contracts/Token/VC/Mutant/SrcMut.lean ;; + TokenSpecMut) echo Contracts/Token/VC/Mutant/SpecMut.lean ;; + *) echo "Contracts/$1/VC/Export.lean" ;; + esac +} +check() { # check DIR NAMESPACE_PREFIX + local dir="$1" ns="$2" sol name rc f want got out + for sol in "$dir"/*.sol; do + name="$(basename "$sol" .sol)" + out="$(out_of "$name")" + # A dry run proves nothing, so solar-verify exits 1; 2 is an error. + rc=0 + "$SOLAR_VERIFY" --dry-run --dump-smt "$tmp/$name.smt2" --dump-lean "$tmp/$name.lean" \ + --lean-namespace "$ns.$name" "$sol" > /dev/null 2> "$tmp/$name.err" || rc=$? + if [[ $rc -gt 1 ]]; then cat "$tmp/$name.err" >&2; exit "$rc"; fi + # The export imports the library by its module path in this repository. + sed -i 's/^import SolidCore\.Verify\.VC\.Term$/import Verify.VC.Term/' "$tmp/$name.lean" + if ! cmp -s "$tmp/$name.lean" "$out"; then + echo "error: $out differs from solar-verify's export" >&2 + status=1 + fi + # A function outside the Lean fragment is left raw: refused, never checked. + grep '^-- Left raw' "$tmp/$name.lean" | sed "s|^-- Left raw, outside the Lean fragment: |refused ($name): |" >&2 || true + for f in "$sol" "$tmp/$name.smt2"; do + want="$(grep " $(basename "$f")\$" "$dir/MANIFEST" | cut -d' ' -f1)" + got="$(sha256sum "$f" | cut -d' ' -f1)" + if [[ "$want" != "$got" ]]; then + echo "error: $(basename "$f"): sha256 $got, $dir/MANIFEST says ${want:-nothing}" >&2 + status=1 + fi + done + done +} +check scripts/verify SolidCore.Verify.VC.Export +check scripts/verify/mutant SolidCore.Verify.VC.Export.Mutant +# solar-verify's spec exports, bound to the counter milestone's compiler and bytecode +# (solar-tv/milestone/counter's manifest). +counter_compiler="0.8.38+commit.1134e61f.solar.0.3.0-dev" +counter_bytecode="daed21b0c790bb2c08bcf999c9ebc6fea950c213ea0a799418552aa14c18f6ec" +spec_of() { # spec_of SOURCE MODULE OUT + rm -f "$tmp/spec.lean" + "$SOLAR_VERIFY" --dry-run --emit-lean-spec "$tmp/spec.lean" --lean-spec-module "$2" \ + --lean-spec-compiler "$counter_compiler" --lean-spec-bytecode-sha256 "$counter_bytecode" \ + "$1" > /dev/null 2> "$tmp/spec.err" || true + if [[ ! -s "$tmp/spec.lean" ]]; then + cat "$tmp/spec.err" >&2 + echo "error: solar-verify wrote no spec export for $1" >&2 + status=1 + return + fi + sed -i 's/^import SolidCore\.Spec\.Contract$/import Verify.Spec.Contract/' "$tmp/spec.lean" + if ! cmp -s "$tmp/spec.lean" "$3"; then + echo "error: $3 differs from solar-verify's spec export" >&2 + diff "$tmp/spec.lean" "$3" >&2 || true + status=1 + fi +} +spec_of scripts/verify/CounterMilestone.sol SolidCore.Spec.Export.Counter Contracts/Counter/Spec/Export.lean +spec_of scripts/verify/mutant/CounterSpecMut.sol SolidCore.Spec.Export.CounterSpecMut \ + Contracts/Counter/Spec/ExportWrong.lean +exit "$status" diff --git a/scripts/verify/mutant/CounterSpecMut.sol b/scripts/verify/mutant/CounterSpecMut.sol new file mode 100644 index 00000000..0e6d8d4b --- /dev/null +++ b/scripts/verify/mutant/CounterSpecMut.sol @@ -0,0 +1,8 @@ +// SPDX-License-Identifier: UNLICENSED +pragma solidity ^0.8.28; +contract Counter { + uint256 x; + /// @custom:ensures x == old(x) + d + 1 + function inc(uint256 d) external { x += d; } + function get() external view returns (uint256) { return x; } +} diff --git a/scripts/verify/mutant/CounterSrcMut.sol b/scripts/verify/mutant/CounterSrcMut.sol new file mode 100644 index 00000000..4888a009 --- /dev/null +++ b/scripts/verify/mutant/CounterSrcMut.sol @@ -0,0 +1,8 @@ +// SPDX-License-Identifier: UNLICENSED +pragma solidity ^0.8.28; +contract Counter { + uint256 x; + /// @custom:ensures x == old(x) + d + function inc(uint256 d) external { x += d + 1; } + function get() external view returns (uint256) { return x; } +} diff --git a/scripts/verify/mutant/MANIFEST b/scripts/verify/mutant/MANIFEST new file mode 100644 index 00000000..e7d7f041 --- /dev/null +++ b/scripts/verify/mutant/MANIFEST @@ -0,0 +1,12 @@ +# SHA-256 of the mutants of ../Token.sol and of solar-verify's transcripts of them (--dry-run --dump-smt). +# Exported with the same solar-verify as ../MANIFEST into Contracts/Token/VC/Mutant (--lean-namespace SolidCore.Verify.VC.Export.Mutant.NAME). +# TokenSrcMut: line 40, transfer credits amount + 1. TokenSpecMut: line 33, the recipient clause claims old + amount + 1. +7d9e63fce842edd61266528e84206a5a9815f1399f7756c0a0ea34799cacf3d2 TokenSpecMut.sol +70fe01828715a428790c073162f481941d2758d80562eaeb5a48d6d2b8e1cfe8 TokenSrcMut.sol +796fd3eda4a952cf78c8aa3cc6bb7494f0ea5d81094943b1d0299d80e495e772 TokenSpecMut.smt2 +7616295111ee5a10d43c4ee695e098a31e0c7ae8ad3ac16d3adf63b778d4744e TokenSrcMut.smt2 +# CounterSrcMut: inc adds d + 1. CounterSpecMut: inc's clause claims old(x) + d + 1. +50106ede6130f1751bb61a2412d7358bdef842f29ea02bfc8083a2c2cb054013 CounterSrcMut.sol +afaec6975bea758e12835d06dafce1c218409d260471a7a039df235b1e91b224 CounterSpecMut.sol +809c14522fe1a0babe2fe61cf046edf5d24591aef580279d5bcf21449a356bc6 CounterSrcMut.smt2 +bc69abfa93b0a5b831dbc347d55ae8fc121a7b05dddf165d94e5e3f0a86bb003 CounterSpecMut.smt2 diff --git a/scripts/verify/mutant/TokenSpecMut.sol b/scripts/verify/mutant/TokenSpecMut.sol new file mode 100644 index 00000000..91c03e71 --- /dev/null +++ b/scripts/verify/mutant/TokenSpecMut.sol @@ -0,0 +1,50 @@ +// SPDX-License-Identifier: MIT +pragma solidity ^0.8.20; + +/// A minimal token. The invariant ties the ghost sum of balances to totalSupply, with +/// Certora-style ghost updates written next to every balance write. +/// @custom:ghost uint256 sumBalances +/// @custom:invariant totalSupply == sumBalances +contract Token { + mapping(address => uint256) public balanceOf; + uint256 public totalSupply; + address public owner; + + modifier onlyOwner() { + require(msg.sender == owner, "not owner"); + _; + } + + /// @custom:ensures owner == msg.sender + constructor() { + owner = msg.sender; + } + + /// @custom:ensures balanceOf[to] == old(balanceOf[to]) + amount + /// @custom:ensures totalSupply == old(totalSupply) + amount + /// @custom:ensures forall address a :: a != to ==> balanceOf[a] == old(balanceOf[a]) + function mint(address to, uint256 amount) external onlyOwner { + totalSupply += amount; + /// @custom:ghost sumBalances = sumBalances + amount + balanceOf[to] += amount; + } + + /// @custom:ensures msg.sender != to ==> balanceOf[msg.sender] == old(balanceOf[msg.sender]) - amount + /// @custom:ensures msg.sender != to ==> balanceOf[to] == old(balanceOf[to]) + amount + 1 + /// @custom:ensures forall address a :: a != msg.sender && a != to ==> balanceOf[a] == old(balanceOf[a]) + /// @custom:ensures totalSupply == old(totalSupply) + function transfer(address to, uint256 amount) external returns (bool) { + uint256 bal = balanceOf[msg.sender]; + require(bal >= amount, "insufficient"); + balanceOf[msg.sender] = bal - amount; + balanceOf[to] += amount; + return true; + } + + /// @custom:ensures balanceOf[msg.sender] == old(balanceOf[msg.sender]) - amount + function burn(uint256 amount) external { + balanceOf[msg.sender] -= amount; + /// @custom:ghost sumBalances = sumBalances - amount + totalSupply -= amount; + } +} diff --git a/scripts/verify/mutant/TokenSrcMut.sol b/scripts/verify/mutant/TokenSrcMut.sol new file mode 100644 index 00000000..22df88f4 --- /dev/null +++ b/scripts/verify/mutant/TokenSrcMut.sol @@ -0,0 +1,50 @@ +// SPDX-License-Identifier: MIT +pragma solidity ^0.8.20; + +/// A minimal token. The invariant ties the ghost sum of balances to totalSupply, with +/// Certora-style ghost updates written next to every balance write. +/// @custom:ghost uint256 sumBalances +/// @custom:invariant totalSupply == sumBalances +contract Token { + mapping(address => uint256) public balanceOf; + uint256 public totalSupply; + address public owner; + + modifier onlyOwner() { + require(msg.sender == owner, "not owner"); + _; + } + + /// @custom:ensures owner == msg.sender + constructor() { + owner = msg.sender; + } + + /// @custom:ensures balanceOf[to] == old(balanceOf[to]) + amount + /// @custom:ensures totalSupply == old(totalSupply) + amount + /// @custom:ensures forall address a :: a != to ==> balanceOf[a] == old(balanceOf[a]) + function mint(address to, uint256 amount) external onlyOwner { + totalSupply += amount; + /// @custom:ghost sumBalances = sumBalances + amount + balanceOf[to] += amount; + } + + /// @custom:ensures msg.sender != to ==> balanceOf[msg.sender] == old(balanceOf[msg.sender]) - amount + /// @custom:ensures msg.sender != to ==> balanceOf[to] == old(balanceOf[to]) + amount + /// @custom:ensures forall address a :: a != msg.sender && a != to ==> balanceOf[a] == old(balanceOf[a]) + /// @custom:ensures totalSupply == old(totalSupply) + function transfer(address to, uint256 amount) external returns (bool) { + uint256 bal = balanceOf[msg.sender]; + require(bal >= amount, "insufficient"); + balanceOf[msg.sender] = bal - amount; + balanceOf[to] += amount + 1; + return true; + } + + /// @custom:ensures balanceOf[msg.sender] == old(balanceOf[msg.sender]) - amount + function burn(uint256 amount) external { + balanceOf[msg.sender] -= amount; + /// @custom:ghost sumBalances = sumBalances - amount + totalSupply -= amount; + } +} diff --git a/tv/SolarTV/Stages/Assembly.lean b/tv/SolarTV/Stages/Assembly.lean index a26e3e76..be3f879b 100644 --- a/tv/SolarTV/Stages/Assembly.lean +++ b/tv/SolarTV/Stages/Assembly.lean @@ -36,19 +36,128 @@ namespace SolarTV.Assembly inductive Instr where | op (byte : Nat) | push (value : Nat) + /-- An opcode that reads the byte after it as its immediate: DUPN, SWAPN or EXCHANGE + (EIP-8024). -/ + | opImm (byte imm : Nat) deriving DecidableEq, Repr def PUSH0 : Nat := 0x5f def PUSH1 : Nat := 0x60 def PUSH32 : Nat := 0x7f def JUMPDEST : Nat := 0x5b +def DUPN : Nat := 0xe6 +def SWAPN : Nat := 0xe7 +def EXCHANGE : Nat := 0xe8 + +/-- Whether an opcode reads the byte after it as an immediate (EIP-8024's DUPN, SWAPN and +EXCHANGE), so that decoding steps over two bytes. -/ +def hasImmediate (byte : Nat) : Bool := byte == DUPN || byte == SWAPN || byte == EXCHANGE + +/-! ### EIP-8024 immediates + +The immediates of DUPN, SWAPN and EXCHANGE as solar's assembler writes them +(`encode_stack_depth` and `encode_exchange` in `crates/evmir/src/op.rs`) and as EIP-8024 decodes +them (EthLib's `decodeSingle` and `decodePair`). A depth counts from 1 at the top: DUPN of depth +`n` pushes a copy of the `n`th word and SWAPN of depth `n` exchanges the top with the word `n` +below it, so EVM IR's `dup i` and `swap i` are depth `i + 1`. EXCHANGE exchanges the words at two +depths `n < m` below the top, with `n + m ≤ 30`: EVM IR's `exchange n m`. -/ + +/-- The immediate of DUPN or SWAPN for a depth from 17 to 235. -/ +def encodeDepth (n : Nat) : Nat := (n + 111) % 256 + +/-- The depth a DUPN or SWAPN immediate encodes, from 17 to 235; none for 91 to 127. -/ +def decodeDepth (x : Nat) : Option Nat := + if 90 < x ∧ x < 128 then none else some ((x + 145) % 256) + +/-- Whether DUPN and SWAPN reach a depth. -/ +def depthOk (n : Nat) : Bool := 17 ≤ n && n ≤ 235 + +/-- The immediate of EXCHANGE for the depths `n < m` with `n + m ≤ 30`. -/ +def encodePair (n m : Nat) : Nat := + (if m ≤ 16 then 16 * (n - 1) + (m - 1) else 16 * (29 - m) + (n - 1)) ^^^ 143 + +/-- The depths an EXCHANGE immediate encodes; none for 82 to 127. -/ +def decodePair (x : Nat) : Option (Nat × Nat) := + if 81 < x ∧ x < 128 then none + else + let k := x ^^^ 143 + if k / 16 < k % 16 then some (k / 16 + 1, k % 16 + 1) else some (k % 16 + 1, 29 - k / 16) + +/-- Whether EXCHANGE reaches a pair of depths. -/ +def pairOk (n m : Nat) : Bool := 1 ≤ n && n < m && n + m ≤ 30 + +/-- Whether the byte after an opcode with an immediate encodes an operand of it. -/ +def immediateOk (byte imm : Nat) : Bool := + if byte = EXCHANGE then (decodePair imm).isSome else (decodeDepth imm).isSome + +/-- Each immediate that decodes is the encoding of what it decodes to. -/ +def depthRound (x : Nat) : Bool := + match decodeDepth x with + | some n => depthOk n && encodeDepth n == x + | none => true + +/-- Each EXCHANGE immediate that decodes is the encoding of the pair it decodes to. -/ +def pairRound (x : Nat) : Bool := + match decodePair x with + | some (n, m) => pairOk n m && encodePair n m == x + | none => true + +set_option maxRecDepth 8000 in +theorem decodeDepth_encodeDepth_all : + ∀ n < 256, depthOk n = true → decodeDepth (encodeDepth n) = some n := by + decide + +/-- Decoding the immediate of a depth DUPN and SWAPN reach gives the depth. -/ +theorem decodeDepth_encodeDepth {n : Nat} (h : depthOk n = true) : + decodeDepth (encodeDepth n) = some n := + decodeDepth_encodeDepth_all n (by simp [depthOk] at h; omega) h + +theorem encodeDepth_lt (n : Nat) : encodeDepth n < 256 := Nat.mod_lt _ (by decide) + +set_option maxRecDepth 8000 in +theorem depthRound_all : ∀ x < 256, depthRound x = true := by decide + +/-- A byte that decodes to a depth is that depth's encoding, and DUPN and SWAPN reach it. -/ +theorem encodeDepth_decodeDepth {x n : Nat} (hx : x < 256) (h : decodeDepth x = some n) : + depthOk n = true ∧ encodeDepth n = x := by + have := depthRound_all x hx + simp only [depthRound, h, Bool.and_eq_true, beq_iff_eq] at this + exact this + +theorem decodePair_encodePair_all : + ∀ n < 32, ∀ m < 32, pairOk n m = true → + decodePair (encodePair n m) = some (n, m) ∧ encodePair n m < 256 := by + decide + +/-- Decoding the immediate of a pair EXCHANGE reaches gives the pair. -/ +theorem decodePair_encodePair {n m : Nat} (h : pairOk n m = true) : + decodePair (encodePair n m) = some (n, m) ∧ encodePair n m < 256 := + decodePair_encodePair_all n (by simp [pairOk] at h; omega) m (by simp [pairOk] at h; omega) h + +set_option maxRecDepth 8000 in +theorem pairRound_all : ∀ x < 256, pairRound x = true := by decide + +/-- A byte that decodes to a pair is that pair's encoding, and EXCHANGE reaches it. -/ +theorem encodePair_decodePair {x n m : Nat} (hx : x < 256) (h : decodePair x = some (n, m)) : + pairOk n m = true ∧ encodePair n m = x := by + have := pairRound_all x hx + simp only [pairRound, h, Bool.and_eq_true, beq_iff_eq] at this + exact this + +/-- No immediate that decodes is a PUSH opcode (PUSH0 to PUSH32) or JUMPDEST, so a scan for +jump destinations that steps over the immediate as an opcode of its own (as EIP-8024 keeps it) +stays on the same boundaries. -/ +theorem immediateOk_not_push {byte imm : Nat} (h : immediateOk byte imm = true) : + ¬(0x5b ≤ imm ∧ imm ≤ 0x7f) := by + unfold immediateOk decodePair decodeDepth at h + split at h <;> split at h <;> simp_all <;> omega /-- The big-endian value of `bytes`. -/ def bigEndian (bytes : List Nat) : Nat := bytes.foldl (fun value byte => value * 256 + byte) 0 /-- The instruction at `pc` of `code` and the offset after it, or `none` past the end of the -code or for a push whose immediate runs past it, as the checker reads it. -/ +code or for a push or an opcode whose immediate runs past it, as the checker reads it. -/ def decode (code : List Nat) (pc : Nat) : Option (Instr × Nat) := match code[pc]? with | none => none @@ -59,6 +168,12 @@ def decode (code : List Nat) (pc : Nat) : Option (Instr × Nat) := some (.push (bigEndian ((code.drop (pc + 1)).take (byte - PUSH1 + 1))), pc + 1 + (byte - PUSH1 + 1)) else none + else if hasImmediate byte then + -- NOTE: EthLib reads 0 past the end of the code and halts on an immediate that encodes no + -- depth; the walk refuses both, as solar's assembler does. + match code[pc + 1]? with + | some imm => if immediateOk byte imm then some (.opImm byte imm, pc + 2) else none + | none => none else some (.op byte, pc + 1) /-- Linear decoding of `code` from `pc`, each instruction at its offset, for at most `fuel` @@ -85,6 +200,8 @@ inductive Item where /-- Entry `index` of a stride table whose first entry is label `table`: a `JUMPDEST` `index` strides past the table's offset. -/ | entry (table index stride : Nat) + /-- An opcode with its one-byte immediate: DUPN, SWAPN or EXCHANGE (EIP-8024). -/ + | opImm (byte imm : Nat) deriving DecidableEq, Repr /-- The instruction an item is at a layout that puts each label at `offset`. -/ @@ -96,6 +213,7 @@ def Item.expected (offset : Nat → Nat) : Item → Instr | .immutable _ _ => .push 0 | .pushTable labels => .push (bigEndian (labels.map offset)) | .entry _ _ _ => .op JUMPDEST + | .opImm byte imm => .opImm byte imm /-- Whether an item is placed where the layout says at `pc`: a label at its offset, a packed table's every offset in one byte, so that the word's bytes are the offsets, and a stride table's @@ -123,16 +241,43 @@ theorem decode_advances {code : List Nat} {pc next : Nat} {instr : Instr} unfold decode at h split at h · simp at h - · split at h - · rcases h with ⟨_, rfl⟩ - omega - · split at h - · split at h - · rcases h with ⟨_, rfl⟩ - omega - · simp at h - · rcases h with ⟨_, rfl⟩ - omega + · repeat' split at h + all_goals first + | (simp at h; done) + | (simp only [Option.some.injEq, Prod.mk.injEq] at h; obtain ⟨-, rfl⟩ := h; omega) + +/-- An instruction decodes to an opcode only from its byte, one byte on, when the byte is no +push and takes no immediate. -/ +theorem decode_op_inv {code : List Nat} {pc next byte : Nat} + (h : decode code pc = some (.op byte, next)) : + code[pc]? = some byte ∧ byte ≠ PUSH0 ∧ ¬(PUSH1 ≤ byte ∧ byte ≤ PUSH32) ∧ + hasImmediate byte = false ∧ next = pc + 1 := by + unfold decode at h + split at h + · simp at h + · rename_i b hb + repeat' split at h + all_goals simp only [Option.some.injEq, Prod.mk.injEq, reduceCtorEq, Instr.op.injEq, + false_and] at h + all_goals first + | (rename_i h0 h1 hi; obtain ⟨rfl, rfl⟩ := h; exact ⟨hb, h0, h1, by simpa using hi, rfl⟩) + | skip + all_goals simp_all + +/-- An opcode with an immediate decodes from its byte and the next, two bytes on, when the +next byte encodes an operand of it. -/ +theorem decode_opImm_inv {code : List Nat} {pc next byte imm : Nat} + (h : decode code pc = some (.opImm byte imm, next)) : + code[pc]? = some byte ∧ hasImmediate byte = true ∧ code[pc + 1]? = some imm ∧ + immediateOk byte imm = true ∧ next = pc + 2 := by + unfold decode at h + split at h + · simp at h + · rename_i b hb + repeat' split at h + all_goals simp only [Option.some.injEq, Prod.mk.injEq, reduceCtorEq, Instr.opImm.injEq, + false_and] at h + all_goals simp_all /-- Each item takes at least a byte. -/ theorem walk_length {code : List Nat} {offset : Nat → Nat} {pc : Nat} {items : List Item} @@ -245,4 +390,42 @@ theorem example_fault (stream : List (Nat × Instr)) : | cons decoded _ _ => simp [decode, bigEndian, Item.expected, PUSH0, PUSH1, PUSH32] at decoded +/-! DUPN of depth 17 (`dup 16`): the immediate 0x80, two bytes on. A JUMPDEST byte or no byte +after DUPN encodes no depth, which the walk refuses. -/ + +theorem example_dupn : + Walk [0xe6, 0x80, 0x00] (fun _ => 0) 0 [.opImm DUPN (encodeDepth 17), .op 0x00] + [(0, .opImm 0xe6 0x80), (2, .op 0x00)] := + .cons (by rfl) rfl (.cons (by rfl) rfl .nil) + +theorem example_dupn_jumpdest : decode [0xe6, 0x5b] 0 = none := by decide + +theorem example_dupn_short : decode [0xe6] 0 = none := by decide + +theorem example_exchange : decodePair (encodePair 1 29) = some (1, 29) := by decide + +/-- A wrong immediate fails: DUPN with 0x81 (depth 18) where the item is depth 17's 0x80 has no +walk, though 0x81 is a valid immediate, as the checker reports. -/ +theorem example_dupn_wrong (stream : List (Nat × Instr)) : + ¬ Walk [0xe6, 0x81, 0x00] (fun _ => 0) 0 [.opImm DUPN (encodeDepth 17), .op 0x00] stream := by + intro w + cases w with + | cons decoded _ _ => + have e : decode [0xe6, 0x81, 0x00] 0 = some (.opImm 0xe6 0x81, 2) := by decide + rw [e] at decoded + simp [Item.expected, DUPN, encodeDepth] at decoded + +/-- A wrong EXCHANGE immediate fails the same way: pair (1, 3)'s byte where (1, 2)'s is due. -/ +theorem example_exchange_wrong (stream : List (Nat × Instr)) : + ¬ Walk [0xe8, encodePair 1 3, 0x00] (fun _ => 0) 0 + [.opImm EXCHANGE (encodePair 1 2), .op 0x00] stream := by + intro w + cases w with + | cons decoded _ _ => + have e : decode [0xe8, encodePair 1 3, 0x00] 0 = some (.opImm 0xe8 (encodePair 1 3), 2) := by + decide + rw [e] at decoded + simp only [Item.expected, Option.some.injEq, Prod.mk.injEq, Instr.opImm.injEq] at decoded + exact absurd decoded.1.2 (by decide) + end SolarTV.Assembly diff --git a/tv/SolarTV/Stages/Link.lean b/tv/SolarTV/Stages/Link.lean index 46966911..25bcd23a 100644 --- a/tv/SolarTV/Stages/Link.lean +++ b/tv/SolarTV/Stages/Link.lean @@ -166,7 +166,22 @@ theorem decode_congr {code code' : List Nat} {pc next : Nat} {instr : Instr} · rfl simp only [len, fits, take, ↓reduceIte] · simp [fits] at h - · simp only [hr, ↓reduceIte] at h ⊢; exact h + · simp only [hr, ↓reduceIte] at h ⊢ + by_cases hi : hasImmediate byte = true + · simp only [hi, ↓reduceIte] at h ⊢ + cases hm : code[pc + 1]? with + | none => rw [hm] at h; simp at h + | some imm => + rw [hm] at h + by_cases ok : immediateOk byte imm = true + · simp only [ok, ↓reduceIte, Option.some.injEq, Prod.mk.injEq] at h + obtain ⟨rfl, rfl⟩ := h + rw [same (pc + 1) (by omega) (by omega), hm] + simp [ok] + · simp [ok] at h + · simp only [Bool.not_eq_true] at hi + simp only [hi] at h ⊢ + exact h /-- The offsets a walk reaches are at least where it starts. -/ theorem walk_ge {code : List Nat} {offset : Nat → Nat} {pc : Nat} {items : List Item} diff --git a/tv/W1Proofs/Items.lean b/tv/W1Proofs/Items.lean index ac56f999..12be416f 100644 --- a/tv/W1Proofs/Items.lean +++ b/tv/W1Proofs/Items.lean @@ -38,9 +38,11 @@ namespace SolarTV.Milestone.W1 open SolarTV.Assembly -/-- The opcode of a stack operation, or `none` for one with no single-byte opcode: `dup` and -`swap` past the sixteenth word and `exchange` take an immediate, and the exporter writes none -of them. -/ +/-- The opcode of a stack operation, or `none` for one no opcode reaches: `dup` and `swap` of the +first sixteen words are DUP1 to DUP16 and SWAP1 to SWAP16, deeper ones DUPN and SWAPN with the +depth's immediate up to depth 235, and `exchange` EXCHANGE with its pair's immediate, as solar's +assembler encodes them where the EVM version has EIP-8024's opcodes. Where it has not, the +assembler writes no such opcode and the walk finds none. -/ def stackItem : EVM.Op → Option Item | .add => some (.op 0x01) | .mul => some (.op 0x02) | .sub => some (.op 0x03) | .div => some (.op 0x04) | .sdiv => some (.op 0x05) | .mod => some (.op 0x06) @@ -54,11 +56,70 @@ def stackItem : EVM.Op → Option Item | .calldatasize => some (.op 0x36) | .returndatasize => some (.op 0x3d) | .pop => some (.op 0x50) | .push value => some (.push value.toNat) - -- NOTE: DUP1..16 and SWAP1..16 only; deeper positions and EXCHANGE take an immediate, - -- outside these items. - | .dup index => if index.val < 16 then some (.op (0x80 + index.val)) else none - | .swap index => if index.val < 16 then some (.op (0x90 + index.val)) else none - | .exchange _ _ => none + | .dup index => + if index.val < 16 then some (.op (0x80 + index.val)) + else if depthOk (index.val + 1) then some (.opImm DUPN (encodeDepth (index.val + 1))) + else none + | .swap index => + if index.val < 16 then some (.op (0x90 + index.val)) + else if depthOk (index.val + 1) then some (.opImm SWAPN (encodeDepth (index.val + 1))) + else none + | .exchange first second => + if pairOk first.val second.val then some (.opImm EXCHANGE (encodePair first.val second.val)) + else none + +/-! The immediates `stackItem` writes decode back to the operation: DUPN and SWAPN to the +depth `index + 1`, EXCHANGE to its pair, each a valid immediate, so the walk's decoding of the +bytes (`decode`) reads the item and nothing else. -/ + +theorem stackItem_dup_opImm {index : Fin 256} {byte imm : Nat} + (h : stackItem (.dup index) = some (.opImm byte imm)) : + byte = DUPN ∧ decodeDepth imm = some (index.val + 1) ∧ immediateOk byte imm = true := by + simp only [stackItem] at h + split at h + · cases h + · split at h + · rename_i hd + cases h + have := decodeDepth_encodeDepth hd + exact ⟨rfl, this, by simp [immediateOk, DUPN, EXCHANGE, this]⟩ + · cases h + +theorem stackItem_swap_opImm {index : Fin 256} {byte imm : Nat} + (h : stackItem (.swap index) = some (.opImm byte imm)) : + byte = SWAPN ∧ decodeDepth imm = some (index.val + 1) ∧ immediateOk byte imm = true := by + simp only [stackItem] at h + split at h + · cases h + · split at h + · rename_i hd + cases h + have := decodeDepth_encodeDepth hd + exact ⟨rfl, this, by simp [immediateOk, SWAPN, EXCHANGE, this]⟩ + · cases h + +theorem stackItem_exchange_opImm {first second : Fin 32} {byte imm : Nat} + (h : stackItem (.exchange first second) = some (.opImm byte imm)) : + byte = EXCHANGE ∧ decodePair imm = some (first.val, second.val) ∧ + immediateOk byte imm = true := by + simp only [stackItem] at h + split at h + · rename_i hp + cases h + have := (decodePair_encodePair hp).1 + exact ⟨rfl, this, by simp [immediateOk, this]⟩ + · cases h + +/-- The bytes of an item `stackItem` writes with an immediate decode to that item, two bytes on. -/ +theorem decode_opImm_of_valid {code : List Nat} {pc byte imm : Nat} + (hb : code[pc]? = some byte) (hi : code[pc + 1]? = some imm) (hh : hasImmediate byte = true) + (ok : immediateOk byte imm = true) : decode code pc = some (.opImm byte imm, pc + 2) := by + have h0 : byte ≠ PUSH0 := by + intro e; subst e; simp [hasImmediate, PUSH0, DUPN, SWAPN, EXCHANGE] at hh + have h1 : ¬(PUSH1 ≤ byte ∧ byte ≤ PUSH32) := by + simp only [hasImmediate, Bool.or_eq_true, beq_iff_eq, DUPN, SWAPN, EXCHANGE] at hh + simp only [PUSH1, PUSH32]; omega + simp [decode, hb, hi, h0, h1, hh, ok] /-- The opcode of a memory instruction, or `none` for a copy or hash, which the program runs as effects. -/ diff --git a/vendor/loom/Loom.lean b/vendor/loom/Loom.lean deleted file mode 100644 index ae15f6a1..00000000 --- a/vendor/loom/Loom.lean +++ /dev/null @@ -1 +0,0 @@ -import Loom.MonadAlgebras.WP.Basic diff --git a/vendor/loom/Loom/MonadAlgebras/Instances/Basic.lean b/vendor/loom/Loom/MonadAlgebras/Instances/Basic.lean deleted file mode 100644 index a91536b9..00000000 --- a/vendor/loom/Loom/MonadAlgebras/Instances/Basic.lean +++ /dev/null @@ -1,26 +0,0 @@ -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 deleted file mode 100644 index a4cc273a..00000000 --- a/vendor/loom/Loom/MonadAlgebras/WP/Basic.lean +++ /dev/null @@ -1,148 +0,0 @@ -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/README.md b/vendor/loom/README.md deleted file mode 100644 index e6c285fe..00000000 --- a/vendor/loom/README.md +++ /dev/null @@ -1,39 +0,0 @@ -# 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 c1fc82ea1dc371c3078e3c5a80bd27a5d9209d40 Mon Sep 17 00:00:00 2001 From: alpharush <0xalpharush@protonmail.com> Date: Fri, 13 Nov 2026 00:39:53 -0600 Subject: [PATCH 8/8] fix(assemble): place immutables at their encoded width --- SolidCore/Refinement/Solar/AssembleFast.lean | 46 ++++++++++++++----- SolidCore/Refinement/Solar/AssembleSim.lean | 8 ++-- tv/SolarTV/Stages/Assembly.lean | 47 +++++++++++++++++--- tv/SolarTV/Stages/AssemblyCheck.lean | 4 +- tv/SolarTV/Stages/Link.lean | 10 +++++ tv/W1Proofs/Items.lean | 2 +- 6 files changed, 94 insertions(+), 23 deletions(-) diff --git a/SolidCore/Refinement/Solar/AssembleFast.lean b/SolidCore/Refinement/Solar/AssembleFast.lean index beb1c02a..e670d2ee 100644 --- a/SolidCore/Refinement/Solar/AssembleFast.lean +++ b/SolidCore/Refinement/Solar/AssembleFast.lean @@ -47,6 +47,16 @@ def decodeS : List Nat → Nat → Option (SolarTV.Assembly.Instr × Nat × List | [] => none else some (.op byte, pc + 1, tl) +/-- `Item.placed` at offset `pc` of the code whose rest from `pc` is the list. -/ +def placedS (rest : List Nat) (offset : Nat → Nat) (pc : Nat) : Item → Bool + | .immutable _ bytes => + decide (1 ≤ bytes) && decide (bytes ≤ 32) && rest.head? == some (PUSH1 + bytes - 1) + | item => item.placed [] offset pc + +theorem placedS_drop (code : List Nat) (offset : Nat → Nat) (pc : Nat) (item : Item) : + placedS (code.drop pc) offset pc item = item.placed code offset pc := by + cases item <;> first | rfl | simp only [placedS, Item.placed, List.head?_drop] + /-- `walk` from offset `pc` of the code whose rest from `pc` is the list: whether the walk succeeds. -/ def walkS (offset : Nat → Nat) : List Nat → Nat → List Item → Bool @@ -55,7 +65,7 @@ def walkS (offset : Nat → Nat) : List Nat → Nat → List Item → Bool match decodeS rest pc with | none => false | some (instr, next, rest') => - instr == item.expected offset && labelAt offset pc item && walkS offset rest' next items + instr == item.expected offset && placedS rest offset pc item && walkS offset rest' next items /-- The checker `check`, with the walk on the rest of the code and without the labels' check, which the walk implies. -/ @@ -152,14 +162,14 @@ theorem walkS_drop (code : List Nat) (offset : Nat → Nat) : | 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] + simp only [walkS, walk, decodeS_drop, placedS_drop] cases hd : decode code pc with | none => rfl | some x => obtain ⟨instr, next⟩ := x simp only [Option.map_some] rw [walkS_drop code offset items next (decode_next_le hd)] - cases h1 : instr == item.expected offset <;> cases h2 : labelAt offset pc item <;> + cases h1 : instr == item.expected offset <;> cases h2 : item.placed code offset pc <;> cases walk code offset next items <;> simp only [beq_iff_eq, beq_eq_false_iff_ne] at h1 <;> simp only [h1, Bool.and_false, Bool.and_true, and_true, and_false, ↓reduceIte, @@ -224,7 +234,12 @@ theorem decode_boundary {code : ByteArray} {pc next : Nat} {i : SolarTV.Assembly obtain ⟨hb', -, h1, -, rfl⟩ := decode_op_inv h have := hbyteOf pc b hb' unfold PUSH1 PUSH32 at h1 - exact step pc hb (by omega) hn + have hx : (byteAt code pc).toNat < 0x60 ∨ 0x7f < (byteAt code pc).toNat := by + rw [this] + cases Nat.decLt b 0x60 with + | isTrue hlt => exact .inl hlt + | isFalse hge => exact .inr (Nat.lt_of_not_le (fun hle => h1 ⟨by omega, hle⟩)) + exact step pc hb hx hn | opImm b imm => obtain ⟨hb', him, hi, hok, rfl⟩ := decode_opImm_inv h have e1 := hbyteOf pc b hb' @@ -232,9 +247,19 @@ theorem decode_boundary {code : ByteArray} {pc next : Nat} {i : SolarTV.Assembly have hnp := immediateOk_not_push hok have hb1 : b = 0xe6 ∨ b = 0xe7 ∨ b = 0xe8 := by simp only [hasImmediate, DUPN, SWAPN, EXCHANGE, Bool.or_eq_true, beq_iff_eq] at him - omega - have h1 := step pc hb (by omega) (by omega) - exact step (pc + 1) h1 (by omega) hn + rcases him with (e | e) | e + · exact .inl e + · exact .inr (.inl e) + · exact .inr (.inr e) + have hx : (byteAt code pc).toNat < 0x60 ∨ 0x7f < (byteAt code pc).toNat := + .inr (by rcases hb1 with e | e | e <;> omega) + have h1 := step pc hb hx (by omega) + have hy : (byteAt code (pc + 1)).toNat < 0x60 ∨ 0x7f < (byteAt code (pc + 1)).toNat := by + rw [e2] + cases Nat.decLt imm 0x60 with + | isTrue hlt => exact .inl hlt + | isFalse hge => exact .inr (Nat.lt_of_not_le (fun hle => hnp ⟨by omega, hle⟩)) + exact step (pc + 1) h1 hy hn | push v => obtain ⟨b, hb', ⟨h0, -, rfl⟩ | ⟨h1, h2, rfl, -, -⟩⟩ := decode_push h · have := hbyteOf pc b hb' @@ -243,7 +268,8 @@ theorem decode_boundary {code : ByteArray} {pc next : Nat} {i : SolarTV.Assembly · have e := hbyteOf pc b hb' have e' : nextOpcode code pc = pc + 1 + (b - PUSH1 + 1) := by rw [nextOpcode_eq_opLen, opLen_eq, e] - unfold PUSH1 PUSH32 at h1 h2 ⊢ + unfold PUSH1 at h1 ⊢ + unfold PUSH32 at h2 simp only [h1, h2, and_self, ↓reduceIte] omega have := boundary_next hb (by rw [e']; exact hn) @@ -263,14 +289,14 @@ theorem walk_labels {code : ByteArray} {offset : Nat → Nat} : obtain ⟨instr, next⟩ := x rw [hd] at hw simp only at hw - by_cases ok : instr = item.expected offset ∧ labelAt offset pc item = true + by_cases ok : instr = item.expected offset ∧ item.placed (bytesOf code) offset pc = true · simp only [ok, and_self, ↓reduceIte] at hw have hw' : (walk (bytesOf code) offset next items).isSome = true := by cases h' : walk (bytesOf code) offset next items <;> simp [h'] at hw ⊢ obtain ⟨hpc, hnext⟩ := decode_boundary hd have hbpc := hb hpc rcases List.mem_cons.1 hl with rfl | hl - · have hoff : offset l = pc := by simpa [labelAt] using ok.2 + · have hoff : offset l = pc := by simpa [Item.placed] using ok.2 have hi : instr = .op SolarTV.Assembly.JUMPDEST := by simpa [Item.expected] using ok.1 rw [hi] at hd obtain ⟨hbyte, -⟩ := decode_op hd diff --git a/SolidCore/Refinement/Solar/AssembleSim.lean b/SolidCore/Refinement/Solar/AssembleSim.lean index d0e1e63f..6a0abd67 100644 --- a/SolidCore/Refinement/Solar/AssembleSim.lean +++ b/SolidCore/Refinement/Solar/AssembleSim.lean @@ -43,7 +43,7 @@ theorem seg_of_walk {code : List Nat} {offset : Nat → Nat} {pc : Nat} {items : Seg code offset pc items code.length := by induction w with | nil => exact .nil - | cons d l _ ih => exact .cons d l ih + | cons d l _ ih => exact .cons d (fun label he => by subst he; simpa [Item.placed] using l) ih theorem Seg.split {code : List Nat} {offset : Nat → Nat} : ∀ {pc pc'' : Nat} {A B : List Item}, Seg code offset pc (A ++ B) pc'' → @@ -431,7 +431,7 @@ theorem exec_stack {o : SolarTV.Machine.Oracle} {call : SolarTV.Call} {b : Nat} 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 ⊢ + cases op <;> simp [stackNeed, opByte] at h ⊢ <;> exact h.1 theorem lowerInstr_stack {op : SolarTV.EVM.Op} (hne : ∀ v, op ≠ .push v) : lowerInstr (.op (.stack op)) = [.op ((opByte op).getD 0xfe)] := by @@ -894,7 +894,7 @@ theorem exec_sim {p : Program} {c : Cert} {code : ByteArray} (G : Glob p c code) 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 | _ | _ | _ | _ + · 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' @@ -969,6 +969,8 @@ theorem exec_sim {p : Program} {c : Cert} {code : ByteArray} (G : Glob p c code) rw [hM']; omega · simp [blockStep] at hok' · simp [blockStep] at hok' + · simp [blockStep] at hok' + · simp [blockStep] at hok' · rcases e with _ | _ | _ | _ | _ | _ | _ | _ | _ | _ | _ | _ | _ | _ | n | _ | _ | _ all_goals try (simp [blockStep] at hok'; done) · -- SLOAD. diff --git a/tv/SolarTV/Stages/Assembly.lean b/tv/SolarTV/Stages/Assembly.lean index be3f879b..09ad9a50 100644 --- a/tv/SolarTV/Stages/Assembly.lean +++ b/tv/SolarTV/Stages/Assembly.lean @@ -149,8 +149,19 @@ jump destinations that steps over the immediate as an opcode of its own (as EIP- stays on the same boundaries. -/ theorem immediateOk_not_push {byte imm : Nat} (h : immediateOk byte imm = true) : ¬(0x5b ≤ imm ∧ imm ≤ 0x7f) := by - unfold immediateOk decodePair decodeDepth at h - split at h <;> split at h <;> simp_all <;> omega + intro ⟨h1, h2⟩ + unfold immediateOk at h + cases Nat.decEq byte EXCHANGE with + | isTrue hb => + rw [if_pos hb] at h + unfold decodePair at h + rw [if_pos ⟨by omega, by omega⟩] at h + exact Bool.false_ne_true h + | isFalse hb => + rw [if_neg hb] at h + unfold decodeDepth at h + rw [if_pos ⟨by omega, by omega⟩] at h + exact Bool.false_ne_true h /-- The big-endian value of `bytes`. -/ def bigEndian (bytes : List Nat) : Nat := @@ -215,11 +226,15 @@ def Item.expected (offset : Nat → Nat) : Item → Instr | .entry _ _ _ => .op JUMPDEST | .opImm byte imm => .opImm byte imm -/-- Whether an item is placed where the layout says at `pc`: a label at its offset, a packed -table's every offset in one byte, so that the word's bytes are the offsets, and a stride table's -entry its index of strides past the table's offset. -/ -def Item.placed (offset : Nat → Nat) (pc : Nat) : Item → Bool +/-- Whether an item is placed where the layout says at `pc` of `code`: a label at its offset, a +packed table's every offset in one byte, so that the word's bytes are the offsets, a stride table's +entry its index of strides past the table's offset, and an immutable's placeholder a +`PUSH` of its width, `1 ≤ bytes ≤ 32`, which a deployment's linking overwrites byte for +byte: a `PUSH0` or a narrower push of zero decodes to the same push but is no placeholder. -/ +def Item.placed (code : List Nat) (offset : Nat → Nat) (pc : Nat) : Item → Bool | .label l => offset l == pc + | .immutable _ bytes => + decide (1 ≤ bytes) && decide (bytes ≤ 32) && code[pc]? == some (PUSH1 + bytes - 1) | .pushTable labels => labels.all (offset · < 256) | .entry table index stride => offset table + index * stride == pc | _ => true @@ -232,7 +247,7 @@ inductive Walk (code : List Nat) (offset : Nat → Nat) : | nil : Walk code offset code.length [] [] | cons {pc next : Nat} {item : Item} {items : List Item} {stream : List (Nat × Instr)} : decode code pc = some (item.expected offset, next) → - item.placed offset pc = true → + item.placed code offset pc = true → Walk code offset next items stream → Walk code offset pc (item :: items) ((pc, item.expected offset) :: stream) @@ -404,6 +419,24 @@ theorem example_dupn_short : decode [0xe6] 0 = none := by decide theorem example_exchange : decodePair (encodePair 1 29) = some (1, 29) := by decide +/-- An immutable's placeholder is a push of its width: a 32-byte placeholder walks as PUSH32 of +zeros, and a PUSH0 or PUSH1 0 in its place, which decodes to the same push of zero, has no walk. -/ +theorem example_immutable : + Walk (0x7f :: List.replicate 32 0) (fun _ => 0) 0 [.immutable 0 32] [(0, .push 0)] := + .cons (by decide) (by decide) .nil + +theorem example_immutable_push0 (stream : List (Nat × Instr)) : + ¬ Walk [0x5f] (fun _ => 0) 0 [.immutable 0 32] stream := by + intro w + cases w with + | cons _ placed _ => exact absurd placed (by decide) + +theorem example_immutable_push1 (stream : List (Nat × Instr)) : + ¬ Walk [0x60, 0x00] (fun _ => 0) 0 [.immutable 0 32] stream := by + intro w + cases w with + | cons _ placed _ => exact absurd placed (by decide) + /-- A wrong immediate fails: DUPN with 0x81 (depth 18) where the item is depth 17's 0x80 has no walk, though 0x81 is a valid immediate, as the checker reports. -/ theorem example_dupn_wrong (stream : List (Nat × Instr)) : diff --git a/tv/SolarTV/Stages/AssemblyCheck.lean b/tv/SolarTV/Stages/AssemblyCheck.lean index b1b435ef..58789e65 100644 --- a/tv/SolarTV/Stages/AssemblyCheck.lean +++ b/tv/SolarTV/Stages/AssemblyCheck.lean @@ -18,7 +18,7 @@ def walk (code : List Nat) (offset : Nat → Nat) : Nat → List Item → Option match decode code pc with | none => none | some (instr, next) => - if instr = item.expected offset ∧ item.placed offset pc = true then + if instr = item.expected offset ∧ item.placed code offset pc = true then match walk code offset next items with | some rest => some ((pc, instr) :: rest) | none => none @@ -44,7 +44,7 @@ theorem walk_sound {code : List Nat} {offset : Nat → Nat} : obtain ⟨instr, next⟩ := r rw [hd] at h simp only at h - by_cases ok : instr = item.expected offset ∧ item.placed offset pc = true + by_cases ok : instr = item.expected offset ∧ item.placed code offset pc = true · simp only [ok, and_self, ite_true] at h cases hw : walk code offset next items with | none => rw [hw] at h; cases h diff --git a/tv/SolarTV/Stages/Link.lean b/tv/SolarTV/Stages/Link.lean index 25bcd23a..4c68eea5 100644 --- a/tv/SolarTV/Stages/Link.lean +++ b/tv/SolarTV/Stages/Link.lean @@ -363,4 +363,14 @@ theorem linked_instructions {code : List Nat} {offset : Nat → Nat} {pc : Nat} clear decoded labels rest cases item <;> simp [linkedStream, Item.linked, ih] +/-- A walk places each immutable item as a `PUSH` of its width (`Item.placed`), so +linking needs no check of its own. -/ +theorem walk_placed {code : List Nat} {offset : Nat → Nat} {pc : Nat} {items : List Item} + {stream : List (Nat × Instr)} (w : Walk code offset pc items stream) : + placed code stream items = true := by + induction w with + | nil => simp [placed] + | @cons pc next item items stream _ hp _ ih => + cases item <;> simp_all [placed, Item.placed] + end SolarTV.Assembly diff --git a/tv/W1Proofs/Items.lean b/tv/W1Proofs/Items.lean index 12be416f..1fa3f84d 100644 --- a/tv/W1Proofs/Items.lean +++ b/tv/W1Proofs/Items.lean @@ -324,6 +324,6 @@ theorem table_stride : theorem table_too_few : itemsWith [.packed] ⟨[[.jumpTable [1]], [.stop]]⟩ = none := by decide /-- An offset of 256 does not fit its byte. -/ -theorem table_wide (pc : Nat) : (Item.pushTable [1]).placed (fun _ => 256) pc = false := rfl +theorem table_wide (pc : Nat) : (Item.pushTable [1]).placed [] (fun _ => 256) pc = false := rfl end SolarTV.Milestone.W1