Congress_Buggy.v 15.1 KB
Newer Older
Jakob Botsch Nielsen's avatar
Jakob Botsch Nielsen committed
1
2
3
4
5
6
7
(* In this file we introduce a reentrancy problem in the Congress
contract described in Congress.v. We then use one of our blockchain
implementations (the depth first local block chain) to prove that this
version can send out too many transactions. This is done by
constructing a contract that actually exploits this version of the
Congress and then just asking Coq to compute. *)

8
9
10
11
12
From Coq Require Import ZArith.
From Coq Require Import Morphisms.
From Coq Require Import Psatz.
From Coq Require Import Permutation.
From SmartContracts Require Import Blockchain.
13
From SmartContracts Require Import Serializable.
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
From SmartContracts Require Import Monads.
From SmartContracts Require Import Containers.
From SmartContracts Require Import Automation.
From SmartContracts Require Import Extras.
From SmartContracts Require Import BoundedN.
From RecordUpdate Require Import RecordUpdate.
From Coq Require Import List.

Import ListNotations.
Import RecordSetNotations.

Section CongressBuggy.
Context {BaseTypes : ChainBase}.

Local Open Scope Z.
Set Primitive Projections.
30
Set Nonrecursive Elimination Schemes.
31
32
33
34
35

Definition ProposalId := nat.

Inductive CongressAction :=
  | cact_transfer (to : Address) (amount : Amount)
36
  | cact_call (to : Address) (amount : Amount) (msg : SerializedValue).
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

Record Proposal :=
  build_proposal {
    actions : list CongressAction;
    votes : FMap Address Z;
    vote_result : Z;
    proposed_in : nat;
  }.

Instance proposal_settable : Settable _ :=
  settable! build_proposal <actions; votes; vote_result; proposed_in>.

Record Rules :=
  build_rules {
    min_vote_count_permille : Z;
    margin_needed_permille : Z;
    debating_period_in_blocks : nat;
  }.

Record Setup :=
  build_setup {
    setup_rules : Rules;
  }.

Inductive Msg :=
  | transfer_ownership : Address -> Msg
  | change_rules : Rules -> Msg
  | add_member : Address -> Msg
  | remove_member : Address -> Msg
  | create_proposal : list CongressAction -> Msg
  | vote_for_proposal : ProposalId -> Msg
  | vote_against_proposal : ProposalId -> Msg
  | retract_vote : ProposalId -> Msg
  | finish_proposal : ProposalId -> Msg
  | finish_proposal_remove : ProposalId -> Msg.

Record State :=
  build_state {
    owner : Address;
    state_rules : Rules;
    proposals : FMap nat Proposal;
    next_proposal_id : ProposalId;
    members : FMap Address unit;
  }.

Instance state_settable : Settable _ :=
  settable! build_state <owner; state_rules; proposals; next_proposal_id; members>.

85
Section Serialization.
86

87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
Global Instance rules_serializable : Serializable Rules :=
  Derive Serializable Rules_rect <build_rules>.

Global Instance setup_serializable : Serializable Setup :=
  Derive Serializable Setup_rect <build_setup>.

Global Instance congress_action_serializable : Serializable CongressAction :=
  Derive Serializable CongressAction_rect <cact_transfer, cact_call>.

Global Instance proposal_serializable : Serializable Proposal :=
  Derive Serializable Proposal_rect <build_proposal>.

Global Instance msg_serializable : Serializable Msg :=
  Derive Serializable Msg_rect <transfer_ownership, change_rules, add_member, remove_member,
                                create_proposal, vote_for_proposal, vote_against_proposal,
                                retract_vote, finish_proposal, finish_proposal_remove>.

Global Instance state_serializable : Serializable State :=
  Derive Serializable State_rect <build_state>.
106

107
End Serialization.
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130

Definition validate_rules (rules : Rules) : bool :=
    (rules.(min_vote_count_permille) >=? 0)
        && (rules.(min_vote_count_permille) <=? 1000)
        && (rules.(margin_needed_permille) >=? 0)
        && (rules.(margin_needed_permille) <=? 1000)
        && (0 <=? rules.(debating_period_in_blocks))%nat.

