aboutsummaryrefslogtreecommitdiff
path: root/src/main/java/org/gnunet/voting/Ballot.java
blob: 49f1465722012090ba6c5eaeb8d40e9ed1500cf8 (plain) (blame)
1
2
3
4
5
6
7
8
9
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
/*
 This file is part of GNUnet.
  (C) 2012, 2013 Christian Grothoff (and other contributing authors)

  GNUnet is free software; you can redistribute it and/or modify
  it under the terms of the GNU General Public License as published
  by the Free Software Foundation; either version 3, or (at your
  option) any later version.

  GNUnet is distributed in the hope that it will be useful, but
  WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  General Public License for more details.

  You should have received a copy of the GNU General Public License
  along with GNUnet; see the file COPYING.  If not, write to the
  Free Software Foundation, Inc., 59 Temple Place - Suite 330,
  Boston, MA 02111-1307, USA.
 */

package org.gnunet.voting;

import com.google.common.base.Joiner;
import com.google.common.base.Optional;
import com.google.common.collect.BiMap;
import com.google.common.collect.HashBiMap;
import com.google.common.collect.Maps;
import org.gnunet.util.*;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.*;
import java.util.regex.Pattern;

/**
 * Public information about an election.
 */
public class Ballot {

    String topic;
    List<String> choices;
    AbsoluteTime electionStartTime;
    AbsoluteTime electionEndTime;
    BiMap<String,PeerIdentity> authorities;
    SortedMap<String,CryptoECC.Signature> registrationSigs;
    CryptoECC.PublicKey caPub;
    CryptoECC.PublicKey issuerPub;
    CryptoECC.Signature issuerSig;
    CryptoECC.PublicKey voter_pub;
    CryptoECC.Signature permission;
    CryptoECC.PublicKey voter_sig;
    SortedMap<String,CryptoECC.Signature> vouchers;

    /**
     * Choice in plaintext.
     * This field would be encrypted in a secure version.
     */
    int choiceId = -1;

    /**
     * Load a ballot from file.
     *
     * @throws InvalidBallotException
     * @param filename
     */
    public Ballot(String filename) {
        Configuration cfg = new Configuration();
        cfg.parse(filename);
        fillBallot(cfg);
    }

    public Ballot(Configuration cfg) {
        fillBallot(cfg);
    }

    private void fillBallot(Configuration cfg) {
        Optional<String> optTopic = cfg.getValueString("election", "TOPIC");
        if (!optTopic.isPresent()) {
            throw new InvalidBallotException("ballot has no topic");
        }
        topic = optTopic.get();
        Optional<String> optChoices = cfg.getValueString("election", "CHOICES");
        if (!optChoices.isPresent()) {
            throw new InvalidBallotException("ballot has no choices");
        }
        choices = Arrays.asList(optChoices.get().split(Pattern.quote("//")));
        if (choices.size() < 2) {
            throw new InvalidBallotException("less than two choices present");
        }
        authorities = HashBiMap.create();
        for (Map.Entry<String,String> e : cfg.getSection("authorities").entrySet()) {
            String alias = e.getKey();
            PeerIdentity peerIdentity = PeerIdentity.fromString(e.getValue());
            if (peerIdentity == null) {
                throw new InvalidBallotException(
                        String.format("authority %s has invalid peer identity", alias));
            }
            authorities.put(alias, peerIdentity);
        }
        if (authorities.size() < 1) {
            throw new InvalidBallotException("ballot must specify at least one authority");
        }
        Optional<String> optCaPub = cfg.getValueString("election", "CA_PUB");
        if (!optCaPub.isPresent()) {
            throw new InvalidBallotException("no CA pub key given");
        }
        caPub = CryptoECC.PublicKey.fromString(optCaPub.get());
        if (null == caPub) {
            throw new InvalidBallotException("CA pub key invalid");
        }
        Optional<String> optIssuerPub = cfg.getValueString("election", "ISSUER_PUB");
        if (optIssuerPub.isPresent()) {
            issuerPub = CryptoECC.PublicKey.fromString(optIssuerPub.get());
            Optional<String> optIssuerSig = cfg.getValueString("election", "ISSUER_SIG");
            if (!optIssuerSig.isPresent()) {
                throw new InvalidBallotException("issuer public key present, but no signature");
            }
            issuerSig = CryptoECC.Signature.fromString(optIssuerSig.get());
        }
        registrationSigs = new TreeMap<String, CryptoECC.Signature>();
        for (Map.Entry<String,String> e : cfg.getSection("registration-signatures").entrySet()) {
            CryptoECC.Signature sig = CryptoECC.Signature.fromString(e.getValue());
            if (null == sig) {
                throw new InvalidBallotException("registration signature has invalid format");
            }
            if (!authorities.containsKey(e.getKey())) {
                throw new InvalidBallotException("ballot contains superfluous registration signature");
            }
            registrationSigs.put(e.getKey(), sig);
        }
        Optional<String> optChoiceId = cfg.getValueString("vote", "CHOICE_ID");
        if (optChoiceId.isPresent()) {
            choiceId = Integer.parseInt(optChoiceId.get());
            if (choiceId < 0 || choiceId >= choices.size()) {
                throw new InvalidBallotException("invalid choice in vote");
            }
        } else {
            choiceId = -1;
        }
    }

