package tezos-protocol-016-PtMumbai

  1. Overview
  2. Docs
Legend:
Page
Library
Module
Module type
Parameter
Class
Class type
Source

Source file tx_rollup_l2_context.ml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
(*****************************************************************************)
(*                                                                           *)
(* Open Source License                                                       *)
(* Copyright (c) 2022 Marigold <contact@marigold.dev>                        *)
(* Copyright (c) 2022 Nomadic Labs <contact@nomadic-labs.com>                *)
(* Copyright (c) 2022 Oxhead Alpha <info@oxheadalpha.com>                    *)
(*                                                                           *)
(* Permission is hereby granted, free of charge, to any person obtaining a   *)
(* copy of this software and associated documentation files (the "Software"),*)
(* to deal in the Software without restriction, including without limitation *)
(* the rights to use, copy, modify, merge, publish, distribute, sublicense,  *)
(* and/or sell copies of the Software, and to permit persons to whom the     *)
(* Software is furnished to do so, subject to the following conditions:      *)
(*                                                                           *)
(* The above copyright notice and this permission notice shall be included   *)
(* in all copies or substantial portions of the Software.                    *)
(*                                                                           *)
(* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR*)
(* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,  *)
(* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL   *)
(* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*)
(* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING   *)
(* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER       *)
(* DEALINGS IN THE SOFTWARE.                                                 *)
(*                                                                           *)
(*****************************************************************************)

open Tx_rollup_l2_storage_sig
open Tx_rollup_l2_context_sig

let metadata_encoding =
  Data_encoding.(
    conv
      (fun {counter; public_key} -> (counter, public_key))
      (fun (counter, public_key) -> {counter; public_key})
      (obj2 (req "counter" int64) (req "public_key" Bls.Public_key.encoding)))

(** {1 Type-Safe Storage Access and Gas Accounting} *)

