std:EVM/State/Layout/Validate

lib/EVM/State/Layout/Validate.omg

lib/EVM/State/Layout/Validate.omg591 lines
1let Structure = std:Reflection/Structure
2{- The validity predicate of storage format version 2: the invariants that
3   the access code relies on, not an allocation policy. Identifiers, member
4   order, gaps, shared subgraphs, tags, strides and the hashed block are
5   data. The local clauses hold for every node, reachable or not; the source
6   match follows the source type from the root.
7-}
8let Address = std:EVM/State/Layout/Address
9let D = std:EVM/State/Layout/Description
10let L = std:List
11let N = std:Natural
12let O = std:Optional
13let R = std:Region
14let require
15    : Bool -> Text -> List Text
16    = \condition message -> if condition then ([] : List Text) else [ message ]
17let pairwise
18    : forall {A : Type} -> (A -> A -> Bool) -> List A -> Bool
19    = \{A} related ->
20        List/elim
21          (\(_ : List A) -> Bool)
22          True
23          (\(first : A) (rest : List A) (checked : Bool) -> L.all (related first) rest && checked)
24let unique
25    : forall {A : Type} -> (A -> A -> Bool) -> List A -> Bool
26    = \{A} equal -> pairwise (\(a b : A) -> if equal a b then False else True)
27let maximum : List Natural -> Natural = L.fold (\(n rest : Natural) -> N.max n rest) 0
28let onSlot : Natural -> Bool = \bits -> N.isZero (Natural/mod bits 256)
29let separate
30    : R.Region -> R.Region -> Bool
31    = \a b ->
32        N.isZero a.size
33        || N.isZero b.size
34        || N.lessThanEqual (R.end a) b.start
35        || N.lessThanEqual (R.end b) a.start
36let regions
37    : Natural -> List R.Region -> List Text
38    = \bits parts ->
39        require (pairwise separate parts) "storage members overlap"
40        # require
41            (L.all (\(part : R.Region) -> N.lessThanEqual (R.end part) bits) parts)
42            "storage region extends beyond its object"
43let extent
44    : Natural -> Natural -> List Text
45    = \bits expected -> require (N.equal bits expected) "storage node has an inconsistent extent"
46let scalarKey
47    : D.Scalar -> { kind : Natural, bits : Natural }
48    = \kind ->
49        merge
50          { Unsigned = \bits -> { kind = 0, bits }
51          , Boolean = { kind = 1, bits = 1 }
52          , String = { kind = 2, bits = 0 }
53          , NaturalNumber = { kind = 3, bits = 0 }
54          , IntegerNumber = { kind = 4, bits = 0 }
55          }
56          kind
57let scalarEqual
58    : D.Scalar -> D.Scalar -> Bool
59    = \a b ->
60        let x = scalarKey a
61        let y = scalarKey b
62        in  N.equal x.kind y.kind && N.equal x.bits y.bits
63let fixed
64    : D.Scalar -> Optional Natural
65    = \kind ->
66        merge
67          { Unsigned = \bits -> Some bits
68          , Boolean = Some 1
69          , String = None Natural
70          , NaturalNumber = None Natural
71          , IntegerNumber = None Natural
72          }
73          kind
74-- Every node a node refers to, keys included.
75let references
76    : D.Form -> List Natural
77    = \form ->
78        merge
79          { Primitive = \_ -> ([] : List Natural)
80          , Blob = \_ -> ([] : List Natural)
81          , Fields = \fields -> L.map (\(field : D.Member) -> field.child) fields
82          , Choice =
83              \choice ->
84                L.map (\(alternative : D.Alternative) -> alternative.child) choice.alternatives
85          , List = \list -> [ list.element ]
86          , Dictionary = \entry -> [ entry.key, entry.value ]
87          , Unsupported = \_ -> ([] : List Natural)
88          }
89          form
90-- A node with a header or an array that starts on a slot boundary: a list,
91-- a blob or a mapping.
92let anchored
93    : D.Form -> Bool
94    = \form ->
95        merge
96          { Primitive = \_ -> False
97          , Blob = \_ -> True
98          , Fields = \_ -> False
99          , Choice = \_ -> False
100          , List = \_ -> True
101          , Dictionary = \_ -> True
102          , Unsupported = \_ -> False
103          }
104          form
105
106{- Alignment. An anchored node must start on a slot boundary of its object.
107   A node's phase is the bit offset modulo 256 at which it must start so
108   that every anchored node inside it does: 0 for an anchored node, and for
109   a record or union the phase its aligned children demand, shifted by
110   their offsets; none if it holds no anchored node inline. A node whose
111   children demand different phases is invalid. An object starts on a slot
112   boundary, so a root, a list element of stride a multiple of 256 and a
113   mapping value need phase 0.
114
115   Finite dataflow over inline edges computes the phases. A pass resolves
116   every node whose inline children have resolved. An acyclic path has at
117   most as many nodes as the graph; after that many passes, an unresolved
118   node has an inline cycle or a missing dependency. Lists and mappings
119   store out of line, so recursion through them is not an inline cycle.
120-}
121let Phase : Type = Optional Natural
122let Status : Type = { id : Natural, phase : Optional Phase }
123let Placed : Type = { child : Natural, offset : Natural }
124let shift
125    : Natural -> Natural -> Natural
126    = \phase offset -> Natural/mod (phase + N.minus 256 (Natural/mod offset 256)) 256
127let status
128    : List Status -> Natural -> Optional Phase
129    = \known id ->
130        O.andThen
131          (L.find (\(entry : Status) -> N.equal entry.id id) known)
132          (\(entry : Status) -> entry.phase)
133-- The phase of a node of known phase: none when it is unknown.
134let phaseOf
135    : List Status -> Natural -> Phase
136    = \known id -> O.andThen (status known id) (\(phase : Phase) -> phase)
137-- The phases that children at offsets demand of their parent, if every
138-- child has resolved.
139let demands
140    : List Status -> List Placed -> Optional (List Natural)
141    = \known children ->
142        L.fold
143          (\(placed : Placed) (rest : Optional (List Natural)) ->
144             O.andThen
145               (status known placed.child)
146               (\(phase : Phase) ->
147                  O.map
148                    (\(others : List Natural) ->
149                       O.fold (\(p : Natural) -> [ shift p placed.offset ] # others) others phase)
150                    rest))
151          (Some ([] : List Natural))
152          children
153let members
154    : D.Form -> List Placed
155    = \form ->
156        merge
157          { Primitive = \_ -> ([] : List Placed)
158          , Blob = \_ -> ([] : List Placed)
159          , Fields =
160              \fields ->
161                L.map (\(field : D.Member) -> { child = field.child, offset = field.offset }) fields
162          , Choice =
163              \choice ->
164                L.map
165                  (\(alternative : D.Alternative) ->
166                     { child = alternative.child, offset = choice.payload })
167                  choice.alternatives
168          , List = \_ -> ([] : List Placed)
169          , Dictionary = \_ -> ([] : List Placed)
170          , Unsupported = \_ -> ([] : List Placed)
171          }
172          form
173let resolve
174    : List D.Node -> List Status
175    = \nodes ->
176        let pass =
177              \(known : List Status) ->
178                L.map
179                  (\(node : D.Node) ->
180                     { id = node.id
181                     , phase =
182                         if anchored node.form
183                         then Some (Some 0)
184                         else O.map L.head (demands known (members node.form))
185                     })
186                  nodes
187        in  N.fold
188              (L.length nodes)
189              (\(continue : List Status -> List Status) (known : List Status) ->
190                 if L.all (\(entry : Status) -> O.isSome entry.phase) known
191                 then known
192                 else continue (pass known))
193              (\(known : List Status) -> known)
194              (L.map (\(node : D.Node) -> { id = node.id, phase = None Phase }) nodes)
195let agree
196    : List Natural -> Bool
197    = \phases -> O.fold (\(first : Natural) -> L.all (N.equal first) phases) True (L.head phases)
198-- Requires a node of a phase to start on a slot boundary.
199let startsOnSlot
200    : Phase -> Text -> List Text
201    = \phase message -> O.fold (\(p : Natural) -> require (N.isZero p) message) [] phase
202-- The entries of a list's data or a direct mapping's array, `kind`, at a
203-- stride: an entry (`part`) of `width` bits never crosses a slot unless it
204-- covers whole slots, and one with slot-aligned storage starts on a slot
205-- boundary, so its stride is a multiple of 256. A stride of 0 is left to
206-- a zero-width entry by `width <= stride`.
207let strideProblems
208    : Text -> Text -> Natural -> Phase -> Natural -> List Text
209    = \kind part width phase stride ->
210        require (N.lessThanEqual width stride) "a ${kind} stride is smaller than its ${part}"
211        # require
212            (N.lessThanEqual stride 256 || onSlot stride)
213            "a ${kind} stride above 256 bits must be a multiple of 256"
214        # require
215            (O.fold (\(p : Natural) -> N.isZero p && onSlot stride) True phase)
216            "a ${kind} ${part} with slot-aligned storage must start on a slot boundary"
217let nodeProblems
218    : List D.Node -> List Status -> D.Node -> List Text
219    = \nodes
220       known
221       node ->
222        let bits = node.bits
223        let size = Address.width nodes
224        let consistent =
225              \(message : Text) ->
226                require (O.fold agree True (demands known (members node.form))) message
227        let exact = extent bits
228        let parts = regions bits
229        let local =
230              merge
231                { Primitive =
232                    \kind ->
233                      O.fold exact [ "an unbounded scalar needs dynamic storage" ] (fixed kind)
234                , Blob =
235                    \kind ->
236                      require (O.isNone (fixed kind)) "a fixed scalar was described as a blob"
237                      # exact 256
238                , Fields =
239                    \fields ->
240                      let ranges =
241                            L.map
242                              (\(field : D.Member) ->
243                                 { start = field.offset, size = size field.child })
244                              fields
245                      in  require
246                            (unique Text/equal (L.map (\(field : D.Member) -> field.name) fields))
247                            "duplicate storage member label"
248                          # parts ranges
249                          # exact (maximum (L.map R.end ranges))
250                          # consistent
251                              "members with slot-aligned storage do not share a slot boundary"
252                , Choice =
253                    \choice ->
254                      let alternatives = choice.alternatives
255                      let tags =
256                            L.map (\(alternative : D.Alternative) -> alternative.tag) alternatives
257                      let payload =
258                            { start = choice.payload
259                            , size =
260                                maximum
261                                  (L.map
262                                     (\(alternative : D.Alternative) -> size alternative.child)
263                                     alternatives)
264                            }
265                      let ranges = [ { start = 0, size = choice.width }, payload ]
266                      in  require
267                            (if L.null alternatives then False else True)
268                            "a union needs at least one alternative"
269                          # require
270                              (unique
271                                 Text/equal
272                                 (L.map
273                                    (\(alternative : D.Alternative) -> alternative.name)
274                                    alternatives))
275                              "duplicate storage member label"
276                          # require
277                              (unique N.equal tags
278                               && L.all
279                                    (\(tag : Natural) ->
280                                       N.lessThanEqual (N.bitLength tag) choice.width)
281                                    tags)
282                              "union tags must be distinct and fit their discriminator"
283                          # parts ranges
284                          # exact (maximum (L.map R.end ranges))
285                          # consistent
286                              "alternatives with slot-aligned storage do not share a slot boundary"
287                , List =
288                    \list ->
289                      exact 256
290                      # strideProblems
291                          "list"
292                          "element"
293                          (size list.element)
294                          (phaseOf known list.element)
295                          list.stride
296                , Dictionary =
297                    \entry ->
298                      merge
299                        { Hashed =
300                            exact 256
301                            # startsOnSlot
302                                (phaseOf known entry.value)
303                                "a mapping value with slot-aligned storage must start on a slot boundary"
304                        , Direct =
305                            \stride ->
306                              let key = size entry.key
307                              let word = N.lessThanEqual key 256
308                              in  require
309                                    (O.isNone (phaseOf known entry.key))
310                                    "a direct mapping key must have a fixed width"
311                                  # require word "a direct mapping key must fit one word"
312                                  # (if word
313                                     then exact (Address.directBits key stride)
314                                     else ([] : List Text))
315                                  # strideProblems
316                                      "direct mapping"
317                                      "value"
318                                      (size entry.value)
319                                      (phaseOf known entry.value)
320                                      stride
321                        }
322                        entry.addressing
323                , Unsupported = \why -> [ why ]
324                }
325                node.form
326        in  L.map
327              (\(message : Text) -> "storage node ${Natural/show node.id}: ${message}")
328              (L.concatMap
329                 (\(id : Natural) ->
330                    require (O.isSome (Address.find nodes id)) "unknown storage layout node")
331                 (references node.form)
332               # require
333                   (O.isSome (status known node.id))
334                   "storage graph has an inline cycle or an unresolved dependency"
335               # local)
336-- Match the supplied source structure by induction on that structure. This
337-- does not compare to the automatic layout, and follows shared graph nodes at
338-- each occurrence of a source field or alternative. A shape also says
339-- whether its type can be a mapping key: one without a mapping inside.
340let Matcher : Type = List D.Node -> Natural -> List Text
341-- Every clause, the source match of the root included.
342let described
343    : Matcher -> D.Description -> List Text
344    = \matches description ->
345        let nodes = description.nodes
346        let known = resolve nodes
347        let rootSlots = Address.rootSlots description
348        in  require (N.equal description.version D.version) "unsupported storage manifest version"
349            # require
350                (unique N.equal (L.map (\(node : D.Node) -> node.id) nodes))
351                "duplicate storage layout node identifier"
352            # require
353                (N.lessThanEqual (R.end description.space) (N.pow2 256))
354                "storage reservation exceeds the EVM address space"
355            # L.concatMap (nodeProblems nodes known) nodes
356            # startsOnSlot
357                (phaseOf known description.root)
358                "the root object's slot-aligned storage must start on a slot boundary"
359            # require
360                (N.lessThanEqual rootSlots description.space.size)
361                "the root object exceeds the reservation"
362            # Address.hashingProblems
363                description.space
364                rootSlots
365                (Address.objectSlots description.nodes)
366                description.hashing
367            # matches nodes description.root
368-- A shape hands its matcher to a continuation (`check`), so that `problems`
369-- of an unknown source is stuck on the source's fold, with the shared
370-- `algebra` and `described` as its arguments: conversion compares two such
371-- predicates (every `Layout.Selection` type holds one) by sharing, and a
372-- type read back in normal form spells the clauses out once. Applying
373-- `described` inside the fold instead would spell them out in every case of
374-- the algebra (52 MB of text instead of 7.8 MB for `Layout.Selection S`);
375-- applying it outside the fold, to an unknown matcher, would unfold the
376-- clauses on each comparison.
377let Shape
378    : Type
379    = { matches : Matcher
380      , keyable : Bool
381      , check : (Matcher -> D.Description -> List Text) -> D.Description -> List Text
382      }
383let shaped
384    : Matcher -> Bool -> Shape
385    = \matches keyable -> { matches, keyable, check = \next -> next matches }
386let mismatch : List Text = [ "storage manifest does not describe the declared type" ]
387let inspect
388    : List D.Node -> Natural -> (D.Form -> List Text) -> List Text
389    = \nodes id check ->
390        O.fold
391          (\(node : D.Node) -> check node.form)
392          [ "unknown storage layout node" ]
393          (Address.find nodes id)
394let matchScalar
395    : D.Scalar -> Matcher
396    = \kind nodes id ->
397        inspect
398          nodes
399          id
400          (\form ->
401             merge
402               { Primitive =
403                   \other ->
404                     require
405                       (scalarEqual kind other)
406                       "storage manifest does not describe the declared type"
407               , Blob =
408                   \other ->
409                     require
410                       (scalarEqual kind other)
411                       "storage manifest does not describe the declared type"
412               , Fields = \_ -> mismatch
413               , Choice = \_ -> mismatch
414               , List = \_ -> mismatch
415               , Dictionary = \_ -> mismatch
416               , Unsupported = \_ -> mismatch
417               }
418               form)
419let Child : Type = { name : Text, child : Natural }
420let Field : Type = { name : Text, shape : Shape }
421let matchFields
422    : List D.Node -> List Field -> List Child -> List Text
423    = \nodes expected actual ->
424        require
425          (N.equal (L.length expected) (L.length actual))
426          "storage manifest does not describe the declared type"
427        # L.concatMap
428            (\(field : Field) ->
429               O.fold
430                 (\(child : Child) ->
431                    L.map
432                      (\(message : Text) -> "${field.name}: ${message}")
433                      (field.shape.matches nodes child.child))
434                 mismatch
435                 (L.find (\(child : Child) -> Text/equal field.name child.name) actual))
436            expected
437let keyable : List Field -> Bool = L.all (\(field : Field) -> field.shape.keyable)
438let matchRecord
439    : List Field -> Matcher
440    = \fields nodes id ->
441        inspect
442          nodes
443          id
444          (\form ->
445             merge
446               { Primitive = \_ -> mismatch
447               , Blob = \_ -> mismatch
448               , Fields =
449                   \members ->
450                     matchFields
451                       nodes
452                       fields
453                       (L.map
454                          (\(member : D.Member) -> { name = member.name, child = member.child })
455                          members)
456               , Choice = \_ -> mismatch
457               , List = \_ -> mismatch
458               , Dictionary = \_ -> mismatch
459               , Unsupported = \_ -> mismatch
460               }
461               form)
462-- Zero storage decodes to tag 0, so tag 0 must select the default
463-- alternative: the first case of the reflected union, in the order of its
464-- `cases` fold (the kernel's label order, which `default` also uses).
465let defaultTag
466    : List Field -> List D.Alternative -> List Text
467    = \fields alternatives ->
468        O.fold
469          (\(first : Field) ->
470             O.fold
471               (\(alternative : D.Alternative) ->
472                  require
473                    (N.isZero alternative.tag)
474                    "union tag 0 must select the first reflected alternative")
475               ([] : List Text)
476               (L.find
477                  (\(alternative : D.Alternative) -> Text/equal alternative.name first.name)
478                  alternatives))
479          ([] : List Text)
480          (L.head fields)
481let matchUnion
482    : List Field -> Matcher
483    = \fields nodes id ->
484        inspect
485          nodes
486          id
487          (\form ->
488             merge
489               { Primitive = \_ -> mismatch
490               , Blob = \_ -> mismatch
491               , Fields = \_ -> mismatch
492               , Choice =
493                   \choice ->
494                     matchFields
495                       nodes
496                       fields
497                       (L.map
498                          (\(alternative : D.Alternative) ->
499                             { name = alternative.name, child = alternative.child })
500                          choice.alternatives)
501                     # defaultTag fields choice.alternatives
502               , List = \_ -> mismatch
503               , Dictionary = \_ -> mismatch
504               , Unsupported = \_ -> mismatch
505               }
506               form)
507let matchList
508    : Matcher -> Matcher
509    = \child nodes id ->
510        inspect
511          nodes
512          id
513          (\form ->
514             merge
515               { Primitive = \_ -> mismatch
516               , Blob = \_ -> mismatch
517               , Fields = \_ -> mismatch
518               , Choice = \_ -> mismatch
519               , List = \list -> child nodes list.element
520               , Dictionary = \_ -> mismatch
521               , Unsupported = \_ -> mismatch
522               }
523               form)
524let matchMapping
525    : Shape -> Matcher -> Matcher
526    = \key value nodes id ->
527        inspect
528          nodes
529          id
530          (\form ->
531             merge
532               { Primitive = \_ -> mismatch
533               , Blob = \_ -> mismatch
534               , Fields = \_ -> mismatch
535               , Choice = \_ -> mismatch
536               , List = \_ -> mismatch
537               , Dictionary =
538                   \entry ->
539                     require key.keyable "a mapping key cannot contain a mapping"
540                     # key.matches nodes entry.key
541                     # value nodes entry.value
542               , Unsupported = \_ -> mismatch
543               }
544               form)
545let scalar : D.Scalar -> Shape = \kind -> shaped (matchScalar kind) True
546let record : List Field -> Shape = \fields -> shaped (matchRecord fields) (keyable fields)
547let union : List Field -> Shape = \fields -> shaped (matchUnion fields) (keyable fields)
548-- One top-level algebra, so that conversion compares two matchers of the
549-- same unknown type by sharing (see `std:EVM/State/Layout/Derive`).
550let algebra
551    : Structure.FamilyAlgebra {} (\(_ : {} -> Type) -> Shape) {}
552    = Structure.algebra
553        {=}
554        (\(_ : Type) -> Shape)
555        { leaf = {=}
556        , bool = scalar D.Scalar.Boolean
557        , word = \bits -> scalar (D.Scalar.Unsigned bits)
558        , text = scalar D.Scalar.String
559        , natural = scalar D.Scalar.NaturalNumber
560        , integer = scalar D.Scalar.IntegerNumber
561        , double = shaped (\_ _ -> [ "Double has no storage representation" ]) True
562        , function = \A B argument result -> shaped (matchMapping argument result.matches) False
563        , list = \A child -> shaped (matchList child.matches) child.keyable
564        , optional =
565            \A child ->
566              union [ { name = "None", shape = record [] }, { name = "Some", shape = child } ]
567        , pair =
568            \A B first second ->
569              record [ { name = "1", shape = first }, { name = "2", shape = second } ]
570        , record =
571            \A build fields ->
572              record
573                (fields
574                   (List Field)
575                   (\B name position child project rest -> rest # [ { name, shape = child } ])
576                   [])
577        , union =
578            \A cases fold ->
579              union
580                (cases
581                   (List Field)
582                   (\B name position child inject rest -> rest # [ { name, shape = child } ])
583                   [])
584        }
585let shape
586    : forall {A : Type} -> D.Of A -> Shape
587    = \{A} source -> source.fold (\(_ : {} -> Type) -> Shape) algebra
588let problems
589    : forall {A : Type} -> D.Of A -> D.Description -> List Text
590    = \{A} source -> (shape source).check described
591in  { problems }
Your result
Complete file: lib/EVM/State/Layout/Validate.omg · with imports