Congress.v 30.3 KB
Newer Older
Jakob Botsch Nielsen's avatar
Jakob Botsch Nielsen committed
1
2
3
4
5
6
(* In this file we implement a Congress and prove it correct up to a
specification. The Congress is a simplified version of the DAO in
which members vote on proposals. We implement the contract in Gallina
and then show that it does not send out more transactions than
expected from the number of created proposals. *)

7
From Coq Require Import ZArith.
8
From Coq Require Import Morphisms.
9
10
From Coq Require Import Psatz.
From Coq Require Import Permutation.
11
From SmartContracts Require Import Blockchain.
12
From SmartContracts Require Import Serializable.
13
From SmartContracts Require Import Monads.
14
From SmartContracts Require Import Containers.
15
From SmartContracts Require Import Automation.
16
From SmartContracts Require Import Extras.
17
From SmartContracts Require Import ChainedList.
18
From RecordUpdate Require Import RecordUpdate.
19
From Coq Require Import List.
20

Jakob Botsch Nielsen's avatar
Jakob Botsch Nielsen committed
21
22
23
Import ListNotations.
Import RecordSetNotations.

24
Section Congress.
25
Context {BaseTypes : ChainBase}.
26
27

Local Open Scope Z.
28
Set Primitive Projections.
29

Jakob Botsch Nielsen's avatar
Jakob Botsch Nielsen committed
30
31
Definition ProposalId := nat.

32
33
Inductive CongressAction :=
  | cact_transfer (to : Address) (amount : Amount)
34
  | cact_call (to : Address) (amount : Amount) (msg : SerializedValue).
35

Jakob Botsch Nielsen's avatar
Jakob Botsch Nielsen committed
36
Record Proposal :=
37
  build_proposal {
38
    actions : list CongressAction;
39
    votes : FMap Address Z;
40
    vote_result : Z;
41
    proposed_in : nat;
Jakob Botsch Nielsen's avatar
Jakob Botsch Nielsen committed
42
43
  }.

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

Jakob Botsch Nielsen's avatar
Jakob Botsch Nielsen committed
47
Record Rules :=
48
49
50
  build_rules {
    min_vote_count_permille : Z;
    margin_needed_permille : Z;
51
    debating_period_in_blocks : nat;
Jakob Botsch Nielsen's avatar
Jakob Botsch Nielsen committed
52
53
54
  }.

Record Setup :=
55
56
  build_setup {
    setup_rules : Rules;
Jakob Botsch Nielsen's avatar
Jakob Botsch Nielsen committed
57
58
59
  }.

Inductive Msg :=
60
61
62
63
64
65
66
67
68
  | 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.
Jakob Botsch Nielsen's avatar
Jakob Botsch Nielsen committed
69
70

Record State :=
71
72
73
  build_state {
    owner : Address;
    state_rules : Rules;
74
    proposals : FMap nat Proposal;
75
    next_proposal_id : ProposalId;
76
    members : FMap Address unit;
Jakob Botsch Nielsen's avatar
Jakob Botsch Nielsen committed
77
78
  }.

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

82
Section Serialization.
83

84
Definition deserialize_rules (v : SerializedValue) : option Rules :=
Jakob Botsch Nielsen's avatar
Jakob Botsch Nielsen committed
85
  do '(a, b, c) <- deserialize v;
86
87
  Some (build_rules a b c).

88
Global Program Instance rules_serializable : Serializable Rules :=
89
90
91
92
93
94
95
  {| serialize r := let (a, b, c) := r in serialize (a, b, c);
     (* Why does
     deserialize v :=
       do '((a, b), c) <- deserialize v;
       Some (build_rules a b c); |}.
       not work here? *)
     deserialize := deserialize_rules; |}.
96
97
98
99
100
Next Obligation.
  intros x. unfold deserialize_rules.
  rewrite deserialize_serialize.
  reflexivity.
Qed.
101

