-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNode.java
More file actions
302 lines (260 loc) · 10.7 KB
/
Node.java
File metadata and controls
302 lines (260 loc) · 10.7 KB
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
import java.io.IOException;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ThreadLocalRandom;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* Phase King implementation: single node
*
* @author Project2100
*/
public class Node {
static {
// This thread should be "main"
Thread.currentThread().setUncaughtExceptionHandler((thread, exception) -> {
Logger.getLogger(Node.class.getName()).log(Level.SEVERE, "Uncaught exception in thread: " + thread.getName(), exception);
System.exit(1);
});
}
private static final ThreadLocalRandom RNG = ThreadLocalRandom.current();
/**
* Node identifier, used for deciding whether the node is king at any given phase
*/
private static int identifier;
/**
* Number of nodes
*/
private static int nodeCount;
/**
* How many nodes can go awry before the protocol fails (maxByz < ceil(n/4))
*/
private static int maxByzantine;
/**
* How many phases are executed, based on the maximum number of Byzantine nodes
*/
private static int phaseCount;
/**
* The communication channels with the coordinator
*/
private static Socket coordinator;
private static Socket[] peers;
private static boolean verbose = false;
/**
* Synchronization routine, with the help of the coordinator
*
* @throws IOException
*/
private static void sync(int message) throws IOException {
coordinator.getOutputStream().write(message);
coordinator.getInputStream().read();
}
/**
* The procedure:
*
* - Join an UDP/IP multicast group by means of a specific IP address
* - Connect to the coordinator with a standard TCP/IP socket, address is
* given as argument
*
*
* @param args
* @throws IOException
* @throws InterruptedException
*/
public static void main(String[] args) throws IOException, InterruptedException {
// Read and validate options
String coordName = "";
int port = -1;
for (int i = 0; i < args.length; i++) switch (args[i]) {
case "-n" -> {
i++;
if (i == args.length) throw new RuntimeException("Missing node count");
else {
nodeCount = Integer.valueOf(args[i]);
maxByzantine = (int) (Math.ceil(nodeCount / 4) - 1);
phaseCount = maxByzantine + 1;
}
}
case "-c" -> {
i++;
if (i == args.length) throw new RuntimeException("Missing coordinator hostname");
else coordName = args[i];
}
case "-p" -> {
i++;
if (i == args.length) throw new RuntimeException("Missing TCP port");
else port = Integer.valueOf(args[i]);
}
case "-v" -> {
verbose = true;
}
default -> throw new RuntimeException("Unrecognized option: " + args[i]);
}
if (coordName.equals("")) {
System.out.println("Please provide the coordinator hostname");
return;
}
if (port <= 0) {
System.out.println("Please provide a valid TCP port");
return;
}
if (nodeCount > 127 || nodeCount < 0) {
System.out.println("Pleass provide a node count between 1 and 127");
return;
}
// Open a listening socket for the group
// Working under the assumption that all peers won't fail during the connection phase
@SuppressWarnings({"resource"})
ServerSocket listener = new ServerSocket(port, nodeCount - 1, InetAddress.getLocalHost());
// Connect to the coordinator
int retries = 0;
while (true) try {
// This call is blocking, can also throw (e.g.: the server hasn't opened its listening socket yet)
// ID is received only when all other peers do connect to the coordinator
coordinator = new Socket(InetAddress.getByName(coordName), port);
identifier = coordinator.getInputStream().read();
break;
}
catch (IOException ex) {
if (coordinator == null && retries < 3) {
System.out.println("Failed connecting to coordinator, retrying in two seconds...");
retries++;
// Best known way to handle the containers' concurrent startup, for now... "depends_on" option isn't a sure-fire solution, but helps a lot
Thread.sleep(2000);
}
else throw new RuntimeException("Failed connecting after " + retries + " retries. Quitting...", ex);
}
// CONNECTION PHASE
// IMPORTANT: At this point, every node is guaranteed to have opened a listening socket, because the coordinator acted as a barrier beforehand
// If the node's ID is below the index, it listens, if it's above, it connects
int nodeIndex = identifier - 1;
peers = new Socket[nodeCount];
for (int i = 0; i < peers.length; i++) {
if (i < nodeIndex) {
peers[i] = listener.accept();
}
else if (i > nodeIndex) {
peers[i] = new Socket(InetAddress.getByName("phaseking_node_" + (i + 1) + ".phaseking_pk_net"), port);
}
else listener.close(); // Essentially, at this point the listener is done
}
// SYNC
if (verbose) System.out.format("Fully connected. Standing by...\n", identifier);
sync(210);
// From now on, this node's behaviour will be entirely regulated by the control values supplied by the coordinator:
// 0: honest
// 1: random
// *: terminate
while (true) switch (coordinator.getInputStream().read()) {
case 0 -> {
if (verbose) System.out.println("I'm honest");
coordinator.getOutputStream().write(beHonest() ? 1 : 0);
}
case 1 -> {
if (verbose) System.out.println("I'm random");
beRandom();
coordinator.getOutputStream().write(2);
}
default -> {
for (int i = 0; i < peers.length; i++) {
if (i == identifier - 1) continue;
peers[i].close();
}
coordinator.close();
return;
}
}
}
/**
* The honest node.
*
* On each phase: for round 1, the node shares its value, gathers those of
* all others, and computes the majority; for round 2, if it is King then it
* shares its majority, serving as the tiebreaker for others, and becoming
* its new value; otherwise decides whether its new value is the majority or
* the tiebreaker received from the king.
*
* @return
* @throws IOException
*/
static boolean beHonest() throws IOException {
// Get an initial value
boolean consensus = RNG.nextBoolean();
for (int phase = 0; phase < phaseCount; phase++) {
// Round 1
// All nodes share their consensus
boolean[] groupValues = new boolean[nodeCount];
for (int i = 0; i < nodeCount; i++) {
if (i == identifier - 1) continue;
peers[i].getOutputStream().write(consensus ? 1 : 0);
groupValues[i] = peers[i].getInputStream().read() == 1;
}
groupValues[identifier - 1] = consensus;
// Compute the majority
int trueCount = 0;
int falseCount = 0;
for (boolean groupValue : groupValues) if (groupValue) trueCount++; else falseCount++;
boolean majority = trueCount > falseCount;
int majCount = majority ? trueCount : falseCount;
if (verbose) System.out.format("(PHASE %d - ROUND 1) Holding value: %b, majority: %b (%d occurrences)\n", phase + 1, consensus, majority, majCount);
sync(210);
// Round 2
// If this node is king, send its majority to everybody else as the tiebreaker, otherwise listen and decide
if (phase == identifier - 1) {
if (verbose) System.out.format("(PHASE %d - ROUND 2) I am King, sending tiebreaker: %b\n", phase + 1, majority);
for (int i = 0; i < nodeCount; i++) {
if (i == identifier - 1) continue;
peers[i].getOutputStream().write(majority ? 1 : 0);
}
consensus = majority; // majority and tiebreaker will be subjectively the same anyways
}
else {
boolean tiebreaker = peers[phase].getInputStream().read() == 1;
if (majCount > nodeCount / 2 + maxByzantine) {
if (verbose) System.out.format("(PHASE %d - ROUND 2) High consensus, choosing majority: %b\n", phase + 1, majority);
consensus = majority;
}
else {
if (verbose) System.out.format("(PHASE %d - ROUND 2) Consensus not high enough, choosing tiebreaker: %b\n", phase + 1, tiebreaker);
consensus = tiebreaker;
}
}
sync(210);
}
return consensus;
}
/**
* The random node.
*
* On each phase: for round 1, send a random value to each node and ignore
* the received values; for round 2, if this node is king, send random
* tiebreakers to each node, else ignore the received tiebreaker
*
* @throws IOException
*/
static void beRandom() throws IOException {
for (int phase = 0; phase < phaseCount; phase++) {
// Round 1
for (int i = 0; i < nodeCount; i++) {
if (i == identifier - 1) continue;
peers[i].getOutputStream().write(RNG.nextInt(2));
peers[i].getInputStream().read();
}
if (verbose) System.out.format("(PHASE %d - ROUND 1) Randomizing\n", phase + 1);
sync(210);
// Round 2
if (phase == identifier - 1) {
if (verbose) System.out.format("(PHASE %d - ROUND 2) I am King, bombs away\n", phase + 1);
for (int i = 0; i < nodeCount; i++) {
if (i == identifier - 1) continue;
peers[i].getOutputStream().write(RNG.nextInt(2));
}
}
else {
peers[phase].getInputStream().read();
}
sync(210);
}
}
}