-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.cpp
More file actions
284 lines (242 loc) · 10.4 KB
/
server.cpp
File metadata and controls
284 lines (242 loc) · 10.4 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
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
#include "server.h"
//#include <iostream>
Server::Server(Blockchain<File>* chainPtr):
blockChainPtr(chainPtr), tcpServer(nullptr), networkSession(nullptr), port(0)
{
QNetworkConfigurationManager manager;
if (manager.capabilities() & QNetworkConfigurationManager::NetworkSessionRequired) {
// Get saved network configuration
QSettings settings(QSettings::UserScope, QLatin1String("QtProject"));
settings.beginGroup(QLatin1String("QtNetwork"));
const QString id = settings.value(QLatin1String("DefaultNetworkConfiguration")).toString();
settings.endGroup();
// If the saved network configuration is not currently discovered use the system default
QNetworkConfiguration config = manager.configurationFromIdentifier(id);
if ((config.state() & QNetworkConfiguration::Discovered) !=
QNetworkConfiguration::Discovered) {
config = manager.defaultConfiguration();
}
networkSession = new QNetworkSession(config, this);
connect(networkSession, SIGNAL(opened()), this, SLOT(sessionOpened()));
networkSession->open();
} else {
sessionOpened();
}
connect(tcpServer, SIGNAL(newConnection()), this, SLOT(handleConnection()));
}
Server::~Server() {
delete networkSession;
delete tcpServer;
}
void Server::sessionOpened()
{
// Save the used configuration
if (networkSession) {
QNetworkConfiguration config = networkSession->configuration();
QString id;
if (config.type() == QNetworkConfiguration::UserChoice)
id = networkSession->sessionProperty(QLatin1String("UserChoiceConfiguration")).toString();
else
id = config.identifier();
QSettings settings(QSettings::UserScope, QLatin1String("QtProject"));
settings.beginGroup(QLatin1String("QtNetwork"));
settings.setValue(QLatin1String("DefaultNetworkConfiguration"), id);
settings.endGroup();
}
tcpServer = new QTcpServer(this);
if (!tcpServer->listen()) {
QMessageBox::critical(0, tr("Blockchain Server"),
tr("Unable to start the server: %1.")
.arg(tcpServer->errorString()));
close();
return;
}
QList<QHostAddress> ipAddressesList = QNetworkInterface::allAddresses();
// use the first non-localhost IPv4 address
for (int i = 0; i < ipAddressesList.size(); ++i) {
if (ipAddressesList.at(i) != QHostAddress::LocalHost &&
ipAddressesList.at(i).toIPv4Address()) {
ipAddress = ipAddressesList.at(i).toString();
break;
}
}
// if we did not find one, use IPv4 localhost
if (ipAddress.isEmpty())
ipAddress = QHostAddress(QHostAddress::LocalHost).toString();
port = tcpServer->serverPort();
// cout << ipAddress.toStdString() << " port: " << port << endl;
}
void Server::handleConnection() {
while (tcpServer->hasPendingConnections())
{
// cerr << "In handleConnection\n";
QTcpSocket* socket = tcpServer->nextPendingConnection();
connect(socket, SIGNAL(readyRead()), this, SLOT(readBlocks()));
connect(socket, SIGNAL(disconnected()), socket, SLOT(deleteLater()));
}
}
void Server::readBlocks() {
QTcpSocket* socket = static_cast<QTcpSocket*>(sender());
const int Timeout = 8 * 1000;
QString peerAddress = (socket->peerAddress().toString().contains("::ffff:")) ? socket->peerAddress().toString().mid(7) : socket->peerAddress().toString();
while (socket->bytesAvailable() < (quint64)sizeof(quint64)) {
if (!(socket->waitForReadyRead(2 * Timeout))) {
emit error(socket->error(), socket->errorString(), peerAddress, socket->peerPort());
return;
}
}
quint64 blockSize;
QDataStream in(socket);
in >> blockSize;
// cerr << blockSize << endl;
while (socket->bytesAvailable() < blockSize) {
if (!(socket->waitForReadyRead(Timeout))) {
emit error(socket->error(), socket->errorString(), peerAddress, socket->peerPort());
return;
}
}
quint8 transfer;
in >> transfer;
if (transfer != TRANSFERMODE) {
sendBlocks(socket, -100);
socket->disconnectFromHost();
return;
}
quint16 otherPort;
in >> otherPort;
emit addConnection(peerAddress, otherPort);
// QString text = "Connected to:<br>";
// text += "<b>IP Address:</b> " + peerAddress + "<br><b>Port:</b> ";
// text += QString::number(otherPort) + "<br>";
// emit updateTextBrowser(text);
qint8 mode;
in >> mode;
// cerr << QString::number(mode).toStdString() << endl;
qint8 serverMode;
// cerr << "read contents\n";
/* there are 5 modes FROM CLIENT (all NON-negative):
* 0 : client blockchain is broken -> server sends its blockchain
* 1 : client wants server hash -> server sends its hash
* 2 : client is sending hash -> server compares (sends all good if everything matches, else its blockchain)
* 3 : client is sending blocks -> new blocks added, server appends to end of blockchain and sends its hash
* 4 : client is sending entire blockchain -> server checks sent blockchain for errors and compares it to other nodes (if all good, uses that blockchain)
*/
if (mode > 1) {
QByteArray packet;
in >> packet;
// cerr << packet.toStdString() << endl;
if (mode == 2) {
// cerr << "In mode == 2, checking on index... " << blockChainPtr->getInd() << endl;
serverMode = (packet == (blockChainPtr->hash())) ? 0 : -2;
// cerr << QString::number(serverMode).toStdString() << endl;
}
else if (mode == 3) {
// cerr << "In mode == 3\n";
// cerr << "checking on index... " << blockChainPtr->getInd() << endl;
QString text = "New blocks received from: ";
text += "<b>IP Address:</b> " + peerAddress + " <b>Port:</b> ";
text += QString::number(otherPort) + "<br>";
emit updateTextBrowser(text);
if(!(blockChainPtr->addBlocks(packet))) {
emit updateTextBrowser("Node <b>IP:</b> " + peerAddress + " <b>Port:</b> " + QString::number(otherPort)
+ " contains the following errors:<br>" + (blockChainPtr->getErrors()));
serverMode = -2;
}
else {
serverMode = -1;
}
emit lengthAdded();
}
else {
/* blockchain is also stored in RAM */
blockChainPtr->save();
Blockchain<File> importedChain(packet);
QString errors = importedChain.getErrors();
if (errors.isEmpty()) {
if (blockChainPtr->hash() !=
QCryptographicHash::hash(packet, QCryptographicHash::Sha3_512).toHex()) {
if (!(blockChainPtr->equals(importedChain))) {
if (blockChainPtr->length() <= importedChain.length()) {
blockChainPtr->operator =(importedChain);
blockChainPtr->save();
emit updateTextBrowser("<b>Note:</b> Blockchain updated!<br>Using blockchain from <b>IP:</b> "
+ peerAddress + " <b>Port:</b> " + QString::number(otherPort) + "<br>");
emit modeChange();
serverMode = 0;
}
else {
emit updateTextBrowser("Sending blockchain on this computer to: <b>IP:</b> "
+ peerAddress + " <b>Port:</b> " + QString::number(otherPort) + "<br>");
serverMode = -2;
}
}
else {
blockChainPtr->save();
emit updateTextBrowser("<b>Note:</b> Blockchain synced with <b>IP:</b> "
+ peerAddress + " <b>Port:</b> " + QString::number(otherPort) + "<br>");
emit modeChange();
serverMode = 0;
}
}
}
else {
emit updateTextBrowser("Node <b>IP:</b> " + peerAddress + " <b>Port:</b> " + QString::number(otherPort)
+ " contains the following errors:<br>" + (blockChainPtr->getErrors()));
emit updateTextBrowser("Sending blockchain on this computer to connected node...<br>");
serverMode = -2;
}
emit lengthAdded();
}
}
else if (!mode) {
serverMode = -2;
}
else if (mode == 1) {
serverMode = -1;
}
/* there are 4 modes FROM SERVER (all NON-positive):
* 0 : Server + client blockchain is up to date
* -1 : Server sends hash
* -2 : Server sends its blockchain
* -100 : Error has occured
*/
sendBlocks(socket, serverMode);
// cerr << "gonna disconnect this bad boy\n";
// cerr << "checking on index... " << blockChainPtr->getInd() << endl;
socket->disconnectFromHost();
// cerr << "bad boy disconnected\n";
}
void Server::sendBlocks(QTcpSocket *socket, qint8 mode)
{
// cerr << "In sendBlocks\n";
QByteArray block;
QDataStream out(&block, QIODevice::WriteOnly);
out << (quint64) 0;
out << mode;
QByteArray message;
if (mode && (mode != -100)) {
// cerr << "if (mode)" << endl;
if (mode == -1) {
message = blockChainPtr->hash();
}
else if (mode == -2) {
QString path = QCoreApplication::applicationDirPath() + "/blockchain";
QFile ifs(path);
if (!ifs.open(QIODevice::ReadOnly)) {
QMessageBox messageBox;
messageBox.critical(0,"Error",("Cannot open:\n" + path + "\n"));
// // cerr << "Can not open: " << path << " !" << endl;
exit(1);
}
message = ifs.readAll();
ifs.close();
}
out << message;
// // cerr << (quint64)(block.size() - sizeof(quint64)) << endl;
}
out.device()->seek(0);
out << (quint64)(block.size() - sizeof(quint64));
// cerr << "Writing size in server..." << endl;
// cerr << (quint64)(block.size() - sizeof(quint64)) << endl;
socket->write(block);
}