Congress.v 30.3 KB
Newer Older
1
From Coq Require Import ZArith.
2
From Coq Require Import Morphisms.
3
4
5
From Coq Require Import Psatz.
From Coq Require Import Program.
From Coq Require Import Permutation.
6
From SmartContracts Require Import Blockchain.
7
8
From SmartContracts Require Import Oak.
From SmartContracts Require Import Monads.
9
From SmartContracts Require Import Containers.
10
From SmartContracts Require Import Automation.
11
From SmartContracts Require Import Extras.
12
From RecordUpdate Require Import RecordUpdate.
13
From Coq Require Import List.
14

Jakob Botsch Nielsen's avatar
Jakob Botsch Nielsen committed
15
16
17
Import ListNotations.
Import RecordSetNotations.

18
Section Congress.
19
Context {BaseTypes : ChainBase}.
20
21

Local Open Scope Z.
22
Set Primitive Projections.
23

Jakob Botsch Nielsen's avatar
Jakob Botsch Nielsen committed
24
25
Definition ProposalId := nat.

26
27
28
29
Inductive CongressAction :=
  | cact_transfer (to : Address) (amount : Amount)
  | cact_call (to : Address) (amount : Amount) (msg : OakValue).

Jakob Botsch Nielsen's avatar
Jakob Botsch Nielsen committed
30
Record Proposal :=
31
  build_proposal {
32
    actions : list CongressAction;
33
    votes : FMap Address Z;
34
    vote_result : Z;
35
    proposed_in : nat;
Jakob Botsch Nielsen's avatar
Jakob Botsch Nielsen committed
36
37
  }.

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

Jakob Botsch Nielsen's avatar
Jakob Botsch Nielsen committed
41
Record Rules :=
42
43
44
  build_rules {
    min_vote_count_permille : Z;
    margin_needed_permille : Z;
45
    debating_period_in_blocks : nat;
Jakob Botsch Nielsen's avatar
Jakob Botsch Nielsen committed
46
47
48
  }.

Record Setup :=
49
50
  build_setup {
    setup_rules : Rules;
Jakob Botsch Nielsen's avatar
Jakob Botsch Nielsen committed
51
52
53
  }.

Inductive Msg :=
54
55
56
57
58
59
60
61
62
  | 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
63
64

Record State :=
65
66
67
  build_state {
    owner : Address;
    state_rules : Rules;
68
    proposals : FMap nat Proposal;
69
    next_proposal_id : ProposalId;
70
    members : FMap Address unit;
Jakob Botsch Nielsen's avatar
Jakob Botsch Nielsen committed
71
72
  }.

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

76
Section Equivalences.
77
78
79
80
81

Definition deserialize_rules (v : OakValue) : option Rules :=
  do '((a, b), c) <- deserialize v;
  Some (build_rules a b c).

82
Global Program Instance rules_equivalence : OakTypeEquivalence Rules :=
83
84
85
86
87
88
89
  {| 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; |}.
90
91
92
93
94
Next Obligation.
  intros x. unfold deserialize_rules.
  rewrite deserialize_serialize.
  reflexivity.
Qed.
95

96
Global Program Instance setup_equivalence : OakTypeEquivalence Setup :=
97
98
99
100
  {| serialize s := serialize s.(setup_rules);
     deserialize or :=
       do rules <- deserialize or;
       Some (build_setup rules); |}.
101
102
103
104
105
106
Next Obligation.
  intros x.
  simpl.
  rewrite deserialize_serialize.
  reflexivity.
Qed.
107
108
109
110
111
112
113
114

Definition deserialize_congress_action (v : OakValue) : option CongressAction :=
  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).

