diff --git a/EvmYul/EVM/Gas.lean b/EvmYul/EVM/Gas.lean index e5ebec8..0d8ec5a 100644 --- a/EvmYul/EVM/Gas.lean +++ b/EvmYul/EVM/Gas.lean @@ -161,22 +161,26 @@ def Ctload : ℕ := -/ def L (n : ℕ) : ℕ := n - (n / 64) -def Cnew (t : AccountAddress) (val : UInt256) (σ : AccountMap .EVM) : ℕ := +def Cnew {τ : OperationType} (t : AccountAddress) (val : UInt256) + (σ : AccountMap τ) : ℕ := if EvmYul.State.dead σ t && val != ⟨0⟩ then Gnewaccount else 0 def Cxfer (val : UInt256) : ℕ := if val != ⟨0⟩ then Gcallvalue else 0 -def Cextra (t r : AccountAddress) (val : UInt256) (σ : AccountMap .EVM) (A : Substate) : ℕ := +def Cextra {τ : OperationType} (t r : AccountAddress) (val : UInt256) + (σ : AccountMap τ) (A : Substate) : ℕ := Caccess t A + Cxfer val + Cnew r val σ -def Cgascap (t r : AccountAddress) (val g : UInt256) (σ : AccountMap .EVM) (μ : MachineState) (A : Substate) := +def Cgascap {τ : OperationType} (t r : AccountAddress) (val g : UInt256) + (σ : AccountMap τ) (μ : MachineState) (A : Substate) := if μ.gasAvailable.toNat >= Cextra t r val σ A then min (L <| (μ.gasAvailable.toNat - Cextra t r val σ A)) g.toNat else g.toNat -def Ccallgas (t r : AccountAddress) (val g : UInt256) (σ : AccountMap .EVM) (μ : MachineState) (A : Substate) : ℕ := +def Ccallgas {τ : OperationType} (t r : AccountAddress) (val g : UInt256) + (σ : AccountMap τ) (μ : MachineState) (A : Substate) : ℕ := match val with | ⟨0⟩ => Cgascap t r val g σ μ A | _ => Cgascap t r val g σ μ A + GasConstants.Gcallstipend @@ -184,7 +188,8 @@ def Ccallgas (t r : AccountAddress) (val g : UInt256) (σ : AccountMap .EVM) (μ /-- NB Assumes stack coherence. -/ -def Ccall (t r : AccountAddress) (val g : UInt256) (σ : AccountMap .EVM) (μ : MachineState) (A : Substate) : ℕ := +def Ccall {τ : OperationType} (t r : AccountAddress) (val g : UInt256) + (σ : AccountMap τ) (μ : MachineState) (A : Substate) : ℕ := Cgascap t r val g σ μ A + Cextra t r val σ A /-- diff --git a/EvmYul/EVM/PrecompiledContracts.lean b/EvmYul/EVM/PrecompiledContracts.lean index 414bdf9..55ed827 100644 --- a/EvmYul/EVM/PrecompiledContracts.lean +++ b/EvmYul/EVM/PrecompiledContracts.lean @@ -20,13 +20,13 @@ import EvmYul.FFI.ffi open EvmYul -def Ξ_ECREC - (σ : (AccountMap .EVM)) +def Ξ_ECREC {τ : OperationType} + (σ : (AccountMap τ)) (g : UInt256) (A : Substate) - (I : ExecutionEnv .EVM) + (I : ExecutionEnv τ) : - (Bool × AccountMap .EVM × UInt256 × Substate × ByteArray) + (Bool × AccountMap τ × UInt256 × Substate × ByteArray) := let gᵣ : ℕ := 3000 @@ -53,13 +53,13 @@ def Ξ_ECREC .empty (true, σ, g - .ofNat gᵣ, A, o) -def Ξ_SHA256 - (σ : AccountMap .EVM) +def Ξ_SHA256 {τ : OperationType} + (σ : AccountMap τ) (g : UInt256) (A : Substate) - (I : ExecutionEnv .EVM) + (I : ExecutionEnv τ) : - (Bool × AccountMap .EVM × UInt256 × Substate × ByteArray) + (Bool × AccountMap τ × UInt256 × Substate × ByteArray) := let gᵣ : ℕ := let l := I.calldata.size @@ -77,13 +77,13 @@ def Ξ_SHA256 .empty (true, σ, g - .ofNat gᵣ, A, o) -def Ξ_RIP160 - (σ : AccountMap .EVM) +def Ξ_RIP160 {τ : OperationType} + (σ : AccountMap τ) (g : UInt256) (A : Substate) - (I : ExecutionEnv .EVM) + (I : ExecutionEnv τ) : - (Bool × AccountMap .EVM × UInt256 × Substate × ByteArray) + (Bool × AccountMap τ × UInt256 × Substate × ByteArray) := let gᵣ : ℕ := let l := I.calldata.size @@ -101,13 +101,13 @@ def Ξ_RIP160 .empty (true, σ, g - .ofNat gᵣ, A, o) -def Ξ_ID - (σ : AccountMap .EVM) +def Ξ_ID {τ : OperationType} + (σ : AccountMap τ) (g : UInt256) (A : Substate) - (I : ExecutionEnv .EVM) + (I : ExecutionEnv τ) : - (Bool × AccountMap .EVM × UInt256 × Substate × ByteArray) + (Bool × AccountMap τ × UInt256 × Substate × ByteArray) := let gᵣ : ℕ := let l := I.calldata.size @@ -139,15 +139,7 @@ def expModAux (m : ℕ) (a : ℕ) (c : ℕ) : ℕ → ℕ def expMod (m : ℕ) (b : UInt256) (n : ℕ) : ℕ := expModAux m 1 b.toNat n -def Ξ_EXPMOD - (σ : AccountMap .EVM) - (g : UInt256) - (A : Substate) - (I : ExecutionEnv .EVM) - : - (Bool × AccountMap .EVM × UInt256 × Substate × ByteArray) -:= - let data := I.calldata +def Ξ_EXPMOD_gasCost (data : ByteArray) : ℕ := let base_length := nat_of_slice data 0 32 let exp_length := nat_of_slice data 32 32 let modulus_length := nat_of_slice data 64 32 @@ -155,46 +147,58 @@ def Ξ_EXPMOD -- We don't want to call `nat_of_slice` unless we need it let exp := λ () ↦ nat_of_slice data (96 + base_length) exp_length - let gᵣ := - let multiplication_complexity x y := ((max x y + 7) / 8) ^ 2 - let adjusted_exp_length := - if exp_length ≤ 32 && exp () == 0 then - 0 + let multiplication_complexity x y := ((max x y + 7) / 8) ^ 2 + let adjusted_exp_length := + if exp_length ≤ 32 && exp () == 0 then + 0 + else + if exp_length ≤ 32 then + Nat.log 2 (exp ()) else - if exp_length ≤ 32 then - Nat.log 2 (exp ()) - else - let length_part := 8 * (exp_length - 32) - let bits_part := - let exp_head := nat_of_slice data (96 + base_length) 32 - if 32 < exp_length ∧ exp_head != 0 then - Nat.log 2 exp_head - else - 0 - length_part + bits_part - let iterations := max adjusted_exp_length 1 - let G_quaddivisor := 3 + let length_part := 8 * (exp_length - 32) + let bits_part := + let exp_head := nat_of_slice data (96 + base_length) 32 + if 32 < exp_length ∧ exp_head != 0 then + Nat.log 2 exp_head + else + 0 + length_part + bits_part + let iterations := max adjusted_exp_length 1 + let G_quaddivisor := 3 + max 200 (multiplication_complexity base_length modulus_length * iterations / G_quaddivisor) - max 200 (multiplication_complexity base_length modulus_length * iterations / G_quaddivisor) +def Ξ_EXPMOD_output (data : ByteArray) : ByteArray := + let base_length := nat_of_slice data 0 32 + let exp_length := nat_of_slice data 32 32 + let modulus_length := nat_of_slice data 64 32 + let modulus := nat_of_slice data (96 + base_length + exp_length) modulus_length + if modulus_length == 0 || modulus == 0 then + ffi.ByteArray.zeroes ⟨modulus_length⟩ + else + let base := nat_of_slice data 96 base_length + let exp := nat_of_slice data (96 + base_length) exp_length + let expmod_base := BE (expMod modulus (.ofNat base) exp) + let expmod_zeroes := + if modulus_length ≥ expmod_base.size then + ffi.ByteArray.zeroes ⟨modulus_length - expmod_base.size⟩ + else + ByteArray.empty + expmod_zeroes ++ expmod_base +def Ξ_EXPMOD {τ : OperationType} + (σ : AccountMap τ) + (g : UInt256) + (A : Substate) + (I : ExecutionEnv τ) + : + (Bool × AccountMap τ × UInt256 × Substate × ByteArray) +:= + let data := I.calldata + let gᵣ := Ξ_EXPMOD_gasCost data if g.toNat < gᵣ then (false, ∅, ⟨0⟩, A, .empty) else - let modulus := nat_of_slice data (96 + base_length + exp_length) modulus_length - let o : ByteArray := - if modulus_length == 0 || modulus == 0 then - ffi.ByteArray.zeroes ⟨modulus_length⟩ - else - let base := nat_of_slice data 96 base_length - let exp := nat_of_slice data (96 + base_length) exp_length - let expmod_base := BE (expMod modulus (.ofNat base) exp) - let expmod_zeroes := - if modulus_length ≥ expmod_base.size then - ffi.ByteArray.zeroes ⟨modulus_length - expmod_base.size⟩ - else - ByteArray.empty - expmod_zeroes ++ expmod_base - (true, σ, g - .ofNat gᵣ, A, o) + (true, σ, g - .ofNat gᵣ, A, Ξ_EXPMOD_output data) private def expmodOutput := let (_, _, _, _, o) := @@ -214,13 +218,13 @@ private def expmodOutput := E : ByteArray := ⟨#[2]⟩ M : ByteArray := ⟨#[100]⟩ -def Ξ_BN_ADD - (σ : AccountMap .EVM) +def Ξ_BN_ADD {τ : OperationType} + (σ : AccountMap τ) (g : UInt256) (A : Substate) - (I : ExecutionEnv .EVM) + (I : ExecutionEnv τ) : - (Bool × AccountMap .EVM × UInt256 × Substate × ByteArray) + (Bool × AccountMap τ × UInt256 × Substate × ByteArray) := let gᵣ : ℕ := 150 @@ -268,13 +272,13 @@ private def bn_addOutput₁ := x : ByteArray := UInt256.toByteArray ⟨1⟩ y : ByteArray := UInt256.toByteArray ⟨2⟩ -def Ξ_BN_MUL - (σ : AccountMap .EVM) +def Ξ_BN_MUL {τ : OperationType} + (σ : AccountMap τ) (g : UInt256) (A : Substate) - (I : ExecutionEnv .EVM) + (I : ExecutionEnv τ) : - (Bool × AccountMap .EVM × UInt256 × Substate × ByteArray) + (Bool × AccountMap τ × UInt256 × Substate × ByteArray) := let gᵣ : ℕ := 6000 @@ -307,13 +311,13 @@ private def bn_mulOutput := y₁ : ByteArray := UInt256.toByteArray ⟨2⟩ n : ByteArray := UInt256.toByteArray ⟨2⟩ -def Ξ_SNARKV - (σ : AccountMap .EVM) +def Ξ_SNARKV {τ : OperationType} + (σ : AccountMap τ) (g : UInt256) (A : Substate) - (I : ExecutionEnv .EVM) + (I : ExecutionEnv τ) : - (Bool × AccountMap .EVM × UInt256 × Substate × ByteArray) + (Bool × AccountMap τ × UInt256 × Substate × ByteArray) := let d := I.calldata let k := d.size / 192 @@ -343,13 +347,13 @@ private def snarkvOutput := x : ByteArray := UInt256.toByteArray ⟨1⟩ y : ByteArray := UInt256.toByteArray ⟨2⟩ -def Ξ_BLAKE2_F - (σ : AccountMap .EVM) +def Ξ_BLAKE2_F {τ : OperationType} + (σ : AccountMap τ) (g : UInt256) (A : Substate) - (I : ExecutionEnv .EVM) + (I : ExecutionEnv τ) : - (Bool × AccountMap .EVM × UInt256 × Substate × ByteArray) + (Bool × AccountMap τ × UInt256 × Substate × ByteArray) := let d := I.calldata let gᵣ : ℕ := fromByteArrayBigEndian (d.extract 0 4) @@ -365,13 +369,13 @@ def Ξ_BLAKE2_F dbg_trace s!"Ξ_BLAKE2_F failed: {e}" (false, ∅, ⟨0⟩, A, .empty) -def Ξ_PointEval - (σ : AccountMap .EVM) +def Ξ_PointEval {τ : OperationType} + (σ : AccountMap τ) (g : UInt256) (A : Substate) - (I : ExecutionEnv .EVM) + (I : ExecutionEnv τ) : - (Bool × AccountMap .EVM × UInt256 × Substate × ByteArray) + (Bool × AccountMap τ × UInt256 × Substate × ByteArray) := let d := I.calldata let gᵣ : ℕ := 50000 @@ -385,3 +389,19 @@ def Ξ_PointEval | .error e => dbg_trace s!"Ξ_PointEval failed: {e}" (false, ∅, ⟨0⟩, A, .empty) + +def runPrecompiledContract {τ : OperationType} (precompiled : PrecompiledContract) + (σ : AccountMap τ) (g : UInt256) (A : Substate) + (I : ExecutionEnv τ) : + Bool × AccountMap τ × UInt256 × Substate × ByteArray := + match precompiled with + | .ecrec => Ξ_ECREC σ g A I + | .sha256 => Ξ_SHA256 σ g A I + | .rip160 => Ξ_RIP160 σ g A I + | .identity => Ξ_ID σ g A I + | .expmod => Ξ_EXPMOD σ g A I + | .bnAdd => Ξ_BN_ADD σ g A I + | .bnMul => Ξ_BN_MUL σ g A I + | .snarkv => Ξ_SNARKV σ g A I + | .blake2F => Ξ_BLAKE2_F σ g A I + | .pointEval => Ξ_PointEval σ g A I diff --git a/EvmYul/EVM/Semantics.lean b/EvmYul/EVM/Semantics.lean index 14dcf58..f11f7eb 100644 --- a/EvmYul/EVM/Semantics.lean +++ b/EvmYul/EVM/Semantics.lean @@ -136,6 +136,10 @@ def swap (n : ℕ) : Transformer := local instance : MonadLift Option (Except EVM.ExecutionException) := ⟨Option.option (.error .StackUnderflow) .ok⟩ +structure ChildFrameChainContext where + totalGasUsedInBlock : ℕ + transactionReceipts : Array TransactionReceipt + mutual def call (fuel : Nat) @@ -171,6 +175,9 @@ def call (fuel : Nat) (blocks := evmState.blocks) (σ := σ) -- σ in Θ(σ, ..) (σ₀ := evmState.σ₀) + (chainContext := + { totalGasUsedInBlock := evmState.totalGasUsedInBlock + transactionReceipts := evmState.transactionReceipts }) (A := A') -- A* in Θ(.., A*, ..) (s := source) (o := evmState.executionEnv.sender) -- Iₒ in Θ(.., Iₒ, ..) @@ -189,11 +196,9 @@ def call (fuel : Nat) -- otherwise (σ, CCALLGAS(σ, μ, A), A, 0, ()) .ok (evmState.createdAccounts, evmState.toState.accountMap, .ofNat callgas, A', false, .empty) - -- n ≡ min({μs[6], ‖o‖}) - let n : UInt256 := min outSize (.ofNat o.size) - - let μ'ₘ := writeBytes o 0 evmState.toMachineState outOffset.toNat n.toNat -- μ′_m[μs[5] ... (μs[5] + n − 1)] = o[0 ... (n − 1)] - let μ'ₒ := o -- μ′o = o + let μ'ₘ := + evmState.toMachineState.finishExternalCall o + inOffset inSize outOffset outSize let μ'_g := μ'ₘ.gasAvailable + g' -- Ccall is subtracted in X as part of C let codeExecutionFailed : Bool := !z @@ -204,11 +209,7 @@ def call (fuel : Nat) -- NB. `MachineState` here does not contain the `Stack` nor the `PC`, thus incomplete. let μ'incomplete : MachineState := { μ'ₘ with - returnData := μ'ₒ gasAvailable := μ'_g - activeWords := - let m : ℕ:= MachineState.M evmState.toMachineState.activeWords.toNat inOffset.toNat inSize.toNat - .ofNat <| MachineState.M m outOffset.toNat outSize.toNat } @@ -260,6 +261,8 @@ def step (fuel : ℕ) (gasCost : ℕ) (instr : Option (Operation .EVM × Option evmState.blocks σStar evmState.σ₀ + { totalGasUsedInBlock := evmState.totalGasUsedInBlock + transactionReceipts := evmState.transactionReceipts } evmState.toState.substate Iₐ Iₒ @@ -296,6 +299,7 @@ def step (fuel : ℕ) (gasCost : ℕ) (instr : Option (Operation .EVM × Option { evmState' with activeWords := .ofNat <| MachineState.M evmState.activeWords.toNat μ₁.toNat μ₂.toNat returnData := newReturnData + H_return := ByteArray.empty gasAvailable := .ofNat <| evmState.gasAvailable.toNat - L (evmState.gasAvailable.toNat) + g'.toNat } @@ -327,6 +331,8 @@ def step (fuel : ℕ) (gasCost : ℕ) (instr : Option (Operation .EVM × Option evmState.blocks σStar evmState.σ₀ + { totalGasUsedInBlock := evmState.totalGasUsedInBlock + transactionReceipts := evmState.transactionReceipts } evmState.toState.substate Iₐ Iₒ @@ -354,6 +360,7 @@ def step (fuel : ℕ) (gasCost : ℕ) (instr : Option (Operation .EVM × Option { evmState' with activeWords := .ofNat <| MachineState.M evmState.activeWords.toNat μ₁.toNat μ₂.toNat returnData := newReturnData + H_return := ByteArray.empty gasAvailable := .ofNat <| evmState.gasAvailable.toNat - L (evmState.gasAvailable.toNat) + g'.toNat } .ok <| evmState'.replaceStackAndIncrPC (stack.push x) @@ -529,6 +536,7 @@ def Ξ -- Type `Ξ` using `\GX` or `\Xi` (blocks : ProcessedBlocks) (σ : AccountMap .EVM) (σ₀ : AccountMap .EVM) + (chainContext : ChildFrameChainContext) (g : UInt256) (A : Substate) (I : ExecutionEnv .EVM) @@ -545,6 +553,8 @@ def Ξ -- Type `Ξ` using `\GX` or `\Xi` { defState with accountMap := σ σ₀ := σ₀ + totalGasUsedInBlock := chainContext.totalGasUsedInBlock + transactionReceipts := chainContext.transactionReceipts executionEnv := I substate := A createdAccounts := createdAccounts @@ -567,6 +577,7 @@ def Lambda (blocks : ProcessedBlocks) (σ : AccountMap .EVM) (σ₀ : AccountMap .EVM) + (chainContext : ChildFrameChainContext) (A : Substate) (s : AccountAddress) -- sender (o : AccountAddress) -- original transactor @@ -651,7 +662,8 @@ def Lambda , perm := w , blobVersionedHashes := blobVersionedHashes } - match Ξ f createdAccounts genesisBlockHeader blocks σStar σ₀ g AStar exEnv with + match Ξ f createdAccounts genesisBlockHeader blocks σStar σ₀ + chainContext g AStar exEnv with | .error e => if e == .OutOfFuel then throw .OutOfFuel .ok (a, createdAccounts, σ, ⟨0⟩, AStar, false, .empty) @@ -695,6 +707,75 @@ def Lambda | none => RLP <| .𝕃 [.𝔹 s, .𝔹 n] | some ζ => .some <| BE 255 ++ s ++ ζ ++ ffi.KEC i +/-- +Recipient-credit step of the message-call account-map prelude. + +This mirrors equations (124)-(126) for `Θ`: a missing recipient is +materialized only for nonzero value, while an existing recipient is credited. +-/ +def thetaCallRecipientCredit + (σ : AccountMap .EVM) (r : AccountAddress) (v : UInt256) : + AccountMap .EVM := + match σ.find? r with + | none => + if v != ⟨0⟩ then + σ.insert r { (default : Account .EVM) with balance := v } + else + σ + | some acc => + σ.insert r { acc with balance := acc.balance + v } + +/-- +Sender-debit step of the message-call account-map prelude. + +The balance precondition is checked by the caller-side opcode semantics before +`Θ`; this helper only mirrors the unconditional debit shape used inside `Θ`. +-/ +def thetaCallSourceDebit + (σ : AccountMap .EVM) (s : AccountAddress) (v : UInt256) : + AccountMap .EVM := + match σ.find? s with + | none => σ + | some acc => + σ.insert s { acc with balance := acc.balance - v } + +/-- +Full account-map prelude for an EVM message call. +-/ +def thetaCallTransfer + (σ : AccountMap .EVM) (s r : AccountAddress) (v : UInt256) : + AccountMap .EVM := + thetaCallSourceDebit (thetaCallRecipientCredit σ r v) s v + +/-- +Execution environment installed for a `Θ` child frame. +-/ +def thetaCallExecutionEnv + (blobVersionedHashes : List ByteArray) + (s o r : AccountAddress) + (c : ToExecute .EVM) + (p v' : UInt256) + (d : ByteArray) + (e : Nat) + (H : BlockHeader) + (w : Bool) : ExecutionEnv .EVM := + { + codeOwner := r + sender := o + gasPrice := p.toNat + calldata := d + source := s + weiValue := v' + depth := e + perm := w + code := + match c with + | ToExecute.Precompiled _ => default + | ToExecute.Code code => code + header := H + blobVersionedHashes := blobVersionedHashes + } + /-- Message cal `σ` - evm state @@ -721,6 +802,7 @@ def Θ (fuel : Nat) (blocks : ProcessedBlocks) (σ : AccountMap .EVM) (σ₀ : AccountMap .EVM) + (chainContext : ChildFrameChainContext) (A : Substate) (s : AccountAddress) (o : AccountAddress) @@ -742,61 +824,19 @@ def Θ (fuel : Nat) | fuel + 1 => do -- (124) (125) (126) - let σ'₁ := - match σ.find? r with - | none => - if v != ⟨0⟩ then - σ.insert r { (default : Account .EVM) with balance := v} - else - σ - | some acc => - σ.insert r { acc with balance := acc.balance + v} - - -- If `v` ≠ 0 then the sender must have passed the `INSUFFICIENT_ACCOUNT_FUNDS` check - let σ₁ := - match σ'₁.find? s with - | none => σ'₁ - | some acc => - σ'₁.insert s { acc with balance := acc.balance - v} + let σ₁ := thetaCallTransfer σ s r v let I : ExecutionEnv .EVM := - { - codeOwner := r -- Equation (132) - sender := o -- Equation (133) - gasPrice := p.toNat -- Equation (134) - calldata := d -- Equation (135) - source := s -- Equation (136) - weiValue := v' -- Equation (137) - depth := e -- Equation (138) - perm := w -- Equation (139) - -- Note that we don't use an address, but the actual code. Equation (141)-ish. - code := - match c with - | ToExecute.Precompiled _ => default - | ToExecute.Code code => code - header := H - blobVersionedHashes := blobVersionedHashes - } + thetaCallExecutionEnv blobVersionedHashes s o r c p v' d e H w -- Equation (131) - -- Note that the `c` used here is the actual code, not the address. TODO - Handle precompiled contracts. let (createdAccounts, z, σ'', g', A'', out) ← match c with | ToExecute.Precompiled p => - match p with - | 1 => .ok <| (∅, Ξ_ECREC σ₁ g A I) - | 2 => .ok <| (∅, Ξ_SHA256 σ₁ g A I) - | 3 => .ok <| (∅, Ξ_RIP160 σ₁ g A I) - | 4 => .ok <| (∅, Ξ_ID σ₁ g A I) - | 5 => .ok <| (∅, Ξ_EXPMOD σ₁ g A I) - | 6 => .ok <| (∅, Ξ_BN_ADD σ₁ g A I) - | 7 => .ok <| (∅, Ξ_BN_MUL σ₁ g A I) - | 8 => .ok <| (∅, Ξ_SNARKV σ₁ g A I) - | 9 => .ok <| (∅, Ξ_BLAKE2_F σ₁ g A I) - | 10 => .ok <| (∅, Ξ_PointEval σ₁ g A I) - | _ => default + .ok <| (createdAccounts, runPrecompiledContract p σ₁ g A I) | ToExecute.Code _ => - match Ξ fuel createdAccounts genesisBlockHeader blocks σ₁ σ₀ g A I with + match Ξ fuel createdAccounts genesisBlockHeader blocks σ₁ σ₀ + chainContext g A I with | .error e => if e == .OutOfFuel then throw .OutOfFuel pure (createdAccounts, false, σ, ⟨0⟩, A, .empty) @@ -806,10 +846,10 @@ def Θ (fuel : Nat) pure (a, true, b, c, d, o) -- Equation (127) - let σ' := if σ'' == ∅ then σ else σ'' + let σ' := if σ''.isEmpty then σ else σ'' -- Equation (129) - let A' := if σ'' == ∅ then A else A'' + let A' := if σ''.isEmpty then A else A'' -- Equation (119) .ok (createdAccounts, σ', g', A', z, out) @@ -887,6 +927,8 @@ def Υ (fuel : ℕ) blocks σ₀ σ₀ + { totalGasUsedInBlock := 0 + transactionReceipts := #[] } AStar S_T S_T @@ -911,6 +953,8 @@ def Υ (fuel : ℕ) blocks σ₀ σ₀ + { totalGasUsedInBlock := 0 + transactionReceipts := #[] } AStar S_T S_T diff --git a/EvmYul/MachineStateOps.lean b/EvmYul/MachineStateOps.lean index 490a9f5..c7e0422 100644 --- a/EvmYul/MachineStateOps.lean +++ b/EvmYul/MachineStateOps.lean @@ -78,6 +78,9 @@ def gas (self : MachineState) : UInt256 := section ReturnData +def freshExternalCall (gas : UInt256) : MachineState := + { (default : MachineState) with gasAvailable := gas } + def setReturnData (self : MachineState) (r : ByteArray) : MachineState := { self with returnData := r } @@ -97,6 +100,21 @@ def returndatacopy (self : MachineState) (mstart rstart size : UInt256) : Machin .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 diff --git a/EvmYul/Maps/AccountMap.lean b/EvmYul/Maps/AccountMap.lean index 3b8ecca..89ad6e9 100644 --- a/EvmYul/Maps/AccountMap.lean +++ b/EvmYul/Maps/AccountMap.lean @@ -65,17 +65,17 @@ def AccountMap.transferBalance (τ : OperationType) (σ : AccountMap τ) (from_a | .some σ' => σ'.increaseBalance τ to_addr amount def toExecute (τ : OperationType) (σ : AccountMap τ) (t : AccountAddress) : ToExecute τ := - if /- t is a precompiled account -/ t ∈ π then - ToExecute.Precompiled t - else Id.run do - match τ with - | .EVM => - -- We use the code directly without an indirection a'la `codeMap[t]`. - let .some tDirect := σ.find? t | ToExecute.Code default - ToExecute.Code tDirect.code - | .Yul => - let .some tDirect := σ.find? t | ToExecute.Code default - ToExecute.Code tDirect.code + match PrecompiledContract.ofAddress? t with + | some precompiled => ToExecute.Precompiled precompiled + | none => Id.run do + match τ with + | .EVM => + -- We use the code directly without an indirection a'la `codeMap[t]`. + let .some tDirect := σ.find? t | ToExecute.Code default + ToExecute.Code tDirect.code + | .Yul => + let .some tDirect := σ.find? t | ToExecute.Code default + ToExecute.Code tDirect.code def L_S (σ : PersistentAccountMap .EVM) : Array (ByteArray × ByteArray) := σ.foldl diff --git a/EvmYul/Semantics.lean b/EvmYul/Semantics.lean index 07e65a9..f14f9d2 100644 --- a/EvmYul/Semantics.lean +++ b/EvmYul/Semantics.lean @@ -215,7 +215,6 @@ def swap (n : ℕ) : Transformer .EVM := else .error .StackUnderflow --- TODO: Yul halting for `SELFDESTRUCT` def step {τ : OperationType} (op : Operation τ) (arg : Option (UInt256 × Nat) := .none) : Transformer τ := Id.run do let _ : Id Unit := -- For debug logging match τ with @@ -391,7 +390,7 @@ def step {τ : OperationType} (op : Operation τ) (arg : Option (UInt256 × Nat) | .Yul, .REVERT => λ yulState lits ↦ match (dispatchBinaryMachineStateOp .Yul MachineState.evmRevert) yulState lits with | .error e => .error e - | .ok (_, _) => .error (Yul.Exception.Revert) + | .ok (s, _) => .error (Yul.Exception.Revert s) | .EVM, .SELFDESTRUCT => λ evmState ↦ match evmState.stack.pop with @@ -510,7 +509,7 @@ def step {τ : OperationType} (op : Operation τ) (arg : Option (UInt256 × Nat) let yulState' := yulState.setState { yulState.toState with accountMap := accountMap', substate := A'} - .ok <| (yulState', none) + .error (Yul.Exception.YulHalt yulState' ⟨0⟩) | _ => .error .InvalidArguments | τ, .INVALID => dispatchInvalid τ | .EVM, .Push .PUSH0 => λ evmState => diff --git a/EvmYul/State/Account.lean b/EvmYul/State/Account.lean index f0cee58..746bbdf 100644 --- a/EvmYul/State/Account.lean +++ b/EvmYul/State/Account.lean @@ -8,16 +8,72 @@ 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 π : Batteries.RBSet AccountAddress compare := - Batteries.RBSet.ofList ((List.range 11).tail.map (Fin.ofNat _)) compare + Batteries.RBSet.ofList (PrecompiledContract.all.map PrecompiledContract.address) compare inductive ToExecute (τ : OperationType) where | Code (code : Yul.Ast.contractCode τ) - | Precompiled (precompiled : AccountAddress) + | Precompiled (precompiled : PrecompiledContract) structure PersistentAccountState (τ : OperationType) where nonce : UInt256 diff --git a/EvmYul/State/AccountOps.lean b/EvmYul/State/AccountOps.lean index 9b87964..931a5f8 100644 --- a/EvmYul/State/AccountOps.lean +++ b/EvmYul/State/AccountOps.lean @@ -32,7 +32,7 @@ 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 => false -- Yul statements always hold code. + | .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 diff --git a/EvmYul/Yul/Ast.lean b/EvmYul/Yul/Ast.lean index 7f7c513..99be310 100644 --- a/EvmYul/Yul/Ast.lean +++ b/EvmYul/Yul/Ast.lean @@ -47,6 +47,7 @@ mutual 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 diff --git a/EvmYul/Yul/Exception.lean b/EvmYul/Yul/Exception.lean index fdd9b4b..610a44a 100644 --- a/EvmYul/Yul/Exception.lean +++ b/EvmYul/Yul/Exception.lean @@ -13,8 +13,10 @@ inductive Exception where | MissingContract (s : String) : Exception | MissingContractFunction (s : String) : Exception | InvalidExpression : Exception + | UnknownIdentifier (s : String) : Exception + | DuplicateDeclaration (s : String) : Exception | YulEXTCODESIZENotImplemented : Exception - | Revert : Exception + | Revert (state : Yul.State) : Exception | YulHalt (state : Yul.State) (value : UInt256) : Exception -- | StopInvoked : Exception @@ -29,8 +31,10 @@ instance : Repr Exception where | .MissingContract s => "MissingContract: " ++ s | .MissingContractFunction f => "MissingContractFunction: " ++ f | .InvalidExpression => "InvalidExpression" + | .UnknownIdentifier s => "UnknownIdentifier: " ++ s + | .DuplicateDeclaration s => "DuplicateDeclaration: " ++ s | .YulEXTCODESIZENotImplemented => "YulEXTCODESIZENotImplemented" - | .Revert => "Revert" + | .Revert _ => "Revert" | .YulHalt _ _ => "YulHalt: (holds a state and a value)" diff --git a/EvmYul/Yul/Interpreter.lean b/EvmYul/Yul/Interpreter.lean index 3e8adfc..a691bae 100644 --- a/EvmYul/Yul/Interpreter.lean +++ b/EvmYul/Yul/Interpreter.lean @@ -7,6 +7,7 @@ import EvmYul.Yul.StateOps import EvmYul.Yul.SizeLemmas import EvmYul.Yul.Exception +import EvmYul.EVM.Gas import EvmYul.Semantics set_option maxHeartbeats 400000 -- Needs more than 200000 @@ -37,6 +38,82 @@ def multifill' (vars : List Identifier) : Except Yul.Exception (State × List Li | .ok (s, rets) => .ok (s.multifill vars rets) | .error e => .error e +def firstDuplicate? : List Identifier → Option Identifier + | [] => .none + | var :: vars => + if vars.contains var then .some var else firstDuplicate? vars + +def firstDeclared? (s : State) (vars : List Identifier) : Option Identifier := + vars.find? (fun var => (s.lookup? var).isSome) + +def firstUndeclared? (s : State) (vars : List Identifier) : Option Identifier := + vars.find? (fun var => (s.lookup? var).isNone) + +def checkDeclaration (s : State) (vars : List Identifier) : Except Yul.Exception Unit := + match firstDuplicate? vars with + | .some var => .error (.DuplicateDeclaration var) + | .none => + match firstDeclared? s vars with + | .some var => .error (.DuplicateDeclaration var) + | .none => .ok () + +def checkAssignment (s : State) (vars : List Identifier) : Except Yul.Exception Unit := + match firstDuplicate? vars with + | .some _ => .error .InvalidArguments + | .none => + match firstUndeclared? s vars with + | .some var => .error (.UnknownIdentifier var) + | .none => .ok () + +def restoreRevertedContractCallState (s₀ s₂ : State) + (inOffset inSize outOffset outSize : Literal) : + Except Yul.Exception (State × List Literal) := + match s₀ with + | .OutOfFuel => .error .OutOfFuel + | .Checkpoint j => .ok (.Checkpoint j, [⟨0⟩]) + | .Ok sharedState₀ varstore => + let returnData := s₂.toMachineState.H_return + let machineState₃ := + s₀.toMachineState.finishExternalCall returnData + inOffset inSize outOffset outSize + let sharedState₃ := + { sharedState₀ with + toMachineState := machineState₃ + } + .ok (.Ok sharedState₃ varstore, [⟨0⟩]) + +def restoreSuccessfulContractCallState (s₀ s₂ : State) + (varstore : VarStore) (returnData : ByteArray) + (inOffset inSize outOffset outSize : Literal) : + Except Yul.Exception (State × List Literal) := + match s₀ with + | .OutOfFuel => .error .OutOfFuel + | .Checkpoint j => .ok (.Checkpoint j, [⟨0⟩]) + | .Ok sharedState₀ _ => + match s₂ with + | .OutOfFuel => .error .OutOfFuel + | .Checkpoint j => .ok (.Checkpoint j, [⟨0⟩]) + | .Ok sharedState₂ _ => + let machineState₃ := + s₀.toMachineState.finishExternalCall returnData + inOffset inSize outOffset outSize + let sharedState₃ := + { sharedState₀ with + toMachineState := machineState₃ + accountMap := + if sharedState₂.accountMap.isEmpty then + sharedState₀.accountMap + else + sharedState₂.accountMap + substate := + if sharedState₂.accountMap.isEmpty then + sharedState₀.substate + else + sharedState₂.substate + createdAccounts := sharedState₂.createdAccounts + } + .ok (.Ok sharedState₃ varstore, [⟨1⟩]) + def setStatic (s : State) (p : Bool) : State := match s with | .OutOfFuel => .OutOfFuel @@ -50,16 +127,114 @@ def setStatic (s : State) (p : Bool) : State := } .Ok sharedState' varstore -def buildContractCallEmptyReturnState (s₀ : State) (accountMap₁ : Option (AccountMap .Yul)) (v : Literal) : Except Yul.Exception (State × List Literal) := +def addAccessedAccount (s : State) (addr : AccountAddress) : State := + s.setState (EvmYul.State.addAccessedAccount s.toState addr) + +def callRecipientCredit {τ : OperationType} + (accountMap : AccountMap τ) + (recipient : AccountAddress) + (value : UInt256) : AccountMap τ := + match accountMap.find? recipient with + | none => + if value != ⟨0⟩ then + accountMap.insert recipient + { (default : Account τ) with balance := value } + else + accountMap + | some account => + accountMap.insert recipient + { account with balance := account.balance + value } + +def callSourceDebit {τ : OperationType} + (accountMap : AccountMap τ) + (source : AccountAddress) + (value : UInt256) : AccountMap τ := + match accountMap.find? source with + | none => accountMap + | some account => + accountMap.insert source + { account with balance := account.balance - value } + +def callTransferUnchecked {τ : OperationType} + (accountMap : AccountMap τ) + (source recipient : AccountAddress) + (value : UInt256) : AccountMap τ := + callSourceDebit (callRecipientCredit accountMap recipient value) source value + +def callTransferAccountMap? (accountMap : AccountMap .Yul) + (source recipient : AccountAddress) (value : UInt256) : + Option (AccountMap .Yul) := + if value ≤ (accountMap.find? source |>.option ⟨0⟩ (·.balance)) then + some (callTransferUnchecked accountMap source recipient value) + else + none + +def buildContractCallEmptyReturnState (s₀ : State) + (accountMap₁ : Option (AccountMap .Yul)) + (inOffset inSize outOffset outSize v : Literal) : + Except Yul.Exception (State × List Literal) := match s₀ with | .OutOfFuel => .error .OutOfFuel | .Checkpoint j => .ok (.Checkpoint j, [⟨0⟩]) | .Ok sharedState₀ varstore => - let sharedState₁ := {sharedState₀ with H_return := ByteArray.empty, - returnData := ByteArray.empty, - accountMap := accountMap₁.getD s₀.toSharedState.accountMap } + let machineState₁ := + s₀.toMachineState.finishExternalCall ByteArray.empty + inOffset inSize outOffset outSize + let sharedState₁ := + { sharedState₀ with + toMachineState := machineState₁ + accountMap := accountMap₁.getD s₀.toSharedState.accountMap + } .ok (.Ok sharedState₁ varstore, [v]) +def buildContractCallReturnState (s₀ : State) (accountMap₂ : AccountMap .Yul) + (substate₂ : Substate) (returnData : ByteArray) + (inOffset inSize outOffset outSize v : Literal) : + Except Yul.Exception (State × List Literal) := + match s₀ with + | .OutOfFuel => .error .OutOfFuel + | .Checkpoint j => .ok (.Checkpoint j, [⟨0⟩]) + | .Ok sharedState₀ varstore => + let machineState₃ := + s₀.toMachineState.finishExternalCall returnData + inOffset inSize outOffset outSize + let sharedState₃ := + { sharedState₀ with + toMachineState := machineState₃ + accountMap := accountMap₂ + substate := substate₂ + } + .ok (.Ok sharedState₃ varstore, [v]) + +def buildPrecompiledContractCallState (s₀ : State) (accountMap₁ : AccountMap .Yul) + (precompiled : PrecompiledContract) (gas : Literal) + (executionEnv : ExecutionEnv .Yul) + (inOffset inSize outOffset outSize : Literal) : + Except Yul.Exception (State × List Literal) := + let (z, accountMap₂, _, substate₂, returnData) := + runPrecompiledContract precompiled accountMap₁ gas s₀.toState.substate executionEnv + if z then + let accountMap₃ := + if accountMap₂.isEmpty then s₀.toSharedState.accountMap else accountMap₂ + buildContractCallReturnState s₀ accountMap₃ substate₂ returnData + inOffset inSize outOffset outSize ⟨1⟩ + else + buildContractCallEmptyReturnState s₀ .none + inOffset inSize outOffset outSize ⟨0⟩ + +/-- + `selectSwitchCase` returns the first switch case body whose literal matches + the evaluated switch condition, or the default body if no case matches. + + This matches Solidity/Yul switch control flow: non-selected case and default + bodies are not executed. +-/ +def selectSwitchCase (cond : Literal) (defaultBody : List Stmt) : + List (Literal × List Stmt) → List Stmt + | [] => defaultBody + | ((val, stmts) :: cases') => + if val = cond then stmts else selectSwitchCase cond defaultBody cases' + mutual def primCall (fuel : ℕ) (s₀ : State) (prim : Operation .Yul) (args : List Literal) : Except Yul.Exception (State × List Literal) := @@ -71,26 +246,53 @@ def primCall (fuel : ℕ) (s₀ : State) (prim : Operation .Yul) (args : List Li match prim with | .CALL => match args with - | _ :: address_arg :: value :: inOffset :: inSize :: outOffset :: outSize :: _ => + | gas :: address_arg :: value :: inOffset :: inSize :: outOffset :: outSize :: _ => if ¬s₀.executionEnv.perm ∧ value ≠ ⟨0⟩ then throw .StaticModeViolation let address := AccountAddress.ofUInt256 address_arg + let s₀Accessed := addAccessedAccount s₀ address let calldata₁ := s₀.toMachineState.memory.readWithPadding inOffset.toNat inSize.toNat - let accountMap₁Opt := (s₀.sharedState.accountMap.transferBalance .Yul s₀.executionEnv.codeOwner address value) + let callGas : UInt256 := + .ofNat <| + EvmYul.EVM.Ccallgas address address value gas + s₀.sharedState.accountMap s₀.toMachineState s₀.toState.substate + let accountMap₁Opt := + callTransferAccountMap? + s₀.sharedState.accountMap + s₀.executionEnv.codeOwner + address + value match accountMap₁Opt with | .none => - buildContractCallEmptyReturnState s₀ .none ⟨0⟩ -- Insufficient funds: return 0 to indicate error, with empty return data + buildContractCallEmptyReturnState s₀Accessed .none + inOffset inSize outOffset outSize ⟨0⟩ -- Insufficient funds: return 0 to indicate error, with empty return data | .some accountMap₁ => if s₀.executionEnv.depth ≥ 1024 then - buildContractCallEmptyReturnState s₀ .none ⟨0⟩ -- Reached depth limit: return 0 to indicate error, with empty return data + buildContractCallEmptyReturnState s₀Accessed .none + inOffset inSize outOffset outSize ⟨0⟩ -- Reached depth limit: return 0 to indicate error, with empty return data else - match s₀ with + match s₀Accessed with | .OutOfFuel => .error .OutOfFuel | .Checkpoint j => .ok (.Checkpoint j, [⟨0⟩]) | .Ok sharedState varstore => - match s₀.sharedState.accountMap.find? address with + match EvmYul.toExecute .Yul s₀.sharedState.accountMap address with + | .Precompiled precompiled => + let executionEnv₁ := { sharedState.executionEnv with + calldata := calldata₁, + code := default, + codeOwner := address, + source := s₀.executionEnv.codeOwner, + weiValue := value + depth := s₀.executionEnv.depth + 1 + } + buildPrecompiledContractCallState + s₀Accessed accountMap₁ precompiled callGas + executionEnv₁ inOffset inSize outOffset outSize + | .Code _ => + match s₀.sharedState.accountMap.find? address with | .none => - buildContractCallEmptyReturnState s₀ accountMap₁ ⟨1⟩ -- No contract at the provided address, return 1 to indicate success, with empty return data. (Like STOP opcode). + buildContractCallEmptyReturnState s₀Accessed accountMap₁ + inOffset inSize outOffset outSize ⟨1⟩ -- No contract at the provided address, return 1 to indicate success, with empty return data. (Like STOP opcode). | .some yulContract => let executionEnv₁ := { sharedState.executionEnv with calldata := calldata₁, @@ -99,92 +301,67 @@ def primCall (fuel : ℕ) (s₀ : State) (prim : Operation .Yul) (args : List Li source := s₀.executionEnv.codeOwner, weiValue := value depth := s₀.executionEnv.depth + 1 - } + } let sharedState₁ := { sharedState with executionEnv := executionEnv₁, - memory := ByteArray.mk #[], + toMachineState := + EvmYul.MachineState.freshExternalCall callGas, accountMap := accountMap₁ } let s₁ : State := .Ok sharedState₁ default - match callDispatcher fuel₁ .none s₁ with + match callDispatcher fuel₁ (some yulContract.code) s₁ with | .error (.YulHalt s₂ _) => - let memory₃ := s₂.toMachineState.H_return.copySlice 0 s₀.toMachineState.memory outOffset.toNat (min outSize.toNat s₂.toMachineState.H_return.size) - match s₂ with - | .OutOfFuel => .error .OutOfFuel - | .Checkpoint j => .ok (.Checkpoint j, [⟨0⟩]) - | .Ok sharedState₂ _ => - - -- Restore ExecutionEnv - let executionEnv₃ := { sharedState₂.executionEnv with - calldata := default, - code := s₀.executionEnv.code, - codeOwner := s₀.executionEnv.codeOwner, - source := s₀.executionEnv.source, - weiValue := s₀.executionEnv.weiValue, - } - let sharedState₃ := { sharedState₂ with - memory := memory₃, - returnData := s₂.toMachineState.H_return, - executionEnv := executionEnv₃, - H_return := ByteArray.empty - } - .ok (.Ok sharedState₃ varstore, [⟨1⟩]) + restoreSuccessfulContractCallState s₀ s₂ varstore + s₂.toMachineState.H_return + inOffset inSize outOffset outSize + | .error (.Revert s₂) => + restoreRevertedContractCallState s₀Accessed s₂ + inOffset inSize outOffset outSize | .error e => .error e | .ok (s₂, _) => - - /- We note here that if: - `outOffset.toNat + (min outSize.toNat s₂.toMachineState.H_return.size) ≥ UInt256.size` - then we are writing beyond the theoretical memory size limit. - The yellow paper is unclear on the semantics of this (at the time of writing). - We follow the https://github.com/NethermindEth/nethermind execution client (for example). - And we expand the memory beyond the theoretical 2^256 bit max size if needed. - In practice, this is essentially impossible to occur due to the - prohibitively large gas cost of allocating this much memory. - - Similarly in other places in `primCall` where `memory₃` is constructed in this way. - -/ - let memory₃ := s₂.toMachineState.H_return.copySlice 0 s₀.toMachineState.memory outOffset.toNat (min outSize.toNat s₂.toMachineState.H_return.size) - match s₂ with - | .OutOfFuel => .error .OutOfFuel - | .Checkpoint j => .ok (.Checkpoint j, [⟨0⟩]) - | .Ok sharedState₂ _ => - - -- Restore ExecutionEnv - let executionEnv₃ := { sharedState₂.executionEnv with - calldata := default, - code := s₀.executionEnv.code, - codeOwner := s₀.executionEnv.codeOwner, - source := s₀.executionEnv.source, - weiValue := s₀.executionEnv.weiValue, - } - let sharedState₃ := { sharedState₂ with - memory := memory₃, - returnData := s₂.toMachineState.H_return, - H_return := ByteArray.empty, - executionEnv := executionEnv₃ - } - .ok (.Ok sharedState₃ varstore, [⟨1⟩]) + restoreSuccessfulContractCallState s₀ s₂ varstore + ByteArray.empty inOffset inSize outOffset outSize | _ => .error .InvalidArguments -- Incorrect number of arguments, this case should be impossible if the Yul code is parsed correctly. Guaranteed by the compiler. | .STATICCALL => match args with - | _ :: address_arg :: inOffset :: inSize :: outOffset :: outSize :: _ => - if ¬s₀.executionEnv.perm then throw .StaticModeViolation - let s₀Static : State := setStatic s₀ false + | gas :: address_arg :: inOffset :: inSize :: outOffset :: outSize :: _ => let address := AccountAddress.ofUInt256 address_arg - let calldata₁ := s₀Static.toMachineState.memory.readWithPadding inOffset.toNat inSize.toNat + let s₀Accessed := addAccessedAccount s₀ address + let s₀Static : State := setStatic s₀Accessed false + let calldata₁ := s₀.toMachineState.memory.readWithPadding inOffset.toNat inSize.toNat + let callGas : UInt256 := + .ofNat <| + EvmYul.EVM.Ccallgas address address ⟨0⟩ gas + s₀.sharedState.accountMap s₀.toMachineState s₀.toState.substate - if s₀Static.toSharedState.executionEnv.depth ≥ 1024 + if s₀.executionEnv.depth ≥ 1024 then - buildContractCallEmptyReturnState s₀Static .none ⟨0⟩ -- Reached depth limit: return 0 to indicate error, with empty return data + buildContractCallEmptyReturnState s₀Accessed .none + inOffset inSize outOffset outSize ⟨0⟩ -- Reached depth limit: return 0 to indicate error, with empty return data else match s₀Static with | .OutOfFuel => .error .OutOfFuel | .Checkpoint j => .ok (.Checkpoint j, [⟨0⟩]) | .Ok sharedState varstore => - match s₀Static.sharedState.accountMap.find? address with + match EvmYul.toExecute .Yul s₀.sharedState.accountMap address with + | .Precompiled precompiled => + let executionEnv₁ := { s₀Static.executionEnv with + calldata := calldata₁, + code := default, + codeOwner := address, + source := s₀Static.executionEnv.codeOwner, + weiValue := ⟨0⟩ + depth := s₀Static.toSharedState.executionEnv.depth + 1 + } + buildPrecompiledContractCallState + s₀Accessed s₀.sharedState.accountMap precompiled callGas + executionEnv₁ inOffset inSize outOffset outSize + | .Code _ => + match s₀.sharedState.accountMap.find? address with | .none => - buildContractCallEmptyReturnState s₀Static .none ⟨1⟩ -- No contract at the provided address, return 1 to indicate success, with empty return data. (Like STOP opcode). + buildContractCallEmptyReturnState s₀Accessed .none + inOffset inSize outOffset outSize ⟨1⟩ -- No contract at the provided address, return 1 to indicate success, with empty return data. (Like STOP opcode). | .some yulContract => let executionEnv₁ := { s₀Static.executionEnv with calldata := calldata₁, @@ -196,78 +373,72 @@ def primCall (fuel : ℕ) (s₀ : State) (prim : Operation .Yul) (args : List Li } let sharedState₁ := { sharedState with executionEnv := executionEnv₁, - memory := ByteArray.mk #[], + toMachineState := + EvmYul.MachineState.freshExternalCall callGas, } let s₁ : State := .Ok sharedState₁ default - match callDispatcher fuel₁ .none s₁ with + match callDispatcher fuel₁ (some yulContract.code) s₁ with | .error (.YulHalt s₂ _) => - let memory₃ := s₂.toMachineState.H_return.copySlice 0 s₀Static.toMachineState.memory outOffset.toNat (min outSize.toNat s₂.toMachineState.H_return.size) - match s₂ with - | .OutOfFuel => .error .OutOfFuel - | .Checkpoint j => .ok (.Checkpoint j, [⟨0⟩]) - | .Ok sharedState₂ _ => - -- Restore ExecutionEnv - let executionEnv₃ := { sharedState₂.executionEnv with - calldata := default, - code := s₀.executionEnv.code, - codeOwner := s₀.executionEnv.codeOwner, - source := s₀.executionEnv.source, - weiValue := s₀.executionEnv.weiValue, - } - let sharedState₃ := { sharedState₂ with - memory := memory₃, - returnData := s₂.toMachineState.H_return, - H_return := ByteArray.empty, - executionEnv := executionEnv₃ - } - .ok (setStatic (.Ok sharedState₃ varstore) s₀.executionEnv.perm, [⟨1⟩]) + restoreSuccessfulContractCallState s₀ s₂ varstore + s₂.toMachineState.H_return + inOffset inSize outOffset outSize + | .error (.Revert s₂) => + restoreRevertedContractCallState s₀Accessed s₂ + inOffset inSize outOffset outSize | .error e => .error e | .ok (s₂, _) => - - let memory₃ := s₂.toMachineState.H_return.copySlice 0 s₀Static.toMachineState.memory outOffset.toNat (min outSize.toNat s₂.toMachineState.H_return.size) - match s₂ with - | .OutOfFuel => .error .OutOfFuel - | .Checkpoint j => .ok (.Checkpoint j, [⟨0⟩]) - | .Ok sharedState₂ _ => - -- Restore ExecutionEnv - let executionEnv₃ := { sharedState₂.executionEnv with - calldata := default, - code := s₀.executionEnv.code, - codeOwner := s₀.executionEnv.codeOwner, - source := s₀.executionEnv.source, - weiValue := s₀.executionEnv.weiValue, - } - let sharedState₃ := { sharedState₂ with - memory := memory₃, - returnData := s₂.toMachineState.H_return, - H_return := ByteArray.empty, - executionEnv := executionEnv₃ - } - .ok (setStatic (.Ok sharedState₃ varstore) s₀.executionEnv.perm, [⟨1⟩]) + restoreSuccessfulContractCallState s₀ s₂ varstore + ByteArray.empty inOffset inSize outOffset outSize | _ => .error .InvalidArguments -- Incorrect number of arguments, this case should be impossible if the Yul code is parsed correctly. Guaranteed by the compiler. | .CALLCODE => match args with - | _ :: address_arg :: value :: inOffset :: inSize :: outOffset :: outSize :: _ => - if ¬s₀.executionEnv.perm ∧ value ≠ ⟨0⟩ then throw .StaticModeViolation + | gas :: address_arg :: value :: inOffset :: inSize :: outOffset :: outSize :: _ => let address := AccountAddress.ofUInt256 address_arg + let s₀Accessed := addAccessedAccount s₀ address let calldata₁ := s₀.toMachineState.memory.readWithPadding inOffset.toNat inSize.toNat - let accountMap₁Opt := (s₀.sharedState.accountMap.transferBalance .Yul s₀.executionEnv.codeOwner s₀.executionEnv.codeOwner value) + let callGas : UInt256 := + .ofNat <| + EvmYul.EVM.Ccallgas address s₀.executionEnv.codeOwner value gas + s₀.sharedState.accountMap s₀.toMachineState s₀.toState.substate + let accountMap₁Opt := + callTransferAccountMap? + s₀.sharedState.accountMap + s₀.executionEnv.codeOwner + s₀.executionEnv.codeOwner + value match accountMap₁Opt with | .none => - buildContractCallEmptyReturnState s₀ .none ⟨0⟩ -- Insufficient funds: return 0 to indicate error, with empty return data + buildContractCallEmptyReturnState s₀Accessed .none + inOffset inSize outOffset outSize ⟨0⟩ -- Insufficient funds: return 0 to indicate error, with empty return data | .some accountMap₁ => if s₀.executionEnv.depth ≥ 1024 then - buildContractCallEmptyReturnState s₀ accountMap₁ ⟨0⟩ -- Reached depth limit: return 0 to indicate error, with empty return data + buildContractCallEmptyReturnState s₀Accessed .none + inOffset inSize outOffset outSize ⟨0⟩ -- Reached depth limit: return 0 to indicate error, with empty return data else - match s₀ with + match s₀Accessed with | .OutOfFuel => .error .OutOfFuel | .Checkpoint j => .ok (.Checkpoint j, [⟨0⟩]) | .Ok sharedState varstore => - match s₀.sharedState.accountMap.find? address with + match EvmYul.toExecute .Yul s₀.sharedState.accountMap address with + | .Precompiled precompiled => + let executionEnv₁ := { sharedState.executionEnv with + calldata := calldata₁, + code := default, + codeOwner := s₀.executionEnv.codeOwner, + source := s₀.executionEnv.codeOwner, + weiValue := value + depth := s₀.executionEnv.depth + 1 + } + buildPrecompiledContractCallState + s₀Accessed accountMap₁ precompiled callGas + executionEnv₁ inOffset inSize outOffset outSize + | .Code _ => + match s₀.sharedState.accountMap.find? address with | .none => - buildContractCallEmptyReturnState s₀ accountMap₁ ⟨1⟩ -- No contract at the provided address, return 1 to indicate success, with empty return data. (Like STOP opcode). + buildContractCallEmptyReturnState s₀Accessed accountMap₁ + inOffset inSize outOffset outSize ⟨1⟩ -- No contract at the provided address, return 1 to indicate success, with empty return data. (Like STOP opcode). | .some yulContract => let executionEnv₁ := { sharedState.executionEnv with calldata := calldata₁, @@ -279,73 +450,61 @@ def primCall (fuel : ℕ) (s₀ : State) (prim : Operation .Yul) (args : List Li } let sharedState₁ := { sharedState with executionEnv := executionEnv₁, - memory := ByteArray.mk #[], + toMachineState := + EvmYul.MachineState.freshExternalCall callGas, accountMap := accountMap₁ } let s₁ : State := .Ok sharedState₁ default - match callDispatcher fuel₁ yulContract.code s₁ with + match callDispatcher fuel₁ (some yulContract.code) s₁ with | .error (.YulHalt s₂ _) => - let memory₃ := s₂.toMachineState.H_return.copySlice 0 s₀.toMachineState.memory outOffset.toNat (min outSize.toNat s₂.toMachineState.H_return.size) - match s₂ with - | .OutOfFuel => .error .OutOfFuel - | .Checkpoint j => .ok (.Checkpoint j, [⟨0⟩]) - | .Ok sharedState₂ _ => - -- Restore ExecutionEnv - let executionEnv₃ := { sharedState₂.executionEnv with - calldata := default, - code := s₀.executionEnv.code, - codeOwner := s₀.executionEnv.codeOwner, - source := s₀.executionEnv.source, - weiValue := s₀.executionEnv.weiValue, - } - let sharedState₃ := { sharedState₂ with - memory := memory₃, - returnData := s₂.toMachineState.H_return, - H_return := ByteArray.empty, - executionEnv := executionEnv₃ - } - .ok (.Ok sharedState₃ varstore, [⟨1⟩]) + restoreSuccessfulContractCallState s₀ s₂ varstore + s₂.toMachineState.H_return + inOffset inSize outOffset outSize + | .error (.Revert s₂) => + restoreRevertedContractCallState s₀Accessed s₂ + inOffset inSize outOffset outSize | .error e => .error e | .ok (s₂, _) => - let memory₃ := s₂.toMachineState.H_return.copySlice 0 s₀.toMachineState.memory outOffset.toNat (min outSize.toNat s₂.toMachineState.H_return.size) - match s₂ with - | .OutOfFuel => .error .OutOfFuel - | .Checkpoint j => .ok (.Checkpoint j, [⟨0⟩]) - | .Ok sharedState₂ _ => - -- Restore ExecutionEnv - let executionEnv₃ := { sharedState₂.executionEnv with - calldata := default, - code := s₀.executionEnv.code, - codeOwner := s₀.executionEnv.codeOwner, - source := s₀.executionEnv.source, - weiValue := s₀.executionEnv.weiValue, - } - let sharedState₃ := { sharedState₂ with - memory := memory₃, - returnData := s₂.toMachineState.H_return, - H_return := ByteArray.empty, - executionEnv := executionEnv₃ - } - .ok (.Ok sharedState₃ varstore, [⟨1⟩]) + restoreSuccessfulContractCallState s₀ s₂ varstore + ByteArray.empty inOffset inSize outOffset outSize | _ => .error .InvalidArguments -- Incorrect number of arguments, this case should be impossible if the Yul code is parsed correctly. Guaranteed by the compiler. | .DELEGATECALL => match args with - | _ :: address_arg :: inOffset :: inSize :: outOffset :: outSize :: _ => + | gas :: address_arg :: inOffset :: inSize :: outOffset :: outSize :: _ => let address := AccountAddress.ofUInt256 address_arg + let s₀Accessed := addAccessedAccount s₀ address let calldata₁ := s₀.toMachineState.memory.readWithPadding inOffset.toNat inSize.toNat + let callGas : UInt256 := + .ofNat <| + EvmYul.EVM.Ccallgas address s₀.executionEnv.codeOwner ⟨0⟩ gas + s₀.sharedState.accountMap s₀.toMachineState s₀.toState.substate if s₀.executionEnv.depth ≥ 1024 then - buildContractCallEmptyReturnState s₀ .none ⟨0⟩ -- Reached depth limit: return 0 to indicate error, with empty return data + buildContractCallEmptyReturnState s₀Accessed .none + inOffset inSize outOffset outSize ⟨0⟩ -- Reached depth limit: return 0 to indicate error, with empty return data else - match s₀ with + match s₀Accessed with | .OutOfFuel => .error .OutOfFuel | .Checkpoint j => .ok (.Checkpoint j, [⟨0⟩]) | .Ok sharedState varstore => - match s₀.sharedState.accountMap.find? address with + match EvmYul.toExecute .Yul s₀.sharedState.accountMap address with + | .Precompiled precompiled => + let executionEnv₁ := { sharedState.executionEnv with + calldata := calldata₁, + code := default, + codeOwner := s₀.executionEnv.codeOwner + depth := s₀.executionEnv.depth + 1 + } + buildPrecompiledContractCallState + s₀Accessed s₀.sharedState.accountMap precompiled callGas + executionEnv₁ inOffset inSize outOffset outSize + | .Code _ => + match s₀.sharedState.accountMap.find? address with | .none => - buildContractCallEmptyReturnState s₀ .none ⟨1⟩ -- No contract at the provided address, return 1 to indicate success, with empty return data. (Like STOP opcode). + buildContractCallEmptyReturnState s₀Accessed .none + inOffset inSize outOffset outSize ⟨1⟩ -- No contract at the provided address, return 1 to indicate success, with empty return data. (Like STOP opcode). | .some yulContract => let executionEnv₁ := { sharedState.executionEnv with calldata := calldata₁, @@ -355,54 +514,23 @@ def primCall (fuel : ℕ) (s₀ : State) (prim : Operation .Yul) (args : List Li } let sharedState₁ := { sharedState with executionEnv := executionEnv₁, - memory := ByteArray.mk #[] + toMachineState := + EvmYul.MachineState.freshExternalCall callGas } let s₁ : State := .Ok sharedState₁ default - match callDispatcher fuel₁ yulContract.code s₁ with + match callDispatcher fuel₁ (some yulContract.code) s₁ with | .error (.YulHalt s₂ _) => - let memory₃ := s₂.toMachineState.H_return.copySlice 0 s₀.toMachineState.memory outOffset.toNat (min outSize.toNat s₂.toMachineState.H_return.size) - match s₂ with - | .OutOfFuel => .error .OutOfFuel - | .Checkpoint j => .ok (.Checkpoint j, [⟨0⟩]) - | .Ok sharedState₂ _ => - -- Restore ExecutionEnv - let executionEnv₃ := { sharedState₂.executionEnv with - calldata := default, - code := s₀.executionEnv.code, - codeOwner := s₀.executionEnv.codeOwner, - source := s₀.executionEnv.source, - weiValue := s₀.executionEnv.weiValue, - } - let sharedState₃ := { sharedState₂ with - memory := memory₃, - returnData := s₂.toMachineState.H_return, - H_return := ByteArray.empty, - executionEnv := executionEnv₃ - } - .ok (.Ok sharedState₃ varstore, [⟨1⟩]) + restoreSuccessfulContractCallState s₀ s₂ varstore + s₂.toMachineState.H_return + inOffset inSize outOffset outSize + | .error (.Revert s₂) => + restoreRevertedContractCallState s₀Accessed s₂ + inOffset inSize outOffset outSize | .error e => .error e | .ok (s₂, _) => - let memory₃ := s₂.toMachineState.H_return.copySlice 0 s₀.toMachineState.memory outOffset.toNat (min outSize.toNat s₂.toMachineState.H_return.size) - match s₂ with - | .OutOfFuel => .error .OutOfFuel - | .Checkpoint j => .ok (.Checkpoint j, [⟨0⟩]) - | .Ok sharedState₂ _ => - -- Restore ExecutionEnv - let executionEnv₃ := { sharedState₂.executionEnv with - calldata := default, - code := s₀.executionEnv.code, - codeOwner := s₀.executionEnv.codeOwner, - source := s₀.executionEnv.source, - weiValue := s₀.executionEnv.weiValue, - } - let sharedState₃ := { sharedState₂ with - memory := memory₃, - returnData := s₂.toMachineState.H_return, - H_return := ByteArray.empty, - executionEnv := executionEnv₃ - } - .ok (.Ok sharedState₃ varstore, [⟨1⟩]) + restoreSuccessfulContractCallState s₀ s₂ varstore + ByteArray.empty inOffset inSize outOffset outSize | _ => .error .InvalidArguments -- Incorrect number of arguments, this case should be impossible if the Yul code is parsed correctly. Guaranteed by the compiler. | _ => match step prim .none s₀ args with | .ok (s, lit) => .ok (s, lit.toList) @@ -449,7 +577,7 @@ def primCall (fuel : ℕ) (s₀ : State) (prim : Operation .Yul) (args : List Li match fOpt with | .none => .error (.MissingContractFunction (yulFunctionNameOption.getD ".none")) | .some f => - let s₁ := 👌 s.initcall f.params args + let s₁ := 👌 s.initcall f.params f.rets args match exec fuel' (.Block f.body) codeOverride s₁ with | .error e => .error e | .ok s₂ => @@ -466,7 +594,7 @@ def primCall (fuel : ℕ) (s₀ : State) (prim : Operation .Yul) (args : List Li | 0 => .error .OutOfFuel | .succ fuel' => let f := FunctionDefinition.Def [] [] [s.executionEnv.code.dispatcher] - let s₁ := 👌 s.initcall f.params [] + let s₁ := 👌 s.initcall f.params f.rets [] match exec fuel' (.Block f.body) codeOverride s₁ with | .error e => .error e | .ok s₂ => @@ -499,31 +627,24 @@ def primCall (fuel : ℕ) (s₀ : State) (prim : Operation .Yul) (args : List Li | .succ fuel' => multifill' vars (call fuel' args yulFunctionName codeOverride s) | .error e => .error e - /-- - `execSwitchCases` executes each case of a `switch` statement. - -/ - def execSwitchCases (fuel : Nat) (codeOverride : Option YulContract) (s : State) : List (Literal × List Stmt) → Except Yul.Exception (List (Literal × (Except Yul.Exception State))) - | [] => .ok [] - | ((val, stmts) :: cases') => - match fuel with - | 0 => .error .OutOfFuel - | .succ fuel' => - match exec fuel' (.Block stmts) codeOverride s with - | .error (.YulHalt s₂ v) => - match execSwitchCases fuel' codeOverride s cases' with - | .error e => .error e - | .ok s₃ => - .ok ((val, .error (.YulHalt s₂ v)) :: s₃) - | .error e => - match execSwitchCases fuel' codeOverride s cases' with - | .error e => .error e - | .ok s₃ => - .ok ((val, .error e) :: s₃) - | .ok s₂ => - match execSwitchCases fuel' codeOverride s cases' with - | .error e => .error e - | .ok s₃ => - .ok ((val, .ok s₂) :: s₃) + def evalValues (fuel : Nat) (expr : Expr) (codeOverride : Option YulContract) (s : State) : Except Yul.Exception (State × List Literal) := + match fuel with + | 0 => .error .OutOfFuel + | .succ fuel' => + match expr with + | .Call (Sum.inl prim) args => + match reverse' (evalArgs fuel' args.reverse codeOverride s) with + | .ok (s, args) => primCall fuel' s prim args + | .error e => .error e + | .Call (Sum.inr yulFunctionName) args => + match reverse' (evalArgs fuel' args.reverse codeOverride s) with + | .ok (s, args) => call fuel' args yulFunctionName codeOverride s + | .error e => .error e + | .Var id => + match s.lookup? id with + | .some val => .ok (s, [val]) + | .none => .error (.UnknownIdentifier id) + | .Lit val => .ok (s, [val]) /-- `eval` evaluates an expression. @@ -531,24 +652,22 @@ def primCall (fuel : ℕ) (s₀ : State) (prim : Operation .Yul) (args : List Li - calls evaluated here are assumed to have coarity 1 -/ def eval (fuel : Nat) (expr : Expr) (codeOverride : Option YulContract) (s : State) : Except Yul.Exception (State × Literal) := + head' (evalValues fuel expr codeOverride s) + + def execSeq (fuel : Nat) (stmts : List Stmt) (codeOverride : Option YulContract) (s : State) : Except Yul.Exception State := match fuel with | 0 => .error .OutOfFuel | .succ fuel' => - match expr with - - -- We hit these two cases (`PrimCall` and `Call`) when evaluating: - -- - -- 1. f() (expression statements) - -- 2. g(f()) (calls in function arguments) - -- 3. if f() {...} (if conditions) - -- 4. for {...} f() ... (for conditions) - -- 5. switch f() ... (switch conditions) - - | .Call (Sum.inl prim) args => evalPrimCall fuel' prim (reverse' (evalArgs fuel' args.reverse codeOverride s)) - | .Call (Sum.inr yulFunctionName) args => - evalCall fuel' yulFunctionName codeOverride (reverse' (evalArgs fuel' args.reverse codeOverride s)) - | .Var id => .ok (s, s[id]!) - | .Lit val => .ok (s, val) + match stmts with + | [] => .ok s + | stmt :: stmts => + match exec fuel' stmt codeOverride s with + | .error e => .error e + | .ok s₁ => + match s₁ with + | .Ok _ _ => execSeq fuel' stmts codeOverride s₁ + | .OutOfFuel => .ok s₁ + | .Checkpoint _ => .ok s₁ /-- `exec` executs a single statement. @@ -558,24 +677,23 @@ def primCall (fuel : ℕ) (s₀ : State) (prim : Operation .Yul) (args : List Li | 0 => .error .OutOfFuel | .succ fuel' => match stmt with - | .Block [] => .ok s - | .Block (stmt :: stmts) => - let s₁ := exec fuel' stmt codeOverride s - match s₁ with - | .error e => .error e - | .ok s₁ => exec fuel' (.Block stmts) codeOverride s₁ + | .Block stmts => + match execSeq fuel' stmts codeOverride s with + | .error e => .error e + | .ok s₁ => .ok (s₁.restrictStoreTo s.store) | .Let vars exprOption => + match checkDeclaration s vars with + | .error e => .error e + | .ok () => match exprOption with - | .none => .ok (List.foldr (λ var s ↦ s.insert var ⟨0⟩) s vars) - | .some expr => - match expr with - | .Call (Sum.inl prim) args => - execPrimCall fuel' prim vars (reverse' (evalArgs fuel' args.reverse codeOverride s)) - | .Call (Sum.inr yulFunctionName) args => - execCall fuel' yulFunctionName vars codeOverride (reverse' (evalArgs fuel' args.reverse codeOverride s)) - | .Var identifier => .ok (s.insert vars.head! s[identifier]!) -- It should be safe to call head! here if the Yul code is parsed correctly. - | .Lit literal => .ok (s.insert vars.head! literal) -- It should be safe to call head! here if the Yul code is parsed correctly. + | .none => .ok (s.zeroFill vars) + | .some expr => multifill' vars (evalValues fuel' expr codeOverride s) + + | .Assign vars expr => + match checkAssignment s vars with + | .error e => .error e + | .ok () => multifill' vars (evalValues fuel' expr codeOverride s) | .If cond body => match eval fuel' cond codeOverride s with @@ -599,13 +717,7 @@ def primCall (fuel : ℕ) (s₀ : State) (prim : Operation .Yul) (args : List Li match eval fuel' cond codeOverride s with | .error e => .error e | .ok (s₁, cond) => - match execSwitchCases fuel' codeOverride s₁ cases' with - | .error e => .error e - | .ok branches => - match exec fuel' (.Block default') codeOverride s₁ with - | .error e => .error e - | .ok s₂ => - (List.foldr (λ (valᵢ, sᵢ) s ↦ if valᵢ = cond then sᵢ else s) (.ok s₂) branches) + exec fuel' (.Block (selectSwitchCase cond default' cases')) codeOverride s₁ -- A `Break` or `Continue` in the pre or post is a compiler error, -- so we assume it can't happen and don't modify the state in these @@ -642,11 +754,15 @@ def primCall (fuel : ℕ) (s₀ : State) (prim : Operation .Yul) (args : List Li | .error e => .error e | .ok s₃ => let s₄ := s₃✏️⟦s⟧? - match exec fuel' (.For cond post body) codeOverride s₄ with - | .error e => .error e - | .ok s₅ => - let s₆ := s₅✏️⟦s⟧? - .ok s₆ + match s₃ with + | .OutOfFuel => .ok s₄ + | .Checkpoint (.Leave _ _) => .ok s₄ + | _ => + match exec fuel' (.For cond post body) codeOverride s₄ with + | .error e => .error e + | .ok s₅ => + let s₆ := s₅✏️⟦s⟧? + .ok s₆ end def execTopLevel (fuel : Nat) (stmt : Stmt) (s : State) : State := @@ -659,8 +775,10 @@ def execTopLevel (fuel : Nat) (stmt : Stmt) (s : State) : State := | .error (.MissingContract _) => default | .error (.MissingContractFunction _) => default -- We do not model fallback functions | .error .InvalidExpression => default + | .error (.UnknownIdentifier _) => default + | .error (.DuplicateDeclaration _) => default | .error .YulEXTCODESIZENotImplemented => default - | .error .Revert => s + | .error (.Revert _) => s | .error (.YulHalt s _) => s | .ok s => s diff --git a/EvmYul/Yul/StateOps.lean b/EvmYul/Yul/StateOps.lean index 357d782..a0d5924 100644 --- a/EvmYul/Yul/StateOps.lean +++ b/EvmYul/Yul/StateOps.lean @@ -16,6 +16,19 @@ def multifill (vars : List Identifier) (vals : List Literal) : Yul.State → Yul | s@(Ok _ _) => (List.zip vars vals).foldr (λ (var, val) s ↦ s.insert var val) s | s => s +def zeroFill (vars : List Identifier) : Yul.State → Yul.State := + vars.foldr (λ var s ↦ s.insert var ⟨0⟩) + +def restrictVarStore (store scope : VarStore) : VarStore := + store.sdiff (store.sdiff scope) + +def restrictStoreTo (scope : VarStore) : Yul.State → Yul.State + | Ok sharedState store => Ok sharedState (restrictVarStore store scope) + | Checkpoint (.Continue sharedState store) => Checkpoint (.Continue sharedState (restrictVarStore store scope)) + | Checkpoint (.Break sharedState store) => Checkpoint (.Break sharedState (restrictVarStore store scope)) + | Checkpoint (.Leave sharedState store) => Checkpoint (.Leave sharedState (restrictVarStore store scope)) + | s => s + -- | Overwrite the EvmYul.Yul.State state of some state. def setSharedState (sharedState : EvmYul.SharedState .Yul) : Yul.State → Yul.State | Ok _ store => Ok sharedState store @@ -53,10 +66,11 @@ def diverge : Yul.State → Yul.State | s => s -- | Initialize function parameters and return values in varstore. -def initcall (params : List Identifier) (args : List Literal) : Yul.State → Yul.State +def initcall (params rets : List Identifier) (args : List Literal) : Yul.State → Yul.State | s@(Ok _ _) => let s₁ := s.setStore default - s₁.multifill params args + let s₂ := s₁.zeroFill rets + s₂.multifill params args | s => s -- | Since it literally does not matter what happens if the state is non-Ok, we just use the default. @@ -93,13 +107,16 @@ def overwrite? (s s' : Yul.State) : Yul.State := -- STATE QUERIES -- ============================================================================ --- | Lookup the literal associated with an variable in the varstore, returning 0 if not found. +def lookup? (var : Identifier) : Yul.State → Option Literal + | Ok _ store => store.lookup var + | Checkpoint (.Continue _ store) => store.lookup var + | Checkpoint (.Break _ store) => store.lookup var + | Checkpoint (.Leave _ store) => store.lookup var + | _ => .none + +-- | Lookup the literal associated with a variable in the varstore, returning 0 if not found. def lookup! (var : Identifier) : Yul.State → Literal - | Ok _ store => (store.lookup var).get! - | Checkpoint (.Continue _ store) => (store.lookup var).get! - | Checkpoint (.Break _ store) => (store.lookup var).get! - | Checkpoint (.Leave _ store) => (store.lookup var).get! - | _ => ⟨0⟩ + | s => (s.lookup? var).getD ⟨0⟩ -- ============================================================================ -- STATE NOTATION @@ -150,7 +167,7 @@ notation:65 s:64 "🏪⟦" s' "⟧" => Yul.State.setStore s s' notation:65 s:64 "🇪⟦" sharedState "⟧" => Yul.State.setSharedState sharedState s notation:65 "🪫" s:64 => Yul.State.diverge s notation:65 "👌" s:64 => Yul.State.mkOk s -notation:65 s:64 "☎️⟦" params "," args "⟧" => Yul.State.initcall params args s +notation:65 s:64 "☎️⟦" params "," rets "," args "⟧" => Yul.State.initcall params rets args s notation:65 s:64 "✏️⟦" s' "⟧?" => Yul.State.overwrite? s s' notation:64 (priority := high) "🧟" s:max => Yul.State.reviveJump s diff --git a/EvmYul/Yul/YulNotation.lean b/EvmYul/Yul/YulNotation.lean index 5863ae6..65a30ea 100644 --- a/EvmYul/Yul/YulNotation.lean +++ b/EvmYul/Yul/YulNotation.lean @@ -273,7 +273,7 @@ partial def translateStmt (stmt : TSyntax `stmt) : TermElabM Term := let (lit, cs) := litCase; `(($lit, [$cs,*])) let switchCases ← lits.zip cases |>.mapM f let dflt ← match dflts with - | .none => `([.Break]) + | .none => `([]) | .some dflts => `([$(←dflts.mapM translateStmt),*]) `(Stmt.Switch $expr [$switchCases,*] $dflt) @@ -309,7 +309,7 @@ partial def translateStmt (stmt : TSyntax `stmt) : TermElabM Term := | `(stmt| $ids:ident,* := $expr:expr) => do let ids' := (ids : TSyntaxArray _).map translateIdent let expr ← translateExpr expr - `(Stmt.Let [$ids',*] (.some $expr)) + `(Stmt.Assign [$ids',*] $expr) -- ExprStmt | `(stmt| $expr:expr) => do @@ -373,10 +373,10 @@ example : = Stmt.Break := rfl example : = Stmt.Let ["a", "b"] (.some (.Call (Sum.inr "f") [Expr.Lit ⟨42⟩])) := rfl example : = Stmt.Let ["a"] .none := rfl example : = Stmt.Let ["a"] (.some (.Lit ⟨5⟩)) := rfl -example : = Stmt.Let ["a", "b"] (.some (.Call (Sum.inr "f") [Expr.Lit ⟨42⟩])) := rfl -example : = Stmt.Let ["a"] (.some (.Lit ⟨42⟩)) := rfl +example : = Stmt.Assign ["a", "b"] (.Call (Sum.inr "f") [Expr.Lit ⟨42⟩]) := rfl +example : = Stmt.Assign ["a"] (.Lit ⟨42⟩) := rfl -example : = Stmt.Let ["c"] (.some (Expr.Call (Sum.inl (Operation.StopArith Operation.SAOp.ADD)) [Expr.Var "a", Expr.Var "b"])) := rfl +example : = Stmt.Assign ["c"] (Expr.Call (Sum.inl (Operation.StopArith Operation.SAOp.ADD)) [Expr.Var "a", Expr.Var "b"]) := rfl example : = Stmt.Let ["c"] (.some (Expr.Call (Sum.inl (Operation.StopArith Operation.SAOp.SUB)) [Expr.Var "a", Expr.Var "b"])) := rfl example : = Stmt.Let ["a"] (.some (.Lit ⟨5⟩)) := rfl example : @@ -438,6 +438,11 @@ example : = Stmt.Switch (Expr.Var "a") [(⟨42⟩, [.Continue])] [.Break] := rfl +example : = Stmt.Switch (.Lit ⟨1⟩) [(⟨2⟩, [])] [] := rfl + example : = Stmt.Let ["a", "b", "c"] .none := rfl example : = Stmt.ExprStmtCall (.Call (Sum.inl (.System (.REVERT))) [(Expr.Lit ⟨0⟩), (Expr.Lit ⟨0⟩)]) := rfl example : = Stmt.If (.Lit ⟨1⟩) [Stmt.Leave] := rfl diff --git a/EvmYul/Yul/YulSemanticsTests/Main.lean b/EvmYul/Yul/YulSemanticsTests/Main.lean index 6387de3..90a0782 100644 --- a/EvmYul/Yul/YulSemanticsTests/Main.lean +++ b/EvmYul/Yul/YulSemanticsTests/Main.lean @@ -1244,6 +1244,177 @@ def test₅ := | .error e => repr e | .ok s => s!"{s.toSharedState.accountMap.toList.map (fun (a : AccountAddress × Account .Yul) => repr a.1 ++ " " ++ repr a.2.storage.toList)}" +def test₆ := + let stmt : Stmt := + .Switch (.Lit ⟨1⟩) + [(⟨1⟩, [])] + [.ExprStmtCall + (.Call (Sum.inl (.System (.REVERT))) [.Lit ⟨0⟩, .Lit ⟨0⟩])] + match exec 99 stmt .none stateEg₁ with + | .error e => repr e + | .ok _ => "selected" + +def showVar? (name : Identifier) : State → String + | .Ok _ store => + match store.lookup name with + | .some value => toString value.toNat + | .none => "none" + | .Checkpoint _ => "checkpoint" + | .OutOfFuel => "out-of-fuel" + +def showExecVar (name : Identifier) (stmt : Stmt) (s : State) : String := + match exec 99 stmt .none s with + | .error e => toString (repr e) + | .ok s => showVar? name s + +def showExecMode (stmt : Stmt) (s : State) : String := + match exec 99 stmt .none s with + | .error e => toString (repr e) + | .ok (.Ok _ _) => "regular" + | .ok (.Checkpoint (.Break _ _)) => "break" + | .ok (.Checkpoint (.Continue _ _)) => "continue" + | .ok (.Checkpoint (.Leave _ _)) => "leave" + | .ok .OutOfFuel => "out-of-fuel" + +def test₇ := + let stmt : Stmt := + .Block + [ .Block [.Let ["x"] (.some (.Lit ⟨1⟩))] + , .Let ["y"] (.some (.Var "x")) + ] + showExecVar "y" stmt stateEg₁ + +def test₈ := + let stmt : Stmt := + .Block + [ .Let ["x"] (.some (.Lit ⟨1⟩)) + , .Block [.Let ["x"] (.some (.Lit ⟨2⟩))] + , .Let ["y"] (.some (.Var "x")) + ] + showExecVar "y" stmt stateEg₁ + +def stateWithX : State := + .Ok stateEg₁.toSharedState ((∅ : VarStore).insert "x" ⟨1⟩) + +def test₉ := + showExecVar "x" (.Assign ["x"] (.Lit ⟨2⟩)) stateWithX + +def test₁₀ := + showExecVar "x" (.Assign ["x"] (.Lit ⟨2⟩)) stateEg₁ + +def auditAddressUInt256 : UInt256 := ⟨100⟩ +def auditCalleeAddressUInt256 : UInt256 := ⟨101⟩ +def auditAddress := AccountAddress.ofUInt256 auditAddressUInt256 +def auditCalleeAddress := AccountAddress.ofUInt256 auditCalleeAddressUInt256 + +def auditStateWithContract (code : YulContract) : State := + let account : Account .Yul := + { code := code + , balance := ⟨1000⟩ + , nonce := ⟨0⟩ + , storage := ∅ + , tstorage := ∅ + } + let accountMap : AccountMap .Yul := (∅ : AccountMap .Yul).insert auditAddress account + let sharedState : SharedState .Yul := + { (Inhabited.default : SharedState .Yul) with + accountMap := accountMap + executionEnv := + { (Inhabited.default : ExecutionEnv .Yul) with + codeOwner := auditAddress + code := code + perm := true + } + } + .Ok sharedState ∅ + +def returnInitContract : YulContract := + { dispatcher := .Block [] + , functions := + (∅ : Finmap (fun (_ : YulFunctionName) ↦ Yul.Ast.FunctionDefinition)) + |>.insert "f" (.Def [] ["r"] []) + } + +def test₁₁ := + let stmt : Stmt := .Let ["x"] (.some (.Call (Sum.inr "f") [])) + showExecVar "x" stmt (auditStateWithContract returnInitContract) + +def callRevertState : State := + let callerCode : YulContract := + { dispatcher := .Block [] + , functions := ∅ + } + let calleeCode : YulContract := + { dispatcher := + .ExprStmtCall + (.Call (Sum.inl (.System (.REVERT))) [.Lit ⟨0⟩, .Lit ⟨0⟩]) + , functions := ∅ + } + let callerAccount : Account .Yul := + { code := callerCode + , balance := ⟨1000⟩ + , nonce := ⟨0⟩ + , storage := ∅ + , tstorage := ∅ + } + let calleeAccount : Account .Yul := + { code := calleeCode + , balance := ⟨0⟩ + , nonce := ⟨0⟩ + , storage := ∅ + , tstorage := ∅ + } + let accountMap : AccountMap .Yul := + ((∅ : AccountMap .Yul).insert auditAddress callerAccount) + |>.insert auditCalleeAddress calleeAccount + let sharedState : SharedState .Yul := + { (Inhabited.default : SharedState .Yul) with + accountMap := accountMap + executionEnv := + { (Inhabited.default : ExecutionEnv .Yul) with + codeOwner := auditAddress + code := callerCode + perm := true + } + } + .Ok sharedState ∅ + +def test₁₂ := + let stmt : Stmt := + .Let ["ok"] + (.some + (.Call (Sum.inl (.System (.CALL))) + [ .Lit ⟨100000⟩ + , .Lit auditCalleeAddressUInt256 + , .Lit ⟨7⟩ + , .Lit ⟨0⟩ + , .Lit ⟨0⟩ + , .Lit ⟨0⟩ + , .Lit ⟨0⟩ + ])) + showExecVar "ok" stmt callRevertState + +def selfdestructState : State := + match callRevertState with + | .Ok sharedState _ => .Ok sharedState ((∅ : VarStore).insert "after" ⟨0⟩) + | s => s + +def test₁₃ := + let stmt : Stmt := + .Block + [ .ExprStmtCall + (.Call (Sum.inl (.System (.SELFDESTRUCT))) [.Lit auditCalleeAddressUInt256]) + , .Assign ["after"] (.Lit ⟨1⟩) + ] + showVar? "after" (execTopLevel 99 stmt selfdestructState) + +def test₁₄ := + let stmt : Stmt := + showExecMode stmt stateEg₁ + end Yul @@ -1259,3 +1430,12 @@ def main : IO Unit := do IO.println (s!"test₃: {test₃} -- " ++ (if s!"{test₃}" = "StaticModeViolation" then "Success" else "Failure")) IO.println (s!"test₄: {test₄} -- " ++ (if s!"{test₄}" = "[1 [], 2 [(0, 5)], 3 [], 4 []]" then "Success" else "Failure")) IO.println (s!"test₅: {test₅} -- " ++ (if s!"{test₅}" = "[1 [], 2 [(0, 5)], 3 [], 4 []]" then "Success" else "Failure")) + IO.println (s!"test₆: {test₆} -- " ++ (if s!"{test₆}" = "selected" then "Success" else "Failure")) + IO.println (s!"test₇: {test₇} -- " ++ (if s!"{test₇}" = "UnknownIdentifier: x" then "Success" else "Failure")) + IO.println (s!"test₈: {test₈} -- " ++ (if s!"{test₈}" = "DuplicateDeclaration: x" then "Success" else "Failure")) + IO.println (s!"test₉: {test₉} -- " ++ (if s!"{test₉}" = "2" then "Success" else "Failure")) + IO.println (s!"test₁₀: {test₁₀} -- " ++ (if s!"{test₁₀}" = "UnknownIdentifier: x" then "Success" else "Failure")) + IO.println (s!"test₁₁: {test₁₁} -- " ++ (if s!"{test₁₁}" = "0" then "Success" else "Failure")) + IO.println (s!"test₁₂: {test₁₂} -- " ++ (if s!"{test₁₂}" = "0" then "Success" else "Failure")) + IO.println (s!"test₁₃: {test₁₃} -- " ++ (if s!"{test₁₃}" = "0" then "Success" else "Failure")) + IO.println (s!"test₁₄: {test₁₄} -- " ++ (if s!"{test₁₄}" = "regular" then "Success" else "Failure")) diff --git a/README.md b/README.md index fbc60f0..72d3531 100644 --- a/README.md +++ b/README.md @@ -99,4 +99,4 @@ These tests are defined in `EvmYul/Yul/YulSemanticsTests/Main.lean`. ## SELFDESTRUCT -- Halting for `SELFDESTRUCT` is not implemented and the semantics for `SELFDESTRUCT` have limitations, such as not triggering the fallback function in a contract that is the recipient of the ether from the contract the self-destructs. We may remove the semantics for `SELFDESTRUCT` once its status changes from deprecated to not being supported. \ No newline at end of file +- Yul `SELFDESTRUCT` halts execution after applying the modelled account and substate effects. The semantics for `SELFDESTRUCT` still have limitations, such as not triggering the fallback function in a contract that is the recipient of the ether from the contract the self-destructs. We may remove the semantics for `SELFDESTRUCT` once its status changes from deprecated to not being supported.