(** A value of type ['a key] identifies a value of type ['a] in an
    underlying, untyped storage.

    This GADT is used to enforce type-safety of the abstraction of
    the transactions rollup context. For this abstraction to work,
    it is necessary to ensure that the serialization of values ['a
    key] and ['b key] cannot collide. To that end, we use
    [Data_encoding] (see {!packed_key_encoding}). *)
type _ key =
  | Address_metadata : address_index -> metadata key
  | Address_count : int32 key
  | Address_index : Tx_rollup_l2_address.t -> address_index key
  | Ticket_count : int32 key
  | Ticket_index : Alpha_context.Ticket_hash.t -> ticket_index key
  | Ticket_ledger : ticket_index * address_index -> Tx_rollup_l2_qty.t key

(** A monomorphic version of {!Key}, used for serialization purposes. *)
type packed_key = Key : 'a key -> packed_key

(** The encoding used to serialize keys to be used with an untyped storage. *)
let packed_key_encoding : packed_key Data_encoding.t =
  Data_encoding.(
    union
      ~tag_size:`Uint8
      [
        case
          (Tag 0)
          ~title:"Address_metadata"
          Tx_rollup_l2_address.Indexable.index_encoding
          (function Key (Address_metadata idx) -> Some idx | _ -> None)
          (fun idx -> Key (Address_metadata idx));
        case
          (Tag 1)
          ~title:"Address_count"
          empty
          (function Key Address_count -> Some () | _ -> None)
          (fun () -> Key Address_count);
        case
          (Tag 2)
          ~title:"Address_index"
          Tx_rollup_l2_address.encoding
          (function Key (Address_index addr) -> Some addr | _ -> None)
          (fun addr -> Key (Address_index addr));
        case
          (Tag 3)
          ~title:"Ticket_count"
          empty
          (function Key Ticket_count -> Some () | _ -> None)
          (fun () -> Key Ticket_count);
        case
          (Tag 4)
          ~title:"Ticket_index"
          Alpha_context.Ticket_hash.encoding
          (function Key (Ticket_index ticket) -> Some ticket | _ -> None)
          (fun ticket -> Key (Ticket_index ticket));
        case
          (Tag 5)
          ~title:"Ticket_ledger"
          (tup2
             Ticket_indexable.index_encoding
             Tx_rollup_l2_address.Indexable.index_encoding)
          (function
            | Key (Ticket_ledger (ticket, address)) -> Some (ticket, address)
            | _ -> None)
          (fun (ticket, address) -> Key (Ticket_ledger (ticket, address)));
      ])

(** [value_encoding key] returns the encoding to be used to serialize
    and deserialize values associated to a [key] from and to the
    underlying storage. *)
let value_encoding : type a. a key -> a Data_encoding.t =
  let open Data_encoding in
  function
  | Address_metadata _ -> metadata_encoding
  | Address_count -> int32
  | Address_index _ -> Tx_rollup_l2_address.Indexable.index_encoding
  | Ticket_count -> int32
  | Ticket_index _ -> Ticket_indexable.index_encoding
  | Ticket_ledger _ -> Tx_rollup_l2_qty.encoding

(** {1 Errors} *)

type error += Key_cannot_be_serialized

type error += Value_cannot_be_serialized

type error += Value_cannot_be_deserialized

let () =
  let open Data_encoding in
  (* Key cannot be serialized *)
  register_error_kind
    `Permanent
    ~id:"tx_rollup_key_cannot_be_serialized"
    ~title:"Key cannot be serialized"
    ~description:"Tried to serialize an invalid key."
    empty
    (function Key_cannot_be_serialized -> Some () | _ -> None)
    (fun () -> Key_cannot_be_serialized) ;
  (* Value cannot be serialized *)
  register_error_kind
    `Permanent
    ~id:"tx_rollup_value_cannot_be_serialized"
    ~title:"Value cannot be serialized"
    ~description:"Tried to serialize an invalid value."
    empty
    (function Value_cannot_be_serialized -> Some () | _ -> None)
    (fun () -> Value_cannot_be_serialized) ;
  (* Value cannot be deserialized *)
  register_error_kind
    `Permanent
    ~id:"tx_rollup_value_cannot_be_deserialized"
    ~title:"Value cannot be deserialized"
    ~description:
      "A value has been serialized in the Tx_rollup store, but cannot be \
       deserialized."
    empty
    (function Value_cannot_be_deserialized -> Some () | _ -> None)
    (fun () -> Value_cannot_be_deserialized)

(** {1 The Context Functor} *)

module Make (S : STORAGE) : CONTEXT with type t = S.t and type 'a m = 'a S.m =
struct
  type t = S.t

  type 'a m = 'a S.m

  module Syntax = struct
    include S.Syntax

    let ( let*? ) res f =
      match res with Result.Ok v -> f v | Result.Error error -> fail error

    let fail_unless cond error =
      let open S.Syntax in
      if cond then return () else fail error

    let fail_when cond error =
      let open S.Syntax in
      if cond then fail error else return ()
  end

  let bls_verify : (Bls.Public_key.t * bytes) list -> signature -> bool m =
   fun accounts aggregated_signature ->
    let open Syntax in
    let msgs = List.map (fun (pk, msg) -> (pk, None, msg)) accounts in
    return (Bls.aggregate_check msgs aggregated_signature)

  let unwrap_or : type a. a option -> error -> a S.m =
   fun opt err ->
    match opt with Some x -> S.Syntax.return x | None -> S.Syntax.fail err

  let serialize_key : type a. a key -> bytes m =
   fun key ->
    unwrap_or
      (Data_encoding.Binary.to_bytes_opt packed_key_encoding (Key key))
      Key_cannot_be_serialized

  let serialize_value : type a. a Data_encoding.t -> a -> bytes m =
   fun encoding value ->
    unwrap_or
      (Data_encoding.Binary.to_bytes_opt encoding value)
      Value_cannot_be_serialized

  let deserialize_value : type a. a Data_encoding.t -> bytes -> a m =
   fun encoding value ->
    unwrap_or
      (Data_encoding.Binary.of_bytes_opt encoding value)
      Value_cannot_be_deserialized

  (** [get ctxt key] is a type-safe [get] function. *)
  let get : type a. t -> a key -> a option m =
   fun ctxt key ->
    let open Syntax in
    let value_encoding = value_encoding key in
    let* key = serialize_key key in
    let* value = S.get ctxt key in
    match value with
    | Some value ->
        let* value = deserialize_value value_encoding value in
        return (Some value)
    | None -> return None

  (** [set ctxt key value] is a type-safe [set] function. *)
  let set : type a. t -> a key -> a -> t m =
   fun ctxt key value ->
    let open Syntax in
    let value_encoding = value_encoding key in
    let* key = serialize_key key in
    let* value = serialize_value value_encoding value in
    S.set ctxt key value

  let remove : type a. t -> a key -> t m =
   fun ctxt key ->
    let open Syntax in
    let* key = serialize_key key in
    S.remove ctxt key

  module Address_metadata = struct
    let get ctxt idx = get ctxt (Address_metadata idx)

    let incr_counter ctxt idx =
      let open Syntax in
      let* metadata = get ctxt idx in
      match metadata with
      | Some meta ->
          let new_counter = Int64.succ meta.counter in
          let* () =
            fail_unless
              Compare.Int64.(new_counter >= meta.counter)
              Counter_overflow
          in
          set ctxt (Address_metadata idx) {meta with counter = new_counter}
      | None -> fail (Unknown_address_index idx)

    let init_with_public_key ctxt idx public_key =
      let open Syntax in
      let* metadata = get ctxt idx in
      match metadata with
      | None -> set ctxt (Address_metadata idx) {counter = 0L; public_key}
      | Some _ -> fail (Metadata_already_initialized idx)

    module Internal_for_tests = struct
      let set ctxt idx metadata = set ctxt (Address_metadata idx) metadata
    end
  end

  module Address_index = struct
    let count ctxt =
      let open Syntax in
      let+ count = get ctxt Address_count in
      Option.value ~default:0l count

    let init_counter ctxt = set ctxt Address_count 0l

    let associate_index ctxt addr =
      let open Syntax in
      let* i = count ctxt in
      let new_count = Int32.succ i in
      let* () =
        fail_unless Compare.Int32.(new_count >= i) Too_many_l2_addresses
      in
      (* This can not fail as by construction [count ctxt] is always positive. *)
      let idx = Indexable.index_exn i in
      let* ctxt = set ctxt (Address_index addr) idx in
      let+ ctxt = set ctxt Address_count new_count in
      (ctxt, idx)

    let get ctxt addr = get ctxt (Address_index addr)

    let get_or_associate_index ctxt addr =
      let open Syntax in
      let* index_opt = get ctxt addr in
      match index_opt with
      | Some idx -> return (ctxt, `Existed, idx)
      | None ->
          let+ ctxt, idx = associate_index ctxt addr in
          (ctxt, `Created, idx)

    module Internal_for_tests = struct
      let set_count ctxt count = set ctxt Address_count count
    end
  end

  module Ticket_index = struct
    let count ctxt =
      let open Syntax in
      let+ count = get ctxt Ticket_count in
      Option.value ~default:0l count

    let init_counter ctxt = set ctxt Ticket_count 0l

    let associate_index ctxt ticket =
      let open Syntax in
      let* i = count ctxt in
      let new_count = Int32.succ i in
      let* () =
        fail_unless Compare.Int32.(new_count >= i) Too_many_l2_tickets
      in
      (* This can not fail as by construction [count ctxt] is always positive. *)
      let idx = Indexable.index_exn i in
      let* ctxt = set ctxt (Ticket_index ticket) idx in
      let+ ctxt = set ctxt Ticket_count new_count in
      (ctxt, idx)

    let get ctxt ticket = get ctxt (Ticket_index ticket)

    let get_or_associate_index ctxt ticket =
      let open Syntax in
      let* index_opt = get ctxt ticket in
      match index_opt with
      | Some idx -> return (ctxt, `Existed, idx)
      | None ->
          let+ ctxt, idx = associate_index ctxt ticket in
          (ctxt, `Created, idx)

    module Internal_for_tests = struct
      let set_count ctxt count = set ctxt Ticket_count count
    end
  end

  module Ticket_ledger = struct
    let get_opt ctxt tidx aidx = get ctxt (Ticket_ledger (tidx, aidx))

    let get ctxt tidx aidx =
      let open Syntax in
      let+ res = get_opt ctxt tidx aidx in
      Option.value ~default:Tx_rollup_l2_qty.zero res

    let set ctxt tidx aidx = set ctxt (Ticket_ledger (tidx, aidx))

    let remove ctxt tidx aidx = remove ctxt (Ticket_ledger (tidx, aidx))

    let spend ctxt tidx aidx qty =
      let open Syntax in
      let* src_balance = get ctxt tidx aidx in
      match Tx_rollup_l2_qty.sub src_balance qty with
      | None -> fail Balance_too_low
      | Some remainder when Tx_rollup_l2_qty.(remainder > zero) ->
          set ctxt tidx aidx remainder
      | Some _ -> remove ctxt tidx aidx

    let credit ctxt tidx aidx qty =
      let open Syntax in
      let* balance = get ctxt tidx aidx in
      match Tx_rollup_l2_qty.add balance qty with
      | None -> fail Balance_overflow
      | Some new_balance -> set ctxt tidx aidx new_balance

    module Internal_for_tests = struct
      let get_opt = get_opt
    end
  end
end
OCaml

Innovation. Community. Security.