forked from sqfasd/dpos-pbft
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnode.js
67 lines (55 loc) · 1.59 KB
/
node.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
var net = require('net');
var Peer = require('./peer');
var BlockChain = require('./blockchain');
var protocol = require('./protocol');
var Block = require('./block');
var Transaction = require('./transaction');
var PORT = 10000;
function Node(i, isBad) {
this.id = i;
this.isBad = isBad;
this.peerIds = [];
this.peers = {};
this.server = net.createServer(this.onConnection_.bind(this));
this.server.listen(PORT + i, function() {
console.log('node ' + i + ' ready to accept');
});
this.blockchain = new BlockChain(this);
this.blockchain.on('new-message', this.broadcast.bind(this));
}
Node.prototype.connect = function() {
for (var i = 0; i < 5; ++i) {
var rand = Math.floor(Math.random() * 10);
if (rand !== this.id && !this.peers[rand]) {
var peer = new Peer(rand, PORT + rand, this.id);
peer.setMessageCb(this.processMessage_.bind(this));
this.peerIds.push(rand);
this.peers[rand] = peer;
}
}
}
Node.prototype.printBlockChain = function() {
this.blockchain.printBlockChain();
}
Node.prototype.start = function() {
this.blockchain.start();
}
Node.prototype.stop = function() {
}
Node.prototype.broadcast = function(msg) {
for (var i in this.peers) {
this.peers[i].send(msg);
}
}
Node.prototype.onConnection_ = function(socket) {
var peer = new Peer(socket, this.id);
peer.setMessageCb(this.processMessage_.bind(this));
}
Node.prototype.processMessage_ = function(peer, msg) {
var peerId = peer.getId();
if (!this.peers[peerId]) {
this.peers[peerId] = peer;
}
this.blockchain.processMessage(msg);
}
module.exports = Node;