-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
435 lines (359 loc) · 10.9 KB
/
main.go
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
package main
import (
"bigw-voting/bgw"
"bigw-voting/commands"
"bigw-voting/p2p"
"bigw-voting/shamir"
"bigw-voting/ui"
"bigw-voting/util"
"crypto/sha256"
"encoding/json"
"fmt"
"net"
"os"
"os/signal"
"sort"
"time"
upnp "github.com/huin/goupnp/dcps/internetgateway2"
)
var votepack *Votepack
var localVotes map[string]int
var allVoters []*Voter
var localStatus string
var externalIP string
func main() {
parseCommandline()
votepack = NewVotepackFromFile(flagVotepackFilename)
if flagTrusteeExport {
ExportTrusteeVote()
}
commands.VotepackTrustees = votepack.TrusteeVotes
commands.RegisterAll()
go ui.Start()
defer ui.Stop()
time.Sleep(100 * time.Millisecond)
ui.NewVote(votepack.Candidates, SubmitVotes)
// Find local IP for BGW as well as for UPNP mapping
ifaces, err := net.Interfaces()
if err != nil {
panic(err)
}
var localIP string
for _, i := range ifaces {
addrs, err := i.Addrs()
if err != nil {
panic(err)
}
for _, addr := range addrs {
switch v := addr.(type) {
case *net.IPNet:
if !util.IsPublicIP(v.IP.String()) && v.IP.To4() != nil {
localIP = v.IP.String()
break
}
case *net.IPAddr:
if !util.IsPublicIP(v.IP.String()) && v.IP.To4() != nil {
localIP = v.IP.String()
break
}
}
}
}
if !flagNoUPNP {
clients, _, err := upnp.NewWANIPConnection1Clients()
if err != nil {
panic(err)
}
if len(clients) > 1 {
ui.Stop()
panic("detected multiple gateway devices")
}
if len(clients) < 1 {
util.Warnln("Did not detect any gateway devices, if you are behind a NAT, you cannot act as an intermediate")
}
if len(clients) == 1 {
client := clients[0]
util.Infof("Using local IP %v for port mapping\n", localIP)
// Check for an entry before creating one
intPort, _, _, _, _, err := client.GetSpecificPortMappingEntry("", 42069, "udp")
if intPort != 42069 {
util.Infoln("Creating new port mapping")
// Create a new port mapping allowing all remotes to connect to us on port 42069 for 30 minutes
err = client.AddPortMapping("", 42069, "udp", 42069, localIP, true, "BIGW Voting", 1800)
if err != nil {
panic(err)
}
}
util.Infoln("Port mapping is established")
// Get external IP
externalIP, err = client.GetExternalIPAddress()
if err != nil {
panic(err)
}
util.Infof("Starting intermediate server at external IP: %v:42069\n", externalIP)
}
}
externalIP = flagExternalIP
// Find our public IP
if !util.IsPublicIP(externalIP) {
var extIP string
for _, i := range ifaces {
addrs, err := i.Addrs()
if err != nil {
panic(err)
}
for _, addr := range addrs {
switch v := addr.(type) {
case *net.IPNet:
if util.IsPublicIP(v.IP.String()) {
extIP = v.IP.String()
break
}
case *net.IPAddr:
if util.IsPublicIP(v.IP.String()) {
extIP = v.IP.String()
break
}
}
}
}
externalIP = extIP
}
localStatus = "Voting InProgress"
p2p.Setup(externalIP, NewPeerCallback)
_, err = p2p.StartConnection(fmt.Sprintf("%v:%v", flagIntermediateIP, flagIntermediatePort), flagPeerIP)
if err != nil {
ui.Stop()
panic(err)
}
// Wait for Ctrl-C
quit := make(chan os.Signal, 1)
signal.Notify(quit, os.Interrupt)
<-quit
}
// NewPeerCallback serves as the callback for when new peers are connected.
// It verifies the votepack is consistent and syncs trustee votes.
func NewPeerCallback(p *p2p.Peer) {
// Create voter structure
voter := NewVoter(p)
allVoters = append(allVoters, voter)
// Start a goroutine (one per peer) for a listener
go listener(voter)
// Verify votepack with new peer
util.Infoln("Verifying votepack with new peer")
hash := sha256.Sum256(votepack.Export())
err := p.SendMessage(append([]byte("VotepackVerify "), hash[:]...))
if err != nil {
util.Errorf("Unable to send message to %v, %v\n", p.PeerAddress.IP.String(), err)
}
ui.AddPeerToList(p.PeerAddress.IP.String(), "Votepack Verified")
// Send our current status to the peer
err = p.SendMessage([]byte("StatusUpdate " + localStatus))
if err != nil {
util.Errorf("Unable to send message to %v, %v\n", p.PeerAddress.IP.String(), err)
}
// Update nick for new peer
// if commands.Nick != "" {
// err := p2p.BroadcastMessage([]byte("Nick "+commands.Nick), 0)
// if err != nil {
// util.Errorln(err)
// return
// }
// }
// Update the peer with our trustee votes
for _, v := range commands.LocalTrusteeVotes {
err = p2p.BroadcastMessage([]byte("TrusteeVote "+v.Name), 0)
if err != nil {
util.Errorln(err)
return
}
}
}
// SubmitVotes is the callback for the instantFunoff voting submit button
func SubmitVotes(submittedVotes map[string]int) {
localStatus = "Voting Complete"
localVotes = submittedVotes
// UpdateStatus to all peers
err := p2p.BroadcastMessage([]byte("StatusUpdate "+localStatus), 0)
if err != nil {
util.Errorf("Unable to broadcast status update: %v\n", err)
}
for _, v := range allVoters {
if v.Status != "Voting Complete" {
// Don't begin BGW if peers have not finished voting
return
}
}
// Proceed with BGW
go RunBGW()
}
// RunBGW begins the BGW protocol, with circuits for each round of voting
func RunBGW() {
// A IRV is used to eliminate candidates until there are only 3 left
// https://en.wikipedia.org/wiki/Instant-runoff_voting
// For each round of IRV, the number of votes must be tallied for each candidate.
// This means there must be a BGW circuit for each candidate for each round.
// In a 5 candidate election, that means there must be 5+4 = 9 circuits.
// Create deep copy of elements, so we don't mess up the original candidates
currentCandidates := make([]string, len(votepack.Candidates))
copy(currentCandidates, votepack.Candidates)
sortedPeerIPs := p2p.GetAllPeerIPs()
sort.Strings(sortedPeerIPs)
allPeerIPs := append(sortedPeerIPs, externalIP)
sort.Strings(allPeerIPs)
for len(currentCandidates) > 3 {
// Add votes for each candidate (in alphabetical order)
currentVotes := make(map[string]int)
sort.Strings(currentCandidates)
irvVote := getIRVVote(currentCandidates, localVotes)
// Pre-calculate trustee votes
trusteeVotes := make(map[string]int)
for _, v := range commands.LocalTrusteeVotes {
trusteeIRV := getIRVVote(currentCandidates, v.Votes)
trusteeVotes[trusteeIRV]++
}
for _, v := range currentCandidates {
// Synchronise peers using status
localStatus = "Tallying " + v
err := p2p.BroadcastMessage([]byte("StatusUpdate "+localStatus), 0)
if err != nil {
util.Errorf("Unable to broadcast status update: %v\n", err)
}
for {
var desynchronised bool
for _, v := range allVoters {
if v.Status != localStatus {
desynchronised = true
break
}
}
if !desynchronised {
break
}
}
// Should we vote for this candidate?
shouldVote := 0
util.Infoln("Running tally for", v)
util.Infoln("IRV", irvVote)
if v == irvVote {
util.Infoln("Voting for candidate", v)
shouldVote = 1
}
// Create BGW circuit
head, shares := bgw.NewVotingCircuit(shouldVote+trusteeVotes[v], externalIP, sortedPeerIPs)
// Send shares to peers
for k, v := range shares {
for _, voter := range allVoters {
if voter.Peer.PeerAddress.IP.String() == k {
// Marshal shares
b, err := json.Marshal(v)
if err != nil {
util.Errorln("Unable to marshal peer shares")
}
util.Infoln("Sending:", string(append([]byte("YourShares "), b...)))
err = voter.Peer.SendMessage(append([]byte("YourShares "), b...))
if err != nil {
util.Errorf("Unable to broadcast peer share: %v\n", err)
}
}
}
}
// Wait for all peer shares to be received
for {
if len(receivedPeerShares) == len(sortedPeerIPs) {
break
}
time.Sleep(100 * time.Millisecond)
}
// Sort peer shares then descend circuit
var sortedPeerShares []int
for _, v := range sortedPeerIPs {
sortedPeerShares = append(sortedPeerShares, receivedPeerShares[v]...)
}
util.Infoln("Descending circuit with", sortedPeerShares)
bgw.DescendCircuit(head, sortedPeerShares)
// Get output of circuit and broadcast
circuitOut := head.GetOutput()
util.Infoln("Broadcasting", fmt.Sprintf("MyOutput %v", circuitOut))
err = p2p.BroadcastMessage([]byte(fmt.Sprintf("MyOutput %v", circuitOut)), 0)
if err != nil {
util.Errorf("Unable to broadcast circuit output: %v\n", err)
}
receivedPeerOutputs[externalIP] = circuitOut
// Wait for all peer outputs to be recieved
for {
// Note: allPeerIPs not sortedPeerIPs as we add our result in
if len(receivedPeerOutputs) == len(allPeerIPs) {
break
}
time.Sleep(100 * time.Millisecond)
}
util.Infoln("Local circuit output is", receivedPeerOutputs[externalIP])
// Sort peer outputs then add votes
var sortedPeerOutputs [][2]int
for k, v := range allPeerIPs {
util.Infof("x: %v, peer: %v, peer-out: %v\n", k+1, v, receivedPeerOutputs[v])
sortedPeerOutputs = append(sortedPeerOutputs, [2]int{k + 1, receivedPeerOutputs[v]})
}
util.Infoln("Reconstructing with", sortedPeerOutputs)
currentVotes[v], err = shamir.ReconstructSecret(sortedPeerOutputs)
if err != nil {
util.Errorln("Could not reconstruct circuit output: ", err)
}
util.Infoln("Reconstructed", currentVotes[v])
// Clear all received maps to prevent bad results
receivedPeerOutputs = make(map[string]int)
receivedPeerShares = make(map[string][]int)
}
util.Infoln(currentVotes)
// Ensure that the number of votes does not exceed the number of peers + trustees + us
var numOfVotes int
for _, v := range currentVotes {
numOfVotes += v
}
if numOfVotes > len(p2p.GetAllPeerIPs())+len(commands.AllTrusteeVotes)+1 {
util.Errorln("A peer has voted twice! Number of votes exceeds the number of peer + trustees")
return
}
// Eliminate worst candidate
var worstCandidate string
worstCandidateVotes := -1
for k, v := range currentVotes {
if v < worstCandidateVotes || worstCandidateVotes == -1 {
worstCandidate = k
worstCandidateVotes = currentVotes[k]
}
}
util.Infoln("Eliminating candidate", worstCandidate)
for k, v := range currentCandidates {
if v == worstCandidate {
currentCandidates = append(currentCandidates[:k], currentCandidates[k+1:]...)
}
}
}
util.Infoln("ELECTED CANDIDATES:")
util.Infoln(currentCandidates)
}
// getIRVVote gets the best vote for a given set of candidates
func getIRVVote(currentCandidates []string, votes map[string]int) string {
orderedVotes := make([]string, len(votes))
for k, v := range votes {
orderedVotes[v-1] = k
}
// Find best vote for current candidates
var selected string
for _, v := range orderedVotes {
// Check that candidate voted for is a current candidate
for _, w := range currentCandidates {
if w == v {
selected = v
break
}
}
// If we have found the candidate then we are all good
if selected != "" {
break
}
}
return selected
}