Definition init
           (chain : Chain)
           (ctx : ContractCallContext)
           (setup : Setup) : option State :=
  if validate_rules setup.(setup_rules) then
    Some {| owner := ctx.(ctx_from);
            state_rules := setup.(setup_rules);
            proposals := FMap.empty;
            next_proposal_id := 1%nat;
            members := FMap.empty |}
  else
    None.

Definition add_proposal (actions : list CongressAction) (chain : Chain) (state : State) : State :=
  let id := state.(next_proposal_id) in
131
  let slot_num := chain.(current_slot) in
132
133
134
135
  let proposal := {| actions := actions;
                     votes := FMap.empty;
                     vote_result := 0;
                     proposed_in := slot_num |} in
136
137
  state<|proposals ::= FMap.add id proposal|>
       <|next_proposal_id ::= S|>.
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152

Definition vote_on_proposal
           (voter : Address)
           (pid : ProposalId)
           (vote : Z)
           (state : State)
  : option State :=
  do proposal <- FMap.find pid state.(proposals);
  let old_vote := match FMap.find voter proposal.(votes) with
                 | Some old => old
                 | None => 0
                 end in
  let new_votes := FMap.add voter vote proposal.(votes) in
  let new_vote_result := proposal.(vote_result) - old_vote + vote in
  let new_proposal :=
153
154
      proposal<|votes := new_votes|>
              <|vote_result := new_vote_result|> in
155
156
157
158
159
160
161
162
163
164
165
166
  Some (state<|proposals ::= FMap.add pid new_proposal|>).

Definition do_retract_vote
           (voter : Address)
           (pid : ProposalId)
           (state : State)
  : option State :=
  do proposal <- FMap.find pid state.(proposals);
  do old_vote <- FMap.find voter proposal.(votes);
  let new_votes := FMap.remove voter proposal.(votes) in
  let new_vote_result := proposal.(vote_result) - old_vote in
  let new_proposal :=
167
168
      proposal<|votes := new_votes|>
              <|vote_result := new_vote_result|> in
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
  Some (state<|proposals ::= FMap.add pid new_proposal|>).

Definition congress_action_to_chain_action (act : CongressAction) : ActionBody :=
  match act with
  | cact_transfer to amt => act_transfer to amt
  | cact_call to amt msg => act_call to amt msg
  end.

Definition proposal_passed (proposal : Proposal) (state : State) : bool :=
  let rules := state.(state_rules) in
  let total_votes_for_proposal := Z.of_nat (FMap.size proposal.(votes)) in
  let total_members := Z.of_nat (FMap.size state.(members)) in
  let aye_votes := (proposal.(vote_result) + total_votes_for_proposal) / 2 in
  let vote_count_permille := total_votes_for_proposal * 1000 / total_members in
  let aye_permille := aye_votes * 1000 / total_votes_for_proposal in
  let enough_voters := vote_count_permille >=? rules.(min_vote_count_permille) in
  let enough_ayes := aye_permille >=? rules.(margin_needed_permille) in
  enough_voters && enough_ayes.

Definition do_finish_proposal
           (ctx : ContractCallContext)
           (pid : ProposalId)
           (state : State)
           (chain : Chain)
  : option (State * list ActionBody) :=
  do proposal <- FMap.find pid state.(proposals);
  let rules := state.(state_rules) in
  let debate_end := (proposal.(proposed_in) + rules.(debating_period_in_blocks))%nat in
197
  let cur_slot := chain.(current_slot) in
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
  if (cur_slot <? debate_end)%nat then
    None
  else
    let response_acts :=
        if proposal_passed proposal state
        then proposal.(actions)
        else [] in
    let response_chain_acts := map congress_action_to_chain_action response_acts in
    let self_call_msg := serialize (finish_proposal_remove pid) in
    let self_call := act_call (ctx_contract_address ctx) 0 self_call_msg in
    Some (state, response_chain_acts ++ [self_call]).

