Congress.v 10.6 KB
Newer Older
Jakob Botsch Nielsen's avatar
Jakob Botsch Nielsen committed
1
2
3
4
5
6
7
8
Require Import Blockchain.
Require Import Coq.Strings.String.
Require Import List.
Import ListNotations.
Require Import ZArith.
Require Import
  Coq.FSets.FMapList
  Coq.Structures.OrderedTypeEx.
Jakob Botsch Nielsen's avatar
Jakob Botsch Nielsen committed
9
Require Import RecordUpdate.RecordUpdate.
Jakob Botsch Nielsen's avatar
Jakob Botsch Nielsen committed
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
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
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
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
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
Import RecordSetNotations.

Definition TxOut := nat.
Definition ProposalId := nat.
Definition Chain := nat.

Record Proposal :=
  {
    txs : TxOut ;
    votes : list (Address * Z) ;
    voteResult : Z ;
    proposedIn : BlockId
  }.

Record Rules :=
  {
    minVoteCountPermille : Z ;
    marginNeededPermille : Z ;
    debatingPeriodInBlocks : Z
  }.

Record Setup :=
  {
    setupRules : Rules
  }.

Inductive Msg :=
| TransferOwnership : Address -> Msg
| ChangeRules : Rules -> Msg
| AddMember : Address -> Msg
| RemoveMember : Address -> Msg
| CreateProposal : list TxOut -> Msg
| VoteForProposal : ProposalId -> Msg
| VoteAgainstProposal : ProposalId -> Msg
| RetractVote : ProposalId -> Msg
| FinishProposal : ProposalId -> Msg.

Record State :=
  {
    owner : Address ;
    stateRules : Rules ;
    proposals : list (ProposalId * Proposal) ;
    nextProposalId : ProposalId ;
    members : list Address
  }.

Instance etaState : Settable _ :=
  mkSettable
    ((constructor Build_State) <*> owner
                               <*> stateRules
                               <*> proposals
                               <*> nextProposalId
                               <*> members)%set.

Definition version : Version := 1.

Definition validateRules (rules : Rules) : bool :=
    (rules.(minVoteCountPermille) >=? 0)%Z
        && (rules.(minVoteCountPermille) <=? 1000)%Z
        && (rules.(marginNeededPermille) >=? 0)%Z
        && (rules.(marginNeededPermille) <=? 1000)%Z
        && (rules.(debatingPeriodInBlocks) >=? 0)%Z.
  

Definition init (setup : Setup) (chain : Chain) (details : ContractCallDetails) : option State :=
  if validateRules setup.(setupRules) then
    Some {| owner := details.(from) ;
            stateRules := setup.(setupRules) ; 
            proposals := [] ;
            nextProposalId := 1 ;
            members := [] |}
  else
    None.

