Congress.v 30.1 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
19
20
21
Section Congress.
Context {BaseTypes : ChainBaseTypes}.

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
77
78
79
80
81
82
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)
83
        && (0 <=? rules.(debating_period_in_blocks))%nat.
84

85
86
87
88
Definition init
           (chain : Chain)
           (ctx : ContractCallContext)
           (setup : Setup) : option State :=
89
90
  if validate_rules setup.(setup_rules) then
    Some {| owner := ctx.(ctx_from);
91
            state_rules := setup.(setup_rules);
92
            proposals := FMap.empty;
93
            next_proposal_id := 1%nat;
94
            members := FMap.empty |}
Jakob Botsch Nielsen's avatar
Jakob Botsch Nielsen committed
95
96
97
  else
    None.

98
Definition add_proposal (actions : list CongressAction) (chain : Chain) (state : State) : State :=
99
  let id := state.(next_proposal_id) in
100
  let slot_num := chain.(block_header).(slot_number) in
101
  let proposal := {| actions := actions;
102
                     votes := FMap.empty;
103
                     vote_result := 0;
104
                     proposed_in := slot_num |} in
105
  let new_proposals := FMap.add id proposal state.(proposals) in
106
  state<|proposals := new_proposals|><|next_proposal_id := (id + 1)%nat|>.
107
108
109

Definition vote_on_proposal
           (voter : Address)
110
111
112
113
           (pid : ProposalId)
           (vote : Z)
           (state : State)
  : option State :=
114
115
  do proposal <- FMap.find pid state.(proposals);
  let old_vote := match FMap.find voter proposal.(votes) with
116
                 | Some old => old
117
                 | None => 0
118
                 end in
119
  let new_votes := FMap.add voter vote proposal.(votes) in
120
  let new_vote_result := proposal.(vote_result) - old_vote + vote in
121
122
123
  let new_proposal :=
      proposal<|votes := new_votes|><|vote_result := new_vote_result|> in
  Some (state<|proposals ::= FMap.add pid new_proposal|>).
124

125
Definition do_retract_vote
126
           (voter : Address)
127
128
129
           (pid : ProposalId)
           (state : State)
  : option State :=
130
131
132
  do proposal <- FMap.find pid state.(proposals);
  do old_vote <- FMap.find voter proposal.(votes);
  let new_votes := FMap.remove voter proposal.(votes) in
133
  let new_vote_result := proposal.(vote_result) - old_vote in
134
135
136
  let new_proposal :=
      proposal<|votes := new_votes|><|vote_result := new_vote_result|> in
  Some (state<|proposals ::= FMap.add pid new_proposal|>).
137

138
Definition congress_action_to_chain_action (act : CongressAction) : ActionBody :=
139
140
141
142
143
  match act with
  | cact_transfer to amt => act_transfer to amt
  | cact_call to amt msg => act_call to amt msg
  end.

144
Definition do_finish_proposal
145
146
           (pid : ProposalId)
           (state : State)
147
           (chain : Chain)
148
  : option (State * list ActionBody) :=
149
  do proposal <- FMap.find pid state.(proposals);
150
  let rules := state.(state_rules) in
151
152
153
  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
154
155
    None
  else
156
    let new_state := state<|proposals ::= FMap.remove pid|> in
157
    let total_votes_for_proposal := Z.of_nat (FMap.size proposal.(votes)) in
158
    let total_members := Z.of_nat (FMap.size state.(members)) in
159
160
161
162
163
164
165
166
    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
    let response_acts :=
        if (enough_voters && enough_ayes)%bool
        then proposal.(actions)
167
        else [] in
168
169
    let response_chain_acts := map congress_action_to_chain_action response_acts in
    Some (new_state, response_chain_acts).
170

171
Definition receive
172
           (chain : Chain)
173
           (ctx : ContractCallContext)
174
           (state : State)
175
           (maybe_msg : option Msg)
176
  : option (State * list ActionBody) :=
177
178
  let sender := ctx.(ctx_from) in
  let is_from_owner := (sender =? state.(owner))%address in
179
  let is_from_member := FMap.mem sender state.(members) in
180
  let without_actions := option_map (fun new_state => (new_state, [])) in
181
182
  match maybe_msg, is_from_owner, is_from_member with
  | Some (transfer_ownership new_owner), true, _ =>
183
        Some (state<|owner := new_owner|>, [])
184

185
  | Some (change_rules new_rules), true, _ =>
186
        if validate_rules new_rules then
187
            Some (state<|state_rules := new_rules|>, [])
188
        else
189
            None
190

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

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

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

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

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

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

209
  | Some (finish_proposal pid), _, _ =>
210
        do_finish_proposal pid state chain
211

212
213
  | _, _, _ =>
        None
214
215
216
217
218
219
220

  end.

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

221
Global Program Instance rules_equivalence : OakTypeEquivalence Rules :=
222
223
224
225
226
227
228
  {| 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; |}.