102
Global Program Instance setup_serializable : Serializable Setup :=
103
104
105
106
  {| serialize s := serialize s.(setup_rules);
     deserialize or :=
       do rules <- deserialize or;
       Some (build_setup rules); |}.
107
108
Next Obligation.
  intros x.
109
  cbn.
110
111
112
  rewrite deserialize_serialize.
  reflexivity.
Qed.
113

114
Definition deserialize_congress_action (v : SerializedValue) : option CongressAction :=
115
116
117
118
119
120
  do val <- deserialize v;
  Some (match val with
  | inl (to, amount) => cact_transfer to amount
  | inr (to, amount, msg) => cact_call to amount msg
  end).

121
Global Program Instance congress_action_serializable : Serializable CongressAction :=
122
123
124
125
126
127
128
129
  {| serialize ca :=
       serialize
         match ca with
         | cact_transfer to amount => inl (to, amount)
         | cact_call to amount msg => inr (to, amount, msg)
         end;
     deserialize := deserialize_congress_action; |}.
Next Obligation.
130
  intros ca.
131
  unfold deserialize_congress_action.
132
133
  rewrite deserialize_serialize.
  destruct ca; reflexivity.
134
135
Qed.

136
Definition deserialize_proposal (v : SerializedValue) : option Proposal :=
137
138
139
  do '(a, b, c, d) <- deserialize v;
  Some (build_proposal a b c d).

140
Global Program Instance proposal_serializable : Serializable Proposal :=
141
142
143
144
145
146
  {| serialize p :=
       let (a, b, c, d) := p in
       serialize (a, b, c, d);
     deserialize := deserialize_proposal;
  |}.
Next Obligation.
147
  intros p.
148
  unfold deserialize_proposal.
149
150
  rewrite deserialize_serialize.
  destruct p; reflexivity.
151
152
Qed.

153
Definition serialize_msg (m : Msg) : SerializedValue :=
154
155
156
157
158
159
160
161
162
163
164
165
166
  serialize
    match m with
    | transfer_ownership a => (0, serialize a)
    | change_rules r => (1, serialize r)
    | add_member a => (2, serialize a)
    | remove_member a => (3, serialize a)
    | create_proposal l => (4, serialize l)
    | vote_for_proposal pid => (5, serialize pid)
    | vote_against_proposal pid => (6, serialize pid)
    | retract_vote pid => (7, serialize pid)
    | finish_proposal pid => (8, serialize pid)
    end.

167
Definition deserialize_msg (v : SerializedValue) : option Msg :=
168
169
170
171
172
173
174
175
176
177
178
179
180
181
  do '(tag, v) <- deserialize v;
  match tag with
  | 0 => option_map transfer_ownership (deserialize v)
  | 1 => option_map change_rules (deserialize v)
  | 2 => option_map add_member (deserialize v)
  | 3 => option_map remove_member (deserialize v)
  | 4 => option_map create_proposal (deserialize v)
  | 5 => option_map vote_for_proposal (deserialize v)
  | 6 => option_map vote_against_proposal (deserialize v)
  | 7 => option_map retract_vote (deserialize v)
  | 8 => option_map finish_proposal (deserialize v)
  | _ => None
  end.

182
Global Program Instance msg_serializable : Serializable Msg :=
183
184
  {| serialize := serialize_msg; deserialize := deserialize_msg; |}.
Next Obligation.
185
  intros msg.
186
  unfold serialize_msg, deserialize_msg.
187
  destruct msg; repeat (cbn; rewrite deserialize_serialize); reflexivity.
188
189
Qed.

190
Definition serialize_state (s : State) : SerializedValue :=
191
192
193
  let (a, b, c, d, e) := s in
  serialize (a, b, c, d, e).

194
Definition deserialize_state (v : SerializedValue) : option State :=
195
196
197
  do '(a, b, c, d, e) <- deserialize v;
  Some (build_state a b c d e).

198
Global Program Instance state_serializable : Serializable State :=
199
200
201
  {| serialize := serialize_state; deserialize := deserialize_state; |}.
Next Obligation.
  unfold serialize_state, deserialize_state.
