std:EVM/Signature

lib/EVM/Signature.omg

lib/EVM/Signature.omg307 lines
1{-  The EVM signature: the interface of the EVM that the compiler and the
2    reference model share (docs/evm.md, section 4.1).
3
4    It is a record of operations over abstract types: `Val` for the
5    run-time words, `Flag` for the run-time conditions and `Code` for the
6    rest of an execution, so that the state operations are in
7    continuation-passing style.  The compiler takes the operations as
8    variables and reads the instructions off the normal form; the reference
9    model (`std:EVM/Model`) gives them over `Word 256`, `Bool` and a function
10    of the world.
11
12    This is the subset of the first end-to-end slices: the pure word
13    operations of `std:EVM/Model.words`, the hash of a text, the frame's
14    caller, own address, call value and call data, the block's timestamp,
15    the immutables,
16    storage and transient storage, logs, calls to other contracts and
17    their return data, a two-way branch, a switch on literal keys, a
18    bounded loop and the halts.  No operation returns meta-level data,
19    which is what lets staging compute every library function away.
20-}
21
22-- Where a storage word lives.  The reference model keys its storage by
23-- these values, structurally (a direct index modulo 2^bits); the compiler
24-- lowers them to slots (docs/evm.md, section 6.5):
25--
26-- - `Fixed s` is the slot s;
27-- - `Direct { base, bits, index }` is base + (index mod 2^bits): a direct
28--   region of 2^bits slots, aligned and below 2^255, so that an address
29--   is its own slot in region 0, with no hashing;
30-- - `Hashed { domain, parts }` is keccak256(k1 ‖ … ‖ kn ‖ domain) with the
31--   top bit set, each 32 bytes: never a direct slot;
32-- - `Solidity { domain, parts }` is a Solidity (nested) mapping at slot
33--   `domain`: with h0 = domain, hi = keccak256(ki ‖ h(i-1)), the slot hn.
34let Key =
35      \(Val : Type) ->
36        < Fixed : Natural
37        | Direct : { base : Natural, bits : Natural, index : Val }
38        | Hashed : { domain : Natural, parts : List Val }
39        | Solidity : { domain : Natural, parts : List Val }
40        >
41
42-- The pure operations on words: one instruction each, with the operands in
43-- the order of the instruction's stack operands, top first (`sub a b` is
44-- a - b, `shr shift value`).  A comparison gives a flag; `flagVal` gives
45-- the word 0 or 1 an instruction pushes for it.
46let Words =
47      \(Val : Type) (Flag : Type) ->
48        { lit : Natural -> Val
49        , add : Val -> Val -> Val
50        , mul : Val -> Val -> Val
51        , sub : Val -> Val -> Val
52        , div : Val -> Val -> Val
53        , mod : Val -> Val -> Val
54        , sdiv : Val -> Val -> Val
55        , smod : Val -> Val -> Val
56        , addmod : Val -> Val -> Val -> Val
57        , mulmod : Val -> Val -> Val -> Val
58        , exp : Val -> Val -> Val
59        , signextend : Val -> Val -> Val
60        , lt : Val -> Val -> Flag
61        , gt : Val -> Val -> Flag
62        , slt : Val -> Val -> Flag
63        , sgt : Val -> Val -> Flag
64        , eq : Val -> Val -> Flag
65        , isZero : Val -> Flag
66        , and : Val -> Val -> Val
67        , or : Val -> Val -> Val
68        , xor : Val -> Val -> Val
69        , not : Val -> Val
70        , byte : Val -> Val -> Val
71        , shl : Val -> Val -> Val
72        , shr : Val -> Val -> Val
73        , sar : Val -> Val -> Val
74        , clz : Val -> Val
75        , flagLit : Bool -> Flag
76        , flagNot : Flag -> Flag
77        , flagAnd : Flag -> Flag -> Flag
78        , flagOr : Flag -> Flag -> Flag
79        , flagVal : Flag -> Val
80        , select : Flag -> Val -> Val -> Val
81        }
82
83-- Interpret a word interface through another representation. The boundary
84-- conversions are explicit: for naturals, encoding may reduce modulo 2^256.
85-- This is an adapter, not another implementation of arithmetic.
86let mapWords
87    : forall {A B Flag : Type} -> (B -> A) -> (A -> B) -> Words A Flag -> Words B Flag
88    = \{A} {B} {Flag} encode decode w ->
89        let unary = \(f : A -> A) (x : B) -> decode (f (encode x))
90        let binary = \(f : A -> A -> A) (x y : B) -> decode (f (encode x) (encode y))
91        let ternary =
92              \(f : A -> A -> A -> A) (x y z : B) -> decode (f (encode x) (encode y) (encode z))
93        let compare = \(f : A -> A -> Flag) (x y : B) -> f (encode x) (encode y)
94        in  { lit = \(n : Natural) -> decode (w.lit n)
95            , add = binary w.add
96            , mul = binary w.mul
97            , sub = binary w.sub
98            , div = binary w.div
99            , mod = binary w.mod
100            , sdiv = binary w.sdiv
101            , smod = binary w.smod
102            , addmod = ternary w.addmod
103            , mulmod = ternary w.mulmod
104            , exp = binary w.exp
105            , signextend = binary w.signextend
106            , lt = compare w.lt
107            , gt = compare w.gt
108            , slt = compare w.slt
109            , sgt = compare w.sgt
110            , eq = compare w.eq
111            , isZero = \(x : B) -> w.isZero (encode x)
112            , and = binary w.and
113            , or = binary w.or
114            , xor = binary w.xor
115            , not = unary w.not
116            , byte = binary w.byte
117            , shl = binary w.shl
118            , shr = binary w.shr
119            , sar = binary w.sar
120            , clz = unary w.clz
121            , flagLit = w.flagLit
122            , flagNot = w.flagNot
123            , flagAnd = w.flagAnd
124            , flagOr = w.flagOr
125            , flagVal = \(c : Flag) -> decode (w.flagVal c)
126            , select = \(c : Flag) (a b : B) -> decode (w.select c (encode a) (encode b))
127            }
128
129-- The native interpretation of the pure signature. Keeping it beside the
130-- interface lets arithmetic-only clients avoid importing the world model.
131let Word256 = Word 256
132
133let lit : Natural -> Word256 = Word/fromNatural 256
134
135let value : Word256 -> Natural = Word/toNatural
136
137let signextend
138    : Word256 -> Word256 -> Word256
139    = \b x ->
140        if Word/lt b (lit 31)
141        then Word/fromInteger 256 (Word/toInteger (Word/fromNatural (8 * (value b + 1)) (value x)))
142        else x
143
144let byte
145    : Word256 -> Word256 -> Word256
146    = \i x ->
147        if Word/lt i (lit 32)
148        then Word/and (Word/shr (8 * Natural/subtract (value i) 31) x) (lit 255)
149        else lit 0
150
151let nativeWords
152    : Words Word256 Bool
153    = { lit
154      , add = Word/add
155      , mul = Word/mul
156      , sub = Word/sub
157      , div = Word/div
158      , mod = Word/mod
159      , sdiv = Word/sdiv
160      , smod = Word/smod
161      , addmod = Word/addmod
162      , mulmod = Word/mulmod
163      , exp = \(a : Word256) (b : Word256) -> Word/pow a (value b)
164      , signextend
165      , lt = Word/lt
166      , gt = \(a : Word256) (b : Word256) -> Word/lt b a
167      , slt = Word/slt
168      , sgt = \(a : Word256) (b : Word256) -> Word/slt b a
169      , eq = Word/equal
170      , isZero = Word/isZero
171      , and = Word/and
172      , or = Word/or
173      , xor = Word/xor
174      , not = Word/not
175      , byte
176      , shl = \(s : Word256) (x : Word256) -> Word/shl (value s) x
177      , shr = \(s : Word256) (x : Word256) -> Word/shr (value s) x
178      , sar = \(s : Word256) (x : Word256) -> Word/sar (value s) x
179      , clz = \(x : Word256) -> lit (Word/clz x)
180      , flagLit = \(c : Bool) -> c
181      , flagNot = \(c : Bool) -> if c then False else True
182      , flagAnd = Bool/and
183      , flagOr = Bool/or
184      , flagVal = \(c : Bool) -> lit (if c then 1 else 0)
185      , select = \(c : Bool) (a : Word256) (b : Word256) -> if c then a else b
186      }
187
188-- A numeric boundary for tests and arithmetic statements. All operations
189-- still run on the native implementation above; inputs are encoded as words.
190let naturalWords = mapWords lit value nativeWords
191
192let natural =
193      naturalWords
194      // { N = std:Natural.pow2 256
195         , M = Natural/subtract 1 (std:Natural.pow2 256)
196         , H = std:Natural.pow2 255
197         , pow2 = std:Natural.pow2
198         , isNegative = \(x : Natural) -> Word/slt (lit x) (lit 0)
199         , negate = \(x : Natural) -> value (Word/sub (lit 0) (lit x))
200         , abs =
201             \(x : Natural) ->
202               let w = lit x
203               in  value (if Word/slt w (lit 0) then Word/sub (lit 0) w else w)
204         , bitLength = \(x : Natural) -> Natural/subtract (Word/clz (lit x)) 256
205         }
206
207-- A piece of the data of a log or a halt: the first `size` bytes (1 to 32)
208-- of the word, big-endian.  The data is the chunks' bytes, in order: a
209-- word is a chunk of 32 bytes, a Solidity selector one of 4.
210let Chunk = \(Val : Type) -> { size : Natural, word : Val }
211
212-- A piece of the data of a return whose size is known at run time only: a
213-- chunk, or `size` bytes of call data from `offset`, followed by zeros up
214-- to a multiple of 32 bytes (CALLDATACOPY, as an ABI `bytes` tail).
215let Piece = \(Val : Type) -> < Chunk : Chunk Val | Copy : { offset : Val, size : Val } >
216
217-- The operations.  The frame's constants are words, `timestamp` the
218-- block's TIMESTAMP, the same in every frame of a transaction; `cdload offset` is
219-- CALLDATALOAD, the 32 bytes of call data from the offset, zero beyond its
220-- end (in a constructor, the call data are the arguments that follow the
221-- init code).  `keccakText t` is Keccak-256 of the text's bytes, which the
222-- compiler computes and the model asks its oracle for; `immutable n` is
223-- the n-th immutable of the runtime code, which the init code patches in.
224-- A log has at most four topics (the transition's `log0` to `log4` are its
225-- only builders).  `tload` and `tstore` are TLOAD and TSTORE of a
226-- transient slot.
227--
228-- `call` is CALL with all the gas left, the input data, and no output
229-- area; `staticcall` is STATICCALL.  Each gives the success flag, and the
230-- callee's return data are then read with `rdsize` (RETURNDATASIZE) and
231-- `rdload offset` (the 32 bytes from the offset, which the caller checks
232-- are within the return data first).  `bubble` reverts with the return
233-- data as they are.
234--
235-- `switch v cases default` runs the code of the first case whose key, a
236-- word known at compile time, is v, and the default otherwise.
237-- `loop n init body after` runs `body i s next` for i = 0, 1, …, n - 1,
238-- each iteration given the words s that the previous one passed to
239-- `next` (the first, `init`), then `after` on the last words; the words
240-- are as many as `init` has.  The halts return or revert with data, and
241-- drop the rest of the execution; `output` returns pieces.
242--
243-- `share ws f` is `f ws`: it marks `f` as a body that other places may run
244-- too, with other words.  The compiler generates once the bodies that are
245-- equal, as a join point that each place jumps to with its words.  Only
246-- `std:EVM/Contract` uses it for the bodies that equal entries run; `join`
247-- serves the branches of one body.
248--
249-- `join A k f` is `f k`: `k` is the rest of the execution after a value of
250-- type `A`, which `f` may run from several places.  The compiler generates
251-- `k` once, as a join point that each place jumps to with the words of its
252-- value, where that is cheaper than a copy per place.
253let Call = \(Val : Type) -> { to : Val, value : Val, input : List (Chunk Val) }
254
255let StaticCall = \(Val : Type) -> { to : Val, input : List (Chunk Val) }
256
257let Case = \(Val : Type) (Code : Type) -> { key : Val, code : Code }
258
259let Ops =
260      \(Val : Type) (Flag : Type) (Code : Type) ->
261        { words : Words Val Flag
262        , keccakText : Text -> Val
263        , caller : Val
264        , address : Val
265        , callvalue : Val
266        , cdsize : Val
267        , cdload : Val -> Val
268        , timestamp : Val
269        , immutable : Natural -> Val
270        , sload : Key Val -> (Val -> Code) -> Code
271        , sstore : Key Val -> Val -> Code -> Code
272        , tload : Val -> (Val -> Code) -> Code
273        , tstore : Val -> Val -> Code -> Code
274        , log : List Val -> List (Chunk Val) -> Code -> Code
275        , call : Call Val -> (Flag -> Code) -> Code
276        , staticcall : StaticCall Val -> (Flag -> Code) -> Code
277        , rdsize : (Val -> Code) -> Code
278        , rdload : Val -> (Val -> Code) -> Code
279        , branch : Flag -> Code -> Code -> Code
280        , switch : Val -> List (Case Val Code) -> Code -> Code
281        , loop :
282            Val
283            -> List Val
284            -> (Val -> List Val -> (List Val -> Code) -> Code)
285            -> (List Val -> Code)
286            -> Code
287        , share : List Val -> (List Val -> Code) -> Code
288        , join : forall (A : Type) -> (A -> Code) -> ((A -> Code) -> Code) -> Code
289        , ret : List (Chunk Val) -> Code
290        , output : List (Piece Val) -> Code
291        , revert : List (Chunk Val) -> Code
292        , bubble : Code
293        }
294
295in  { Key
296    , Chunk
297    , Piece
298    , Words
299    , mapWords
300    , nativeWords
301    , naturalWords
302    , natural
303    , Call
304    , StaticCall
305    , Case
306    , Ops
307    }
Your result
Complete file: lib/EVM/Signature.omg · with imports