-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathp2p-server.js
More file actions
87 lines (66 loc) · 2.19 KB
/
p2p-server.js
File metadata and controls
87 lines (66 loc) · 2.19 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
const Websocket = require('ws')
const P2P_PORT = process.env.P2P_PORT || 5001
const peers = process.env.PEERS ? process.env.PEERS.split(',') : []
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}`)
}
connectToPeers() {
peers.forEach((peer) => {
const socket = new Websocket(peer)
socket.on('open', () => this.connectSocket(socket))
})
}
connectSocket(socket) {
this.sockets.push(socket)
console.log('Socket connected')
this.messageHandler(socket)
this.sendChain(socket)
}
messageHandler(socket) {
socket.on('message', (message) => {
const data = JSON.parse(message)
switch (data.type) {
case 'chain':
this.blockchain.replaceChain(data.payload)
break;
case 'transaction':
this.transactionPool.updateOrAddTransaction(data.payload)
break;
case 'clear_transaction':
this.transactionPool.clear()
break;
}
})
}
sendChain(socket) {
socket.send(JSON.stringify({type: 'chain', payload: this.blockchain.chain}))
}
syncChains() {
this.sockets.forEach((socket) => {
this.sendChain(socket)
})
}
sendTransaction(socket, transaction) {
socket.send(JSON.stringify({type: 'transaction', payload: transaction}))
}
broadcastTransaction(transaction) {
this.sockets.forEach((socket) => {
this.sendTransaction(socket, transaction)
})
}
broadcastClearTransactions() {
this.sockets.forEach((socket) => {
socket.send(JSON.stringify({type: 'clear_transactions'}))
})
}
}
module.exports = P2PServer;