forked from rampatra/Algorithms-and-Data-Structures-in-Java
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPeer.java
120 lines (107 loc) · 3.49 KB
/
Peer.java
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
package com.rampatra.blockchain;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.stream.Collectors;
/**
* @author rampatra
* @since 2019-03-09
*/
public class Peer {
private Blockchain blockchain;
private int port;
private ServerSocket server;
private ExecutorService executor = Executors.newSingleThreadExecutor();
Peer(Blockchain blockchain, int port) {
this.blockchain = blockchain;
this.port = port;
startServer();
getLatestBlockFromPeers();
}
/**
* Once a new peer is created, we start the socket server to receive messages from the peers.
*/
private void startServer() {
try {
executor.submit(() -> {
server = new ServerSocket(port);
while (true) {
// we create a new thread for each new client thereby supporting multiple client simultaneously
new Thread(new MessageHandler(server.accept(), this)).start();
}
});
} catch (Exception e) {
throw new RuntimeException(e);
}
}
/**
* Stop the server once a peer is removed from the network.
*/
public void stopServer() {
try {
if (!server.isClosed()) {
server.close();
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
/**
* Once a new peer is created and added to the network, it requests the latest block from
* all the peers and updates its blockchain if it is outdated.
*/
private void getLatestBlockFromPeers() {
sendMessageToPeers(Message.MessageBuilder
.aMessage()
.withMessageType(Message.MessageType.REQUEST_LATEST_BLOCK)
.build());
}
private void sendMessageToPeers(Message message) {
try {
// send to all peers except itself
List<Peer> peers = P2P.getPeers()
.stream()
.filter(peer -> !(peer.port == this.port))
.collect(Collectors.toList());
for (Peer peer : peers) {
Socket client = new Socket("127.0.0.1", peer.port);
ObjectOutputStream out = new ObjectOutputStream(client.getOutputStream());
out.writeObject(message);
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
/**
* Mine, create a new block with the {@code data}, and finally, add it to the blockchain.
*
* @param data
*/
public void mine(String data) {
Block latestBlock = this.blockchain.mine(data);
sendMessageToPeers(Message.MessageBuilder
.aMessage().withMessageType(Message.MessageType.RECEIVE_LATEST_BLOCK)
.withLatestBlock(latestBlock)
.build());
}
public Blockchain getBlockchain() {
return blockchain;
}
public void setBlockchain(Blockchain blockchain) {
this.blockchain = blockchain;
}
public int getPort() {
return port;
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder("Peer{");
sb.append("blockchain=").append(blockchain);
sb.append(", port=").append(port);
sb.append('}');
return sb.toString();
}
}