aboutsummaryrefslogtreecommitdiff
path: root/src/main/java/org/gnunet/voting/BallotTool.java
blob: a1f8991dd33a081a38f171678a66efb542da5f7e (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
470
471
472
473
474
475
476
477
478
/*
 This file is part of GNUnet.
  Copyright (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., 51 Franklin Street, Fifth Floor,
  Boston, MA 02110-1301, USA.
 */

package org.gnunet.voting;


import com.google.common.base.Charsets;
import com.google.common.io.ByteSink;
import com.google.common.io.Files;
import org.gnunet.identity.Identity;
import org.gnunet.identity.IdentityCallback;
import org.gnunet.cadet.Cadet;
import org.gnunet.cadet.CadetRunabout;
import org.gnunet.cadet.ChannelEndHandler;
import org.gnunet.secretsharing.ThresholdPublicKey;
import org.gnunet.testbed.CompressedConfig;
import org.gnunet.util.*;
import org.gnunet.util.getopt.Argument;
import org.gnunet.util.getopt.ArgumentAction;
import org.gnunet.voting.messages.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.Random;

/**
 * Tool for creating, manipulating and submitting ballot files.
 */
public class BallotTool extends Program {
    private static final Logger logger = LoggerFactory
            .getLogger(BallotTool.class);

    @Argument(
            shortname = "e",
            longname = "ego",
            action = ArgumentAction.STORE_STRING,
            description = "ego to use for the operation")
    String egoName = null;

    @Argument(
            shortname = "q",
            longname = "query",
            action = ArgumentAction.SET,
            description = "query election result")
    boolean query = false;

    @Argument(
            shortname = "s",
            longname = "submit",
            action = ArgumentAction.SET,
            description = "submit the vote to the authorities")
    boolean submit = false;

    @Argument(
            shortname = "r",
            longname = "register",
            action = ArgumentAction.SET,
            description = "register an election with the authorities")
    boolean register = false;

    @Argument(
            shortname = "i",
            longname = "issue",
            action = ArgumentAction.SET,
            description = "sign the ballot as issuer (use with -e)")
    boolean issue = false;

    @Argument(
            shortname = "x",
            longname = "select",
            action = ArgumentAction.STORE_STRING,
            argumentName = "CHOICE",
            description = "select and encrypt a vote option (use with -e)")
    String select = null;

    @Argument(
            shortname = "V",
            longname = "verify",
            action = ArgumentAction.SET,
            description = "verify signatures in the ballot and show information")
    boolean verify = false;

    @Argument(
            shortname = "g",
            longname = "group",
            action = ArgumentAction.STORE_STRING,
            description = "incorporate the group cert into the ballot")
    String groupCertFile = null;

    @Argument(
            shortname = "k",
            longname = "getRequestIdentifier-key",
            action = ArgumentAction.SET,
            description = "getRequestIdentifier the threshold public key from authorities")
    boolean requestKey = false;

    @Argument(
            shortname = "t",
            longname = "template",
            action = ArgumentAction.SET,
            description = "write a template ballot to the give ballot file")
    boolean template = false;

    /**
     * The ego to use for the currently executing action.
     */
    private Identity.Ego ego;

    /**
     * The (possibly modified) ballot originally loaded
     * from 'ballotFilename'
     */
    private Ballot ballot;

    /**
     * Filename to read the ballot from, and write modifications to.
     */
    private String ballotFilename;

    /**
     * Our handle to CADET.
     */
    private Cadet cadet;

    /**
     * A channel to 'currentAuthority' or null.
     */
    private Cadet.Channel channel;

    /**
     * The authority we are currently communicating with.
     */
    private PeerIdentity currentAuthority;

    /**
     * Are we finished with communicating over the cadet channel and don't need to worry about
     * disconnection?
     */
    private boolean tunnelCommunicationFinished;

    private RelativeTime tunnelReconnectBackoff = RelativeTime.STD_BACKOFF;

    public class BallotChannelEndHandler implements ChannelEndHandler {
        @Override
        public void onChannelEnd(final Cadet.Channel channel) {
            // FIXME: just re-running 'doCommands' is a bit of a hack
            BallotTool.this.channel = null;
            if (!tunnelCommunicationFinished) {
                logger.warn("cadet channel disconnected, but operation not finished");
                Scheduler.addDelayed(tunnelReconnectBackoff, new Scheduler.Task() {
                    @Override
                    public void run(Scheduler.RunContext ctx) {
                        doCommands();
                    }
                });
                tunnelReconnectBackoff = tunnelReconnectBackoff.backoff();
            }
        }
    }

    /**
     * Destroy the channel to the authority as well
     * as the cadet handle.
     */
    private void endCadet() {
        tunnelCommunicationFinished = true;
        if (null != channel) {
            channel.destroy();
            channel = null;
        }
        if (null != cadet) {
            cadet.destroy();
            cadet = null;
        }
    }

    public class BallotRegisterReceiver extends CadetRunabout {
        public void visit(BallotRegisterSuccessMessage m) {
            System.out.println("ballot successfully registered");
            ballot.addRegistrationSignature(currentAuthority, m.registrationSignature);
            writeBallot();
            endCadet();
        }

        public void visit(BallotRegisterFailureMessage m) {
            System.out.println("registering failed: " + m.reason);
            endCadet();
            setReturnValue(1);
        }
    }

    public class QueryReceiver extends CadetRunabout {
        public void visit(ResultQueryResponseMessage m) {
            if (m.results.length != ballot.choices.size()) {
                System.out.println("failure to query result: malformed response");
            } else {
                System.out.println("got results:");
                for (int i = 0; i < m.results.length; i++) {
                    System.out.println("'" + ballot.choices.get(i) + "': " + m.results[i]);
                }
            }
            endCadet();
        }

        public void visit(ResultQueryFailureMessage m) {
            System.out.println("failure to query result: " + m.reason);
            endCadet();
            setReturnValue(1);
        }
    }


    public class PublicKeyReceiver extends CadetRunabout {
        public void visit(KeyQueryResponseMessage m) {
            System.out.println("got threshold public key!");
            ballot.addThresholdPublicKey(currentAuthority, m);
            writeBallot();
            endCadet();
        }
        public void visit(KeyQueryFailureMessage m) {
            System.out.println("failure to query result: " + m.reason);
            endCadet();
            setReturnValue(1);
        }

    }

    public class SubmitReceiver extends CadetRunabout {

        public void visit(SubmitSuccessMessage m) {
            System.out.println("vote successfully submitted");
            ballot.addConfirmation(currentAuthority, m.confirmationSig);
            writeBallot();
            endCadet();
        }

        public void visit(SubmitFailureMessage m) {
            System.out.println("vote not submitted: " + m.reason);
            if (m.signedAuthorityTime != null) {
                // FIXME: verifyRaw
                System.out.println("authority time: " +
                        AbsoluteTime.fromNetwork(m.signedAuthorityTime.time).toFancyString());
            }
            endCadet();
            setReturnValue(1);
        }
    }

    @Override
    protected String makeHelpText() {
        return "gnunet-ballot [OPTIONS]... BALLOT\n" +
                "Create, modify and execute operation on ballots.";
    }

    private void runTemplate() {
        File f = new File(ballotFilename);
        if (f.exists()) {
            System.err.println("file already exists, not overwriting");
            return;
        }
        InputStream is = getClass().getResourceAsStream("ballot-template.espec");
        ByteSink out = Files.asByteSink(f);
        try {
            out.writeFrom(is);
        } catch (IOException e) {
            System.err.println("could not copy template file: " + e.getMessage());
        }
    }

    /**
     * Write the ballot back to disk.
     */
    private void writeBallot() {
        try {
            Files.write(ballot.serialize(), new File(ballotFilename), Charsets.UTF_8);
        } catch (IOException e) {
            System.err.println("could not write ballot file: " + e.getMessage());
        }
    }

    /**
     * Actually execute the action the user requested.
     */
    void doCommands() {
        if (null != groupCertFile) {
            Configuration groupCertConfig = new Configuration();
            groupCertConfig.parse(groupCertFile);
            GroupCert groupCert = GroupCert.fromGroupCertConfig(groupCertConfig);
            ballot.encodeGroup(groupCert);
            writeBallot();
            return;
        }
        if (register) {
            List<PeerIdentity> remainingAuthorities = ballot.getRemainingRegisterAuthorities();
            if (remainingAuthorities.isEmpty()) {
                System.err.println("all authorities already received the ballot");
                return;
            }
            Random r = new Random();
            currentAuthority = remainingAuthorities.get(r.nextInt(remainingAuthorities.size()));
            System.out.println("registering ballot with authority " + currentAuthority.toString());
            cadet = new Cadet(getConfiguration(), new BallotChannelEndHandler(), new BallotRegisterReceiver());
            channel = cadet.createChannel(currentAuthority, TallyAuthorityDaemon.CADET_PORT, true, true);
            BallotRegisterRequestMessage m = new BallotRegisterRequestMessage();
            CompressedConfig ccfg = new CompressedConfig(ballot.toConfiguration());
            m.compressedBallotConfig = ccfg.compressedData;
            channel.send(m);
            return;
        }
        if (issue) {
            if (null == ego) {
                System.err.println("no ego given");
                setReturnValue(1);
                return;
            }
            ballot.issue(ego.getPrivateKey());
            writeBallot();
            return;
        }
        if (select != null) {
            if (null == ego) {
                System.err.println("no ego given");
                setReturnValue(1);
                return;
            }
            ThresholdPublicKey thresholdPublicKey = ballot.getMajorityThresholdPublicKey();
            if (null == thresholdPublicKey) {
                System.err.println(String.format("no majority threshold public key in ballot (got keys of %s authorities)",
                        (ballot.thresholdPublicKeys == null) ? 0 : ballot.thresholdPublicKeys.size()));
                setReturnValue(1);
                return;
            }
            ballot.encodeChoice(select, thresholdPublicKey, ego.getPrivateKey());
            writeBallot();
            return;
        }
        if (submit) {
            List<PeerIdentity> remainingAuthorities = ballot.getRemainingSubmitAuthorities();
            if (remainingAuthorities.isEmpty()) {
                System.err.println("all authorities already received the ballot");
                return;
            }
            Random r = new Random();
            PeerIdentity authority = remainingAuthorities.get(r.nextInt(remainingAuthorities.size()));
            System.out.println("submitting to authority " + authority.toString());
            currentAuthority = authority;
            cadet = new Cadet(cfg, new BallotChannelEndHandler(), new SubmitReceiver());
            channel = cadet.createChannel(authority, TallyAuthorityDaemon.CADET_PORT, true, true);
            SubmitMessage m = new SubmitMessage();
            if (ballot.voterPub == null) {
                throw new InvalidBallotException("no voter in ballot");
            }
            m.voterPub = ballot.voterPub;
            if (ballot.groupCert == null) {
                throw new InvalidBallotException("no group cert in ballot");
            }
            m.groupCertExpiration = ballot.groupCert.getExpiration().asMessage();
            m.groupCert = ballot.groupCert.getSignature();
            m.ballotGuid = ballot.getBallotGuid();
            if (null == ballot.encryptedVote) {
                throw new InvalidBallotException("no encrypted vote in ballot");
            }
            m.encryptedVote = ballot.encryptedVote;
            channel.send(m);
            return;
        }
        if (verify) {
            System.out.print(ballot.describe());
            return;
        }
        if (query) {
            List<PeerIdentity> remainingAuthorities = ballot.getAuthorities();
            if (remainingAuthorities.isEmpty()) {
                System.err.println("no authorities available");
                setReturnValue(2);
                return;
            }
            Random r = new Random();
            currentAuthority = remainingAuthorities.get(r.nextInt(remainingAuthorities.size()));
            System.out.println("querying authority " + currentAuthority.toString());
            cadet = new Cadet(cfg, new BallotChannelEndHandler(), new QueryReceiver());
            channel = cadet.createChannel(currentAuthority, TallyAuthorityDaemon.CADET_PORT, true, true);
            ResultQueryMessage m = new ResultQueryMessage();
            m.ballotGuid = ballot.getBallotGuid();
            channel.send(m);
            return;
        }
        if (requestKey) {
            List<PeerIdentity> remainingAuthorities = ballot.getRemainingKeyAuthorities();
            if (remainingAuthorities.isEmpty()) {
                System.err.println("all authorities already signed group key");
                return;
            }
            Random r = new Random();
            currentAuthority = remainingAuthorities.get(r.nextInt(remainingAuthorities.size()));
            System.out.println("asking authority for key " + currentAuthority.toString());
            cadet = new Cadet(cfg, new BallotChannelEndHandler(), new PublicKeyReceiver());
            channel = cadet.createChannel(currentAuthority, TallyAuthorityDaemon.CADET_PORT, true, true);
            KeyQueryMessage m = new KeyQueryMessage();
            m.ballotGuid = ballot.getBallotGuid();
            channel.send(m);
            return;
        }
        setReturnValue(1);
        System.err.println("no action specified");
    }

    @Override
    public void run() {
        if (unprocessedArgs.length != 1) {
            System.err.println("no ballot file specified");
            setReturnValue(1);
            return;
        }
        ballotFilename = unprocessedArgs[0];
        if (template)  {
            runTemplate();
            return;
        }
        // all other commands need a loaded ballot file
        File bf = new File(ballotFilename);
        if (!bf.exists()) {
            System.err.println("ballot file does not exist");
            return;
        }
        try {
            ballot = new Ballot(ballotFilename);
        } catch (InvalidBallotException e) {
            System.err.println("Invalid or incomplete ballot:");
            System.err.println(e.getMessage());
            setReturnValue(1);
            return;
        }
        // if there's an ego name, look it up ...
        if (null != egoName) {
            Identity.lookup(getConfiguration(), egoName, new IdentityCallback() {
                @Override
                public void onEgo(Identity.Ego ego) {
                    BallotTool.this.ego = ego;
                    doCommands();
                }
                @Override
                public void onError(String errorMessage) {
                    System.err.println("can't retrieve ego: " + errorMessage);
                    setReturnValue(1);
                }
            });
        } else {
            doCommands();
        }
    }
    public static void main(String args[]) {
        Program tool = new BallotTool();
        int ret = tool.start(args);
        System.exit(ret);
    }
}