-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
182 lines (159 loc) · 6.36 KB
/
server.js
File metadata and controls
182 lines (159 loc) · 6.36 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
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
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
'use strict';
var express = require("express");
var bodyParser = require("body-parser");
var WebSocket = require("ws");
var ethGSV = require('./signing');
const {Blockchain,Transaction} = require('./blockchain');
var http_port = process.argv[2]||3001;
var p2p_port = process.argv[3] || 6001;
var initialPeers = process.argv[4]? [process.argv[4]] : [];
const blockchain = new Blockchain();
var sockets = [];
var MessageType = {
QUERY_LATEST: 0,
QUERY_ALL: 1,
RESPONSE_BLOCKCHAIN: 2
};
var newTransaction = (tx_type, add1, add2, k) => {
const nonce = 1;
const tx = new Transaction(tx_type, nonce, add1, add2);
var s = ethGSV.sign(JSON.stringify(tx), k.privateKey);
tx.signature = s;
console.log(s);
blockchain.pendingTransactions.push(tx);
}
var initHTTPServer = () => {
var app = express();
var k= ethGSV.generateKeyPair();
console.log(k);
app.use(bodyParser.json());
app.get('/blocks',(req, res) => res.send(JSON.stringify(blockchain.chain)));
app.get('/mineBlock', (req, res) => {
res.sendFile(__dirname + "/mine.html");
});
app.post('/mineBlock', (req, res) => {
//console.log(req.body.data);
console.log(`data: ${blockchain.pendingTransactions}`);
blockchain.pendingTransactions.forEach((tx) => {
var tx_data = JSON.parse(JSON.stringify(tx));
tx_data.signature = null;
tx_data.index = null;
if(!ethGSV.verify(JSON.stringify(tx_data), tx.signature, k.address)) {
console.log('false');
blockchain.pendingTransactions.pop(tx);
}
});
var newBlock = blockchain.generateNextBlock(blockchain.pendingTransactions);
//var newBlock = blockchain.generateNextBlock(req.body.data);
blockchain.addBlock(newBlock);
broadcast(responseLatestMsg());
console.log('block added: ' + JSON.stringify(newBlock));
blockchain.pendingTransactions = [];
console.log(blockchain.chain);
res.send(JSON.stringify(blockchain.chain));
});
app.get('/peers', (req, res) => {
console.log(sockets.map(s => s._socket.remoteAddress + ':' + s._socket.remotePort) );
res.send(sockets.map(s => s._socket.remoteAddress + ':' + s._socket.remotePort));
});
app.get('/addPeer', (req, res) => {
res.sendFile(__dirname + '/addPeer.html');
});
app.post('/addPeer', (req, res) => {
console.log([req.body]);
connectToPeers([req.body.peer]);
res.send();
});
app.post('/newTransaction', (req, res) => {
const tx = req.body;
//required = ['tx_type', 'PDid', 'h_enc_PD', 'h_agreement', 'access_list'];
newTransaction(tx.tx_type, tx.add1, tx.add2, k);
res.send(`tx will append at ${blockchain.chain.length} block\n`);
});
app.listen(http_port, () => console.log('Listening http on port: ' + http_port ));
}
var initP2PServer = () => {
var server = new WebSocket.Server({port : p2p_port});
server.on('connection', (ws) => initConnection(ws));
console.log('listening websocket p2p on: ' + p2p_port);
}
var initConnection = (ws) => {
sockets.push(ws);
initMessageHandler(ws);
console.log(`initConnection\n`);
write(ws,queryChainLengthMsg());
}
var initMessageHandler = (ws) => {
ws.on('message', (data) => {
var message = JSON.parse(data);
//console.log(`Received Message: ${JSON.stringify(message)} time: ${new Date().getTime()}\n`);
switch(message.type) {
case MessageType.QUERY_LATEST:
write(ws, responseLatestMsg());
break;
case MessageType.QUERY_ALL:
write(ws, responseChainMsg());
break;
case MessageType.RESPONSE_BLOCKCHAIN:
handleBlockchainResponse(message);
break;
}
})
}
var connectToPeers = (newPeers) => {
newPeers.forEach((peer) => {
var ws = new WebSocket(peer);
ws.on('open', () => initConnection(ws));
ws.on('error', () => {
console.log('connection failed');
});
});
};
var handleBlockchainResponse = (message) => {
console.log(`handleBlockchainResponse\n`);
//console.log(`chain : ${JSON.stringify(message)}`);
var receivedBlocks = JSON.parse(message.data).sort((b1,b2) => (b1.index - b2.index));
var latestBlockReceived = receivedBlocks[receivedBlocks.length-1];
var latestBlockHeld = blockchain.getLatestBlock();
if(latestBlockReceived.index > latestBlockHeld.index) {
console.log('blockchain possibly behind. We got: ' + latestBlockHeld.index + ' Peer got: ' + latestBlockReceived.index);
if(latestBlockHeld.hash == latestBlockReceived.previousHash) {
console.log("We can append the received block to our chain");
blockchain.chain.push(latestBlockReceived);
broadcast(responseLatestMsg());
} else if(receivedBlocks.length == 1) {
console.log("We have to query the chain from our peer");
broadcast(queryAllMsg());
} else {
console.log("Received blockchain is longer than current blockchain");
replaceChain(receivedBlocks);
}
} else {
console.log('received blockchain is not longer than current blockchain. Do nothing');
}
};
var replaceChain = (newBlocks) => {
if(blockchain.isValidChain(newBlocks) && newBlocks.length > blockchain.chain.length) {
console.log('Received blockchain is valid. Replacing current blockchain with received blockchain');
blockchain.chain = newBlocks;
broadcast(responseLatestMsg());
} else {
console.log('Received blockchain invalid');
}
}
var queryChainLengthMsg = () => ({'type': MessageType.QUERY_LATEST});
var queryAllMsg = () => ({'type': MessageType.QUERY_ALL});
var responseLatestMsg = () => ({
'type' : MessageType.RESPONSE_BLOCKCHAIN,
'data' : JSON.stringify([blockchain.getLatestBlock()])
});
var responseChainMsg = () => ({
'type' : MessageType.RESPONSE_BLOCKCHAIN,
'data' : JSON.stringify(blockchain.chain)
});
var write = (ws,message) => { //console.log(`$$$$message: ${JSON.stringify(message)} time : ${new Date().getTime()}\n`)
ws.send(JSON.stringify(message));}
var broadcast = (message) => sockets.forEach(socket => write(socket,message));
connectToPeers(initialPeers);
initHTTPServer();
initP2PServer();