diff --git a/.kiro/specs/strata-solidity-next/requirements.md b/.kiro/specs/strata-solidity-next/requirements.md new file mode 100644 index 0000000..58b8c34 --- /dev/null +++ b/.kiro/specs/strata-solidity-next/requirements.md @@ -0,0 +1,161 @@ +# Requirements Document — `strata-solidity-next` + +## Introduction + +This document holds the requirements that change behavior relative to the +**retrospective baseline** in +[`../strata-solidity-baseline/requirements.md`](../strata-solidity-baseline/requirements.md). +The baseline describes what the code did when it was written and introduces +no new behavior; this document is the only place where its `GAP-*` items +are closed. + +Every requirement below cites the baseline IDs it modifies or closes, as +`CONTRIBUTING.md` requires. Baseline requirements not cited here are +unchanged. + +--- + +### Requirement 1 — Inheritance: a contract is verified with its inherited members + +**Closes:** `GAP-009` (multi-contract inheritance with virtual dispatch), +except for the cases REQ-NEXT-SOL-022..025 report or reject. +**Modifies:** `REQ-SOL-004` (single inheritance via `is`), +`REQ-SOL-005` (diamond inheritance via `baseContracts`), +`REQ-SOL-006` (virtual dispatch across contracts). + +**User Story:** As a developer verifying a contract that inherits from +another, I want what it inherits to be part of what is verified, so that a +contract built from base contracts can be specified and proven at all. + +**Context.** The baseline's `REQ-SOL-004` and `REQ-SOL-005` say inheritance +is accepted "flattened at the AST level", and `design.md` §12.9 attributes +that flattening to `solast.py`. Neither held once the in-Lean frontend +replaced the Python one: solc's AST lists only the members written in a +contract, with its bases named in `baseContracts`, and +`ContractTranslator.translateContract` read only a contract's own members, +so any use of an inherited member failed to translate. These requirements +replace that behavior. + +#### Acceptance Criteria — Flattening + +1. REQ-NEXT-SOL-001. THE Solidity_Translator SHALL verify a contract as the + flattening of its transitive bases and itself, so that every inherited + member resolves in the derived contract's own context (its `self` + parameter, its state parameters, its invariants). +2. REQ-NEXT-SOL-002. THE Solidity_Translator SHALL order a contract's bases + by solc's C3 linearization (`linearizedBaseContracts`): for + `contract C is B1, …, Bn`, `L(C) = C :: merge(L(Bn), …, L(B1), [Bn, …, B1])`. + Inherited members are taken most base first, the reverse of `L(C)`. +3. REQ-NEXT-SOL-003. WHERE a more derived contract declares a function with + the name and parameter types (data locations aside) of an inherited one, + or a `receive`, `fallback` or modifier of the same name, THE + Solidity_Translator SHALL verify the more derived declaration and not + the inherited one. A function of the same name with other parameter + types is an overload, and both are verified. +4. REQ-NEXT-SOL-004. WHERE a public state variable shares its name with an + inherited function (which its getter overrides), THE Solidity_Translator + SHALL NOT verify that function in the deriving contract. +5. REQ-NEXT-SOL-005. THE Solidity_Translator SHALL merge inherited state + variables together with their initializers, `constant` values, + `immutable` markers and Solidity type names, and inherited structs, + enums and modifier definitions. +6. REQ-NEXT-SOL-006. THE Solidity_Translator SHALL emit a struct's type + definition and its synthetic constructor procedure once, for the + contract that declares the struct. +7. REQ-NEXT-SOL-007. THE Solidity_Translator SHALL continue to verify every + contract of the file on its own, so that a base's specifications are + checked against the base as well as against each contract that inherits + them; an obligation of an inherited function SHALL name the contract it + is checked in (`ensures … (in D)`). +8. REQ-NEXT-SOL-008. WHERE an inherited function calls a virtual function, + THE Solidity_Translator SHALL call the most derived override of it. + +#### Acceptance Criteria — Invariants + +9. REQ-NEXT-SOL-009. THE Solidity_Translator SHALL check a base contract's + `@custom:strata invariant`, whether written in the base's NatSpec or on + one of its state variables, at the external entry points of every + contract that inherits it, under the rules of `REQ-SPEC-*` for the + deriving contract. +10. REQ-NEXT-SOL-010. WHERE a base is an `interface` or a `library`, which + have no state, THE Solidity_Translator SHALL NOT take invariants from + it. + +#### Acceptance Criteria — Constructors + +11. REQ-NEXT-SOL-011. THE Solidity_Translator SHALL run each base + constructor when a deriving contract's constructor (explicit, or the + implicit one that checks the initial state) runs: after every + state-variable initializer, before the deriving constructor and outside + its modifiers, most base first (solc's legacy code generator order). +12. REQ-NEXT-SOL-012. THE Solidity_Translator SHALL run a base constructor + with its own modifiers, in a block that a `return` in it exits, with its + parameters and locals renamed apart from the deriving constructor's. +13. REQ-NEXT-SOL-013. THE Solidity_Translator SHALL bind a base + constructor's parameters to the arguments that the most derived + constructor naming its contract gives (`constructor() Base(7)`), + evaluated most derived first in the scope of that constructor. +14. REQ-NEXT-SOL-014. IF a base constructor's arguments are given in an + inheritance specifier (`is Base(7)`), which the AST the translator reads + does not carry, or not at all (an abstract contract), THEN THE + Solidity_Translator SHALL give its parameters unknown values of their + types. +15. REQ-NEXT-SOL-015. IF a base constructor a constructor runs uses a + struct-valued mapping, THEN THE Solidity_Translator SHALL NOT verify + that constructor, nor the invariants it would establish, and SHALL emit + a warning. + +#### Acceptance Criteria — `super` and explicit base calls + +16. REQ-NEXT-SOL-016. THE Solidity_Translator SHALL resolve `super.f(...)` + to the implementation of `f` that follows, in the linearization of the + contract being verified, the contract in which the call is written: the + contract that defines the function, modifier or base constructor it is + in. +17. REQ-NEXT-SOL-017. THE Solidity_Translator SHALL resolve `Base.f(...)`, + for a base `Base`, to the first implementation of `f` in `L(Base)`. +18. REQ-NEXT-SOL-018. THE Solidity_Translator SHALL emit each overridden + implementation that such a call reaches, directly or through another + one, as an internal procedure of the deriving contract named + `__base__`, and no other. +19. REQ-NEXT-SOL-019. THE Solidity_Translator SHALL bind the named + arguments of such a call by name. +20. REQ-NEXT-SOL-020. IF such a call names an overloaded function, or has + no implementation to call, or reaches an implementation that uses a + struct-valued mapping, THEN THE Solidity_Translator SHALL fail with an + `unsupported` error. + +#### Acceptance Criteria — Reporting and rejection + +21. REQ-NEXT-SOL-021. THE Solidity_Translator SHALL emit the warnings of + `REQ-OUT-*` and `REQ-SPEC-*` for a contract's own declarations only, so + that an inherited declaration is reported once, against the contract + that declares it. +22. REQ-NEXT-SOL-022. IF a contract's linearization includes a contract + that the verified file does not define (an imported base, directly or + through another base), THEN THE Solidity_Translator SHALL emit a warning + naming it and the deriving contract, and SHALL verify the contract + without its members. This is the remaining part of `GAP-009`. +23. REQ-NEXT-SOL-023. IF a contract and one of its bases declare state + variables of the same name (a base's private one), THEN THE + Solidity_Translator SHALL fail with an `unsupported` error: they are + different variables. +24. REQ-NEXT-SOL-024. Note. Overloads whose parameters are all integers or + addresses have the same parameter types in Laurel and are rejected, in + a single contract too (unchanged from the baseline). +25. REQ-NEXT-SOL-025. Note. Base constructors run in solc's legacy order; + the IR code generator (`--via-ir`) initializes each contract's state + variables just before its constructor runs. + +#### Characterization + +26. REQ-NEXT-TEST-001. THE Golden_Harness SHALL cover, each with true and + false properties: inherited state, internal calls, modifiers, + invariants, virtual dispatch and a getter override + (`test/examples/inheritance.sol`); overloads + (`inheritance_overloads.sol`); base constructors + (`inheritance_constructors.sol`); C3 order + (`inheritance_linearization.sol`); `super` and explicit base calls + (`inheritance_super.sol`, `inheritance_diamond.sol`); and the reported + or rejected cases (`inheritance_imported.sol`, + `inheritance_struct_mapping.sol`, `inheritance_shadowed_state.sol`). diff --git a/CHANGELOG.md b/CHANGELOG.md index 7efec9a..0be156f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,34 @@ # Changelog +## 2026-10 — Inheritance + +A contract is verified with what it inherits. Before, `contract Child is +Base` failed to translate (`Resolution failed: 'n' is not defined`) as soon +as it used anything Base declared; only interfaces and abstract contracts +that declare no state worked. See REQ-NEXT-SOL-001..025 in +`.kiro/specs/strata-solidity-next/requirements.md`; fixtures +`test/examples/inheritance*.sol`. + +- Bases are ordered by solc's C3 linearization. Inherited state variables, + functions, modifiers, structs, enums and invariants resolve in the + derived contract's context, and an inherited function calls the most + derived override of a virtual function. An override has the parameter + types of what it overrides; an overload stays. A public state variable + overrides the base function its getter implements. +- Each contract of a file is still verified on its own; an obligation of + an inherited function names the contract it is checked in, `(in D)`. +- Base constructors run when a derived contract deploys: after the + state-variable initializers, outside the derived constructor's modifiers, + most base first, each with its own modifiers and with the arguments the + derived constructors give (`constructor() Base(7)`). An inheritance + specifier's arguments (`is Base(7)`) are not read: unknown values. +- `super.f()` follows the linearization from the contract the call is + written in (in a function, a modifier or a base constructor), and + `Base.f()` calls Base's implementation. +- Reported: a base the file does not define, directly or through another + base. Rejected: `super` of an overloaded function, and a base's private + state variable declared again in a derived contract. + ## 2026-10 — Soundness fixes Each of these made a false property verify; each fix has a fixture under diff --git a/FAQ.md b/FAQ.md index cd8582a..5e2e110 100644 --- a/FAQ.md +++ b/FAQ.md @@ -32,7 +32,7 @@ The tradeoff: JVerify specs are type-checked by javac (you get IDE autocomplete - **No heap aliasing** — Solidity storage is a flat key-value store. Two state variables cannot point to the same memory. This eliminates the hardest part of heap reasoning that JVerify must handle. - **No concurrency** — The EVM is single-threaded. No concurrent reasoning needed. -- **No dynamic dispatch** — Solidity has inheritance but external calls are explicit. No virtual method resolution to model. +- **Static dispatch** — external calls are explicit, and the contract a function runs in is known: a virtual function's override and the target of `super` follow from the linearization of the contract being verified, with no run-time types to model. - **Deterministic execution** — Same inputs always produce same outputs (modulo `block.timestamp`). - **Simpler language** — No generics, no lambdas, no closures. The translation from Solidity to Laurel is a single file (~2100 lines) vs JVerify's ~30 files. @@ -78,9 +78,9 @@ The alternatives: Core is too low-level (no built-in heap model), C_Simp is a to See `LIMITATIONS.md` for the full supported/unsupported matrix. In summary: -**Working:** Simple and nested mappings, scalar state vars, `old()`, `forall` with `==>`, key-scoped `modifies`, `sum()` aggregation, contract invariants, loop invariants, `keccak256(...)` as mapping keys. +**Working:** Simple and nested mappings, scalar state vars, `old()`, `forall` with `==>`, key-scoped `modifies`, `sum()` aggregation, contract invariants, loop invariants, `keccak256(...)` as mapping keys, inheritance (inherited state, functions, modifiers, invariants and constructors, and `super`). -**Not working:** Struct fields through mappings (Core limitation), counterexamples for quantified specs (`unknown` instead of a model; see LIMITATIONS.md), external calls/reentrancy, inheritance, assembly. +**Not working:** Struct fields through mappings (Core limitation), counterexamples for quantified specs (`unknown` instead of a model; see LIMITATIONS.md), external calls/reentrancy, assembly, a base contract in another file. ## Why does Solidity need fewer simplification passes than Java? diff --git a/LIMITATIONS.md b/LIMITATIONS.md index 4751901..c317f0e 100644 --- a/LIMITATIONS.md +++ b/LIMITATIONS.md @@ -109,7 +109,7 @@ This is not practical for verifying existing contracts but works for new designs | External calls / reentrancy | ⚠️ Havoc | A call of another contract (through an interface, `this.f()`, an external function value), a low-level `call`, or `new C(…)` may call back into the contract: its state is unknown after the call, except for the contract invariants, which an external function checks before the call and assumes after it. `view` calls and `staticcall` change nothing; nor do `send` and `transfer` (too little gas to). `delegatecall` may change all state, invariants included. Results are unknown values of their type. Constructors cannot be re-entered. `--assume-no-reentrancy` trusts that no call re-enters: calls (other than `delegatecall`) then change nothing | | Assembly / inline Yul | ⚠️ Havoc | Not interpreted. Afterwards, unknown: the Solidity variables a block assigns; every memory variable if it writes memory; all contract state (of its type) if it may write storage (`sstore`, calls). A block that may `return` or `stop` ends the transaction on some paths, as `selfdestruct` does. Rejected: assigning a storage reference, writing memory with a memory struct in scope, ending a constructor, and calling a function that may end the transaction (the code after the call would be verified as if it ran) | | Dynamic arrays (push/pop) | ⚠️ Partial | `.length` and `push` work; `pop` not modeled | -| Inheritance | ⚠️ Partial | Single contract only, no virtual dispatch | +| Inheritance | ✅ Modelled | A contract is verified as the flattening of its bases and itself, ordered by solc's C3 linearization: inherited state, functions, modifiers and invariants are checked in the derived contract's context (an obligation of an inherited function names it: `(in D)`), and an inherited function calls the most derived override. Base constructors run before the derived one, with their modifiers and the arguments the derived constructors give. `super.f()` follows the linearization from the contract the call is written in; `Base.f()` calls Base's implementation. Not covered: a base in another file (reported; its members are absent), the arguments of an inheritance specifier `is Base(7)` (unknown values), `super` of an overloaded function and a base's private state variable declared again (rejected) | | Events / errors | First-class ops | `revert` prunes its path; `emit` is a verification no-op | ## Storage References diff --git a/StrataSolidity/SarifOutput.lean b/StrataSolidity/SarifOutput.lean index f02674d..be88277 100644 --- a/StrataSolidity/SarifOutput.lean +++ b/StrataSolidity/SarifOutput.lean @@ -61,7 +61,10 @@ private def classifyRule (vcr : VCResult) : String := else if summary == "divisor is non-zero" || summary == "modulus is non-zero" then "strata/division-by-zero" else if has label "loopinv" then "strata/loop-invariant-fail" - else if summary.isEmpty && label.startsWith "assert" then "strata/assert-fail" + else if label.startsWith "assert" && (summary.isEmpty || summary.startsWith "assert") then + -- (An `assert` in an inherited function carries its text and the + -- contract it is verified in as summary.) + "strata/assert-fail" else "strata/unknown" /-- How an obligation came out, shared by every output format. -/ diff --git a/StrataSolidity/SolTranslator/ContractTranslator.lean b/StrataSolidity/SolTranslator/ContractTranslator.lean index 89acd82..4ac60fd 100644 --- a/StrataSolidity/SolTranslator/ContractTranslator.lean +++ b/StrataSolidity/SolTranslator/ContractTranslator.lean @@ -90,6 +90,109 @@ private def reprHasLoop (astRepr : String) : Bool := ["ForStatement", "WhileStatement", "DoWhileStatement"].any fun c => (astRepr.splitOn s!"Strata.Solidity.node.{c}").length > 1 +/-! ## Inheritance + +solc does not flatten inherited members: a `ContractDefinition` lists only +the members written in it, and names its direct bases in `baseContracts`. +A contract is therefore verified as the flattening of its bases and +itself, so that inherited state, functions, modifiers and invariants +resolve in the derived contract's own context (its `self`, its state +parameters). Each contract of the file is still verified on its own too. +-/ + +/-- A contract's name, kind, members, documentation and direct bases. -/ +private structure ContractInfo where + name : String + kind : String + members : List (Solidity.node SourceRange) + doc : StrataDDM.Ann String SourceRange + bases : List String + +private def contractInfo? : Solidity.node SourceRange → Option ContractInfo + | .ContractDefinition _ nameAnn kindAnn _ nodesSeq docAnn baseContracts => + some { name := nameAnn.val, kind := kindAnn.val, members := nodesSeq.val.toList, + doc := docAnn, bases := baseContracts.val.toList.map (·.val) } + | _ => none + +/-- Whether a member is a constructor. -/ +private def isConstructorMember : Solidity.node SourceRange → Bool + | .FunctionDefinition _ _ k .. => k.val == "constructor" + | _ => false + +/-- The C3 merge of `seqs`: repeatedly the first head that is in no tail. + `none` if there is none (the hierarchy cannot be linearized). -/ +private def c3Merge (seqs : List (List String)) : Option (List String) := + go seqs (seqs.foldl (· + ·.length) 1) +where + go (seqs : List (List String)) : Nat → Option (List String) + | 0 => none + | fuel + 1 => + let seqs := seqs.filter (!·.isEmpty) + if seqs.isEmpty then some [] else + let inTail (c : String) := seqs.any fun s => (s.drop 1).contains c + match seqs.findSome? fun s => s.head?.filter (!inTail ·) with + | none => none + | some c => (go (seqs.map fun s => if s.head? == some c then s.drop 1 else s) fuel).map (c :: ·) + +/-- The C3 linearization of `name`, most derived first, as solc computes + it (`linearizedBaseContracts`): for `contract C is B1, …, Bn`, + `L(C) = C :: merge(L(Bn), …, L(B1), [Bn, …, B1])` (Solidity lists the + bases most base-like first, the reverse of Python). A base the file does + not define is a leaf: its own bases are unknown. `none` if the bases + cannot be linearized, which solc rejects. -/ +private partial def linearize (ctx : TransCtx) (name : String) : Option (List String) := + match (ctx.contractNodes.lookup name).bind contractInfo? with + | none => some [name] + | some info => do + let direct := info.bases.reverse + let merged ← c3Merge ((← direct.mapM (linearize ctx)) ++ [direct]) + return name :: merged + +/-- solc's type of a parameter, without its data location (`uint256`, + `struct C.Info`), which an override may change (`calldata` to + `memory`). -/ +private def paramTypeKey (ctx : TransCtx) : Solidity.node SourceRange → String + | .VariableDeclaration sr .. => + let ts := (ctx.typeAt? sr "VariableDeclaration").getD "?" + let locations := [" storage ref", " storage pointer", " storage", " memory", " calldata"] + match locations.find? (fun (l : String) => ts.endsWith l) with + | some l => (ts.dropEnd l.length).toString + | none => ts + | _ => "?" + +/-- What a derived definition overrides. A function is keyed by its name + and parameter types: an overload with other parameters is a different + function. `receive` and `fallback` are keyed by kind, constructors by + nothing (a base constructor is not a procedure of the derived contract; + it runs as part of deployment). -/ +private def overrideKey (ctx : TransCtx) : Solidity.node SourceRange → Option String + | .FunctionDefinition _ nameAnn kindAnn _ _ _ params .. => + if kindAnn.val == "constructor" then none + else if kindAnn.val == "function" then + let types := match params with + | .ParameterList _ ps => ps.val.toList.map (paramTypeKey ctx) + | _ => [] + some s!"fn {nameAnn.val}({",".intercalate types})" + else some kindAnn.val + | .ModifierDefinition _ nameAnn .. => some s!"mod {nameAnn.val}" + | _ => none + +/-- The name under which the implementation of `fname` written in `owner` + is emitted when a more derived contract overrides it and a call + reaches it (`super.fname(…)`, `owner.fname(…)`): an internal procedure + of the contract being verified. -/ +private def inheritedImplName (owner fname : String) : String := + s!"__base_{owner}_{fname}" + +/-- A function definition renamed `name`, with internal visibility: how an + overridden implementation is emitted, reachable only from the calls + that name it. -/ +private def asInheritedImpl (name : String) : Solidity.node SourceRange → Option (Solidity.node SourceRange) + | .FunctionDefinition sr nameAnn kindAnn mutAnn _visAnn virtAnn params rets body doc mods => + some (.FunctionDefinition sr { nameAnn with val := name } kindAnn mutAnn + { nameAnn with val := "internal" } virtAnn params rets body doc mods) + | _ => none + /-- Translate a Solidity ContractDefinition to Laurel types and procedures. Contracts become a CompositeType with state variables as fields; functions are emitted as static procedures. @@ -98,8 +201,7 @@ private def reprHasLoop (astRepr : String) : Bool := def translateContract (ctx : TransCtx) (contract : Solidity.node SourceRange) : Except TranslationError (List Procedure × List TypeDefinition × List TranslationWarning) := do match contract with - | .ContractDefinition contractSr nameAnn kindAnn _abstractAnn nodesSeq contractDocAnn baseContracts => do - let baseNames := baseContracts.val.toList.map (·.val) + | .ContractDefinition contractSr nameAnn kindAnn _abstractAnn nodesSeq contractDocAnn _ => do let mut warnings : List TranslationWarning := [] let mut procedures : List Procedure := [] let mut fields : List Field := [] @@ -107,15 +209,118 @@ def translateContract (ctx : TransCtx) (contract : Solidity.node SourceRange) let mut structFieldMap : List (String × List (String × HighType)) := ctx.structFields let mut enumDefs : List (String × List String) := ctx.enumDefs let mut udvtNames : List String := ctx.udvtNames + + -- The bases this contract inherits from, most-base-first (the reverse + -- of the C3 linearization), and every member to verify it with: the + -- bases' members (except their constructors, which are not procedures + -- of this contract) followed by its own, each tagged with the contract + -- that defines it. A definition a more derived contract repeats + -- (`override`) replaces the inherited one. + let some linearization := linearize ctx nameAnn.val + | throw (.unsupported s!"the bases of `{nameAnn.val}` cannot be linearized") + let bases := (linearization.drop 1).reverse.filterMap fun b => + (ctx.contractNodes.lookup b).bind contractInfo? + let ownMembers := nodesSeq.val.toList + -- A base this file does not define (an imported one, or one an imported + -- base inherits) contributes no members, so what it declares does not + -- resolve here, and its functions are entry points that are not checked. + for b in linearization.drop 1 do + if !(ctx.contractNodes.any (·.1 == b)) then + warnings := warnings ++ [{ range := contractSr, message := + s!"base contract `{b}` of `{nameAnn.val}` is not defined in this file: its state, functions and invariants are not part of what is verified here" }] + let taggedAll : List (String × Solidity.node SourceRange) := + bases.flatMap (fun b => (b.members.filter (!isConstructorMember ·)).map ((b.name, ·))) ++ + ownMembers.map ((nameAnn.val, ·)) + -- A public state variable overrides the base function its getter + -- implements (solc allows the shared name only then). + let publicVarNames := taggedAll.filterMap fun (_, m) => match m with + | .VariableDeclaration _ n _ sv _ _ vis .. => + if sv.val == "true" && vis.val == "public" then some n.val else none + | _ => none + let taggedMembers := taggedAll.zipIdx.filterMap fun ((owner, m), i) => + match overrideKey ctx m, m with + | some k, .FunctionDefinition _ fnName kind .. => + if (taggedAll.drop (i + 1)).any (overrideKey ctx ·.2 == some k) then none + else if kind.val == "function" && publicVarNames.contains fnName.val then none + else some (owner, m) + | some k, _ => + if (taggedAll.drop (i + 1)).any (overrideKey ctx ·.2 == some k) then none + else some (owner, m) + | none, _ => some (owner, m) + -- State variables of the same name in different contracts (a base's + -- private one and a derived one) are different variables: not + -- modelled. (Overloads, functions of the same name with different + -- parameters, are distinct procedures, as in a single contract.) + let varOwners := taggedMembers.filterMap fun (owner, m) => match m with + | .VariableDeclaration _ n _ sv .. => if sv.val == "true" then some (n.val, owner) else none + | _ => none + if let some (v, o) := varOwners.find? fun (v, o) => varOwners.any fun (v', o') => v' == v && o' != o then + let others := varOwners.filterMap fun (v', o') => if v' == v && o' != o then some s!"`{o'}`" else none + throw (.unsupported s!"the state variable `{v}` of `{o}`, declared again in {", ".intercalate others}: they are different variables") + -- Members this contract declares itself. Everything inherited is + -- reported where it is written, when its own contract is verified, so + -- only these produce warnings here. + let isOwn (owner : String) : Bool := owner == nameAnn.val + + -- `super.f(…)` in code written in contract `cn` calls the implementation + -- of `f` that follows `cn` in the linearization, and `X.f(…)` (for a + -- base `X`) the first one in X's own linearization. One that a more + -- derived contract overrides is emitted, when a call reaches it, as the + -- internal procedure `__base__`. + let membersOf (cn : String) : List (Solidity.node SourceRange) := + (((ctx.contractNodes.lookup cn).bind contractInfo?).map (·.members)).getD [] + let fnImpl (fname : String) : Solidity.node SourceRange → Bool + | .FunctionDefinition _ n k _ _ _ _ _ body _ _ => + k.val == "function" && n.val == fname && !(body matches .missing_node _) + | _ => false + let implsIn (order : List String) (fname : String) : List (String × Solidity.node SourceRange) := + order.flatMap fun cn => (membersOf cn).filterMap fun m => if fnImpl fname m then some (cn, m) else none + -- What a call of the implementation of `fname` in `owner` is: the + -- procedure itself when it is the one this contract keeps. + let implCallee (owner fname : String) : String := + if taggedMembers.any fun (o, m) => o == owner && fnImpl fname m then fname + else inheritedImplName owner fname + -- The callee of a call of `fname` resolved along `order`, or why there + -- is none to call: `!overloaded` (calls of an overloaded function by + -- `super` are not resolved), `!none`. + let resolveIn (order : List String) (fname : String) : String := + let impls := implsIn order fname + let keys := (impls.filterMap fun (_, m) => overrideKey ctx m).eraseDups + if keys.length > 1 then "!overloaded" + else match impls.head? with + | some (owner, _) => implCallee owner fname + | none => "!none" + let fnNamesIn (order : List String) : List String := + (order.flatMap fun cn => (membersOf cn).filterMap fun + | .FunctionDefinition _ n k .. => if k.val == "function" then some n.val else none + | _ => none).eraseDups + let superImplsFrom (cn : String) : List (String × String) := + let after := (linearization.dropWhile (· != cn)).drop 1 + (fnNamesIn after).map fun f => (f, resolveIn after f) + let explicitImpls : List ((String × String) × String) := + (linearization.filter fun x => ctx.contractNodes.any (·.1 == x)).flatMap fun x => + let order := (linearize ctx x).getD [x] + (fnNamesIn order).map fun f => ((x, f), resolveIn order f) + -- Every overridden implementation a call may reach, for its signature. + let overriddenImpls : List (String × String × Solidity.node SourceRange) := + (fnNamesIn linearization).flatMap fun f => + (implsIn linearization f).filterMap fun (owner, m) => + if implCallee owner f == f then none else some (owner, f, m) + -- Contract invariants may be attached to the contract itself or to any -- of its state variables; solc attaches each NatSpec block to one -- declaration, so there is no ambiguity between contracts in a file. - -- Interfaces and libraries have no state to keep invariant. + -- Interfaces and libraries have no state to keep invariant. A base's + -- invariants constrain the state this contract inherits, so they are + -- checked here too (the state-variable ones come with the merged + -- members below). let isContract := kindAnn.val == "contract" let mut stateVarInvariants : List StrataAnnotation := - if isContract then + (bases.filter (·.kind == "contract")).flatMap (fun b => + (parseStrataAnnotations b.doc.val).filter (·.keyword == "invariant")) ++ + (if isContract then (parseStrataAnnotations contractDocAnn.val).filter (·.keyword == "invariant") - else [] + else []) warnings := warnings ++ annotationWarnings ctx.source s!"{kindAnn.val} `{nameAnn.val}`" (if isContract then ["invariant"] else []) contractDocAnn (fun _ => if isContract then none else @@ -126,16 +331,19 @@ def translateContract (ctx : TransCtx) (contract : Solidity.node SourceRange) let mut immutableNames : List String := [] -- Pass 1: collect struct definitions and state variables - for member in nodesSeq.val do + for (owner, member) in taggedMembers do match member with | .StructDefinition _ sNameAnn membersSeq => do let sFields ← membersSeq.val.toList.mapM (translateFieldDecl { ctx with enumDefs } "struct member") - types := types ++ [.Composite { - name := sNameAnn.val - extending := [] - fields := sFields - instanceProcedures := [] - }] + -- An inherited struct is declared and constructed by the contract + -- that defines it; here it only has to resolve. + if isOwn owner then + types := types ++ [.Composite { + name := sNameAnn.val + extending := [] + fields := sFields + instanceProcedures := [] + }] -- Record field order for argument reordering structFieldMap := structFieldMap ++ [(sNameAnn.val, sFields.map fun f => (f.name.text, f.type.val))] -- Emit a synthetic constructor procedure for the struct. @@ -153,22 +361,24 @@ def translateContract (ctx : TransCtx) (contract : Solidity.node SourceRange) mkStmtExprMd (mkPrimOp .Eq [resultField, paramRef]) let postcondsAsConds : List Condition := postconds.map fun p => { condition := p, summary := none } - procedures := procedures ++ [{ - name := s!"{sNameAnn.val}_constructor" - inputs := ctorInputs - outputs := [ctorOutput] - preconditions := [] - decreases := none - body := .Abstract postcondsAsConds - }] + if isOwn owner then + procedures := procedures ++ [{ + name := s!"{sNameAnn.val}_constructor" + inputs := ctorInputs + outputs := [ctorOutput] + preconditions := [] + decreases := none + body := .Abstract postcondsAsConds + }] | .VariableDeclaration _ nameAnn typeNameOpt stateVarAnn constAnn mutAnn _ _ _ valueOpt docAnn => if stateVarAnn.val == "true" then do if mutAnn.val == "immutable" then immutableNames := immutableNames ++ [nameAnn.val] -- Collect @custom:strata invariant from state variable NatSpec -- (a library's constants are not contract state) - warnings := warnings ++ annotationWarnings ctx.source - s!"state variable `{nameAnn.val}`" (if isContract then ["invariant"] else []) docAnn - (fun _ => if isContract then none else some s!"a {kindAnn.val} has no state, so it is ignored") + if isOwn owner then + warnings := warnings ++ annotationWarnings ctx.source + s!"state variable `{nameAnn.val}`" (if isContract then ["invariant"] else []) docAnn + (fun _ => if isContract then none else some s!"a {kindAnn.val} has no state, so it is ignored") if isContract then for ann in parseStrataAnnotations docAnn.val do match ann with @@ -202,9 +412,11 @@ def translateContract (ctx : TransCtx) (contract : Solidity.node SourceRange) -- Pass 1b: collect modifier definitions (extract pre-_ require statement nodes) -- Modifiers, inlined into the functions that use them. let mut modifierDefs : List (String × List (String × HighTypeMd) × List (Solidity.node SourceRange)) := [] - for member in nodesSeq.val do + let mut modifierSuperImpls : List (String × List (String × String)) := [] + for (owner, member) in taggedMembers do match member with | .ModifierDefinition _ modNameAnn paramsNode bodyOpt => + modifierSuperImpls := modifierSuperImpls ++ [(modNameAnn.val, superImplsFrom owner)] let stmts := match bodyOpt with | .some_node _ (.Block _ stmtsSeq) => stmtsSeq.val.toList | _ => [] @@ -246,7 +458,7 @@ def translateContract (ctx : TransCtx) (contract : Solidity.node SourceRange) -- since both translate to TMap in HighType. let mut arrayStateVars : List String := [] let mut fixedArrayLengths : List (String × Nat) := [] - for member in nodesSeq.val do + for (_, member) in taggedMembers do match member with | .VariableDeclaration _ nameAnn typeNameOpt stateVarAnn _ _ _ _ _ _ _ => if stateVarAnn.val == "true" then @@ -259,7 +471,12 @@ def translateContract (ctx : TransCtx) (contract : Solidity.node SourceRange) | _ => pure () let mut nonPureFunctions : List String := [] let mut functionSigs : List (String × FnSig) := [] - for member in nodesSeq.val do + -- The overridden implementations a call may reach are internal + -- procedures of this contract, so they need signatures too. + let sigMembers : List (Solidity.node SourceRange) := + taggedMembers.map (·.2) ++ overriddenImpls.filterMap fun (owner, f, m) => + asInheritedImpl (inheritedImplName owner f) m + for member in sigMembers do match member with | .FunctionDefinition _ fnNameAnn fnKindAnn fnMutAnn fnVisAnn _ params retParams _ _ _ => let fnIsPure := fnMutAnn.val == "pure" @@ -338,16 +555,48 @@ def translateContract (ctx : TransCtx) (contract : Solidity.node SourceRange) -- Pass 4: translate functions with struct field info, state context, and invariant nodes -- Invariant nodes are re-translated per function so that state variable references -- resolve correctly in each function's context. - -- Mappings some annotation of this contract sums. - let summed := (contractDocAnn :: nodesSeq.val.toList.filterMap fun - | .FunctionDefinition _ _ _ _ _ _ _ _ _ doc _ => some doc - | .VariableDeclaration _ _ _ _ _ _ _ _ _ _ doc => some doc + -- The base constructors deployment runs, most base first. Each gets + -- the arguments that the most derived constructor naming its contract + -- (`constructor() Base(7)`) gives it; those of an inheritance specifier + -- (`is Base(7)`) are not in the AST, and are unknown. + let tctx := { ctx with enumDefs, udvtNames } + let ctorOf (c : String) : Option (Solidity.node SourceRange) := + (((ctx.contractNodes.lookup c).bind contractInfo?).map (·.members)).bind (·.find? isConstructorMember) + let baseCtors : List BaseCtor := bases.filterMap fun b => + match ctorOf b.name with + | some (.FunctionDefinition _ _ _ _ _ _ ps _ (.some_node _ bodyNode) _ mods) => + let params := match ps with + | .ParameterList _ seq => seq.val.toList.filterMap fun + | .VariableDeclaration _ n (.some_type_name _ tn) .. => + let t := translateTypeNode tctx tn + some (n.val, t.highType, t.solName) + | _ => none + | _ => [] + let derived := linearization.takeWhile (· != b.name) + let given := derived.findSome? fun x => + match ctorOf x with + | some (.FunctionDefinition _ _ _ _ _ _ _ _ _ _ xMods) => + xMods.val.toList.findSome? fun + | .ModifierInvocation _ m argsSeq => + if m.val == b.name then some (argsSeq.val.toList, x) else none + | _ => none + | _ => none + some { contractName := b.name, params, body := bodyNode, modifiers := mods.val.toList, + args := if params.isEmpty then some ([], nameAnn.val) else given, + superImpls := superImplsFrom b.name } + | _ => none + -- Mappings some annotation of this contract, or of a base, sums. + let summed := (contractDocAnn :: bases.map (·.doc) ++ taggedMembers.filterMap fun + | (_, .FunctionDefinition _ _ _ _ _ _ _ _ _ doc _) => some doc + | (_, .VariableDeclaration _ _ _ _ _ _ _ _ _ _ doc) => some doc | _ => none).flatMap (summedNames ·.val) - -- A constructor that is not verified (it uses a struct-valued mapping) - -- establishes nothing, so the invariants are neither assumed nor - -- checked: assuming them would make every obligation that relies on - -- them pass. - let ctorSkipped := nodesSeq.val.any fun + -- A constructor that is not verified (it, or a base constructor it + -- runs, uses a struct-valued mapping) establishes nothing, so the + -- invariants are neither assumed nor checked: assuming them would make + -- every obligation that relies on them pass. + let usesStructMapping (n : Solidity.node SourceRange) : Bool := + structMappingNames.any (reprMentions (toString (repr n)) ·) + let ctorSkipped := baseCtors.any (usesStructMapping ·.body) || ownMembers.any fun | .FunctionDefinition _ _ k _ _ _ _ _ bodyOpt _ _ => k.val == "constructor" && match bodyOpt with | .some_node _ _ => structMappingNames.any (reprMentions (toString (repr bodyOpt)) ·) @@ -360,18 +609,22 @@ def translateContract (ctx : TransCtx) (contract : Solidity.node SourceRange) let fnCtx := { baseFnCtx with contractInvariantNatspec := invariants, summedMappings := summed.eraseDups, contractInvariantTexts := if ctorSkipped then [] else natspecInvariantStrs, - modifierDefs := modifierDefs } - for member in nodesSeq.val do + modifierDefs := modifierDefs, + modifierSuperImpls := modifierSuperImpls, + explicitImpls := explicitImpls, + baseConstructors := baseCtors } + for (owner, member) in taggedMembers do match member with | .FunctionDefinition fnSr fnNameAnn fnKindAnn _ _ _ _ _ bodyOpt fnDocAnn fnModifiers => do let fnDesc := functionDesc fnKindAnn.val fnNameAnn.val - -- A modifier defined elsewhere (an imported base contract's) is - -- not inlined. (A base constructor call, `Base(x)`, is fine.) - for inv in fnModifiers.val do - if let .ModifierInvocation invSr modName _ := inv then - if !modifierDefs.any (·.1 == modName.val) && !baseNames.contains modName.val then - warnings := warnings ++ [{ range := invSr, message := - s!"modifier `{modName.val}` is not defined in this contract: {fnDesc} is verified without it" }] + if isOwn owner then + -- A modifier defined elsewhere (an imported base contract's) is + -- not inlined. (A base constructor call, `Base(x)`, is fine.) + for inv in fnModifiers.val do + if let .ModifierInvocation invSr modName _ := inv then + if !modifierDefs.any (·.1 == modName.val) && !linearization.contains modName.val then + warnings := warnings ++ [{ range := invSr, message := + s!"modifier `{modName.val}` is not defined in this contract: {fnDesc} is verified without it" }] let bodyText := match bodyOpt with | .some_node _ _ => toString (repr bodyOpt) | _ => "" @@ -387,31 +640,44 @@ def translateContract (ctx : TransCtx) (contract : Solidity.node SourceRange) else if kw == "modifies" && isCtor then some "frames are not checked for constructors" else if kw == "loop-invariant" then some "it has no loop" else none - warnings := warnings ++ annotationWarnings ctx.source fnDesc allowed fnDocAnn reason let fnAnnotations := parseStrataAnnotationsAt ctx.source fnDocAnn - -- Specs through struct-valued mappings are dropped by translateFunction. - for (ann, r) in fnAnnotations do - match ann with - | .requires e | .ensures e => - if hasStructAccess e then - warnings := warnings ++ [{ range := r, message := - s!"`@custom:strata {ann.keyword} {e}` on {fnDesc} is ignored: struct fields accessed through a mapping are not supported" }] - | .modifies vars => - for (m, key) in SpecParser.unreadableModifiesKeys vars do - warnings := warnings ++ [{ range := r, message := - s!"`@custom:strata modifies {m}[{key}]` on {fnDesc}: the key cannot be read, so the frame of `{m}` is not checked" }] - | _ => pure () - -- Skip functions that reference struct-valued mappings (unsupported in Core) - let usedStructMappings := structMappingNames.filter (reprMentions bodyText ·) + if isOwn owner then + warnings := warnings ++ annotationWarnings ctx.source fnDesc allowed fnDocAnn reason + -- Specs through struct-valued mappings are dropped by translateFunction. + for (ann, r) in fnAnnotations do + match ann with + | .requires e | .ensures e => + if hasStructAccess e then + warnings := warnings ++ [{ range := r, message := + s!"`@custom:strata {ann.keyword} {e}` on {fnDesc} is ignored: struct fields accessed through a mapping are not supported" }] + | .modifies vars => + for (m, key) in SpecParser.unreadableModifiesKeys vars do + warnings := warnings ++ [{ range := r, message := + s!"`@custom:strata modifies {m}[{key}]` on {fnDesc}: the key cannot be read, so the frame of `{m}` is not checked" }] + | _ => pure () + -- Skip functions that reference struct-valued mappings (unsupported in + -- Core); a constructor also when a base constructor it runs does. + let usedStructMappings := structMappingNames.filter fun m => + reprMentions bodyText m || + (isCtor && baseCtors.any fun (b : BaseCtor) => reprMentions (toString (repr b.body)) m) if !usedStructMappings.isEmpty then - let names := ", ".intercalate (usedStructMappings.map (s!"`{·}`")) - warnings := warnings ++ [{ range := fnSr, message := - s!"{fnDesc} is not verified: it uses the struct-valued mapping {names}, which is not supported" }] + if isOwn owner then + let names := ", ".intercalate (usedStructMappings.map (s!"`{·}`")) + let how := if usedStructMappings.any (reprMentions bodyText ·) then "it uses" + else "a base constructor it runs uses" + warnings := warnings ++ [{ range := fnSr, message := + s!"{fnDesc} is not verified: {how} the struct-valued mapping {names}, which is not supported" }] else do - let proc ← translateFunction fnCtx member + -- An inherited function is verified in this contract's context: + -- its state, its invariants. `super` in it refers to the + -- contracts after the one that defines it. + let memberCtx := { fnCtx with superImpls := superImplsFrom owner } + let memberCtx := if isOwn owner then memberCtx else { memberCtx with verifiedIn := some nameAnn.val } + let proc ← translateFunction memberCtx member procedures := procedures ++ [proc] | _ => pure () + -- Without an explicit constructor, deployment runs only the default -- initialization and the state-variable initializers. Check that this -- initial state satisfies the invariants with an implicit, empty @@ -419,7 +685,7 @@ def translateContract (ctx : TransCtx) (contract : Solidity.node SourceRange) -- nothing establishes (an unsatisfiable invariant would make every -- obligation pass). An abstract contract is checked the same way, as -- the initial state of the contracts that derive from it. - let hasCtor := nodesSeq.val.any fun + let hasCtor := ownMembers.any fun | .FunctionDefinition _ _ k _ _ _ _ _ _ _ _ => k.val == "constructor" | _ => false if !invariants.isEmpty && !hasCtor && kindAnn.val == "contract" then @@ -432,6 +698,29 @@ def translateContract (ctx : TransCtx) (contract : Solidity.node SourceRange) ⟨contractSr, #[]⟩ procedures := procedures ++ [← translateFunction fnCtx implicitCtor] + let implOf (p : Procedure) : Option StmtExprMd := match p.body with + | .Transparent e => some e + | .Opaque _ impl _ => impl + | _ => none + + -- The overridden implementations that `super.f(…)` and `X.f(…)` calls + -- reach, directly or through one another. + let mut emittedImpls : List String := [] + for _ in [0:overriddenImpls.length] do + let called := procedures.flatMap fun p => ((implOf p).map calledNames).getD [] + let reached := overriddenImpls.filter fun (owner, f, _) => + let name := inheritedImplName owner f + called.contains s!"{nameAnn.val}_{name}" && !emittedImpls.contains name + if reached.isEmpty then break + for (owner, f, m) in reached do + let name := inheritedImplName owner f + emittedImpls := emittedImpls ++ [name] + if structMappingNames.any (reprMentions (toString (repr m)) ·) then + throw (.unsupported s!"the implementation of `{f}` in `{owner}`, which a `super.{f}(...)` or `{owner}.{f}(...)` call reaches: it uses a struct-valued mapping, which is not supported") + if let some impl := asInheritedImpl name m then + procedures := procedures ++ [← translateFunction + { fnCtx with superImpls := superImplsFrom owner, verifiedIn := some nameAnn.val } impl] + -- A halt (assembly `return` or `stop`, `selfdestruct`) ends the whole -- transaction, keeping the state written so far. It is modelled as a -- return from the function it is in (see `haltLabel`): right in an @@ -439,10 +728,6 @@ def translateContract (ctx : TransCtx) (contract : Solidity.node SourceRange) -- but a function that calls one containing a halt would continue after -- the call, and its remaining code be verified as if it ran. Such calls -- are rejected. - let implOf (p : Procedure) : Option StmtExprMd := match p.body with - | .Transparent e => some e - | .Opaque _ impl _ => impl - | _ => none let solidityName (proc : String) := (proc.drop (nameAnn.val.length + 1)).toString let halting := procedures.filterMap fun p => if (implOf p).any containsHalt then some p.name.text else none @@ -554,6 +839,14 @@ def solidityToLaurelWithWarnings (cmd : Solidity.Command SourceRange) if kindAnn.val == "library" then none else some nameAnn.val | _ => none let ctx := { ctx with contractTypeNames } + -- Contracts are verified one by one, each as the flattening of its + -- bases and itself, so every contract must be reachable by name. + let contractNodes := nodesSeq.val.toList.filterMap + fun (node : Solidity.node SourceRange) => + match node with + | .ContractDefinition _ nameAnn .. => some (nameAnn.val, node) + | _ => none + let ctx := { ctx with contractNodes } let mut allProcedures : List Procedure := [] let mut allTypes : List TypeDefinition := [] let mut allWarnings : List TranslationWarning := [] diff --git a/StrataSolidity/SolTranslator/ExprTranslator.lean b/StrataSolidity/SolTranslator/ExprTranslator.lean index 3df92bd..8c363c5 100644 --- a/StrataSolidity/SolTranslator/ExprTranslator.lean +++ b/StrataSolidity/SolTranslator/ExprTranslator.lean @@ -598,7 +598,7 @@ def externalCallModel (ctx : TransCtx) (sr : SourceRange) (kind : ExternalCallKi else let invs := ctx.reentryInvariants.map fun (inv, text) => (withSourceRangeDeep ctx sr inv, text) invs.map (fun (inv, text) => mkStmtExprMdAnn ctx sr - (mkAssert inv (some s!"invariant {text} holds before the external call"))) ++ + (mkAssert inv (some s!"invariant {text} holds before the external call{(ctx.verifiedIn.map (s!" (in {·})")).getD ""}"))) ++ stateHavoc ctx ++ invs.map (fun (inv, _) => mkStmtExprMd (mkAssume inv)) /-- The value returned by the external call at `sr`, by solc's type of the @@ -1027,6 +1027,34 @@ partial def translateExprAt (ctx : TransCtx) (n : Solidity.node SourceRange) (some (mkStmtExprMd (.Hole (deterministic := false)))) | .FunctionCall sr fnExpr argsSeq kindAnn namesSeq => do + -- `super.f(…)` and `X.f(…)` for a base `X` call an inherited + -- implementation (`ctx.superImpls`, `ctx.explicitImpls`), emitted by + -- `translateContract` as an internal procedure. Checked before the + -- external-call path: solc gives these calls an internal function type. + if let .MemberAccess _ (.Identifier _ baseAnn) member := fnExpr then + let target? : Option (String × String) := + if baseAnn.val == "super" then + (ctx.superImpls.lookup member.val).map (s!"super.{member.val}", ·) + else (ctx.explicitImpls.lookup (baseAnn.val, member.val)).map + (s!"{baseAnn.val}.{member.val}", ·) + if baseAnn.val == "super" && target?.isNone then + throw (.unsupported s!"`super.{member.val}(...)`: no implementation of `{member.val}` follows the contract this call is written in") + if let some (what, callee) := target? then + if callee == "!overloaded" then + throw (.unsupported s!"`{what}(...)` of an overloaded function") + if callee == "!none" then + throw (.unsupported s!"`{what}(...)`: no implementation of `{member.val}` to call") + let args ← argsSeq.val.toList.mapM (translateExpr ctx) + let sig := (ctx.functionSigs.lookup callee).getD { isPure := false, isView := false } + -- Named arguments bind by name, as in any internal call. + let names := namesSeq.val.toList.map (·.val) + let (argNodes, args) ← if names.isEmpty then pure (argsSeq.val.toList, args) else do + let named := names.zip (argsSeq.val.toList.zip args) + let ordered ← sig.paramNames.mapM fun p => match named.lookup p with + | some a => pure a + | none => throw (.typeError s!"call to `{what}` has no argument named `{p}`") + pure (ordered.map (·.1), ordered.map (·.2)) + return ← translateInternalCall ctx sr s!"{ctx.contractName}_{callee}" sig argNodes args if let some c ← translateExternalCall? ctx n then return c.toExpr -- Check the FunctionCall kind match kindAnn.val with @@ -1108,7 +1136,12 @@ partial def translateExprAt (ctx : TransCtx) (n : Solidity.node SourceRange) | _, _ => throw (.typeError "require() needs at least one argument") | "assert" => match args with - | [cond] => return mkStmtExprMdAnn ctx sr (mkAssert cond) + | [cond] => + -- A function verified in a contract that inherits it names that + -- contract: the same `assert` is checked once per such contract. + let summary := ctx.verifiedIn.bind fun c => ctx.source.map fun src => + s!"{String.fromUTF8! (src.toUTF8.extract sr.start.byteIdx sr.stop.byteIdx)} (in {c})" + return mkStmtExprMdAnn ctx sr (mkAssert cond summary) | _ => throw (.typeError "assert() expects exactly one argument") | "keccak256" | "sha256" => return mkStmtExprMd (mkCall nameAnn.val args) diff --git a/StrataSolidity/SolTranslator/StmtTranslator.lean b/StrataSolidity/SolTranslator/StmtTranslator.lean index 61c8126..7706d4c 100644 --- a/StrataSolidity/SolTranslator/StmtTranslator.lean +++ b/StrataSolidity/SolTranslator/StmtTranslator.lean @@ -73,6 +73,118 @@ def resolveInvariants (ctx : TransCtx) (isConstructor : Bool) (invs : List StmtE else invs.map (rewriteStateVarRefs ctx.stateVarNames ctx.mappingStateVars [] · ctx.constantDefs) +/-- The local variables `stmts` declare. -/ +def declaredLocals (stmts : List StmtExprMd) : List String := + stmts.flatMap (collectStmtExprList fun n => match n.val with + | .Assign ts _ => ts.filterMap fun t => match t.val with + | .Declare p => some p.name.text + | _ => none + | .Var (.Declare p) => [p.name.text] + | _ => []) + +/-- The body `bodyNode` of a function or constructor with the modifiers + `invocations` (name, definition, argument nodes) inlined, the first + outermost: each runs its body with its `_` standing for the next + modifier, or for the body. Each part is a labelled block that a `return` + in it exits (the code after `_` still runs), and a modifier's parameters + and locals are renamed apart (they are scoped to it; nor does it see the + function's own `ownNames`). Without modifiers the body is labelled only + when `alwaysLabel`. Labels and renamed names start with `pre`, so that + several bodies can be inlined into one procedure (base constructors into + the derived one). -/ +def inlineModifiers (bodyCtx : TransCtx) (pre : String) (alwaysLabel : Bool) + (ownNames : List String) (bodyNode : Solidity.node SourceRange) + (invocations : List (String × (List (String × HighTypeMd) × List (Solidity.node SourceRange)) × + List (Solidity.node SourceRange))) + : Except TranslationError StmtExprMd := do + let labelled := alwaysLabel || !invocations.isEmpty + let partCtx (label : String) := if !labelled then bodyCtx + else { bodyCtx with returnLabel := some s!"{pre}{label}" } + let bodyStmts ← match bodyNode with + | .Block _ stmtsSeq => translateBlockStmts (partCtx "__body") stmtsSeq.val.toList + | _ => pure [← translateStmt (partCtx "__body") bodyNode] + let mut b := mkStmtExprMd (.Block bodyStmts (if labelled then some s!"{pre}__body" else none)) + for ((m, (params, stmts), argNodes), j) in invocations.reverse.zipIdx do + let k := invocations.length - 1 - j + let args ← argNodes.mapM (translateExpr bodyCtx) + if args.length != params.length then + throw (.typeError s!"modifier `{m}` takes {params.length} argument(s), given {args.length}") + let marker := s!"{pre}__placeholder{k}" + let modCtx := { partCtx s!"__mod{k}" with + localNames := (bodyCtx.localNames.filter (!ownNames.contains ·)) ++ params.map (·.1), + placeholder := some (mkStmtExprMd (.Block [] (some marker))), + -- `super` in a modifier refers to the contracts after the one that + -- defines the modifier. + superImpls := (bodyCtx.modifierSuperImpls.lookup m).getD bodyCtx.superImpls } + let modStmts ← translateBlockStmts modCtx stmts + let renames := (params.map (·.1) ++ declaredLocals modStmts).eraseDups.map fun n => + (n, s!"{pre}__m{k}_{n}") + let paramDecls := (params.zip args).map fun ((p, ty), a) => + mkStmtExprMd (mkLocalVar s!"{pre}__m{k}_{p}" ty (some a)) + let modBlock := mkStmtExprMd (.Block (paramDecls ++ modStmts.map (renameLocals renames)) + (some s!"{pre}__mod{k}")) + let inner := b + b := mapStmtExpr (fun n => match n.val with + | .Block [] (some l) => if l == marker then inner else n + | _ => n) modBlock + return b + +/-- The base constructors `bases` (most base first) of the constructor + whose body context is `bodyCtx` and whose own parameters are + `ownParams`, as statements to run before it: first every base + constructor's parameters get their arguments, in the order solc + evaluates them (most derived first: an argument may read a parameter of + the constructor that gives it), then the bodies run, most base first. + Each body is a block, with its modifiers, that its `return` exits; its + parameters and locals are renamed apart (`__ctor__`). An + unknown argument is an unknown value of the parameter's type. -/ +def baseConstructorStmts (bodyCtx : TransCtx) (ctorOf : String) (ownParams : List String) + (bases : List BaseCtor) : Except TranslationError (List StmtExprMd) := do + let renamed (k : String) (n : String) := s!"__ctor_{k}_{n}" + let paramsOf (k : String) : List String := + ((bases.find? (·.contractName == k)).map fun b => b.params.map (·.1)).getD [] + -- The context of a base constructor's own code: the contract's state, and + -- only that constructor's parameters (which are renamed afterwards). + let scopeOf (params : List String) : TransCtx := + { bodyCtx with localNames := (bodyCtx.localNames.filter (!ownParams.contains ·)) ++ params, + returnNames := [], returnLocations := [] } + let mut binds : List StmtExprMd := [] + for b in bases.reverse do + let args? ← match b.args with + | some (nodes, giver) => + if nodes.length != b.params.length then + throw (.typeError s!"the constructor of `{b.contractName}` takes {b.params.length} argument(s), given {nodes.length}") + if giver == ctorOf then + pure (some (← nodes.mapM (translateExpr bodyCtx))) + else + let gp := paramsOf giver + let args ← nodes.mapM (translateExpr (scopeOf gp)) + pure (some (args.map (renameLocals (gp.map fun p => (p, renamed giver p))))) + | none => pure none + for ((p, ty, solName), i) in b.params.zipIdx do + let v := renamed b.contractName p + match args? with + | some args => + binds := binds ++ [mkStmtExprMd (mkLocalVar v ty args[i]?)] + | none => + binds := binds ++ [mkStmtExprMd (mkLocalVar v ty (some (mkStmtExprMd (.Hole (deterministic := false)))))] + if let some c := mkRangeCond solName (mkStmtExprMd (mkIdentifier v)) then + binds := binds ++ [mkStmtExprMd (mkAssume c)] + let mut bodies : List StmtExprMd := [] + for b in bases do + let params := b.params.map (·.1) + let invocations := b.modifiers.filterMap fun + | .ModifierInvocation _ m argsSeq => + (bodyCtx.modifierDefs.lookup m.val).map fun d => (m.val, d, argsSeq.val.toList) + | _ => none + let inner ← inlineModifiers { scopeOf params with superImpls := b.superImpls } + s!"__ctor_{b.contractName}" true params b.body invocations + let own := (params ++ (declaredLocals [inner]).filter (!·.startsWith "__")).eraseDups + bodies := bodies ++ [mkStmtExprMd (.Block + [renameLocals (own.map fun n => (n, renamed b.contractName n)) inner] + (some s!"__ctor_{b.contractName}"))] + return binds ++ bodies + /-- Translate a Solidity FunctionDefinition to a Laurel Procedure. Inputs, in order (internal call sites must match, see `translateInternalCall`): `self` and `_in` for each scalar state @@ -377,48 +489,12 @@ def translateFunction (ctx : TransCtx) (fn : Solidity.node SourceRange) withSourceRangeDeep ctx r (withSourceRange ctx r e) -- Rewrite postcondition expressions: user parameter names → _param names let specPostExprs := specPostExprs.map (rewriteParamRefs userParamNames) - -- Translate body statements. Modifiers are inlined, the first one - -- outermost: each runs its body with its `_` standing for the next - -- modifier, or for the function's body. Each part is a labelled - -- block that a `return` in it exits (the code after `_` still - -- runs), and a modifier's parameters and locals are renamed apart - -- (they are scoped to it; nor does it see the function's own). let invocations := modifiersSeq.val.toList.filterMap fun | .ModifierInvocation _ m argsSeq => (ctx.modifierDefs.lookup m.val).map fun d => (m.val, d, argsSeq.val.toList) | _ => none - let partCtx (label : String) := if invocations.isEmpty then bodyCtx - else { bodyCtx with returnLabel := some label } - let bodyStmts ← match bodyNode with - | .Block _ stmtsSeq => translateBlockStmts (partCtx "__body") stmtsSeq.val.toList - | _ => pure [← translateStmt (partCtx "__body") bodyNode] - let mut b := mkStmtExprMd (.Block bodyStmts (if invocations.isEmpty then none else some "__body")) let ownNames := userParamInfo.map (·.1) ++ baseOutputs.map (·.name.text) - for ((m, (params, stmts), argNodes), j) in invocations.reverse.zipIdx do - let k := invocations.length - 1 - j - let args ← argNodes.mapM (translateExpr bodyCtx) - if args.length != params.length then - throw (.typeError s!"modifier `{m}` takes {params.length} argument(s), given {args.length}") - let marker := s!"__placeholder{k}" - let modCtx := { partCtx s!"__mod{k}" with - localNames := (bodyCtx.localNames.filter (!ownNames.contains ·)) ++ params.map (·.1), - placeholder := some (mkStmtExprMd (.Block [] (some marker))) } - let modStmts ← translateBlockStmts modCtx stmts - let declared := modStmts.flatMap (collectStmtExprList fun n => match n.val with - | .Assign ts _ => ts.filterMap fun t => match t.val with - | .Declare p => some p.name.text - | _ => none - | .Var (.Declare p) => [p.name.text] - | _ => []) - let renames := (params.map (·.1) ++ declared).eraseDups.map fun n => (n, s!"__m{k}_{n}") - let paramDecls := (params.zip args).map fun ((p, ty), a) => - mkStmtExprMd (mkLocalVar s!"__m{k}_{p}" ty (some a)) - let modBlock := mkStmtExprMd (.Block (paramDecls ++ modStmts.map (renameLocals renames)) - (some s!"__mod{k}")) - let inner := b - b := mapStmtExpr (fun n => match n.val with - | .Block [] (some l) => if l == marker then inner else n - | _ => n) modBlock + let b ← inlineModifiers bodyCtx "" false ownNames bodyNode invocations -- Build preamble: local copies of user params + mapping init assigns let mut preamble : List StmtExprMd := [] -- 0. Return variables start at their type's zero value, as in @@ -477,6 +553,12 @@ def translateFunction (ctx : TransCtx) (fn : Solidity.node SourceRange) if ctx.arrayStateVars.contains name then preamble := preamble ++ [mkStmtExprMd (.Assign [toAssignTarget (mkStmtExprMd (mkIdentifier s!"{name}_length"))] (mkStmtExprMd (mkIdentifier s!"{name}_length_in")))] + -- 4. A constructor runs the base constructors first, after the + -- state-variable initializers (solc's legacy order) and outside its + -- own modifiers. + if isConstructor && !ctx.baseConstructors.isEmpty then + preamble := preamble ++ (← baseConstructorStmts bodyCtx ctx.contractName + (userParamInfo.map (·.1)) ctx.baseConstructors) let bodyExpr := if preamble.isEmpty then b else mkStmtExprMd (.Block (preamble ++ [b]) none) -- Translate contract invariant nodes once in this function's body context, @@ -589,9 +671,12 @@ def translateFunction (ctx : TransCtx) (fn : Solidity.node SourceRange) -- of a function share the function's range, so without distinct -- summaries every `ensures` of a function would collapse into one -- reported obligation. + let inheritedBy := match ctx.verifiedIn with + | some c => s!" (in {c})" + | none => "" let mkPost (sr : SourceRange) (summary : String) (p : StmtExprMd) : Condition := { condition := withSourceRangeDeep ctx sr (withSourceRange ctx sr p), - summary := some summary } + summary := some (summary ++ inheritedBy) } let specConds := (specPostExprs.zip natspecPostsAt).map fun (p, (src, r)) => mkPost r s!"ensures {src}" p let frameConds := frameConditions.map fun (name, p) => diff --git a/StrataSolidity/SolTranslator/Types.lean b/StrataSolidity/SolTranslator/Types.lean index 0e232ee..8d5fb16 100644 --- a/StrataSolidity/SolTranslator/Types.lean +++ b/StrataSolidity/SolTranslator/Types.lean @@ -70,6 +70,28 @@ structure StorageAlias where read of which is an unknown value. -/ target : Option StmtExprMd := none +/-- The constructor of a base contract, which runs when a contract + inheriting it is deployed: before the derived constructor, after the + state-variable initializers. -/ +structure BaseCtor where + /-- The contract it is the constructor of. -/ + contractName : String + /-- Its parameters: name, type, Solidity type name (for the type range). -/ + params : List (String × HighTypeMd × String) + /-- The arguments it is given, and the contract whose constructor gives + them (`constructor() Base(7)`; its parameters are in scope there). + `none` when they are unknown: given where they are not read (an + inheritance specifier, `is Base(7)`), or not given (an abstract + contract). -/ + args : Option (List (Solidity.node SourceRange) × String) + /-- Its body. -/ + body : Solidity.node SourceRange + /-- Its modifier invocations (base-constructor calls included; those + name no modifier and are skipped). -/ + modifiers : List (Solidity.node SourceRange) + /-- What `super.f(…)` calls in it (see `TransCtx.superImpls`). -/ + superImpls : List (String × String) := [] + /-- What an internal call site needs to know about its callee, so that it passes the callee's implicit inputs in their declared order and binds its state outputs (see `translateFunction` for the signature). -/ @@ -216,6 +238,28 @@ structure TransCtx where /-- Names of the contracts and interfaces of the source unit: a value of such a type is an address. -/ contractTypeNames : List String := [] + /-- Every contract of the source unit, by name. solc does not flatten + inherited members into a derived contract, so `translateContract` + reads a contract's bases from here and verifies the contract as the + flattening of its bases and itself. -/ + contractNodes : List (String × Solidity.node SourceRange) := [] + /-- The contract a function defined in one of its bases is being verified + in (`none` for a contract's own functions): obligations name it, as + the same clause is checked once per contract that inherits it. -/ + verifiedIn : Option String := none + /-- What `super.f(…)` calls in the code being translated, by `f`: the + callee's name, or why there is none (`!overloaded`, `!none`). It + depends on the contract the code is written in (see + `ContractTranslator`). -/ + superImpls : List (String × String) := [] + /-- What `X.f(…)` calls, for a base `X`, by `(X, f)`; as `superImpls`. -/ + explicitImpls : List ((String × String) × String) := [] + /-- The `superImpls` of each modifier, by name: those of the contract + that defines it. -/ + modifierSuperImpls : List (String × List (String × String)) := [] + /-- The base constructors a constructor of this contract runs first, in + the order they run (most base first). -/ + baseConstructors : List BaseCtor := [] /-- The `immutable` state variables, which keep their value once the constructor has run. -/ immutableNames : List String := [] diff --git a/docs/guide/src/limitations.md b/docs/guide/src/limitations.md index a0aa8df..6c969cf 100644 --- a/docs/guide/src/limitations.md +++ b/docs/guide/src/limitations.md @@ -43,6 +43,9 @@ mapping(bytes32 => bool) public paymentCaptured; | `type(uint256).max/min` | ✅ | | Contract invariants | ✅ | | Loop invariants | ✅ | +| Inherited state, functions, modifiers and invariants; virtual dispatch | ✅ | +| Base constructors, with their modifiers and arguments | ✅ | +| `super` and `Base.f()`, along the C3 linearization | ✅ | ## Not yet supported @@ -55,5 +58,8 @@ mapping(bytes32 => bool) public paymentCaptured; | External calls / reentrancy (GAP-007) | Not interpreted: a call that may re-enter the contract leaves its state unknown, except for the contract invariants (see [Contract Invariants](./contract_invariants.md#external-calls-and-reentrancy)); `--assume-no-reentrancy` trusts that calls do not re-enter | | Assembly / inline Yul | Not interpreted: what a block may write (the variables it assigns, memory variables, contract state) is unknown afterwards, and a block that may `return` or `stop` ends the transaction on some paths, as `selfdestruct` does. A call of a function that may end the transaction is rejected | | Dynamic arrays (`push`/`pop`) (GAP-008) | `.length` works, `push`/`pop` not modeled | -| Inheritance (GAP-009) | Single contract only, no virtual dispatch | +| A base contract in another file (GAP-009) | Only the contracts of the verified file are flattened into their derived contracts: an imported base's state, functions and invariants are reported as not part of the verification | +| Arguments in an inheritance specifier (`is Base(7)`) | Not read: the base constructor runs with unknown arguments of their types. Arguments given in a constructor (`constructor() Base(7)`) are used | +| A base's private state variable declared again in a derived contract | Rejected: they are different variables | +| `super.f()` of an overloaded function | Rejected | | Lemmas (`@custom:strata lemma`) (GAP-004) | Needs Laurel grammar extension | diff --git a/docs/guide/src/overview.md b/docs/guide/src/overview.md index 028e9ee..04586b3 100644 --- a/docs/guide/src/overview.md +++ b/docs/guide/src/overview.md @@ -35,7 +35,7 @@ Solidity's execution model is simpler than most general-purpose languages: - **No heap aliasing** — storage is a flat key-value store. Two state variables cannot point to the same memory. - **No concurrency** — the EVM is single-threaded. -- **No dynamic dispatch** — inheritance exists but external calls are explicit. +- **Static dispatch** — external calls are explicit, and which override runs follows from the contract being verified. - **Deterministic execution** — same inputs always produce same outputs. These properties eliminate entire classes of verification complexity that tools for Java, Rust, or C must handle. diff --git a/docs/guide/src/supported_features.md b/docs/guide/src/supported_features.md index 42bb006..8a7a977 100644 --- a/docs/guide/src/supported_features.md +++ b/docs/guide/src/supported_features.md @@ -6,7 +6,11 @@ StrataSolidity supports a substantial subset of Solidity. Support is being expan **Core constructs:** - Contracts, functions (public/external/internal/private), state variables, constructors -- Inheritance (single and diamond) +- Inheritance (single and diamond): a contract is verified with everything + it inherits (state, functions, modifiers, invariants, its bases' + constructors), an inherited function calls the most derived override, and + `super` follows the C3 linearization. A base in another file is reported + as not covered (see [Current Limitations](./limitations.md)) - Modifiers, inlined with their arguments (`_` stands for the rest of the function; not modifiers of an imported base contract) **Types:** diff --git a/test/examples/inheritance.sol b/test/examples/inheritance.sol new file mode 100644 index 0000000..7077fe9 --- /dev/null +++ b/test/examples/inheritance.sol @@ -0,0 +1,103 @@ +// SPDX-License-Identifier: MIT +pragma solidity ^0.8.0; + +// A contract is verified as the flattening of its bases and itself: what it +// inherits (state, functions, modifiers, invariants) is checked in its own +// context, and an obligation of an inherited function names the contract it +// is checked in, `(in Fast)`. Each contract is also verified on its own. + +/// @custom:strata invariant count <= limit +contract Counter { + uint256 public limit = 100; + uint256 public count; + address public owner; + + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + /// @custom:strata ensures r == a + 1 + function _plusOne(uint256 a) internal pure returns (uint256 r) { + r = a + 1; + } + + /// @custom:strata ensures r == 1 + function _step() internal pure virtual returns (uint256 r) { + r = 1; + } + + // Refuted in Fast: there `advance` calls Fast's `_step`, which adds 5. + // (Proven in Counter.) + /// @custom:strata requires count + 5 <= limit + /// @custom:strata ensures count == old(count) + 1 + function advance() public { + count = count + _step(); + } +} + +contract Fast is Counter { + /// @custom:strata ensures r == 5 + function _step() internal pure override returns (uint256 r) { + r = 5; + } + + // Passes: the inherited `advance` runs this contract's `_step`. + /// @custom:strata requires count + 5 <= limit + /// @custom:strata ensures count == old(count) + 5 + function advanceFast() external { + count = count + _step(); + } + + // Passes: the inherited modifier's `require` holds in the body. + /// @custom:strata ensures msg.sender == owner + function reset() external onlyOwner { + count = 0; + } + + // Refuted: the same modifier admits only the owner. + /// @custom:strata ensures msg.sender != owner + function resetWrong() external onlyOwner { + count = 0; + } + + // Passes: the inherited internal function is called with its spec. + /// @custom:strata requires count < limit + /// @custom:strata ensures count == old(count) + 1 + function bump() external { + count = _plusOne(count); + } + + // Refuted: `_plusOne` adds one. + /// @custom:strata requires count < limit + /// @custom:strata ensures count == old(count) + function bumpWrong() external { + count = _plusOne(count); + } + + // Passes: the inherited invariant `count <= limit` holds on exit. + function fill() external { + count = limit; + } + + // Refuted: this breaks the inherited invariant. + function overfill() external { + count = limit + 1; + } +} + +contract Named { + uint256 public y; + + function id() external virtual returns (uint256) { + y = 1; + return 1; + } +} + +// Passes: in Renamed, `id` is the getter of the state variable that +// overrides the function, so `y` never changes. +/// @custom:strata invariant y == 0 +contract Renamed is Named { + uint256 public override id = 7; +} diff --git a/test/examples/inheritance_constructors.sol b/test/examples/inheritance_constructors.sol new file mode 100644 index 0000000..b6466a4 --- /dev/null +++ b/test/examples/inheritance_constructors.sol @@ -0,0 +1,137 @@ +// SPDX-License-Identifier: MIT +pragma solidity ^0.8.0; + +// Deploying a contract runs its bases' constructors first, most base first, +// after the state-variable initializers. Each runs with its own modifiers, +// before the derived constructor's modifiers, and a `return` in it ends +// only that constructor. Its arguments are those the derived constructor +// gives (`constructor() Base(7)`); those of an inheritance specifier +// (`is Base(7)`) are not read, so the parameters are unknown values. + +contract Owned { + address public owner; + + constructor() { + owner = msg.sender; + } + + modifier onlyOwner() { + require(msg.sender == owner); + _; + } +} + +// Owned's constructor runs before `onlyOwner`, so the require passes. +contract Vault is Owned { + uint256 public total; + + // Passes. + /// @custom:strata ensures owner == msg.sender && total == 1 + constructor() onlyOwner { + total = 1; + } +} + +contract VaultWrong is Owned { + uint256 public total; + + // Refuted: the body runs, so total is 1. + /// @custom:strata ensures total == 0 + constructor() onlyOwner { + total = 1; + } +} + +contract Counted { + uint256 public x; + + modifier setsX() { + x = 5; + _; + } + + constructor() setsX { + uint256 t = 1; + if (t == 1) { + return; + } + x = 9; + } +} + +// Counted's modifier sets x to 5; its `return` skips `x = 9` but not the +// rest of the deployment. Its local `t` is not this constructor's `t`. +contract Recount is Counted { + uint256 public y; + + // Passes. + /// @custom:strata ensures x == 6 && y == 2 + constructor() { + uint256 t = 2; + y = t; + x = x + 1; + } +} + +contract RecountWrong is Counted { + uint256 public y; + + // Refuted: x is 6. + /// @custom:strata ensures x == 9 + constructor() { + uint256 t = 2; + y = t; + x = x + 1; + } +} + +contract Priced { + uint256 public price; + + constructor(uint256 p) { + price = p; + } +} + +contract Doubled is Priced { + // Passes: Priced's parameter is 2 * q. + /// @custom:strata requires q < 1000 + /// @custom:strata ensures price == 2 * q + constructor(uint256 q) Priced(q * 2) {} +} + +contract Halved is Priced { + // Refuted: price is 2 * q. + /// @custom:strata requires q < 1000 + /// @custom:strata ensures price == q + constructor(uint256 q) Priced(q * 2) {} +} + +contract Middle is Priced { + constructor(uint256 q) Priced(q + 1) {} +} + +contract Top is Middle { + // Passes: Middle's parameter is 4, so Priced's is 5. + /// @custom:strata ensures price == 5 + constructor() Middle(4) {} +} + +contract TopWrong is Middle { + // Refuted: price is 5. + /// @custom:strata ensures price == 4 + constructor() Middle(4) {} +} + +contract Fixed is Priced(7) { + // Fails: the specifier's argument is not read, so price is any uint256 + // value (it is 7). + /// @custom:strata ensures price == 7 + constructor() {} +} + +contract FixedTrue is Priced(7) { + // Passes: whatever the argument, price holds a uint256. + /// @custom:strata ensures price <= type(uint256).max + constructor() {} +} diff --git a/test/examples/inheritance_diamond.sol b/test/examples/inheritance_diamond.sol new file mode 100644 index 0000000..c327ff4 --- /dev/null +++ b/test/examples/inheritance_diamond.sol @@ -0,0 +1,52 @@ +// SPDX-License-Identifier: MIT +pragma solidity ^0.8.0; + +// `super` follows the C3 linearization, which depends on the contract being +// verified: for `D is B, C` the order is D, C, B, A, so `C.setX`'s `super` +// is `B.setX` in D, while it is `A.setX` when C is verified on its own. +// +// An absolute postcondition cannot hold in both linearizations: `C.setX` +// adds 2 to what its `super` produces, which is `val + 1` in D and `val` +// in C alone. The specification below is the one D needs, so it is proven +// for D, `(in D)`, and not for C on its own, where it does not hold. + +contract A { + uint256 public x; + + // Passes. + /// @custom:strata ensures x == val + function setX(uint256 val) public virtual { + x = val; + } +} + +contract B is A { + // Passes. + /// @custom:strata ensures x == val + 1 + function setX(uint256 val) public virtual override { + super.setX(val + 1); + } +} + +contract C is A { + // Not proven in C: there `super.setX` is A's, so x is val + 2. Proven + // in D. + /// @custom:strata ensures x == val + 3 + function setX(uint256 val) public virtual override { + super.setX(val + 2); + } +} + +contract D is B, C { + // Passes. + /// @custom:strata ensures x == val + 3 + function setX(uint256 val) public override(B, C) { + super.setX(val); + } + + // Not proven: x is val + 3. + /// @custom:strata ensures x == val + 2 + function setXWrong(uint256 val) external { + super.setX(val); + } +} diff --git a/test/examples/inheritance_imported.sol b/test/examples/inheritance_imported.sol new file mode 100644 index 0000000..6ea7bc3 --- /dev/null +++ b/test/examples/inheritance_imported.sol @@ -0,0 +1,27 @@ +// SPDX-License-Identifier: MIT +pragma solidity ^0.8.0; + +// A base in another file contributes no members here: its state, +// constructor, functions and invariant are not part of what is verified, +// for the contract that names it and for every contract inheriting it +// through another one. Both are reported. + +import "./lib/Ownable.sol"; + +contract Borrowed is Ownable { + uint256 public own; + + // Passes. + /// @custom:strata ensures own == v + function setOwn(uint256 v) external { + own = v; + } +} + +contract Lent is Borrowed { + // Refuted: `own` is `v`. + /// @custom:strata ensures own == v + 1 + function setOwnWrong(uint256 v) external { + own = v; + } +} diff --git a/test/examples/inheritance_linearization.sol b/test/examples/inheritance_linearization.sol new file mode 100644 index 0000000..48d3e0e --- /dev/null +++ b/test/examples/inheritance_linearization.sol @@ -0,0 +1,43 @@ +// SPDX-License-Identifier: MIT +pragma solidity ^0.8.0; + +// Base constructors run in the reverse of solc's C3 linearization. Here +// L(Z) = Z, K2, K1, A, B, Root, so they run Root, B, A, K1, K2: x is +// (1 * 2) + 1. A depth-first order of the base lists (Root, A, K1, B, K2) +// would give (1 + 1) * 2. + +contract Root { + uint256 public x; + + constructor() { + x = 1; + } +} + +contract A is Root { + constructor() { + x = x + 1; + } +} + +contract B is Root { + constructor() { + x = x * 2; + } +} + +contract K1 is A {} + +contract K2 is B, A {} + +contract Z is K1, K2 { + // Passes. + /// @custom:strata ensures x == 3 + constructor() {} +} + +contract ZWrong is K1, K2 { + // Refuted: x is 3. + /// @custom:strata ensures x == 4 + constructor() {} +} diff --git a/test/examples/inheritance_overloads.sol b/test/examples/inheritance_overloads.sol new file mode 100644 index 0000000..9224aae --- /dev/null +++ b/test/examples/inheritance_overloads.sol @@ -0,0 +1,37 @@ +// SPDX-License-Identifier: MIT +pragma solidity ^0.8.0; + +// An override has the parameter types of the function it replaces; a +// function of the same name with other parameters is an overload, and the +// inherited function stays a function of the derived contract. (Overloads +// whose parameters are all integers or addresses, `f(uint256)` and +// `f(address)`, have the same parameter types in the verifier and are +// rejected, in one contract too.) + +contract Base { + // Passes, also in Derived, where it is inherited. + /// @custom:strata ensures r == a + function f(uint256 a) public pure virtual returns (uint256 r) { + r = a; + } + + // Refuted, also in Derived. + /// @custom:strata ensures r == a + 1 + function g(uint256 a) public pure returns (uint256 r) { + r = a; + } +} + +contract Derived is Base { + // Passes: an overload of `f`, not an override. + /// @custom:strata ensures r == !a + function f(bool a) public pure returns (bool r) { + r = !a; + } + + // Passes: an overload of the inherited `g`. + /// @custom:strata ensures r == a + b + function g(uint256 a, uint256 b) public pure returns (uint256 r) { + r = a + b; + } +} diff --git a/test/examples/inheritance_shadowed_state.sol b/test/examples/inheritance_shadowed_state.sol new file mode 100644 index 0000000..1cc7286 --- /dev/null +++ b/test/examples/inheritance_shadowed_state.sol @@ -0,0 +1,18 @@ +// SPDX-License-Identifier: MIT +pragma solidity ^0.8.0; + +// A derived contract may declare a state variable named like a private one +// of a base: they are different variables, in different storage slots. +// Verifying the flattening would merge them, so the file is rejected. + +contract Base { + uint256 private x; + + function setBase() external { + x = 1; + } +} + +contract Derived is Base { + uint256 public x; +} diff --git a/test/examples/inheritance_struct_mapping.sol b/test/examples/inheritance_struct_mapping.sol new file mode 100644 index 0000000..5552259 --- /dev/null +++ b/test/examples/inheritance_struct_mapping.sol @@ -0,0 +1,41 @@ +// SPDX-License-Identifier: MIT +pragma solidity ^0.8.0; + +// A struct-valued mapping is not supported, and a function using it is not +// verified (reported). A derived constructor that runs a base constructor +// using one is not verified either, nor are the invariants it would +// establish; the derived contract's other functions are. + +contract Registry { + struct P { + uint256 a; + } + mapping(uint256 => P) internal ps; + + constructor() { + ps[1].a = 1; + } +} + +/// @custom:strata invariant m <= 100 +contract Child is Registry { + uint256 public m; + + constructor() { + m = 1; + } + + // Passes. + /// @custom:strata requires v <= 100 + /// @custom:strata ensures m == v + function set(uint256 v) external { + m = v; + } + + // Refuted. + /// @custom:strata requires v <= 100 + /// @custom:strata ensures m == v + 1 + function setWrong(uint256 v) external { + m = v; + } +} diff --git a/test/examples/inheritance_super.sol b/test/examples/inheritance_super.sol new file mode 100644 index 0000000..9a247ed --- /dev/null +++ b/test/examples/inheritance_super.sol @@ -0,0 +1,177 @@ +// SPDX-License-Identifier: MIT +pragma solidity ^0.8.0; + +// `super.f(…)` runs the implementation of `f` that follows, in the +// linearization of the contract being verified, the contract the call is +// written in: in a function, a modifier or a constructor. `Base.f(…)` runs +// the one `Base` has. A chain has one linearization (Top, Mid, Base), so +// each postcondition below holds wherever its contract is verified. + +contract Base { + uint256 public x; + + // Passes. + /// @custom:strata ensures x == val + 1 + function setX(uint256 val) public virtual { + x = val + 1; + } +} + +contract Mid is Base { + // Passes: Base adds 1 to val + 2. + /// @custom:strata ensures x == val + 3 + function setX(uint256 val) public virtual override { + super.setX(val + 2); + } +} + +contract Top is Mid { + // Passes. + /// @custom:strata ensures x == val + 3 + function setX(uint256 val) public override { + super.setX(val); + } + + // Not proven: in Top, `super.setX` is Mid's, which adds 3. + /// @custom:strata ensures x == val + 1 + function viaSuper(uint256 val) external { + super.setX(val); + } + + // Passes: `Base.setX` is Base's implementation. + /// @custom:strata ensures x == val + 1 + function viaBase(uint256 val) external { + Base.setX(val); + } + + // Not proven: Base's adds 1. + /// @custom:strata ensures x == val + 3 + function viaBaseWrong(uint256 val) external { + Base.setX(val); + } +} + +contract Pair { + uint256 public x; + + /// @custom:strata ensures x == a * 10 + b + function set(uint256 a, uint256 b) public virtual { + x = a * 10 + b; + } +} + +contract PairChild is Pair { + // Passes: named arguments bind by name. + /// @custom:strata requires a < 10 && b < 10 + /// @custom:strata ensures x == a * 10 + b + function set(uint256 a, uint256 b) public override { + super.set({b: b, a: a}); + } +} + +contract PairWrong is Pair { + // Not proven: `a` is the tens. + /// @custom:strata requires a < 10 && b < 10 + /// @custom:strata ensures x == b * 10 + a + function set(uint256 a, uint256 b) public override { + super.set({b: b, a: a}); + } +} + +contract Plain { + uint256 public x; + + /// @custom:strata ensures x == 1 + function f() public virtual { + x = 1; + } +} + +// Passes: Middle does not override `f`, so its `super.f` is Plain's, the +// one Leaf has too. +contract Middle is Plain { + /// @custom:strata ensures x == 1 + function g() public { + super.f(); + } +} + +contract Leaf is Middle {} + +contract MA { + uint256 public x; + + /// @custom:strata ensures x == 1 + function f() public virtual { + x = 1; + } +} + +contract MB is MA { + /// @custom:strata ensures x == 2 + function f() public virtual override { + x = 2; + } + + modifier m() { + super.f(); + _; + } +} + +contract MC is MB { + /// @custom:strata ensures x == 3 + function f() public override { + x = 3; + } + + // Passes: `m` is written in MB, where `super.f` is MA's. + /// @custom:strata ensures x == 1 + function g() public m {} + + // Not proven: x is 1. + /// @custom:strata ensures x == 2 + function h() public m {} +} + +contract KA { + /// @custom:strata ensures r == 1 + function k() internal pure virtual returns (uint256 r) { + r = 1; + } +} + +contract KB is KA { + uint256 public x; + + /// @custom:strata ensures r == 2 + function k() internal pure virtual override returns (uint256 r) { + r = 2; + } + + constructor() { + x = super.k(); + } +} + +contract KC is KB { + /// @custom:strata ensures r == 3 + function k() internal pure override returns (uint256 r) { + r = 3; + } + + // Passes: KB's constructor is written in KB, where `super.k` is KA's. + /// @custom:strata ensures x == 1 + constructor() {} +} + +contract KCWrong is KB { + /// @custom:strata ensures r == 3 + function k() internal pure override returns (uint256 r) { + r = 3; + } + + // Refuted: x is 1. + /// @custom:strata ensures x == 2 + constructor() {} +} diff --git a/test/examples/lib/Ownable.sol b/test/examples/lib/Ownable.sol new file mode 100644 index 0000000..702348c --- /dev/null +++ b/test/examples/lib/Ownable.sol @@ -0,0 +1,14 @@ +// SPDX-License-Identifier: MIT +pragma solidity ^0.8.0; + +// A base contract in another file. Only the verified source unit's +// contracts are flattened into their derived contracts, so what this +// declares is reported as not part of the verification. +/// @custom:strata invariant owner != address(0) +contract Ownable { + address public owner; + + constructor() { + owner = msg.sender; + } +} diff --git a/test/expected/inheritance.expected b/test/expected/inheritance.expected new file mode 100644 index 0000000..ad90007 --- /dev/null +++ b/test/expected/inheritance.expected @@ -0,0 +1,34 @@ +✅ 10: invariant count <= limit +✅ 20: ensures r == a + 1 +✅ 20: ensures r == a + 1 (in Fast) +✅ 25: ensures r == 1 +✅ 33: ensures count == old(count) + 1 +❌ 33: ensures count == old(count) + 1 (in Fast) +✅ 34: heap frame (only this contract is modified) +✅ 34: heap frame (only this contract is modified) +✅ 34: invariant count <= limit +✅ 34: invariant count <= limit (in Fast) +✅ 39: invariant count <= limit +✅ 40: ensures r == 5 +✅ 47: ensures count == old(count) + 5 +✅ 48: heap frame (only this contract is modified) +✅ 48: invariant count <= limit +✅ 53: ensures msg.sender == owner +✅ 54: heap frame (only this contract is modified) +✅ 54: invariant count <= limit +❌ 59: ensures msg.sender != owner +✅ 60: heap frame (only this contract is modified) +✅ 60: invariant count <= limit +✅ 66: ensures count == old(count) + 1 +✅ 67: heap frame (only this contract is modified) +✅ 67: invariant count <= limit +❌ 73: ensures count == old(count) +✅ 74: heap frame (only this contract is modified) +✅ 74: invariant count <= limit +✅ 79: heap frame (only this contract is modified) +✅ 79: invariant count <= limit +✅ 84: heap frame (only this contract is modified) +❌ 84: invariant count <= limit +✅ 92: heap frame (only this contract is modified) +✅ 101: invariant y == 0 +29 passed, 4 failed, 0 unknown out of 33 total diff --git a/test/expected/inheritance_constructors.expected b/test/expected/inheritance_constructors.expected new file mode 100644 index 0000000..4409a87 --- /dev/null +++ b/test/expected/inheritance_constructors.expected @@ -0,0 +1,11 @@ +✅ 29: ensures owner == msg.sender && total == 1 +❌ 39: ensures total == 0 +✅ 68: ensures x == 6 && y == 2 +❌ 80: ensures x == 9 +✅ 99: ensures price == 2 * q +❌ 106: ensures price == q +✅ 116: ensures price == 5 +❌ 122: ensures price == 4 +❌ 129: ensures price == 7 +✅ 135: ensures price <= type(uint256).max +5 passed, 5 failed, 0 unknown out of 10 total diff --git a/test/expected/inheritance_diamond.expected b/test/expected/inheritance_diamond.expected new file mode 100644 index 0000000..ca443bf --- /dev/null +++ b/test/expected/inheritance_diamond.expected @@ -0,0 +1,21 @@ +✅ 17: ensures x == val +✅ 17: ensures x == val (in B) +✅ 17: ensures x == val (in C) +✅ 17: ensures x == val (in D) +✅ 18: heap frame (only this contract is modified) +✅ 18: heap frame (only this contract is modified) +✅ 18: heap frame (only this contract is modified) +✅ 18: heap frame (only this contract is modified) +✅ 25: ensures x == val + 1 +✅ 25: ensures x == val + 1 (in D) +✅ 26: heap frame (only this contract is modified) +✅ 26: heap frame (only this contract is modified) +❓ 34: ensures x == val + 3 +✅ 34: ensures x == val + 3 (in D) +✅ 35: heap frame (only this contract is modified) +✅ 35: heap frame (only this contract is modified) +✅ 42: ensures x == val + 3 +✅ 43: heap frame (only this contract is modified) +❓ 48: ensures x == val + 2 +✅ 49: heap frame (only this contract is modified) +18 passed, 0 failed, 2 unknown out of 20 total diff --git a/test/expected/inheritance_imported.expected b/test/expected/inheritance_imported.expected new file mode 100644 index 0000000..a53f0ec --- /dev/null +++ b/test/expected/inheritance_imported.expected @@ -0,0 +1,7 @@ +✅ 15: ensures own == v +✅ 15: ensures own == v (in Lent) +✅ 16: heap frame (only this contract is modified) +✅ 16: heap frame (only this contract is modified) +❌ 23: ensures own == v + 1 +✅ 24: heap frame (only this contract is modified) +5 passed, 1 failed, 0 unknown out of 6 total diff --git a/test/expected/inheritance_imported.warnings b/test/expected/inheritance_imported.warnings new file mode 100644 index 0000000..e531b14 --- /dev/null +++ b/test/expected/inheritance_imported.warnings @@ -0,0 +1,2 @@ +inheritance_imported.sol:11:1: warning: base contract `Ownable` of `Borrowed` is not defined in this file: its state, functions and invariants are not part of what is verified here +inheritance_imported.sol:21:1: warning: base contract `Ownable` of `Lent` is not defined in this file: its state, functions and invariants are not part of what is verified here diff --git a/test/expected/inheritance_linearization.expected b/test/expected/inheritance_linearization.expected new file mode 100644 index 0000000..0125594 --- /dev/null +++ b/test/expected/inheritance_linearization.expected @@ -0,0 +1,3 @@ +✅ 35: ensures x == 3 +❌ 41: ensures x == 4 +1 passed, 1 failed, 0 unknown out of 2 total diff --git a/test/expected/inheritance_overloads.expected b/test/expected/inheritance_overloads.expected new file mode 100644 index 0000000..545bccf --- /dev/null +++ b/test/expected/inheritance_overloads.expected @@ -0,0 +1,7 @@ +✅ 13: ensures r == a +✅ 13: ensures r == a (in Derived) +❌ 19: ensures r == a + 1 +❌ 19: ensures r == a + 1 (in Derived) +✅ 27: ensures r == !a +✅ 33: ensures r == a + b +4 passed, 2 failed, 0 unknown out of 6 total diff --git a/test/expected/inheritance_shadowed_state.expected b/test/expected/inheritance_shadowed_state.expected new file mode 100644 index 0000000..515fed9 --- /dev/null +++ b/test/expected/inheritance_shadowed_state.expected @@ -0,0 +1 @@ +Exception: Solidity to Laurel translation failed: Unsupported: the state variable `x` of `Base`, declared again in `Derived`: they are different variables diff --git a/test/expected/inheritance_struct_mapping.expected b/test/expected/inheritance_struct_mapping.expected new file mode 100644 index 0000000..6496b36 --- /dev/null +++ b/test/expected/inheritance_struct_mapping.expected @@ -0,0 +1,5 @@ +✅ 30: ensures m == v +✅ 31: heap frame (only this contract is modified) +❌ 37: ensures m == v + 1 +✅ 38: heap frame (only this contract is modified) +3 passed, 1 failed, 0 unknown out of 4 total diff --git a/test/expected/inheritance_struct_mapping.warnings b/test/expected/inheritance_struct_mapping.warnings new file mode 100644 index 0000000..fdf8525 --- /dev/null +++ b/test/expected/inheritance_struct_mapping.warnings @@ -0,0 +1,3 @@ +inheritance_struct_mapping.sol:15:5: warning: the constructor is not verified: it uses the struct-valued mapping `ps`, which is not supported +inheritance_struct_mapping.sol:21:1: warning: the invariants of contract `Child` are not verified: its constructor, which must establish them, is not verified +inheritance_struct_mapping.sol:24:5: warning: the constructor is not verified: a base constructor it runs uses the struct-valued mapping `ps`, which is not supported diff --git a/test/expected/inheritance_super.expected b/test/expected/inheritance_super.expected new file mode 100644 index 0000000..6d2282c --- /dev/null +++ b/test/expected/inheritance_super.expected @@ -0,0 +1,60 @@ +✅ 14: ensures x == val + 1 +✅ 14: ensures x == val + 1 (in Mid) +✅ 14: ensures x == val + 1 (in Top) +✅ 15: heap frame (only this contract is modified) +✅ 15: heap frame (only this contract is modified) +✅ 15: heap frame (only this contract is modified) +✅ 22: ensures x == val + 3 +✅ 22: ensures x == val + 3 (in Top) +✅ 23: heap frame (only this contract is modified) +✅ 23: heap frame (only this contract is modified) +✅ 30: ensures x == val + 3 +✅ 31: heap frame (only this contract is modified) +❓ 36: ensures x == val + 1 +✅ 37: heap frame (only this contract is modified) +✅ 42: ensures x == val + 1 +✅ 43: heap frame (only this contract is modified) +❓ 48: ensures x == val + 3 +✅ 49: heap frame (only this contract is modified) +✅ 57: ensures x == a * 10 + b +✅ 57: ensures x == a * 10 + b (in PairChild) +✅ 57: ensures x == a * 10 + b (in PairWrong) +✅ 58: heap frame (only this contract is modified) +✅ 58: heap frame (only this contract is modified) +✅ 58: heap frame (only this contract is modified) +✅ 66: ensures x == a * 10 + b +✅ 67: heap frame (only this contract is modified) +❓ 75: ensures x == b * 10 + a +✅ 76: heap frame (only this contract is modified) +✅ 84: ensures x == 1 +✅ 84: ensures x == 1 (in Leaf) +✅ 84: ensures x == 1 (in Middle) +✅ 85: heap frame (only this contract is modified) +✅ 85: heap frame (only this contract is modified) +✅ 85: heap frame (only this contract is modified) +✅ 93: ensures x == 1 +✅ 93: ensures x == 1 (in Leaf) +✅ 94: heap frame (only this contract is modified) +✅ 94: heap frame (only this contract is modified) +✅ 104: ensures x == 1 +✅ 104: ensures x == 1 (in MC) +✅ 105: heap frame (only this contract is modified) +✅ 105: heap frame (only this contract is modified) +✅ 111: ensures x == 2 +✅ 112: heap frame (only this contract is modified) +✅ 123: ensures x == 3 +✅ 124: heap frame (only this contract is modified) +✅ 129: ensures x == 1 +✅ 130: heap frame (only this contract is modified) +❓ 133: ensures x == 2 +✅ 134: heap frame (only this contract is modified) +✅ 138: ensures r == 1 +✅ 138: ensures r == 1 (in KB) +✅ 138: ensures r == 1 (in KC) +✅ 138: ensures r == 1 (in KCWrong) +✅ 147: ensures r == 2 +✅ 158: ensures r == 3 +✅ 164: ensures x == 1 +✅ 169: ensures r == 3 +❌ 175: ensures x == 2 +54 passed, 1 failed, 4 unknown out of 59 total