package tezos-protocol-alpha

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

Source file delegate_storage.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
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
(*****************************************************************************)
(*                                                                           *)
(* Open Source License                                                       *)
(* Copyright (c) 2018 Dynamic Ledger Solutions, Inc. <contact@tezos.com>     *)
(* Copyright (c) 2021 Nomadic Labs, <contact@nomadic-labs.com>               *)
(* Copyright (c) 2022 G.B. Fefe, <gb.fefe@protonmail.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.                                                 *)
(*                                                                           *)
(*****************************************************************************)

(*
  Some invariants:

  A contract is a delegate <=>
    - it is registered (i.e. in the set {!Storage.Delegates.mem}), and
    - its full staking balance is initialized.

  If a contract is a delegate then :
    - it has no stake in another account, though it may (still) have unstake
        requests from another contract.

  If a contract is not a delegate then:
    - it has no *own* frozen stake (a.k.a. frozen deposits),
    - it has no consensus key.

  Once a contract has become a delegate, it is so forever. There are no ways
  to unregister.
*)

type error +=
  | (* `Permanent *) Unregistered_delegate of Signature.Public_key_hash.t

let () =
  (* Unregistered delegate *)
  register_error_kind
    `Permanent
    ~id:"contract.manager.unregistered_delegate"
    ~title:"Unregistered delegate"
    ~description:"A contract cannot be delegated to an unregistered delegate"
    ~pp:(fun ppf k ->
      Format.fprintf
        ppf
        "The provided public key (with hash %a) is not registered as valid \
         delegate key."
        Signature.Public_key_hash.pp
        k)
    Data_encoding.(obj1 (req "hash" Signature.Public_key_hash.encoding))
    (function Unregistered_delegate k -> Some k | _ -> None)
    (fun k -> Unregistered_delegate k)

type error += No_previous_cycle

let registered = Storage.Delegates.mem

module Contract = struct
  let init ctxt contract delegate =
    let open Lwt_result_syntax in
    let* known_delegate =
      Contract_manager_storage.is_manager_key_revealed ctxt delegate
    in
    let*? () = error_unless known_delegate (Unregistered_delegate delegate) in
    let*! is_registered = registered ctxt delegate in
    let*? () = error_unless is_registered (Unregistered_delegate delegate) in
    let* ctxt = Contract_delegate_storage.init ctxt contract delegate in
    let* balance_and_frozen_bonds =
      Contract_storage.get_balance_and_frozen_bonds ctxt contract
    in
    Stake_storage.add_delegated_stake ctxt delegate balance_and_frozen_bonds

  type error +=
    | (* `Temporary *) Active_delegate
    | (* `Permanent *) Empty_delegate_account of Signature.Public_key_hash.t

  let () =
    register_error_kind
      `Temporary
      ~id:"delegate.already_active"
      ~title:"Delegate already active"
      ~description:"Useless delegate reactivation"
      ~pp:(fun ppf () ->
        Format.fprintf ppf "The delegate is still active, no need to refresh it")
      Data_encoding.empty
      (function Active_delegate -> Some () | _ -> None)
      (fun () -> Active_delegate) ;
    register_error_kind
      `Permanent
      ~id:"delegate.empty_delegate_account"
      ~title:"Empty delegate account"
      ~description:
        "Cannot register a delegate when its implicit account is empty"
      ~pp:(fun ppf delegate ->
        Format.fprintf
          ppf
          "Delegate registration is forbidden when the delegate\n\
          \           implicit account is empty (%a)"
          Signature.Public_key_hash.pp
          delegate)
      Data_encoding.(obj1 (req "delegate" Signature.Public_key_hash.encoding))
      (function Empty_delegate_account c -> Some c | _ -> None)
      (fun c -> Empty_delegate_account c)

  let set_self_delegate c delegate =
    let open Lwt_result_syntax in
    let*! is_registered = registered c delegate in
    if is_registered then
      let* () =
        let* is_inactive = Delegate_activation_storage.is_inactive c delegate in
        fail_unless is_inactive Active_delegate
      in
      Stake_storage.set_active c delegate
    else
      let contract = Contract_repr.Implicit delegate in
      let* pk =
        Contract_manager_storage.get_manager_key
          c
          ~error:(Unregistered_delegate delegate)
          delegate
      in
      let* () =
        let*! is_allocated = Contract_storage.allocated c contract in
        fail_unless is_allocated (Empty_delegate_account delegate)
      in
      let* balance_and_frozen_bonds =
        Contract_storage.get_balance_and_frozen_bonds c contract
      in
      let* c =
        Stake_storage.remove_contract_delegated_stake
          c
          contract
          balance_and_frozen_bonds
      in
      let* c = Contract_delegate_storage.set c contract delegate in
      let* c =
        (* Initializes the full staking balance of [delegate]. *)
        Stake_storage.initialize_delegate
          c
          delegate
          ~delegated:balance_and_frozen_bonds
      in
      let*! c = Storage.Delegates.add c delegate in
      let* c = Delegate_consensus_key.init c delegate pk in
      let* c = Stake_storage.set_active c delegate in
      return c

  type error +=
    | (* `Permanent *) No_deletion of Signature.Public_key_hash.t
    | (* `Temporary *) Current_delegate

  let () =
    register_error_kind
      `Permanent
      ~id:"delegate.no_deletion"
      ~title:"Forbidden delegate deletion"
      ~description:"Tried to unregister a delegate"
      ~pp:(fun ppf delegate ->
        Format.fprintf
          ppf
          "Delegate deletion is forbidden (%a)"
          Signature.Public_key_hash.pp
          delegate)
      Data_encoding.(obj1 (req "delegate" Signature.Public_key_hash.encoding))
      (function No_deletion c -> Some c | _ -> None)
      (fun c -> No_deletion c) ;
    register_error_kind
      `Temporary
      ~id:"delegate.unchanged"
      ~title:"Unchanged delegated"
      ~description:"Contract already delegated to the given delegate"
      ~pp:(fun ppf () ->
        Format.fprintf
          ppf
          "The contract is already delegated to the same delegate")
      Data_encoding.empty
      (function Current_delegate -> Some () | _ -> None)
      (fun () -> Current_delegate)

  let set_delegate c contract delegate =
    let open Lwt_result_syntax in
    let* () =
      match contract with
      | Contract_repr.Originated _ -> return_unit
      | Implicit pkh ->
          let*! is_registered = registered c pkh in
          fail_when is_registered (No_deletion pkh)
    in
    let* () =
      let* current_delegate = Contract_delegate_storage.find c contract in
      match (delegate, current_delegate) with
      | None, None ->
          (* we don't fail in this case in order not to risk breaking
             existing smart contracts. *)
          return_unit
      | Some delegate, Some current_delegate
        when Signature.Public_key_hash.equal delegate current_delegate ->
          tzfail Current_delegate
      | _ -> return_unit
    in
    let* balance_and_frozen_bonds =
      Contract_storage.get_balance_and_frozen_bonds c contract
    in
    let* c =
      Stake_storage.remove_contract_delegated_stake
        c
        contract
        balance_and_frozen_bonds
    in
    match delegate with
    | None ->
        let* c = Contract_delegate_storage.delete c contract in
        return c
    | Some delegate ->
        let* () =
          let*! is_delegate_registered = registered c delegate in
          fail_when
            (not is_delegate_registered)
            (Unregistered_delegate delegate)
        in
        let* c = Contract_delegate_storage.set c contract delegate in
        let* c =
          Stake_storage.add_delegated_stake c delegate balance_and_frozen_bonds
        in
        return c

  let set c contract delegate =
    match (delegate, contract) with
    | Some delegate, Contract_repr.Implicit source
      when Signature.Public_key_hash.equal source delegate ->
        set_self_delegate c delegate
    | _ -> set_delegate c contract delegate
end

let fold = Storage.Delegates.fold

let list = Storage.Delegates.elements

let initial_frozen_deposits ctxt delegate =
  let open Lwt_result_syntax in
  let* stake_opt =
    match Raw_context.find_stake_distribution_for_current_cycle ctxt with
    | Some distribution ->
        return (Signature.Public_key_hash.Map.find delegate distribution)
    | None ->
        (* This branch happens when the stake distribution is not initialized in
           [ctxt], e.g. when RPCs are called or operations are simulated. *)
        let current_cycle = (Raw_context.current_level ctxt).cycle in
        let+ stakes =
          Stake_storage.get_selected_distribution ctxt current_cycle
        in
        List.assoc ~equal:Signature.Public_key_hash.equal delegate stakes
  in
  match stake_opt with
  | None -> return Tez_repr.zero
  | Some {frozen; weighted_delegated = _} -> return frozen

let initial_frozen_deposits_of_previous_cycle ctxt delegate =
  let open Lwt_result_syntax in
  let current_cycle = (Raw_context.current_level ctxt).cycle in
  match Cycle_repr.pred current_cycle with
  | None -> tzfail No_previous_cycle
  | Some previous_cycle -> (
      let+ stakes =
        Stake_storage.get_selected_distribution ctxt previous_cycle
      in
      match
        List.assoc ~equal:Signature.Public_key_hash.equal delegate stakes
      with
      | None -> Tez_repr.zero
      | Some {frozen; weighted_delegated = _} -> frozen)

let current_frozen_deposits ctxt delegate =
  let open Lwt_result_syntax in
  let* full_staking_balance =
    Stake_storage.get_full_staking_balance ctxt delegate
  in
  Lwt.return (Full_staking_balance_repr.total_frozen full_staking_balance)

let frozen_deposits_limit ctxt delegate =
  Storage.Contract.Frozen_deposits_limit.find
    ctxt
    (Contract_repr.Implicit delegate)

let set_frozen_deposits_limit ctxt delegate limit =
  Storage.Contract.Frozen_deposits_limit.add_or_remove
    ctxt
    (Contract_repr.Implicit delegate)
    limit

let spendable_balance ctxt delegate =
  let contract = Contract_repr.Implicit delegate in
  Storage.Contract.Spendable_balance.get ctxt contract

let drain ctxt ~delegate ~destination =
  let open Lwt_result_syntax in
  let destination_contract = Contract_repr.Implicit destination in
  let*! is_destination_allocated =
    Contract_storage.allocated ctxt destination_contract
  in
  let delegate_contract = Contract_repr.Implicit delegate in
  let* ctxt, _, balance_updates1 =
    if not is_destination_allocated then
      Fees_storage.burn_origination_fees
        ctxt
        ~storage_limit:(Z.of_int (Constants_storage.origination_size ctxt))
        ~payer:(`Contract delegate_contract)
    else return (ctxt, Z.zero, [])
  in
  let* manager_balance = spendable_balance ctxt delegate in
  let*? one_percent = Tez_repr.(manager_balance /? 100L) in
  let fees = Tez_repr.(max one one_percent) in
  let*? transferred = Tez_repr.(manager_balance -? fees) in
  let* ctxt, balance_updates2 =
    Token.transfer
      ctxt
      (`Contract delegate_contract)
      (`Contract destination_contract)
      transferred
  in
  return
    ( ctxt,
      not is_destination_allocated,
      fees,
      balance_updates1 @ balance_updates2 )

module For_RPC = struct
  let full_balance ctxt delegate =
    let open Lwt_result_syntax in
    let* own_frozen_deposits =
      Staking_pseudotokens_storage.For_RPC.staked_balance
        ctxt
        ~delegate
        ~contract:(Contract_repr.Implicit delegate)
    in
    let* unstaked_frozen =
      let* result =
        Unstake_requests_storage.prepare_finalize_unstake
          ctxt
          ~for_next_cycle_use_only_after_slashing:false
          (Contract_repr.Implicit delegate)
      in
      match result with
      | None -> return Tez_repr.zero
      | Some {finalizable; unfinalizable} ->
          let* unfinalizable_requests =
            Unstake_requests_storage.For_RPC
            .apply_slash_to_unstaked_unfinalizable
              ctxt
              unfinalizable
          in
          let*? sum_unfinalizable =
            List.fold_left_e
              (fun acc (_cycle, tz) -> Tez_repr.(acc +? tz))
              Tez_repr.zero
              unfinalizable_requests
          in
          let*? sum =
            List.fold_left_e
              (fun acc (_, _cycle, tz) -> Tez_repr.(acc +? tz))
              sum_unfinalizable
              finalizable
          in
          return sum
    in
    let*? all_frozen = Tez_repr.(own_frozen_deposits +? unstaked_frozen) in
    let delegate_contract = Contract_repr.Implicit delegate in
    let* balance_and_frozen_bonds =
      Contract_storage.get_balance_and_frozen_bonds ctxt delegate_contract
    in
    let*? sum = Tez_repr.(all_frozen +? balance_and_frozen_bonds) in
    return sum

  let staking_balance ctxt delegate =
    let open Lwt_result_syntax in
    let*! is_registered = registered ctxt delegate in
    if is_registered then
      Stake_storage.For_RPC.get_staking_balance ctxt delegate
    else return Tez_repr.zero

  let min_delegated_in_current_cycle ctxt delegate =
    let open Lwt_result_syntax in
    let current_cycle = (Raw_context.current_level ctxt).cycle in
    let*! is_registered = registered ctxt delegate in
    if is_registered then
      let+ staking_balance =
        Stake_storage.get_full_staking_balance ctxt delegate
      in
      let min_delegated =
        Full_staking_balance_repr.min_delegated_in_cycle
          ~current_cycle
          staking_balance
      in
      let level_of_min_delegated =
        match
          Full_staking_balance_repr.Internal_for_tests_and_RPCs
          .level_of_min_delegated
            staking_balance
        with
        | None -> None
        | Some level ->
            if Cycle_repr.(level.cycle < current_cycle) then None
            else Some level
      in
      (min_delegated, level_of_min_delegated)
    else return (Tez_repr.zero, None)

  let delegated_balance ctxt delegate =
    let open Lwt_result_syntax in
    let* staking_balance = staking_balance ctxt delegate in
    let* self_staking_balance = full_balance ctxt delegate in
    let*? sum = Tez_repr.(staking_balance -? self_staking_balance) in
    return sum
end
OCaml

Innovation. Community. Security.