forked from sellep/blockchain
-
Notifications
You must be signed in to change notification settings - Fork 0
/
p2p.js
75 lines (58 loc) · 1.27 KB
/
p2p.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
const WebSocket = require('ws');
const Block = require('./block');
const Blockchain = require('./blockchain');
const P2P_PORT = process.env.P2P_PORT || 5001;
const peers = process.env.PEERS ? process.env.PEERS.split(',') : [];
class PeerServer
{
constructor(chain)
{
this.chain = chain;
this.sockets = [];
}
start()
{
const server = new WebSocket.Server({ port: P2P_PORT });
server.on('connection', socket => this.connectSocket(socket));
this.connectToPeers();
console.log(`[P2P] listening for on ${P2P_PORT}`);
}
connectToPeers()
{
peers.forEach(peer =>
{
const socket = new WebSocket(peer);
socket.on('open', () =>
{
this.connectSocket(socket);
});
});
}
connectSocket(socket)
{
this.sockets.push(socket);
socket.on('message', message =>
{
const blocks = JSON.parse(message);
if (!Blockchain.validateBlocks(blocks))
{
console.log("[P2P] incoming chain was invalid");
}
else if (this.chain.sync(blocks))
{
console.log('[P2P] successfully updated chain');
}
});
this.sendTo(socket);
console.log('[P2P] socket connected');
}
broadcast()
{
this.sockets.forEach(socket => this.sendTo(socket));
}
sendTo(socket)
{
socket.send(JSON.stringify(this.chain.blocks));
}
}
module.exports = PeerServer;