aboutsummaryrefslogtreecommitdiff
path: root/src/main/java/org/gnunet/voting/Ballot.java
blob: 0d8de27807a831b47bae8711f988273bea4b4cd7 (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
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
378
379
380
381
382
383
384
385
386
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
/*
 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.primitives.Longs;
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;
    String group;
    List<String> choices;
    AbsoluteTime startTime;
    AbsoluteTime closingTime;
    AbsoluteTime queryTime;
    AbsoluteTime endTime;
    BiMap<String,PeerIdentity> authorities;
    SortedMap<String,CryptoECC.Signature> registrationSigs;
    CryptoECC.PublicSignKey caPub;
    CryptoECC.PublicSignKey issuerPub;
    CryptoECC.Signature issuerSig;
    CryptoECC.PublicSignKey voterPub;
    CryptoECC.Signature voterGroupCert;
    CryptoECC.Signature permission;
    CryptoECC.PublicSignKey voterSig;
    SortedMap<String,CryptoECC.Signature> voucherSigs;

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

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

    /**
     * Load a ballot from a configuration.
     *
     * @param cfg configuration to load ballot from
     * @throws InvalidBallotException
     */
    public Ballot(Configuration cfg) {
        fillBallot(cfg);
    }

    /**
     * Parse the specified time value from the ballot,
     * converting a human-readable time value to human time when no
     * timestamp is given.
     * @param cfg configuration to read the value from
     * @param timeValueName name suffix of the time option
     * @return the time value
     */
    private AbsoluteTime getTime(Configuration cfg, String timeValueName) {
        Optional<String> optTimeHuman = cfg.getValueString("election", "TIME_" + timeValueName);
        Optional<String> optTimeStamp = cfg.getValueString("election", "TIMESTAMP_" + timeValueName);
        if (optTimeStamp.isPresent()) {
            try {
                long stamp = Long.parseLong(optTimeStamp.get());
                return AbsoluteTime.fromSeconds(stamp);
            } catch (NumberFormatException e) {
                throw new InvalidBallotException("time value " + timeValueName + " malformed");
            }
        } else if (optTimeHuman.isPresent()) {
            AbsoluteTime time = AbsoluteTime.fromString(optTimeHuman.get());
            if (null == time) {
                throw new InvalidBallotException("timestamp value " + timeValueName + " malformed");
            }
            return time;
        }
        throw new InvalidBallotException("time value " + timeValueName + " missing");
    }

    /**
     * Fill the ballot with information from the given configuration.
     *
     * @param cfg configuration to read from
     */
    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");
        }
        Optional<String> optGroup = cfg.getValueString("election", "GROUP");
        if (!optGroup.isPresent()) {
            throw new InvalidBallotException("ballot must have elegibility group");
        }
        group = optGroup.get();
        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.PublicSignKey.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.PublicSignKey.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);
        }
        voucherSigs = new TreeMap<String, CryptoECC.Signature>();
        for (Map.Entry<String,String> e : cfg.getSection("vouchers").entrySet()) {
            CryptoECC.Signature sig = CryptoECC.Signature.fromString(e.getValue());
            if (null == sig) {
                throw new InvalidBallotException("voucher signature has invalid format");
            }
            if (!authorities.containsKey(e.getKey())) {
                throw new InvalidBallotException("ballot contains superfluous voucher signature");
            }
            voucherSigs.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;
        }

        Optional<String> optVoterPub = cfg.getValueString("vote", "VOTER_PUB");
        if (optVoterPub.isPresent()) {
            voterPub = CryptoECC.PublicSignKey.fromString(optVoterPub.get());
        }

        startTime = getTime(cfg, "START");
        closingTime = getTime(cfg, "CLOSING");
        queryTime = getTime(cfg, "QUERY");
        endTime = getTime(cfg, "END");
    }

    /**
     * Get a hash code that uniquely defines the election information of
     * the ballot.
     *
     * @return GUID of this ballot
     */
    public HashCode getBallotGuid() {
        if (issuerPub == null) {
            throw new InvalidBallotException("can't compute GUID of a ballot without issuer");
        }
        MessageDigest digest;
        try {
            digest = MessageDigest.getInstance("SHA-512");
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("crypto algorithm required but not provided");
        }
        digest.update(topic.getBytes());
        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);
        digest.update(Longs.toByteArray(startTime.getSeconds()));
        digest.update(Longs.toByteArray(endTime.getSeconds()));
        digest.update(Longs.toByteArray(closingTime.getSeconds()));
        digest.update(Longs.toByteArray(queryTime.getSeconds()));
        return new HashCode(digest.digest());
    }

    /**
     * Encode the given choice permanently in the ballot.
     * Also encodes the voter's public key.
     *
     * @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++;
        }
        voterPub = CryptoECC.computePublicKey(privateKey);
        if (choiceId == -1) {
            throw new InvalidBallotException(String.format("choice '%s' not valid", choice));
        }
    }

    /**
     * Write the current state of the ballot to a configuration.
     *
     * @return a configuration with the state of this ballot
     */
    public Configuration toConfiguration() {
        Configuration cfg = new Configuration();
        cfg.setValueString("election", "TOPIC", topic);
        cfg.setValueString("election", "GROUP", group);
        cfg.setValueString("election", "CHOICES", Joiner.on("//").join(choices));
        cfg.setValueString("election", "CA_PUB", caPub.toString());
        cfg.setValueNumber("election", "TIMESTAMP_START", startTime.getSeconds());
        cfg.setValueNumber("election", "TIMESTAMP_CLOSING", startTime.getSeconds());
        cfg.setValueNumber("election", "TIMESTAMP_QUERY", startTime.getSeconds());
        cfg.setValueNumber("election", "TIMESTAMP_END", startTime.getSeconds());
        for (Map.Entry<String, PeerIdentity> e : authorities.entrySet()) {
            cfg.setValueString("authorities", e.getKey(), e.getValue().toString());
        }
        if (null != registrationSigs) {
            for (Map.Entry<String, CryptoECC.Signature> e : registrationSigs.entrySet()) {
                cfg.setValueString("registration-signatures", e.getKey(), e.getValue().toString());
            }
        }
        if (null != voucherSigs) {
            for (Map.Entry<String, CryptoECC.Signature> e : voucherSigs.entrySet()) {
                cfg.setValueString("vouchers", 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);
        }
        if (null != voterPub) {
            cfg.setValueString("vote", "VOTER_PUB", voterPub.toString());
        }
        return cfg;
    }

    /**
     * Serialize the ballot to a string
     *
     * @return the serialized ballot
     */
    public String serialize() {
        return toConfiguration().serialize();
    }


    /**
     * Get a human readable description of the ballot's current state.
     *
     * @return the ballot description
     */
    public String describe() {
        StringBuilder buf = new StringBuilder();

        buf.append("Topic: ");
        buf.append("'");
        buf.append(topic);
        buf.append("'\n");

        buf.append("Voter Group: ");
        buf.append(group);
        buf.append("\n");

        buf.append("Start Time: ");
        buf.append(startTime.toFancyString());
        buf.append("\n");
        buf.append("Closing Time: ");
        buf.append(closingTime.toFancyString());
        buf.append("\n");
        buf.append("Query Time: ");
        buf.append(queryTime.toFancyString());
        buf.append("\n");
        buf.append("End Time: ");
        buf.append(endTime.toFancyString());
        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");
        }
        if (!voucherSigs.isEmpty()) {
            buf.append("ballot's vote has been submitted to with the following authorities:\n");
            for (Map.Entry<String, CryptoECC.Signature> e : voucherSigs.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();
    }


    /**
     * Get the list of authorities that did not yet receive the ballot's vote.
     *
     * @return list of unsubmitted-to authorities
     */
    public List<PeerIdentity> getRemainingSubmitAuthorities() {
        LinkedList<PeerIdentity> remaining = new LinkedList<PeerIdentity>();
        for (SortedMap.Entry<String,PeerIdentity> x : authorities.entrySet()) {
            if (!voucherSigs.containsKey(x.getKey()))
                remaining.add(x.getValue());
        }
        return remaining;
    }

    /**
     * Get a list of authorities that did not receive the registration for this
     * ballot yet.
     *
     * @return list of authorities that don't know about this ballot
     */
    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;
    }

    /**
     * Add the issuer to the ballot, and sign the election information in the ballot.
     *
     * @param privateKey private key of the issuer
     */
    public void issue(CryptoECC.PrivateKey privateKey) {
        issuerPub = CryptoECC.computePublicKey(privateKey);
        issuerSig = CryptoECC.sign(getBallotGuid().data, privateKey, issuerPub);
    }

    /**
     * Add an authorities registration signature to the list of known registrations.
     *
     * @param currentAuthority authority we registered with
     * @param registrationSignature signature over this ballot's GUID from the authority
     */
    public void addRegistrationSignature(PeerIdentity currentAuthority, CryptoECC.Signature registrationSignature) {
        String alias = authorities.inverse().get(currentAuthority);
        registrationSigs.put(alias, registrationSignature);
    }

    /**
     * Add a voucher, that is, a signature about the fact that an authority received a vote,
     * to the list of vouchers
     *
     * @param currentAuthority authority that received the vote
     * @param voucherSignature signature from the authority
     */
    public void addVoucher(PeerIdentity currentAuthority, CryptoECC.Signature voucherSignature) {
        String alias = authorities.inverse().get(currentAuthority);
        voucherSigs.put(alias, voucherSignature);
    }

    /**
     * Get a list of all authorities.
     *
     * @return list of all authorities
     */
    public List<PeerIdentity> getAuthorities() {
        return new ArrayList<PeerIdentity>(authorities.values());
    }
}