115
Global Program Instance congress_action_equivalence : OakTypeEquivalence CongressAction :=
116
117
118
119
120
121
122
123
  {| 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.
124
  intros ca.
125
  unfold deserialize_congress_action.
126
127
  rewrite deserialize_serialize.
  destruct ca; reflexivity.
128
129
130
131
132
133
Qed.

Definition deserialize_proposal (v : OakValue) : option Proposal :=
  do '(a, b, c, d) <- deserialize v;
  Some (build_proposal a b c d).

134
Global Program Instance proposal_equivalence : OakTypeEquivalence Proposal :=
135
136
137
138
139
140
  {| serialize p :=
       let (a, b, c, d) := p in
       serialize (a, b, c, d);
     deserialize := deserialize_proposal;
  |}.
Next Obligation.
141
  intros p.
142
  unfold deserialize_proposal.
143
144
  rewrite deserialize_serialize.
  destruct p; reflexivity.
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
Qed.

Definition serialize_msg (m : Msg) : OakValue :=
  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.

Definition deserialize_msg (v : OakValue) : option Msg :=
  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.

176
Global Program Instance msg_equivalence : OakTypeEquivalence Msg :=
177
178
  {| serialize := serialize_msg; deserialize := deserialize_msg; |}.
Next Obligation.
179
  intros msg.
180
  unfold serialize_msg, deserialize_msg.
181
  destruct msg; repeat (simpl; rewrite deserialize_serialize); reflexivity.
182
183
184
185
186
187
188
189
190
191
Qed.

Definition serialize_state (s : State) : OakValue :=
  let (a, b, c, d, e) := s in
  serialize (a, b, c, d, e).

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

192
Global Program Instance state_equivalence : OakTypeEquivalence State :=
193
194
195
  {| serialize := serialize_state; deserialize := deserialize_state; |}.
Next Obligation.
  unfold serialize_state, deserialize_state.
196
  destruct x; repeat (simpl; rewrite deserialize_serialize); reflexivity.
197
198
Qed.

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
End Equivalences.

Definition version : Version := 1%nat.

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
  let slot_num := chain.(block_header).(slot_number) in
  let proposal := {| actions := actions;
                     votes := FMap.empty;
                     vote_result := 0;
                     proposed_in := slot_num |} in
  let new_proposals := FMap.add id proposal state.(proposals) in
  state<|proposals := new_proposals|><|next_proposal_id := (id + 1)%nat|>.

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 :=
      proposal<|votes := new_votes|><|vote_result := new_vote_result|> in
  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 :=
      proposal<|votes := new_votes|><|vote_result := new_vote_result|> in
  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
  let cur_slot := chain.(block_header).(slot_number) in
  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.

346
347
348
349
350
351
352
353
354
355
356
357
358
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
359
360
    | [H: ChainEquiv _ _ |- _] => rewrite H in *
    | _ => subst; auto
361
362
363
364
365
366
367
368
369
370
    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.

371
Definition contract : Contract Setup Msg State :=
372
  build_contract version init init_proper receive receive_proper.
373
374
Section Theories.
Local Open Scope nat.
375

376
Definition num_acts_created_in_proposals chain address :=
Jakob Botsch Nielsen's avatar
Jakob Botsch Nielsen committed
377
  let count tx :=
378
379
380
381
382
383
384
385
      match tx_body tx with
      | tx_call msg =>
        match deserialize msg with
        | Some (create_proposal acts) => length acts
        | _ => 0
        end
      | _ => 0
      end in
Jakob Botsch Nielsen's avatar
Jakob Botsch Nielsen committed
386
  sumnat count (incoming_txs chain address).
387
388
389
390
391
392
393
394
395

Definition num_cacts_in_raw_state state :=
  sumnat (fun '(k, v) => length (actions v)) (FMap.elements (proposals state)).

Definition num_cacts_in_state chain address :=
  match contract_state chain address >>= deserialize with
  | Some state => num_cacts_in_raw_state state
  | None => 0
  end.
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
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
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
487
488
489
490
491
492
493
494
495
496
497
Definition num_outgoing_acts l address :=
  let extract a :=
      if address_eqb (act_from a) address
      then 1
      else 0 in
  sumnat extract l.

Instance num_acts_created_in_proposals_proper :
  Proper (ChainEquiv ==> eq ==> eq) num_acts_created_in_proposals.
Proof.
  now repeat intro; subst; unfold num_acts_created_in_proposals;
    match goal with
    | [H: ChainEquiv _ _ |- _] => rewrite H
    end.
Qed.

Instance num_cacts_in_state_proper :
  Proper (ChainEquiv ==> eq ==> eq) num_cacts_in_state.
Proof.
  now repeat intro; subst; unfold num_cacts_in_state;
    match goal with
    | [H: ChainEquiv _ _ |- _] => rewrite H
    end.
Qed.

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 ->
  Forall ActIsFromAccount l ->
  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.

Lemma num_cacts_in_state_deployment (init_env : Environment) ctx setup state contract :
  wc_init Congress.contract init_env ctx setup = Some state ->
  num_cacts_in_state
    (set_contract_state
       contract state
       (add_contract
          contract Congress.contract init_env)) contract = 0.
Proof.
  intros init.
  unfold num_cacts_in_state.
  cbn.
  unfold set_chain_contract_state.
  destruct_address_eq; try congruence.
  cbn in *.
  destruct (deserialize setup); cbn in *; try congruence.
  destruct (Congress.init _ _ _) eqn:congress_init; cbn in *; try congruence.
  inversion init.
  rewrite deserialize_serialize.
  unfold Congress.init in congress_init.
  destruct (validate_rules _); try congruence.
  now inversion congress_init.
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 :
  num_cacts_in_raw_state (add_proposal cacts chain state) <=
  num_cacts_in_raw_state state + length cacts.
Proof.
  unfold add_proposal, num_cacts_in_raw_state, constructor.
  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
498
    Hint Resolve FMap.find_remove : core.
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
    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 ->
  num_cacts_in_raw_state new_state = num_cacts_in_raw_state state.
Proof.
  intros vote.
  unfold vote_on_proposal in vote.
  destruct (FMap.find _ _) eqn:found; cbn in *; try congruence.
  inversion vote.
  unfold num_cacts_in_raw_state.
  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 ->
  num_cacts_in_raw_state new_state = num_cacts_in_raw_state state.
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.
  unfold num_cacts_in_raw_state.
  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
543
  Hint Resolve FMap.find_remove : core.
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
  repeat rewrite FMap.elements_add; auto.
  subst; reflexivity.
Qed.

Lemma remove_proposal_cacts pid state proposal :
  FMap.find pid (proposals state) = Some proposal ->
  num_cacts_in_raw_state (state <| proposals ::= FMap.remove pid |>) +
  length (actions proposal) = num_cacts_in_raw_state state.
Proof.
  intros find.
  unfold num_cacts_in_raw_state.
  cbn.
  rewrite <- (FMap.add_id (proposals state) pid proposal) at 2; auto.
  rewrite <- FMap.add_remove.
  rewrite FMap.elements_add; auto.
  cbn.
  lia.
Qed.
562

563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
(* 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) ->
  num_cacts_in_raw_state new_state + length resp_acts <=
  num_cacts_in_raw_state state +
  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.
    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.
    match goal with
    | [|- context[if ?large_annoying_expression_i_should_refactor then _ else _]] =>
      destruct large_annoying_expression_i_should_refactor
    end; cbn.
    + (* 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.

(* This is the bookkeeping that does the serialization/deserialization
for wc_receive. We should abstract this away. *)
Lemma wc_receive_state_well_behaved
      prev tx from contract amount msg ctx state new_state resp_acts :
  let with_tx := add_tx tx prev in
  tx = build_tx from contract amount (match msg with
                                        | Some msg => tx_call msg
                                        | None => tx_empty
                                      end) ->
  contract_state prev contract = Some state ->
  wc_receive
    Congress.contract
    with_tx
    ctx state msg = Some (new_state, resp_acts) ->
  num_cacts_in_state
    (set_contract_state contract new_state with_tx)
    contract +
  length resp_acts +
  num_acts_created_in_proposals prev contract <=
  num_cacts_in_state with_tx contract +
  num_acts_created_in_proposals with_tx contract.
Proof.
  cbn zeta.
  intros tx_eq prev_state_eq receive.
  cbn -[Congress.receive add_tx] in receive.
  destruct (deserialize state) eqn:deserialize_state; [|cbn in *; congruence].
  destruct msg as [msg|]; [|cbn in *; congruence].
  destruct (deserialize msg) eqn:deserialize_msg; [|cbn in *; congruence].
  cbn -[Congress.receive add_tx] in receive.
  destruct (Congress.receive _ _ _ _)
    as [[new_state' resp_acts']|] eqn:congress_receive;
    [|cbn in *; congruence].
  cbn in receive.
  inversion receive; subst new_state resp_acts.
  unfold num_cacts_in_state.
  cbn -[add_tx].
  unfold set_chain_contract_state.
  destruct_address_eq; try congruence.
  cbn -[add_tx].
  replace (contract_state (add_tx tx prev) contract) with (Some state) by auto.
  cbn -[add_tx].
  rewrite deserialize_state, deserialize_serialize.
  unfold num_acts_created_in_proposals at 2.
  cbn.
  unfold add_tx_to_map.
  destruct_address_eq; [|subst; cbn in *; congruence].
  cbn.
  fold (num_acts_created_in_proposals prev contract).
  replace (tx_body tx) with (tx_call msg) by (subst; auto).
  rewrite deserialize_msg.
  pose proof (receive_state_well_behaved _ _ _ _ _ _ congress_receive).
  lia.
Qed.

Lemma undeployed_contract_no_out_queue_count contract (state : ChainState) :
679
  reachable state ->
680
681
682
683
684
685
  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.
686
  Hint Unfold reachable : core.
687
688
689
690
691
692
693
694
  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 :
695
  reachable state ->
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
  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.
  cbn in *.
  destruct_address_eq; congruence.
Qed.
Hint Resolve undeployed_contract_no_out_queue_count : core.

Arguments num_acts_created_in_proposals : simpl never.
Arguments num_cacts_in_raw_state : simpl never.
Arguments num_cacts_in_state : simpl never.
Arguments num_outgoing_acts !l.

Local Ltac rewrite_queues :=
  repeat
    match goal with
    | [H: chain_state_queue _ = _ |- _] => rewrite H in *
    end.

Local Ltac solve_single :=
  solve [
725
      repeat (progress subst; cbn in *; auto);
726
727
      unfold add_tx_to_map, num_cacts_in_state, num_acts_created_in_proposals, num_outgoing_acts;
      unfold set_chain_contract_state;
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
      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
  | context G[outgoing_txs (env_chain (add_tx ?tx ?env)) ?addr] =>
    let newexp := context G[tx :: outgoing_txs env addr] in
    replace exp with newexp by solve_single
  | context G[add_new_block_header _ _ ?env] =>
    let newexp := context G[env] in
    replace exp with newexp by solve_single
  | context G[add_tx _ ?env] =>
    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.
754

755
756
757
758
(* 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. *)
759
760
761
Local Ltac simpl_goal_invariant :=
  repeat
    match goal with
762
763
764
765
766
767
768
769
    | [|- context[num_cacts_in_state ?env ?addr]] =>
      simpl_exp_invariant constr:(num_cacts_in_state env addr)
    | [|- context[outgoing_txs ?env ?addr]] =>
      simpl_exp_invariant constr:(outgoing_txs env addr)
    | [|- context[num_outgoing_acts ?q ?addr]] =>
      simpl_exp_invariant constr:(num_outgoing_acts q addr)
    | [|- context[num_acts_created_in_proposals ?env ?addr]] =>
      simpl_exp_invariant constr:(num_acts_created_in_proposals env addr)
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
    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.

Theorem congress_txs_well_behaved to contract :
788
  reachable to ->
789
  env_contracts to contract = Some (Congress.contract : WeakContract) ->
790
791
  num_cacts_in_state to contract +
  length (outgoing_txs to contract) +
792
793
794
795
  num_outgoing_acts (chain_state_queue to) contract <=
  num_acts_created_in_proposals to contract.
Proof.
  intros [trace] congress_deployed.
Jakob Botsch Nielsen's avatar
Jakob Botsch Nielsen committed
796
  Hint Resolve contract_addr_format : core.
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
  assert (address_is_contract contract = true) as addr_format by eauto.
  remember empty_state eqn:eq.
  (* Contract cannot have been deployed in empty trace so we solve that immediately. *)
  induction trace as [|? ? ? evts IH evt]; subst; try solve_by_inversion.
  destruct_chain_event; [|invert_chain_step|];
    rewrite_queues;
    repeat
      match goal with
      | [x := ?a : _ |- _] => pose proof (eq_refl : x = a); clearbody x
      end.
  - (* New block added, does not change any of the values *)
    (* so basically just use IH directly. *)
    rewrite_environment_equiv.
    specialize_hypotheses.
    simpl_goal_invariant.
    rewrite num_outgoing_acts_block; auto.
  - (* Transfer step: cannot be to contract, but can come from contract. *)
    rewrite_environment_equiv.
    specialize_hypotheses.
    subst new_acts.
    (* Handle from contract and not from contract separately. *)
    destruct (address_eqb_spec (tx_from tx) contract);
      simpl_goal_invariant;
      simpl_hyp_invariant;
821
      cbn; lia.
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
  - (* Deployment. Can be deployment of contract, in which case we need to *)
    (* establish invariant. *)
    rewrite_environment_equiv.
    subst new_acts.
    cbn in congress_deployed.
    destruct (address_eqb_spec contract to); cycle 1.
    + (* Deployment of different contract. Holds both if from us or not. *)
      specialize_hypotheses.
      destruct (address_eqb_spec (tx_from tx) contract);
        simpl_goal_invariant;
        simpl_hyp_invariant;
        cbn; lia.
    + (* This is deployment of this contract *)
      subst to.
      replace wc with (Congress.contract : WeakContract) in * by congruence.
      (* State starts at 0 *)
      erewrite num_cacts_in_state_deployment; [|eassumption].
      (* Outgoing actions in queue is 0 *)
      assert (num_outgoing_acts (chain_state_queue prev) contract = 0)
        as out_acts by eauto;
        rewrite_queues.
      assert (act_from act <> contract)
        by (eapply undeployed_contract_not_from_self; eauto).
845
846
      simpl_hyp_invariant.
      (* Outgoing transactions is 0 *)
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
      simpl_goal_invariant.
      rewrite undeployed_contract_no_out_txs; auto.
      cbn; lia.
  - (* Call. *)
    rewrite_environment_equiv.
    specialize_hypotheses.
    subst new_acts.
    destruct (address_eqb_spec contract to); cycle 1.
    + (* Not to contract. Essentially same thing as transfer case above. *)
      simpl_goal_invariant.
      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. *)
      cbn in congress_deployed.
      replace wc with (Congress.contract : WeakContract) in * by congruence.
      subst to.
      match goal with
      | [H1: wc_receive _ _ _ _ _ = Some _,
         H2: contract_state _ _ = Some _,
         H3: tx = build_tx _ _ _ _ |- _] =>
        generalize (wc_receive_state_well_behaved _ _ _ _ _ _ _ _ _ _ H3 H2 H1)
      end.
872
873
874
      simpl_goal_invariant.
      rewrite num_outgoing_acts_call.

875
876
877
878
879
880
      destruct (address_eqb_spec contract from);
        simpl_goal_invariant;
        simpl_hyp_invariant;
        intros;
        cbn -[add_tx set_contract_state];
        lia.
881
882
  - (* Permute queue *)
    match goal with
883
884
885
886
887
888
889
890
891
892
893
894
895
896
    | [H: chain_state_env prev = chain_state_env new |- _] =>
      rewrite <- H in *
    end.
    unfold num_outgoing_acts.
    match goal with
    | [Hperm: Permutation _ _ |- _] => rewrite <- Hperm
    end; auto.
Qed.

Corollary congress_txs_after_block
          {ChainBuilder : ChainBuilderType}
          prev baker acts slot finalization_height new :
  builder_add_block prev baker acts slot finalization_height = Some new ->
  forall addr,
Jakob Botsch Nielsen's avatar
Jakob Botsch Nielsen committed
897
    env_contracts new addr = Some (Congress.contract : WeakContract) ->
898
899
900
    length (outgoing_txs new addr) <= num_acts_created_in_proposals new addr.
Proof.
  intros add_block contract congress_at_addr.
901
  pose proof (congress_txs_well_behaved _ _ (builder_reachable new) congress_at_addr).
902
903
904
905
906
  cbn in *.
  lia.
Qed.
End Theories.
End Congress.