Definition receive
           (chain : Chain)
           (ctx : ContractCallContext)
           (state : State)
           (maybe_msg : option Msg)
  : option (State * list ActionBody) :=
  let sender := ctx.(ctx_from) in
  let is_from_owner := (sender =? state.(owner))%address in
  let is_from_member := FMap.mem sender state.(members) in
  let without_actions := option_map (fun new_state => (new_state, [])) in
  match maybe_msg, is_from_owner, is_from_member with
  | Some (transfer_ownership new_owner), true, _ =>
    Some (state<|owner := new_owner|>, [])

  | Some (change_rules new_rules), true, _ =>
    if validate_rules new_rules then
      Some (state<|state_rules := new_rules|>, [])
    else
      None

  | Some (add_member new_member), true, _ =>
    Some (state<|members ::= FMap.add new_member tt|>, [])

  | Some (remove_member old_member), true, _ =>
    Some (state<|members ::= FMap.remove old_member|>, [])

  | Some (create_proposal actions), _, true =>
    Some (add_proposal actions chain state, [])

  | Some (vote_for_proposal pid), _, true =>
    without_actions (vote_on_proposal sender pid 1 state)

  | Some (vote_against_proposal pid), _, true =>
    without_actions (vote_on_proposal sender pid (-1) state)

  | Some (retract_vote pid), _, true =>
    without_actions (do_retract_vote sender pid state)

  | Some (finish_proposal pid), _, _ =>
    do_finish_proposal ctx pid state chain

  | Some (finish_proposal_remove pid), _, _ =>
    if (sender =? ctx_contract_address ctx)%address then
      Some (state<|proposals ::= FMap.remove pid|>, [])
    else
      None

  | _, _, _ =>
        None

  end.

Ltac solve_contract_proper :=
    match goal with
264
265
    | _ => progress subst
    | _ => solve [auto]
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
    | [|- ?x _  = ?x _] => unfold x
    | [|- ?x _ _ = ?x _ _] => unfold x
    | [|- ?x _ _ _ = ?x _ _ _] => unfold x
    | [|- ?x _ _ _ _ = ?x _ _ _ _] => unfold x
    | [|- ?x _ _ _ _ = ?x _ _ _ _] => unfold x
    | [|- ?x _ _ _ _ _ = ?x _ _ _ _ _] => unfold x
    | [|- Some _ = Some _] => f_equal
    | [|- pair _ _ = pair _ _] => f_equal
    | [|- (if ?x then _ else _) = (if ?x then _ else _)] => destruct x
    | [|- match ?x with | _ => _ end = match ?x with | _ => _ end ] => destruct x
    | [H: ChainEquiv _ _ |- _] => rewrite H in *
    end.

Lemma init_proper :
  Proper (ChainEquiv ==> eq ==> eq ==> eq) init.
281
Proof. repeat intro; repeat solve_contract_proper. Qed.
282
283
284

Lemma receive_proper :
  Proper (ChainEquiv ==> eq ==> eq ==> eq ==> eq) receive.
285
Proof. repeat intro; repeat solve_contract_proper. Qed.
286
287

Definition contract : Contract Setup Msg State :=
288
  build_contract init init_proper receive receive_proper.
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

End CongressBuggy.
(* We will show that this contract is buggy and does not satisfy the
   property we proved for the other version of the Congress. We do
   this with a counterexample, where we exploit reentrancy similar to
   the DAO hack. We first define a contract that does this
   exploitation. *)

Section ExploitContract.
Context {Base : ChainBase}.

Definition ExploitSetup := unit.
Definition ExploitState := nat. (* how many times have we called ourselves *)
Definition ExploitMsg := unit.
Definition exploit_init
            (chain : Chain)
            (ctx : ContractCallContext)
            (setup : ExploitSetup) : option ExploitState :=
  Some 0.
Definition exploit_receive
            (chain : Chain)
            (ctx : ContractCallContext)
            (state : ExploitState)
            (msg : option ExploitMsg) : option (ExploitState * list ActionBody) :=
  if 25 <? state then
    Some (state, [])
  else
    let again := finish_proposal 1 in
    Some (S state, [act_call (ctx_from ctx) 0 (serialize again)]).

Instance exploit_init_proper :
  Proper (ChainEquiv ==> eq ==> eq ==> eq) exploit_init.
Proof. now subst. Qed.

Instance exploit_receive_proper :
  Proper (ChainEquiv ==> eq ==> eq ==> eq ==> eq) exploit_receive.
Proof. now subst. Qed.

Definition exploit_contract : Contract ExploitSetup ExploitMsg ExploitState :=
328
  build_contract exploit_init exploit_init_proper exploit_receive exploit_receive_proper.
