Congress.v 29.5 KB
Newer Older
1
From Coq Require Import ZArith.
2
From Coq Require Import Morphisms.
3
4
From Coq Require Import Psatz.
From Coq Require Import Permutation.
5
From SmartContracts Require Import Blockchain.
6
From SmartContracts Require Import Serializable.
7
From SmartContracts Require Import Monads.
8
From SmartContracts Require Import Containers.
9
From SmartContracts Require Import Automation.
10
From SmartContracts Require Import Extras.
11
From SmartContracts Require Import ChainedList.
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
Inductive CongressAction :=
  | cact_transfer (to : Address) (amount : Amount)
28
  | cact_call (to : Address) (amount : Amount) (msg : SerializedValue).
29

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 Serialization.
77

78
Definition deserialize_rules (v : SerializedValue) : option Rules :=
Jakob Botsch Nielsen's avatar
Jakob Botsch Nielsen committed
79
  do '(a, b, c) <- deserialize v;
80
81
  Some (build_rules a b c).

82
Global Program Instance rules_serializable : Serializable 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_serializable : Serializable 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
Definition deserialize_congress_action (v : SerializedValue) : option CongressAction :=
109
110
111
112
113
114
  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_serializable : Serializable 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
Qed.

130
Definition deserialize_proposal (v : SerializedValue) : option Proposal :=
131
132
133
  do '(a, b, c, d) <- deserialize v;
  Some (build_proposal a b c d).

134
Global Program Instance proposal_serializable : Serializable 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
Qed.

147
Definition serialize_msg (m : Msg) : SerializedValue :=
148
149
150
151
152
153
154
155
156
157
158
159
160
  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.

161
Definition deserialize_msg (v : SerializedValue) : option Msg :=
162
163
164
165
166
167
168
169
170
171
172
173
174
175
  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_serializable : Serializable 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
Qed.

184
Definition serialize_state (s : State) : SerializedValue :=
185
186
187
  let (a, b, c, d, e) := s in
  serialize (a, b, c, d, e).

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

192
Global Program Instance state_serializable : Serializable 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
End Serialization.
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222

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

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 :=
245
246
      proposal<|votes := new_votes|>
              <|vote_result := new_vote_result|> in
247
248
249
250
251
252
253
254
255
256
257
258
  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 :=
259
260
      proposal<|votes := new_votes|>
              <|vote_result := new_vote_result|> in
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
  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
288
  let cur_slot := chain.(current_slot) in
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
  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 init init_proper receive receive_proper.
373
374
Section Theories.
Local Open Scope nat.
375

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

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

391
392
Definition num_cacts_in_state env address :=
  match env_contract_states env address >>= deserialize with
393
394
395
  | Some state => num_cacts_in_raw_state state
  | None => 0
  end.
396

397
398
399
400
401
402
403
404
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_cacts_in_state_proper :
405
  Proper (EnvironmentEquiv ==> eq ==> eq) num_cacts_in_state.
406
407
Proof.
  now repeat intro; subst; unfold num_cacts_in_state;
408
    rewrite_environment_equiv.
409
410
411
412
413
414
415
416
417
418
419
420
421
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 ->
422
  Forall act_is_from_account l ->
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
  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.
482
  unfold add_proposal, num_cacts_in_raw_state.
483
484
485
486
  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
487
    Hint Resolve FMap.find_remove : core.
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
    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
532
  Hint Resolve FMap.find_remove : core.
533
534
535
536
537
538
  repeat rewrite FMap.elements_add; auto.
  subst; reflexivity.
Qed.

Lemma remove_proposal_cacts pid state proposal :
  FMap.find pid (proposals state) = Some proposal ->
539
  num_cacts_in_raw_state (state <|proposals ::= FMap.remove pid|>) +
540
541
542
543
544
545
546
547
548
549
550
  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.
551