    public HashCode getBallotGuid() {
        if (issuerSig == null) {
            throw new InvalidBallotException("can't compute GUID of non-issued ballot");
        }
        MessageDigest digest;
        try {
            digest = MessageDigest.getInstance("SHA-512");
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("crypto algorithm required but not provided");
        }
        digest.update(topic.getBytes());
        //digest.update(Longs.toByteArray(electionStartTime.getSeconds()));
        //digest.update(Longs.toByteArray(electionEndTime.getSeconds()));
        for (String choice : choices) {
            digest.update(choice.getBytes());
        }
        for (SortedMap.Entry<String,PeerIdentity> x : authorities.entrySet()) {
            digest.update(x.getKey().getBytes());
            digest.update(x.getValue().data);
        }
        digest.update(issuerPub.x);
        digest.update(issuerPub.y);
        digest.update(caPub.x);
        digest.update(caPub.y);
        return new HashCode(digest.digest());
    }

    /**
     * Encode the given choice permanently in the ballot.
     *
     * @param choice the choice to encode the ballot
     * @param privateKey the private key to use for encoding
     */
    public void encodeChoice(String choice, CryptoECC.PrivateKey privateKey) {
        choiceId = -1;
        int i = 0;
        for (String possibleChoice : choices) {
            if (choice.equals(possibleChoice)) {
                choiceId = i;
            }
            i++;
        }
        if (choiceId == -1) {
            throw new InvalidBallotException(String.format("choice '%s' not valid", choice));
        }
    }

    public Configuration toConfiguration() {
        Configuration cfg = new Configuration();
        cfg.setValueString("election", "TOPIC", topic);
        cfg.setValueString("election", "CHOICES", Joiner.on("//").join(choices));
        cfg.setValueString("election", "CA_PUB", caPub.toString());
        for (Map.Entry<String, PeerIdentity> e : authorities.entrySet()) {
            cfg.setValueString("authorities", e.getKey(), e.getValue().toString());
        }
        for (Map.Entry<String, CryptoECC.Signature> e : registrationSigs.entrySet()) {
            cfg.setValueString("registration-signatures", e.getKey(), e.getValue().toString());
        }
        if (null != issuerPub) {
            cfg.setValueString("election", "ISSUER_PUB", issuerPub.toString());
            cfg.setValueString("election", "ISSUER_SIG", issuerSig.toString());
        }
        if (-1 != choiceId) {
            cfg.setValueNumber("vote", "CHOICE_ID", choiceId);
        }
        return cfg;
    }

    public String serialize() {
        return toConfiguration().serialize();
    }

    public String describe() {
        StringBuilder buf = new StringBuilder();
        buf.append("Topic: ");
        buf.append("'");
        buf.append(topic);
        buf.append("'\n");
        buf.append("Choices:\n");
        for (int i = 0; i < choices.size(); i++) {
            buf.append(""+(i+1));
            buf.append(". '");
            buf.append(choices.get(i));
            buf.append("'\n");
        }
        buf.append("Authorities:\n");
        for (Map.Entry<String, PeerIdentity> e : authorities.entrySet()) {
            buf.append("'");
            buf.append(e.getKey());
            buf.append("', ");
            buf.append(e.getValue().toString());
            buf.append("\n");
        }
        if (issuerPub == null) {
            buf.append("issue status: not issued\n");
        } else {
            buf.append("issue status: issued, GUID ");
            buf.append(getBallotGuid().toString());
            buf.append("\n");
        }
        if (!registrationSigs.isEmpty()) {
            buf.append("ballot is registered with the following authorities:\n");
            for (Map.Entry<String, CryptoECC.Signature> e : registrationSigs.entrySet()) {
                buf.append(e.getKey());
                buf.append(" ");
            }
            buf.append("\n");
        }
        else {
            buf.append("ballot not registered\n");
        }
        if (choiceId != -1) {
            buf.append("choice selected\n");
        } else {
            buf.append("no choice selected\n");
        }
        return buf.toString();
    }

    public List<PeerIdentity> getRemainingSubmitAuthorities() {
        // FIXME: only return remaining authorities
        return new ArrayList<PeerIdentity>(authorities.values());
    }


    public List<PeerIdentity> getRemainingRegisterAuthorities() {
        LinkedList<PeerIdentity> remaining = new LinkedList<PeerIdentity>();
        for (SortedMap.Entry<String,PeerIdentity> x : authorities.entrySet()) {
            if (!registrationSigs.containsKey(x.getKey()))
                remaining.add(x.getValue());
        }
        return remaining;
    }

    public void issue(CryptoECC.PrivateKey privateKey) {
        issuerPub = CryptoECC.computePublicKey(privateKey);
        issuerSig = CryptoECC.sign(getBallotGuid().data, privateKey, issuerPub);
    }

    public void addRegistrationSignature(PeerIdentity currentAuthority, CryptoECC.Signature registrationSignature) {
        String alias = authorities.inverse().get(currentAuthority);
        registrationSigs.put(alias, registrationSignature);
    }

    public List<PeerIdentity> getAuthorities() {
        return new ArrayList<PeerIdentity>(authorities.values());
    }
}