329
330
331
332
333
334
335
336
337
338
339
340

End ExploitContract.

(* With this defined we can give the counterexample with relative ease. We use a
concrete implementation of a blockchain for this. *)
From SmartContracts Require LocalBlockchain.

Section Theories.
  Import LocalBlockchain.

  Open Scope nat.
  Definition exploit_example : option (Address * LocalChainBuilderDepthFirst) :=
341
342
    let chain := @builder_initial _ LocalChainBuilderDepthFirst in
    let creator := BoundedN.of_Z_const AddrSize 10 in
343
344
    let add_block (chain : LocalChainBuilderDepthFirst) act_bodies :=
        let next_header :=
345
346
347
348
349
350
351
352
            {| block_height := S (chain_height chain);
               block_slot := S (current_slot chain);
               block_finalized_height := finalized_height chain;
               block_creator := creator;
               block_reward := 50; |} in
        let acts := map (build_act creator) act_bodies in
        builder_add_block chain next_header acts in
    (* Get some money on the creator *)
353
    do chain <- add_block chain [];
354
355
356
357
358
359
    (* Deploy congress and exploit contracts *)
    let rules :=
        {| min_vote_count_permille := 200;
           margin_needed_permille := 501;
           debating_period_in_blocks := 0; |} in
    let dep_congress := create_deployment 50 contract {| setup_rules := rules |} in
360
    let dep_exploit := create_deployment 0 exploit_contract tt in
361
    do chain <- add_block chain [dep_congress; dep_exploit];
362
    let contracts := map fst (FMap.elements (lc_contracts (lcb_lc chain))) in
363
364
365
    let exploit := nth 0 contracts creator in
    let congress := nth 1 contracts creator in
    (* Add creator to congress, create a proposal to transfer *)
366
    (* some money to exploit contract, vote for the proposal, and execute the proposal *)
367
    let add_creator := add_member creator in
368
369
370
    let create_proposal := create_proposal [cact_transfer exploit 1] in
    let vote_proposal := vote_for_proposal 1 in
    let exec_proposal := finish_proposal 1 in
371
372
    let act_bodies :=
        map (fun m => act_call congress 0 (serialize m))
373
            [add_creator; create_proposal; vote_proposal; exec_proposal] in
374
    do chain <- add_block chain act_bodies;
375
376
    Some (congress, chain).

377
378
  Definition unpacked_exploit_example : Address * LocalChainBuilderDepthFirst :=
    unpack_option exploit_example.
379

380
381
382
383
  Definition num_acts_created_in_proposals (calls : list (ContractCallInfo Msg)) :=
    let count call :=
        match call_msg call with
        | Some (create_proposal acts) => length acts
384
385
        | _ => 0
        end in
386
    sumnat count calls.
387

388
389
390
391
  (* Now we prove that this version of the contract is buggy, i.e. it does not satisfy the
     property we proved for the other version of the Congress. We filter out transactions
     from the congress to the congress as we have those now (due to self calls). *)
  Theorem congress_is_buggy :
392
393
394
395
396
397
398
    exists bstate caddr (trace : ChainTrace empty_state bstate)
           (inc_calls : list (ContractCallInfo Msg)),
      env_contracts bstate caddr = Some (contract : WeakContract) /\
      incoming_calls trace caddr = Some inc_calls /\
      length (filter (fun tx => negb (tx_to tx =? caddr)%address)
                     (outgoing_txs trace caddr)) >
      num_acts_created_in_proposals inc_calls.
399
  Proof.
400
401
    exists (build_chain_state (snd unpacked_exploit_example) []).
    exists (fst unpacked_exploit_example).
402
    exists (builder_trace (snd unpacked_exploit_example)).
403
404
405
406
407
408
409
410
    set (inc_calls := unpack_option
                        (incoming_calls (Msg := Msg)
                                        (builder_trace (snd unpacked_exploit_example))
                                        (fst unpacked_exploit_example))).
    vm_compute in inc_calls.
    exists inc_calls.
    split; [|split].
    - reflexivity.
411
412
    - reflexivity.
    - vm_compute.
413
      clear inc_calls.
414
      lia.
415
  Qed.
416
End Theories.