202
  destruct x; repeat (cbn; rewrite deserialize_serialize); reflexivity.
203
204
Qed.

205
End Serialization.
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228

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
229
  let slot_num := chain.(current_slot) in
230
231
232
233
  let proposal := {| actions := actions;
                     votes := FMap.empty;
                     vote_result := 0;
                     proposed_in := slot_num |} in
234
235
  state<|proposals ::= FMap.add id proposal|>
       <|next_proposal_id ::= S|>.
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250

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 :=
251
252
      proposal<|votes := new_votes|>
              <|vote_result := new_vote_result|> in
253
254
255
256
257
258
259
260
261
262
263
264
  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 :=
265
266
      proposal<|votes := new_votes|>
              <|vote_result := new_vote_result|> in
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
  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
           (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
294
  let cur_slot := chain.(current_slot) in
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
  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 new_state := state<|proposals ::= FMap.remove pid|> in
    Some (new_state, response_chain_acts).

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 pid state chain

  | _, _, _ =>
        None

  end.

352
353
354
355
356
357
358
359
360
361
362
363
364
Ltac solve_contract_proper :=
  repeat
    match goal with
    | [|- ?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
Jakob Botsch Nielsen's avatar
Jakob Botsch Nielsen committed
365
366
    | [H: ChainEquiv _ _ |- _] => rewrite H in *
    | _ => subst; auto
367
368
369
370
371
372
373
374
375
376
    end.

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

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

377
Definition contract : Contract Setup Msg State :=
378
  build_contract init init_proper receive receive_proper.
379
380
Section Theories.
Local Open Scope nat.
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
(* The rules stored in the blockchain's state are always valid *)
Lemma rules_valid bstate caddr :
  reachable bstate ->
  env_contracts bstate caddr = Some (Congress.contract : WeakContract) ->
  exists cstate,
    contract_state bstate caddr = Some cstate /\
    validate_rules cstate.(state_rules) = true.
Proof.
  apply lift_functional_correctness with (DeployFacts := fun _ _ => True)
                                         (CallFacts := fun _ _ => True).
  - intros chain ctx setup result _ init.
    cbn in *.
    unfold Congress.init in init.
    destruct_if; try congruence.
    now inversion_clear init.
  - intros chain ctx prev_state msg new_state new_acts _ prev_valid receive.
    cbn in *.
    destruct msg as [[]|]; cbn in *;
      try solve [
            repeat
              match goal with
              | [H: Some ?x = Some ?y |- _] => inversion_clear H; auto
              | _ => try congruence; destruct_if
              end].
    + destruct_if; try congruence.
      unfold vote_on_proposal in receive.
      destruct (FMap.find _ _); cbn in *; try congruence.
      now inversion_clear receive.
    + destruct_if; try congruence.
      unfold vote_on_proposal in receive.
      destruct (FMap.find _ _); cbn in *; try congruence.
      now inversion_clear receive.
    + destruct_if; try congruence.
      unfold do_retract_vote in receive.
      destruct (FMap.find _ _); cbn in *; try congruence.
      destruct (FMap.find _ _); cbn in *; try congruence.
      now inversion_clear receive.
    + unfold do_finish_proposal in receive.
      destruct (FMap.find _ _); cbn in *; try congruence.
      destruct_if; cbn in *; try congruence.
      now inversion_clear receive.
  - now destruct eval.
Qed.

426
Definition num_acts_created_in_proposals (txs : list Tx) :=
Jakob Botsch Nielsen's avatar
Jakob Botsch Nielsen committed
427
  let count tx :=
428
      match tx_body tx with
429
      | tx_call (Some msg) =>
430
431
432
433
434
435
        match deserialize msg with
        | Some (create_proposal acts) => length acts
        | _ => 0
        end
      | _ => 0
      end in
436
  sumnat count txs.
437

438
Definition num_cacts_in_state state :=
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
  sumnat (fun '(k, v) => length (actions v)) (FMap.elements (proposals state)).

Definition num_outgoing_acts l address :=
  let extract a :=
      if address_eqb (act_from a) address
      then 1
      else 0 in
  sumnat extract l.

Lemma num_outgoing_acts_app q1 q2 address :
  num_outgoing_acts (q1 ++ q2) address =
  num_outgoing_acts q1 address +
  num_outgoing_acts q2 address.
Proof.
  unfold num_outgoing_acts.
  now rewrite sumnat_app.
Qed.

Lemma num_outgoing_acts_block l contract :
  address_is_contract contract = true ->
459
  Forall act_is_from_account l ->
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
  num_outgoing_acts l contract = 0.
Proof.
  intros is_contract all.
  induction all; auto.
  cbn in *.
  destruct_address_eq; try congruence.
  fold (num_outgoing_acts l contract); auto.
Qed.

Lemma num_outgoing_acts_call l contract :
  num_outgoing_acts (map (build_act contract) l) contract = length l.
Proof.
  induction l; auto.
  cbn.
  destruct_address_eq; auto; congruence.
Qed.

Lemma num_outgoing_acts_call_ne to l contract :
  to <> contract ->
  num_outgoing_acts (map (build_act to) l) contract = 0.
Proof.
  intros neq.
  induction l; auto.
  cbn.
  destruct_address_eq; auto; congruence.
Qed.

487
488
489
Lemma num_cacts_in_state_deployment chain ctx setup state :
  init chain ctx setup = Some state ->
  num_cacts_in_state state = 0.
490
491
Proof.
  intros init.
492
  unfold Congress.init in init.
493
  destruct (validate_rules _); try congruence.
494
  now inversion init.
495
496
497
498
499
500
501
502
Qed.

Ltac remember_new_proposal :=
  match goal with
  | [|- context[FMap.add _ ?p]] => remember p as new_proposal
  end.

Lemma add_proposal_cacts cacts chain state :
503
504
  num_cacts_in_state (add_proposal cacts chain state) <=
  num_cacts_in_state state + length cacts.
505
Proof.
506
  unfold add_proposal, num_cacts_in_state.
507
508
509
510
  cbn.
  destruct (FMap.find (next_proposal_id state) (proposals state)) as [proposal|] eqn:find.
  - remember_new_proposal.
    rewrite <- (FMap.add_remove _ (next_proposal_id state) new_proposal).
Jakob Botsch Nielsen's avatar
Jakob Botsch Nielsen committed
511
    Hint Resolve FMap.find_remove : core.
512
513
514
515
516
517
518
519
520
521
522
523
524
    rewrite <- (FMap.add_id _ _ _ find) at 2.
    rewrite <- (FMap.add_remove _ (next_proposal_id state) proposal).
    repeat rewrite FMap.elements_add; auto.
    subst.
    cbn.
    lia.
  - rewrite FMap.elements_add; auto.
    cbn.
    lia.
Qed.

Lemma vote_on_proposal_cacts_preserved addr pid vote_val state new_state :
  vote_on_proposal addr pid vote_val state = Some new_state ->
525
  num_cacts_in_state new_state = num_cacts_in_state state.
526
527
528
529
530
Proof.
  intros vote.
  unfold vote_on_proposal in vote.
  destruct (FMap.find _ _) eqn:found; cbn in *; try congruence.
  inversion vote.
531
  unfold num_cacts_in_state.
532
533
534
535
536
537
538
539
540
541
542
  cbn.
  remember_new_proposal.
  rewrite <- (FMap.add_id (proposals state) pid p) at 2; auto.
  rewrite <- (FMap.add_remove _ pid p).
  rewrite <- (FMap.add_remove _ pid new_proposal).
  repeat rewrite FMap.elements_add; try apply FMap.find_remove.
  subst; reflexivity.
Qed.

Lemma do_retract_vote_cacts_preserved addr pid state new_state :
  do_retract_vote addr pid state = Some new_state ->
543
  num_cacts_in_state new_state = num_cacts_in_state state.
544
545
546
547
548
549
Proof.
  intros retract.
  unfold do_retract_vote in retract.
  destruct (FMap.find _ _) eqn:found; cbn in *; try congruence.
  destruct (FMap.find addr _); cbn in *; try congruence.
  inversion retract.
550
  unfold num_cacts_in_state.
551
552
553
554
555
  cbn.
  remember_new_proposal.
  rewrite <- (FMap.add_id (proposals state) pid p) at 2; auto.
  rewrite <- (FMap.add_remove _ pid p).
  rewrite <- (FMap.add_remove _ pid new_proposal).
Jakob Botsch Nielsen's avatar
Jakob Botsch Nielsen committed
556
  Hint Resolve FMap.find_remove : core.
557
558
559
560
561
562
  repeat rewrite FMap.elements_add; auto.
  subst; reflexivity.
Qed.

Lemma remove_proposal_cacts pid state proposal :
  FMap.find pid (proposals state) = Some proposal ->
563
564
  num_cacts_in_state (state <|proposals ::= FMap.remove pid|>) +
  length (actions proposal) = num_cacts_in_state state.
565
566
Proof.
  intros find.
567
  unfold num_cacts_in_state.
568
569
570
571
572
573
574
  cbn.
  rewrite <- (FMap.add_id (proposals state) pid proposal) at 2; auto.
  rewrite <- FMap.add_remove.
  rewrite FMap.elements_add; auto.
  cbn.
  lia.
Qed.
575

576
577
578
579
580
(* The next lemma shows that when we send out transactions, the
state change will make up for number of outgoing actions queued. *)
Lemma receive_state_well_behaved
      chain ctx state msg new_state resp_acts :
  receive chain ctx state msg = Some (new_state, resp_acts) ->
581
582
583
  msg <> None /\
  num_cacts_in_state new_state + length resp_acts <=
  num_cacts_in_state state +
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
  match msg with
  | Some (create_proposal ls) => length ls
  | _ => 0
  end.
Proof.
  intros receive.
  destruct msg as [msg|]; cbn in *; try congruence.
  destruct msg; cbn in *; try congruence.
  - (* transfer_ownership *)
    destruct_address_eq; try congruence.
    inversion receive; auto.
  - (* change_rules *)
    destruct_address_eq; cbn in *; destruct (validate_rules r); inversion receive; auto.
  - (* add_member *)
    destruct_address_eq; cbn in *; inversion receive; auto.
  - (* remove_member *)
    destruct_address_eq; cbn in *; inversion receive; auto.
  - (* create_proposal *)
    destruct (FMap.mem _ _); inversion receive.
    cbn.
    rewrite <- plus_n_O.
605
    split; auto.
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
    apply add_proposal_cacts.
  - (* vote_for_proposal *)
    destruct (FMap.mem _ _); try congruence.
    destruct (vote_on_proposal _ _ _ _) eqn:vote; cbn in *; try congruence.
    inversion receive; subst.
    erewrite vote_on_proposal_cacts_preserved; eauto.
  - (* vote_against_proposal *)
    destruct (FMap.mem _ _); try congruence.
    destruct (vote_on_proposal _ _ _ _) eqn:vote; cbn in *; try congruence.
    inversion receive; subst.
    erewrite vote_on_proposal_cacts_preserved; eauto.
  - (* retract_vote *)
    destruct (FMap.mem _ _); try congruence.
    destruct (do_retract_vote _ _ _) eqn:retract; cbn in *; try congruence.
    inversion receive; subst.
    erewrite do_retract_vote_cacts_preserved; eauto.
  - (* finish_proposal *)
    unfold do_finish_proposal in receive.
    destruct (FMap.find _ _) eqn:found; cbn in *; try congruence.
    match goal with
    | [H: (if ?a then _ else _) = Some _ |- _] => destruct a
    end; cbn in *; try congruence.
    inversion receive.
    rewrite <- (remove_proposal_cacts _ _ _ found), map_length.
630
    destruct (proposal_passed _ _); cbn.
631
632
633
634
635
636
    + (* I wonder why these asserts are necessary... *)
      assert (forall a b, a + b <= a + b + 0) by (intros; lia); auto.
    + assert (forall a b, a + 0 <= a + b + 0) by (intros; lia); auto.
Qed.

Lemma undeployed_contract_no_out_queue_count contract (state : ChainState) :
637
  reachable state ->
638
639
640
641
642
643
  address_is_contract contract = true ->
  env_contracts state contract = None ->
  num_outgoing_acts (chain_state_queue state) contract = 0.
Proof.
  intros [trace] is_contract undeployed.
  pose proof undeployed_contract_no_out_queue as all; specialize_hypotheses.
644
  Hint Unfold reachable : core.
645
646
647
648
649
650
651
652
  induction all; auto.
  cbn.
  match goal with
  | [H: _ |- _] => now rewrite H; auto
  end.
Qed.

Lemma undeployed_contract_not_from_self contract (state : ChainState) act acts :
653
  reachable state ->
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
  address_is_contract contract = true ->
  env_contracts state contract = None ->
  chain_state_queue state = act :: acts ->
  act_from act <> contract.
Proof.
  intros trace is_contract no_contract_prev queue_eq.
  pose proof (
         undeployed_contract_no_out_queue
           _ _ trace is_contract no_contract_prev) as all.
  rewrite queue_eq in *.
  inversion all.
  destruct_address_eq; congruence.
Qed.

Arguments num_acts_created_in_proposals : simpl never.
669
Arguments num_cacts_in_state : simpl never.
670
671
672
673
674
Arguments num_cacts_in_state : simpl never.
Arguments num_outgoing_acts !l.

Local Ltac solve_single :=
  solve [
675
      repeat (progress subst; cbn in *; auto);
676
      unfold add_balance, num_cacts_in_state, num_acts_created_in_proposals, num_outgoing_acts;
677
      cbn;
678
      unfold set_chain_contract_state;
679
680
681
682
683
684
685
686
      cbn;
      try rewrite address_eq_refl;
      repeat rewrite address_eq_ne by auto;
      cbn;
      destruct_address_eq; congruence].

Local Ltac simpl_exp_invariant exp :=
  match exp with
687
688
689
690
691
  | context G[length (filter ?f (?hd :: ?tl))] =>
    let newexp := context G[S (length (filter f tl))] in
    replace exp with newexp by solve_single
  | context G[filter ?f (?hd :: ?tl)] =>
    let newexp := context G[filter f tl] in
692
    replace exp with newexp by solve_single
693
  | context G[add_new_block_to_env _ ?env] =>
694
695
    let newexp := context G[env] in
    replace exp with newexp by solve_single
696
  | context G[transfer_balance _ _ _ ?env] =>
697
698
699
700
701
702
703
704
705
706
707
    let newexp := context G[env] in
    replace exp with newexp by solve_single
  | context G[set_contract_state _ _ ?env] =>
    let newexp := context G[env] in
    replace exp with newexp by solve_single
  | context G[add_contract _ _ ?env] =>
    let newexp := context G[env] in
    replace exp with newexp by solve_single
  | context G[num_outgoing_acts (?a ++ ?b) _] =>
    rewrite num_outgoing_acts_app
  end.
708

709
710
711
712
(* This tactic performs various simplifications on the goal involving
expressions establishing the invariant. For instance, it tries to rewrite
num_cacts_in_state (add_tx tx env) -> num_cacts_in_state env using some
common tactics. *)
713
714
715
Local Ltac simpl_goal_invariant :=
  repeat
    match goal with
716
717
    | [|- context[num_cacts_in_state ?env ?addr]] =>
      simpl_exp_invariant constr:(num_cacts_in_state env addr)
718
719
    | [|- context[length ?txs]] =>
      simpl_exp_invariant constr:(length txs)
720
721
    | [|- context[num_outgoing_acts ?q ?addr]] =>
      simpl_exp_invariant constr:(num_outgoing_acts q addr)
722
723
    | [|- context[num_acts_created_in_proposals ?txs]] =>
      simpl_exp_invariant constr:(num_acts_created_in_proposals txs)
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
    end.

Local Ltac simpl_hyp_invariant :=
  repeat
    match goal with
    | [IH: context[num_outgoing_acts (?act :: ?acts) ?addr] |- _] =>
      replace (num_outgoing_acts (act :: acts) addr)
        with (S (num_outgoing_acts acts addr))
        in IH
        by solve_single
    | [IH: context[num_outgoing_acts (?act :: ?acts) ?addr] |- _] =>
      replace (num_outgoing_acts (act :: acts) addr)
        with (num_outgoing_acts acts addr)
        in IH
        by solve_single
    end.

741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
Lemma contract_state_from_weak {A} `{Serializable A} env addr state state_strong :
  env_contract_states env addr = Some state ->
  deserialize state = Some state_strong ->
  contract_state env addr = Some state_strong.
Proof.
  intros weak deser.
  unfold contract_state.
  now rewrite weak.
Qed.

Theorem congress_txs_well_behaved bstate contract (trace : ChainTrace empty_state bstate) :
  env_contracts bstate contract = Some (Congress.contract : WeakContract) ->
  exists cstate,
    contract_state bstate contract = Some cstate /\
    num_cacts_in_state cstate +
    length (outgoing_txs trace contract) +
    num_outgoing_acts (chain_state_queue bstate) contract <=
    num_acts_created_in_proposals (incoming_txs trace contract).
759
Proof.
760
  intros congress_deployed.
Jakob Botsch Nielsen's avatar
Jakob Botsch Nielsen committed
761
  Hint Resolve contract_addr_format : core.
762
  assert (address_is_contract contract = true) as addr_format by eauto.
763
764
765
766
  destruct (deployed_contract_state_typed congress_deployed ltac:(auto))
    as [cstate state_eq].
  exists cstate; split; auto.
  revert cstate state_eq.
767
  (* Contract cannot have been deployed in empty trace so we solve that immediately. *)
768
769
  remember empty_state.
  induction trace as [|? ? ? steps IH step]; intros; subst; try solve_by_inversion.
770
  destruct_chain_step.
771
772
  - (* New block added, does not change any of the values *)
    (* so basically just use IH directly. *)
773
    rewrite queue_prev in *.
774
    rewrite_environment_equiv.
775
    cbn in *.
776
    rewrite num_outgoing_acts_block; auto.
777
778
779
  - (* Step *)
    unfold outgoing_txs, incoming_txs in *.
    cbn [trace_txs].
780
    rewrite queue_prev, queue_new in *.
781
    remember (chain_state_env prev).
782
    destruct_action_eval; subst; cbn [eval_tx].
783
784
    + (* Transfer step: cannot be to contract, but can come from contract. *)
      rewrite_environment_equiv.
785
      specialize_hypotheses.
786
787
      (* Handle from contract and not from contract separately. *)
      destruct (address_eqb_spec from contract);
788
789
790
        simpl_goal_invariant;
        simpl_hyp_invariant;
        cbn; lia.
791
792
793
    + (* Deployment. Can be deployment of contract, in which case we need to *)
      (* establish invariant. *)
      rewrite_environment_equiv.
794
795
      unfold contract_state in state_eq.
      cbn in state_eq, congress_deployed.
796
797
798
799
800
801
      destruct (address_eqb_spec contract to) as [<-|]; cycle 1.
      * (* Deployment of different contract. Holds both if from us or not. *)
        specialize_hypotheses.
        destruct (address_eqb_spec from contract);
          simpl_goal_invariant;
          simpl_hyp_invariant;
802
          cbn; lia.
803
804
      * (* This is deployment of this contract *)
        replace wc with (Congress.contract : WeakContract) in * by congruence.
805
806
807
808
        destruct (wc_init_strong ltac:(eassumption)) as [? [result [? [<- ?]]]].
        cbn in state_eq.
        rewrite deserialize_serialize in state_eq.
        replace result with cstate in * by auto with congruence.
809
810
811
        (* State starts at 0 *)
        erewrite num_cacts_in_state_deployment by eassumption.
        (* Outgoing actions in queue is 0 *)
812
        Hint Resolve undeployed_contract_no_out_queue_count : core.
813
        assert (num_outgoing_acts (chain_state_queue prev) contract = 0)
814
          as out_acts by auto.
815
        rewrite queue_prev in out_acts.
816
        remember (build_act from _) as act.
817
818
819
820
821
        assert (act_from act <> contract)
          by (eapply undeployed_contract_not_from_self; eauto).
        simpl_hyp_invariant.
        simpl_goal_invariant.
        (* Outgoing transactions is 0 *)
822
        fold (outgoing_txs steps contract).
823
824
825
826
        rewrite undeployed_contract_no_out_txs; auto.
        cbn. lia.
    + (* Call. *)
      rewrite_environment_equiv.
827
828
829
      unfold contract_state in state_eq.
      cbn in state_eq.
      destruct (address_eqb_spec contract to) as [<-|]; cycle 1.
830
831
      * (* Not to contract. Essentially same thing as transfer case above. *)
        simpl_goal_invariant.
832
        specialize_hypotheses.
833
834
835
836
837
838
        rewrite num_outgoing_acts_call_ne; auto.
        destruct (address_eqb_spec contract from);
          simpl_goal_invariant;
          simpl_hyp_invariant;
          cbn; lia.
      * (* To contract. This will run code. *)
839
        cbn in congress_deployed, state_eq.
840
        replace wc with (Congress.contract : WeakContract) in * by congruence.
841
842
843
844
845
846
847
        destruct (wc_receive_strong ltac:(eassumption))
          as [prev_state_strong [msg_strong [resp_state_strong [? [msg_eq [<- receive]]]]]].
        Hint Resolve contract_state_from_weak : core.
        specialize (IH ltac:(auto) ltac:(auto) prev_state_strong ltac:(eauto)).
        rewrite deserialize_serialize in state_eq.
        replace resp_state_strong with cstate in * by congruence.
        destruct (receive_state_well_behaved _ _ _ _ _ _ ltac:(eassumption)).
848
        simpl_goal_invariant.
849
        cbn.
850
        rewrite num_outgoing_acts_call.
851
852
853
        rewrite address_eq_refl.
        unfold num_acts_created_in_proposals in IH |- *.
        cbn.
854
855
        fold (incoming_txs steps contract) in *.
        fold (outgoing_txs steps contract) in *.
856
857
858
859
860
        fold (num_acts_created_in_proposals (incoming_txs steps contract)) in *.
        destruct msg_strong; try congruence.
        destruct msg; [|cbn in *; congruence].
        cbn in msg_eq.
        rewrite msg_eq.
861
862
        destruct (address_eqb_spec from contract);
          simpl_hyp_invariant;
863
          cbn; lia.
864
  - (* Permute queue *)
865
    unfold num_outgoing_acts.
866
    cbn.
867
    rewrite <- perm, prev_next in *; auto.
868
869
870
871
Qed.

Corollary congress_txs_after_block
          {ChainBuilder : ChainBuilderType}
872
873
          prev new header acts :
  builder_add_block prev header acts = Some new ->
874
  forall addr,
Jakob Botsch Nielsen's avatar
Jakob Botsch Nielsen committed
875
    env_contracts new addr = Some (Congress.contract : WeakContract) ->
876
877
    length (outgoing_txs (builder_trace new) addr) <=
    num_acts_created_in_proposals (incoming_txs (builder_trace new) addr).
878
879
Proof.
  intros add_block contract congress_at_addr.
880
  pose proof (congress_txs_well_behaved _ _ (builder_trace new) congress_at_addr).
881
  destruct H as [? [? ?]].
882
883
884
885
886
  cbn in *.
  lia.
Qed.
End Theories.
End Congress.