552
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
(* 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.
604
    destruct (proposal_passed _ _); cbn.
605
606
607
608
609
610
    + (* 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 wc_receive_state_well_behaved
611
612
613
      from contract amount prev state ctx msg new_state resp_acts
      (trace : ChainTrace empty_state prev) :
  let with_tx := transfer_balance from contract amount prev in
614
  env_contract_states prev contract = Some state ->
615
616
617
618
619
620
621
622
  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 +
623
  num_acts_created_in_proposals (incoming_txs trace contract) <=
624
  num_cacts_in_state with_tx contract +
625
626
  num_acts_created_in_proposals
    (build_tx from contract amount (tx_call msg) :: incoming_txs trace contract).
627
628
Proof.
  cbn zeta.
629
630
  intros prev_state_eq receive.
  cbn -[Congress.receive transfer_balance] in receive.
631
632
633
  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].
634
  cbn -[Congress.receive transfer_balance] in receive.
635
636
637
638
639
640
641
  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.
642
643
  unfold set_chain_contract_state.
  rewrite address_eq_refl.
644
  replace (env_contract_states _ contract) with (Some state) by auto.
645
  cbn.
646
647
  rewrite deserialize_state, deserialize_serialize.
  fold (num_acts_created_in_proposals (incoming_txs trace contract)).
648
649
650
651
652
653
  rewrite deserialize_msg.
  pose proof (receive_state_well_behaved _ _ _ _ _ _ congress_receive).
  lia.
Qed.

Lemma undeployed_contract_no_out_queue_count contract (state : ChainState) :
654
  reachable state ->
655
656
657
658
659
660
  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.
661
  Hint Unfold reachable : core.
662
663
664
665
666
667
668
669
  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 :
670
  reachable state ->
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
  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.
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 solve_single :=
  solve [
693
      repeat (progress subst; cbn in *; auto);
694
      unfold add_balance, num_cacts_in_state, num_acts_created_in_proposals, num_outgoing_acts;
695
      cbn;
696
      unfold set_chain_contract_state;
697
698
699
700
701
702
703
704
      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
705
706
707
708
709
  | 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
710
    replace exp with newexp by solve_single
711
  | context G[add_new_block_to_env _ ?env] =>
712
713
    let newexp := context G[env] in
    replace exp with newexp by solve_single
714
  | context G[transfer_balance _ _ _ ?env] =>
715
716
717
718
719
720
721
722
723
724
725
    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.
726

727
728
729
730
(* 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. *)
731
732
733
Local Ltac simpl_goal_invariant :=
  repeat
    match goal with
734
735
    | [|- context[num_cacts_in_state ?env ?addr]] =>
      simpl_exp_invariant constr:(num_cacts_in_state env addr)
736
737
    | [|- context[length ?txs]] =>
      simpl_exp_invariant constr:(length txs)
738
739
    | [|- context[num_outgoing_acts ?q ?addr]] =>
      simpl_exp_invariant constr:(num_outgoing_acts q addr)
740
741
    | [|- context[num_acts_created_in_proposals ?txs]] =>
      simpl_exp_invariant constr:(num_acts_created_in_proposals txs)
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
    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.

759
Theorem congress_txs_well_behaved to contract (trace : ChainTrace empty_state to) :
760
  env_contracts to contract = Some (Congress.contract : WeakContract) ->
761
  num_cacts_in_state to contract +
762
  length (outgoing_txs trace contract) +
763
  num_outgoing_acts (chain_state_queue to) contract <=
764
  num_acts_created_in_proposals (incoming_txs trace contract).
765
Proof.
766
  intros congress_deployed.
Jakob Botsch Nielsen's avatar
Jakob Botsch Nielsen committed
767
  Hint Resolve contract_addr_format : core.
768
769
770
  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. *)
771
772
  induction trace as [|? ? ? steps IH step]; subst; try solve_by_inversion.
  destruct_chain_step.
773
774
  - (* New block added, does not change any of the values *)
    (* so basically just use IH directly. *)
775
    rewrite queue_prev in *.
776
777
778
779
    rewrite_environment_equiv.
    specialize_hypotheses.
    simpl_goal_invariant.
    rewrite num_outgoing_acts_block; auto.
780
781
782
  - (* Step *)
    unfold outgoing_txs, incoming_txs in *.
    cbn [trace_txs].
783
    rewrite queue_prev, queue_new in *.
784
    remember (chain_state_env prev).
785
    destruct_action_eval; subst pre; cbn [eval_tx].
786
787
    + (* Transfer step: cannot be to contract, but can come from contract. *)
      rewrite_environment_equiv.
788
      specialize_hypotheses.
789
790
      (* Handle from contract and not from contract separately. *)
      destruct (address_eqb_spec from contract);
791
792
793
        simpl_goal_invariant;
        simpl_hyp_invariant;
        cbn; lia.
794
795
796
    + (* Deployment. Can be deployment of contract, in which case we need to *)
      (* establish invariant. *)
      rewrite_environment_equiv.
797
      cbn in congress_deployed.
798
799
800
801
802
803
      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;
804
          cbn; lia.
805
806
807
808
809
810
811
      * (* This is deployment of this contract *)
        replace wc with (Congress.contract : WeakContract) in * by congruence.
        (* State starts at 0 *)
        erewrite num_cacts_in_state_deployment by eassumption.
        (* Outgoing actions in queue is 0 *)
        assert (num_outgoing_acts (chain_state_queue prev) contract = 0)
          as out_acts by eauto.
812
        rewrite queue_prev in out_acts.
813
814
815
816
817
        assert (act_from act <> contract)
          by (eapply undeployed_contract_not_from_self; eauto).
        simpl_hyp_invariant.
        simpl_goal_invariant.
        (* Outgoing transactions is 0 *)
818
        fold (outgoing_txs steps contract).
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
        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 _,
839
           H2: env_contract_states _ _ = Some _ |- _] =>
840
          generalize (wc_receive_state_well_behaved _ _ _ _ _ _ _ _ _ steps H2 H1)
841
842
843
844
845
846
        end.
        simpl_goal_invariant.
        rewrite num_outgoing_acts_call.

        intros.
        cbn -[set_contract_state].
847
848
        fold (incoming_txs steps contract) in *.
        fold (outgoing_txs steps contract) in *.
849
850
851
852
853
        rewrite address_eq_refl.
        destruct (address_eqb_spec from contract);
          simpl_hyp_invariant;
          cbn -[set_contract_state];
          lia.
854
  - (* Permute queue *)
855
    unfold num_outgoing_acts.
856
    cbn.
857
    rewrite <- perm, prev_next in *; auto.
858
859
860
861
Qed.

Corollary congress_txs_after_block
          {ChainBuilder : ChainBuilderType}
862
863
          prev new header acts :
  builder_add_block prev header acts = Some new ->
864
  forall addr,
Jakob Botsch Nielsen's avatar
Jakob Botsch Nielsen committed
865
    env_contracts new addr = Some (Congress.contract : WeakContract) ->
866
867
    length (outgoing_txs (builder_trace new) addr) <=
    num_acts_created_in_proposals (incoming_txs (builder_trace new) addr).
868
869
Proof.
  intros add_block contract congress_at_addr.
870
  pose proof (congress_txs_well_behaved _ _ (builder_trace new) congress_at_addr).
871
872
873
874
875
  cbn in *.
  lia.
Qed.
End Theories.
End Congress.