(*
module Congress exposing (Msg(..), Proposal, ProposalId, Rules, Setup, State, init, receive, version)

{-| Implements a congress contract. This is based on an example contract of the same name
in Ethereum. This is essentially a simpler version of the DAO contract that was exploited
in 2016.

The congress allows its members to vote on proposals. A proposal is a transaction that
will be sent to a specified address if the proposal passes. That means the members of
the congress vote on how the funds are used by the congress.

Initially the creator of the contract is the owner of the congress. The owner has the
capability to add or remove members of the congress but they can also transfer ownership
of the congress to someone else.

The transaction in the proposal can be any arbitrary transaction, including calls to
other contracts. This makes some very interesting interactions possible. For instance,
the congress can be set as its own owner and then members can be added or removed only
by vote, or the rules (like margin required for a proposal to pass) can be changed only
by vote.

-}

import Blockchain2 as Blockchain exposing (Address, Amount, BlockId, Chain, SerializedMsg, Tx, TxOut, Version)
import Dict exposing (Dict)
import Set exposing (Set)


type alias ProposalId =
    Int


type alias Proposal =
    { -- Transactions to make if this proposal succeeds
      txs : List TxOut

    -- What are the votes?
    , votes : Dict Address Int

    -- Vote result (aye = +1, nay = -1)
    , voteResult : Int

    -- When was this proposal made?
    , proposedIn : BlockId
    }


type alias Rules =
    { -- Minimum permille of participating members for a vote to succeed.
      -- For instance, if 500, then at least 50% of the members must participate
      -- in a vote on a proposal for it to succeed.
      minVoteCountPermille : Int

    -- What is the required permille of ayes / total (500 = 50%)
    , marginNeededPermille : Int

    -- Number of blocks to debate a proposal
    , debatingPeriodInBlocks : Int
    }


type alias Setup =
    { rules : Rules }


type Msg
    = TransferOwnership Address
    | ChangeRules Rules
    | AddMember Address
    | RemoveMember Address
    | CreateProposal (List TxOut)
    | VoteForProposal ProposalId
    | VoteAgainstProposal ProposalId
    | RetractVote ProposalId
    | FinishProposal ProposalId


type alias State =
    { owner : Address
    , rules : Rules
    , proposals : Dict ProposalId Proposal
    , nextProposalId : ProposalId
    , members : Set Address
    }


version : Version
version =
    1


init : Setup -> Chain -> Tx -> Maybe State
init { rules } chain tx =
    if validateRules rules then
        Just
            { owner = tx.from
            , rules = rules
            , proposals = Dict.empty
            , nextProposalId = 1
            , members = Set.empty
            }

    else
        Nothing


validateRules : Rules -> Bool
validateRules rules =
    (rules.minVoteCountPermille >= 0)
        && (rules.minVoteCountPermille <= 1000)
        && (rules.marginNeededPermille >= 0)
        && (rules.marginNeededPermille <= 1000)
        && (rules.debatingPeriodInBlocks > 0)


receive : Chain -> State -> Tx -> Maybe Msg -> Maybe ( State, List TxOut )
receive chain state tx maybeMsg =
    let
        sender =
            tx.from

        isFromOwner =
            sender == state.owner

        isFromMember =
            Set.member sender state.members

        withoutTxs =
            Maybe.map (\s -> ( s, [] ))
    in
    case ( isFromOwner, isFromMember, maybeMsg ) of
        ( True, _, Just (TransferOwnership newOwner) ) ->
            Just ( { state | owner = newOwner }, [] )

        ( True, _, Just (ChangeRules newRules) ) ->
            if validateRules newRules then
                Just ( { state | rules = newRules }, [] )

            else
                Nothing

        ( True, _, Just (AddMember member) ) ->
            Just ( { state | members = Set.insert member state.members }, [] )

        ( True, _, Just (RemoveMember member) ) ->
            Just ( { state | members = Set.remove member state.members }, [] )

        ( _, True, Just (CreateProposal txs) ) ->
            Just ( addProposal txs chain state, [] )

        ( _, True, Just (VoteForProposal id) ) ->
            voteProposal sender id 1 state |> withoutTxs

        ( _, True, Just (VoteAgainstProposal id) ) ->
            voteProposal sender id -1 state |> withoutTxs

        ( _, True, Just (RetractVote id) ) ->
            retractVote sender id state |> withoutTxs

        ( _, _, Just (FinishProposal id) ) ->
            finishProposal id state chain

        _ ->
            Nothing


addProposal : List TxOut -> Chain -> State -> State
addProposal proposalTxs chain state =
    let
        id =
            state.nextProposalId

        headBlock =
            Blockchain.headBlock chain

        proposal =
            { txs = proposalTxs
            , votes = Dict.empty
            , voteResult = 0
            , proposedIn = headBlock.header.blockNumber
            }
    in
    { state
        | proposals = Dict.insert id proposal state.proposals
        , nextProposalId = id + 1
    }


voteProposal : Address -> ProposalId -> Int -> State -> Maybe State
voteProposal voter id vote state =
    case Dict.get id state.proposals of
        Nothing ->
            Nothing

        Just proposal ->
            let
                addVote diff =
                    let
                        newProposal =
                            { proposal
                                | votes = Dict.insert voter vote proposal.votes
                                , voteResult = proposal.voteResult + diff
                            }

                        newState =
                            { state | proposals = Dict.insert id newProposal state.proposals }
                    in
                    Just newState
            in
            case Dict.get voter proposal.votes of
                Nothing ->
                    addVote vote

                Just oldVote ->
                    addVote (vote - oldVote)


retractVote : Address -> ProposalId -> State -> Maybe State
retractVote voter id state =
    case Dict.get id state.proposals of
        Nothing ->
            Nothing

        Just proposal ->
            case Dict.get voter proposal.votes of
                Nothing ->
                    Nothing

                Just oldVote ->
                    let
                        newProposal =
                            { proposal
                                | votes = Dict.remove voter proposal.votes
                                , voteResult = proposal.voteResult - oldVote
                            }

                        newState =
                            { state | proposals = Dict.insert id newProposal state.proposals }
                    in
                    Just newState


finishProposal : ProposalId -> State -> Chain -> Maybe ( State, List TxOut )
finishProposal id ({ rules, proposals, members } as state) chain =
    case Dict.get id proposals of
        Nothing ->
            Nothing

        Just proposal ->
            let
                headBlock =
                    Blockchain.headBlock chain

                debateEnd =
                    proposal.proposedIn + rules.debatingPeriodInBlocks
            in
            if headBlock.header.blockNumber < debateEnd then
                Nothing

            else
                let
                    newState =
                        { state | proposals = Dict.remove id proposals }

                    totalVotesForProposal =
                        Dict.size proposal.votes

                    totalMembers =
                        Set.size members

                    -- ayes - nays = voteResult
                    -- ayes + nays = totalVotesForProposal
                    -- => 2ayes = votesResult + totalVotes
                    ayeVotes =
                        (proposal.voteResult + totalVotesForProposal) // 2

                    voteCountPermille =
                        totalVotesForProposal * 1000 // totalMembers

                    ayePermille =
                        ayeVotes * 1000 // totalVotesForProposal

                    responseTxs =
                        if
                            (voteCountPermille >= rules.minVoteCountPermille)
                                && (ayePermille >= rules.marginNeededPermille)
                        then
                            proposal.txs

                        else
                            []
                in
                Just ( newState, responseTxs )
*)