229
230
231
232
233
Next Obligation.
  intros x. unfold deserialize_rules.
  rewrite deserialize_serialize.
  reflexivity.
Qed.
234

235
Global Program Instance setup_equivalence : OakTypeEquivalence Setup :=
236
237
238
239
  {| serialize s := serialize s.(setup_rules);
     deserialize or :=
       do rules <- deserialize or;
       Some (build_setup rules); |}.
240
241
242
243
244
245
Next Obligation.
  intros x.
  simpl.
  rewrite deserialize_serialize.
  reflexivity.
Qed.
246
247
248
249
250
251
252
253

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).

254
Global Program Instance congress_action_equivalence : OakTypeEquivalence CongressAction :=
255
256
257
258
259
260
261
262
  {| 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.
263
  intros ca.
264
  unfold deserialize_congress_action.
265
266
  rewrite deserialize_serialize.
  destruct ca; reflexivity.
267
268
269
270
271
272
Qed.

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

273
Global Program Instance proposal_equivalence : OakTypeEquivalence Proposal :=
274
275
276
277
278
279
  {| serialize p :=
       let (a, b, c, d) := p in
       serialize (a, b, c, d);
     deserialize := deserialize_proposal;
  |}.
Next Obligation.
280
  intros p.
281
  unfold deserialize_proposal.
282
283
  rewrite deserialize_serialize.
  destruct p; reflexivity.
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
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.

315
Global Program Instance msg_equivalence : OakTypeEquivalence Msg :=
316
317
  {| serialize := serialize_msg; deserialize := deserialize_msg; |}.
Next Obligation.
318
  intros msg.
319
  unfold serialize_msg, deserialize_msg.
320
  destruct msg; repeat (simpl; rewrite deserialize_serialize); reflexivity.
321
322
323
324
325
326
327
328
329
330
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).

331
Global Program Instance state_equivalence : OakTypeEquivalence State :=
332
333
334
  {| serialize := serialize_state; deserialize := deserialize_state; |}.
Next Obligation.
  unfold serialize_state, deserialize_state.
335
  destruct x; repeat (simpl; rewrite deserialize_serialize); reflexivity.
336
337
Qed.

338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
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
    | _ => prove
    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.

362
Definition contract : Contract Setup Msg State :=
363
  build_contract version init init_proper receive receive_proper.
364
365
Section Theories.
Local Open Scope nat.
366

367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
Definition num_acts_created_in_proposals chain address :=
  let extract tx :=
      match tx_body tx with
      | tx_call msg =>
        match deserialize msg with
        | Some (create_proposal acts) => length acts
        | _ => 0
        end
      | _ => 0
      end in
  sumnat extract (incoming_txs chain address).

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.
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
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
498
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
543
544
545
546
547
548
549
550
551
552
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).
    Hint Resolve FMap.find_remove.
    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).
  Hint Resolve FMap.find_remove.
  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.
553

554
555
556
557
558
559
560
561
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
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
(* 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) :
  inhabited (ChainTrace empty_state state) ->
  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.
  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 :
  inhabited (ChainTrace empty_state state) ->
  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 [
715
      repeat (progress subst; cbn in *; auto);
716
717
      unfold add_tx_to_map, num_cacts_in_state, num_acts_created_in_proposals, num_outgoing_acts;
      unfold set_chain_contract_state;
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
      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.
744

745
746
747
748
(* 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. *)
749
750
751
Local Ltac simpl_goal_invariant :=
  repeat
    match goal with
752
753
754
755
756
757
758
759
    | [|- 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)
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
    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 :
  inhabited (ChainTrace empty_state to) ->
  env_contracts to contract = Some (Congress.contract : WeakContract) ->
780
781
  num_cacts_in_state to contract +
  length (outgoing_txs to contract) +
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
  num_outgoing_acts (chain_state_queue to) contract <=
  num_acts_created_in_proposals to contract.
Proof.
  intros [trace] congress_deployed.
  Hint Resolve contract_addr_format.
  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;
811
      cbn; lia.
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
  - (* 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).
835
836
      simpl_hyp_invariant.
      (* Outgoing transactions is 0 *)
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
      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.
862
863
864
      simpl_goal_invariant.
      rewrite num_outgoing_acts_call.

865
866
867
868
869
870
      destruct (address_eqb_spec contract from);
        simpl_goal_invariant;
        simpl_hyp_invariant;
        intros;
        cbn -[add_tx set_contract_state];
        lia.
871
872
  - (* Permute queue *)
    match goal with
873
874
875
876
877
878
879
880
881
882
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,
    env_contracts (builder_env new) addr = Some (Congress.contract : WeakContract) ->
    length (outgoing_txs new addr) <= num_acts_created_in_proposals new addr.
Proof.
  intros add_block contract congress_at_addr.
  pose proof (congress_txs_well_behaved _ _ (builder_trace new) congress_at_addr).
  cbn in *.
  lia.
Qed.
End Theories.
End Congress.