-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathp2p-server.js
93 lines (81 loc) · 2.71 KB
/
p2p-server.js
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
const Websocket = require("ws");
const P2P_PORT = process.env.P2P_PORT || 5001;
const peers = process.env.PEERS ? process.env.PEERS.split(',') : [];
const MESSAGE_TYPES = {
chain: "CHAIN",
transaction: "TRANSACTION",
clear_transactions: "CLEAR_TRANSACTIONS"
};
class P2pServer {
constructor(blockchain, transactionPool) {
this.blockchain = blockchain;
this.transactionPool = transactionPool;
this.sockets = [];
}
listen() {
const server = new Websocket.Server({ port: P2P_PORT });
server.on('connection', socket => this.connectSocket(socket));
this.connectToPeers();
console.log(`listening for peer to peer connections on Port: ${P2P_PORT}`)
}
connectSocket(socket) {
this.sockets.push(socket);
console.log('socket connected');
this.messageHandler(socket);
this.sendChain(socket);
}
connectToPeers() {
peers.forEach(peer => {
//ws://localhost:5001
const socket = new Websocket(peer);
socket.on('open', () => this.connectSocket(socket));
socket.onerror = function (error) {
setTimeout(() => {
console.error(`ERROR: close connection to ${peer}`);
//connectToPeers();
socket.close();
}, 5000);
};
});
}
messageHandler(socket) {
socket.on('message', message => {
const data = JSON.parse(message);
switch (data.type) {
case MESSAGE_TYPES.chain:
this.blockchain.replaceChain(data.chain);
break;
case MESSAGE_TYPES.transaction:
this.transactionPool.updateOrAddTransaction(data.transaction);
break;
case MESSAGE_TYPES.clear_transactions:
this.transactionPool.clear();
break;
}
});
}
sendChain(socket) {
socket.send(JSON.stringify({
type: MESSAGE_TYPES.chain,
chain: this.blockchain.chain
}));
}
sendTransaction(socket, transaction) {
socket.send(JSON.stringify({
type: MESSAGE_TYPES.transaction,
transaction: transaction
}));
}
syncChains() {
this.sockets.forEach(socket => this.sendChain(socket));
}
broadcastTransaction(transaction) {
this.sockets.forEach(socket => this.sendTransaction(socket, transaction));
}
broadcastClearTransactions() {
this.sockets.forEach(socket => socket.send(JSON.stringify(
{ type: MESSAGE_TYPES.clear_transactions }
)));
}
}
module.exports = P2pServer;