meerkat-java/destributed-key-generation/src/main/java/Communication/Network.java

71 lines
2.1 KiB
Java
Raw Normal View History

2016-02-17 15:58:20 -05:00
package Communication;
import com.google.protobuf.InvalidProtocolBufferException;
import com.google.protobuf.Message;
import meerkat.protobuf.DKGMessages.*;
import java.util.Queue;
import java.util.concurrent.ArrayBlockingQueue;
/**
* Created by Tzlil on 2/7/2016.
* JointFeldamn protocol assumes all parties can communicate throw broadcast chanel
* and private chanel (for each pair)
* this class simulates it
*/
public class Network {
protected final User[] users;
protected final int n;
protected final Queue<Integer> availableIDs;
public static final int BROADCAST = 0;
public Network(int n) {
this.n = n;
this.users = new User[n];
this.availableIDs = new ArrayBlockingQueue<Integer>(n);
for (int id = 1; id <= n; id++){
availableIDs.add(id);
}
}
2016-03-01 09:49:55 -05:00
public User connect(MailHandler mailHandler){
2016-02-17 15:58:20 -05:00
Integer id = availableIDs.poll();
if (id == null)
return null;
2016-03-01 09:49:55 -05:00
users[id - 1] = new User(id,this,mailHandler);
2016-02-17 15:58:20 -05:00
return users[id - 1];
}
protected boolean sendMessage(User sender,int destination,Mail.Type type,Message message){
if(destination < 1 || destination > n)
return false;
User user = users[destination - 1];
if (user == null)
return false;
Mail mail = Mail.newBuilder()
.setSender(sender.getID())
.setDestination(destination)
.setIsPrivate(true)
.setType(type)
.setMessage(message.toByteString())
.build();
return user.mailbox.add(mail);
}
protected void sendBroadcast(User sender,Mail.Type type,Message message){
User user;
Mail mail = Mail.newBuilder()
.setSender(sender.getID())
.setDestination(BROADCAST)
.setIsPrivate(false)
.setType(type)
.setMessage(message.toByteString())
.build();
for (int i = 0 ; i < n ; i++){
user = users[i];
user.mailbox.add(mail);
}
}
}