-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmainwindow.cpp
522 lines (426 loc) · 17.3 KB
/
mainwindow.cpp
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
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
#include "mainwindow.h"
#include "ui_mainwindow.h"
/* 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)
*/
/* 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
*/
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent), ui(new Ui::MainWindow),
spIndex(0), mode(2), closing(false),
bChain(new Blockchain<File>()), server(new Server(bChain)),
client(server->getPort())
{
ui->setupUi(this);
ui->label->setText("Blockchain Length: " + QString::number(bChain->length()));
ui->ipLabel->setText("IP Address: " + server->getIpAddress());
ui->portLabel->setText("Port: " + QString::number(server->getPort()));
connect(server, SIGNAL(addConnection(QString,quint16)), this, SLOT(saveConnection(QString,quint16)));
connect(server, SIGNAL(updateTextBrowser(QString)), this, SLOT(addText(QString)));
connect(server, SIGNAL(error(int,QString,QString,quint16)), this, SLOT(displayError(int,QString,QString,quint16)));
connect(server, SIGNAL(updateBlockchain(Blockchain<File>, QByteArray)), this, SLOT(newBlockchain(Blockchain<File>, QByteArray)));
connect(server, SIGNAL(lengthAdded()), this, SLOT(updateLengthDisplay()));
connect(server, SIGNAL(modeChange()), this, SLOT(changeMode()));
connect(&client, SIGNAL(error(int,QString,QString,quint16)), this, SLOT(displayError(int,QString,QString,quint16)));
connect(&client, SIGNAL(addConnection(QString,quint16)), this, SLOT(saveConnection(QString,quint16)));
QString errors = bChain->getErrors();
QString path = QCoreApplication::applicationDirPath() + "/connections.txt";
QFile ipaddrresses(path);
if (ipaddrresses.open(QIODevice::ReadOnly | QIODevice::Text)) {
QTextStream ipStream(&ipaddrresses);
// cerr << "in connections.open()\n";
QString serverIP;
quint16 serverPort;
bChainHash = bChain->hash();
mode = (!errors.isEmpty()) ? 0 : 2;
if (!ipStream.atEnd()) {
while (!(ipStream >> serverIP).atEnd()) {
ipStream >> serverPort;
// cerr << "serverIP: " << serverIP.toStdString() << endl;
// cerr << "serverPort: " << serverPort << endl;
setUpConnection(serverIP, serverPort);
}
if (connections.size() > 0) {
errors = bChain->getErrors();
}
}
}
ipaddrresses.close();
if (!errors.isEmpty()) {
mode = 0;
ui->textBrowser->append("The blockchain on this computer has the following errors:");
ui->textBrowser->append("<b>" + errors + "</b>");
ui->textBrowser->append("Please connect to a node to resolve this issue.<br>");
ui->Connect->setEnabled(true);
ui->Store->setEnabled(false);
ui->UpdateBlockchain->setEnabled(false);
}
}
MainWindow::~MainWindow()
{
if (mode) {
closing = true;
on_UpdateBlockchain_clicked();
QString path = QCoreApplication::applicationDirPath() + "/connections.txt";
QFile ipaddrresses(path);
if (ipaddrresses.open(QIODevice::WriteOnly | QIODevice::Text)) {
QTextStream ipStream(&ipaddrresses);
for (const Connection& c : connections) {
ipStream << c.ipAddr << " ";
ipStream << c.portAddr << endl;
}
}
ipaddrresses.close();
}
delete bChain;
delete server;
delete ui;
}
void MainWindow::updateBlockchain() {
bChain->save();
QByteArray commonHash = checkForUpdates();
// cerr << "In updateBlockchain(): " << endl;
// cerr << commonHash.toStdString() << endl;
// cerr << bChainHash.toStdString() << endl;
if ((!commonHash.isEmpty()) && ((commonHash != bChainHash) || (!mode))) {
Connection commonServer = hashMap[commonHash].back();
mode = (bChain->getErrors().isEmpty()) ? 2 : 0;
while (!(setUpConnection(commonServer.ipAddr, commonServer.portAddr))) {
commonHash = checkForUpdates();
commonServer = hashMap[commonHash].back();
}
bChain->save();
bChainHash = bChain->hash();
}
mode = 2;
}
void MainWindow::on_UpdateBlockchain_clicked()
{
ui->textBrowser->append("Saving Blockchain...");
ui->Connect->setEnabled(false);
ui->Store->setEnabled(false);
ui->UpdateBlockchain->setEnabled(false);
updateBlockchain();
ui->textBrowser->append("Done.<br>");
ui->Connect->setEnabled(true);
ui->Store->setEnabled(true);
ui->UpdateBlockchain->setEnabled(true);
}
void MainWindow::on_Store_clicked()
{
QString fileName = QFileDialog::getOpenFileName(this,
tr("Open File"), "",
tr("All Files (*)"));
if (fileName.length() == 0) {
return;
}
QFile ifs(fileName);
ifs.open(QIODevice::ReadOnly);
QByteArray content = ifs.readAll();
ifs.close();
if (content.isEmpty()) {
ui->textBrowser->append(fileName + " is empty.");
}
else {
ui->Connect->setEnabled(false);
ui->Store->setEnabled(false);
ui->UpdateBlockchain->setEnabled(false);
ui->textBrowser->append("Saving " + fileName + " to block...<br>");
updateBlockchain();
QString hash = bChain->addBlock(File(fileName, content));
bChainHash = bChain->hash();
QString path = QCoreApplication::applicationDirPath() + "/blockchain";
QFile blockchain(path);
if (!blockchain.open(QIODevice::ReadOnly)) {
QMessageBox messageBox;
messageBox.critical(0,"Error",("Cannot open:\n" + path + "\n"));
exit(1);
}
qint64 pos = blockchain.size() - 2;
do {
blockchain.seek(--pos);
} while (blockchain.peek(1) != "\n");
blockchain.seek(++pos);
QByteArray data = blockchain.readLine(blockchain.size() - pos);
// cerr << data.toStdString() << endl;
blockchain.close();
// cerr << "in store(), checking index... " << bChain->getInd() << endl;
hashMap.clear();
size_t ctr = 0;
while (ctr < connections.size()) {
Package fromServer = client.talk(connections[ctr].ipAddr, connections[ctr].portAddr, 3, data);
if (fromServer.mode == -1) {
hashMap[fromServer.data].push_back(Connection(connections[ctr].ipAddr,connections[ctr].portAddr));
++ctr;
}
else {
// cerr << "fromServer.mode: " << fromServer.data.toStdString() << endl;
}
}
ui->textBrowser->append("Block mined: " + hash);
ui->label->setText("Blockchain Length: " + QString::number(bChain->length()));
}
ui->textBrowser->append("<br>");
ui->Connect->setEnabled(true);
ui->Store->setEnabled(true);
ui->UpdateBlockchain->setEnabled(true);
}
void MainWindow::on_Save_clicked()
{
if (ui->spinBox_1->value() > bChain->length()) {
ui->textBrowser->append("<b>Index cannot be greater than the length of the blockchain!</b><br>");
return;
}
ui->Connect->setEnabled(false);
ui->Store->setEnabled(false);
ui->UpdateBlockchain->setEnabled(false);
spIndex = ui->spinBox_1->value();
ui->textBrowser->append("Index " + QString::number(spIndex) + " selected.<br>");
File file = bChain->viewAt(spIndex);
QString fileName = (file.getFileName() != "") ? file.getFileName() :
(QString::number(spIndex) + ".txt");
QString selectedFile = QFileDialog::getSaveFileName(this,
tr("Save File"), fileName,
tr("All Files (*)"));
if (!selectedFile.isEmpty()) {
QFile ofs(selectedFile);
ofs.open(QIODevice::WriteOnly);
ui->textBrowser->append("Saving data from " + fileName + " to " + selectedFile + " ...<br>");
ofs.write(file.getData());
ofs.close();
ui->textBrowser->append("Data successfully saved.<br>");
}
ui->Connect->setEnabled(true);
ui->Store->setEnabled(true);
ui->UpdateBlockchain->setEnabled(true);
}
void MainWindow::on_View_clicked()
{
for (size_t i = 1; i <= bChain->length(); ++i) {
ui->textBrowser->append("<b>Index " + QString::number(i) + ":</b>");
ui->textBrowser->append(bChain->viewAt(i).getFileName()+"<br>");
}
}
void MainWindow::on_Connect_clicked()
{
ui->Connect->setEnabled(false);
ui->Store->setEnabled(false);
ui->UpdateBlockchain->setEnabled(false);
Dialog dialog(connections);
connect(&dialog, SIGNAL(selectedSettings(QString, quint16)), this, SLOT(setUpConnection(QString, quint16)));
connect(this, SIGNAL(addNewHost(vector<Connection>)), &dialog, SLOT(updateServerLists(vector<Connection>)));
bChainHash = bChain->hash();
dialog.exec();
if (mode) {
ui->Store->setEnabled(true);
ui->UpdateBlockchain->setEnabled(true);
}
ui->Connect->setEnabled(true);
}
bool MainWindow::setUpConnection(const QString &ip, quint16 port) {
if ((ip == server->getIpAddress()) && (port == server->getPort())) {
// cerr << "LMAO can't connect to yourself bro\n";
removeConnectection(ip, port);
return false;
}
// cerr << "In setUpConnection\n";
QByteArray data;
if (mode == 2) {
// cerr << "mode == 2" << endl;
data = bChainHash;
}
else if (mode > 2) {
bChain->save();
QString path = QCoreApplication::applicationDirPath() + "/blockchain";
QFile blockchain(path);
if (!blockchain.open(QIODevice::ReadOnly)) {
QMessageBox messageBox;
messageBox.critical(0,"Error",("Cannot open:\n" + path + "\n"));
exit(1);
}
if (mode == 3) {
qint64 pos = blockchain.size() - 2;
do {
blockchain.seek(--pos);
} while (blockchain.peek(1) != "\n");
blockchain.seek(++pos);
data = blockchain.readLine(blockchain.size() - pos);
// cerr << data.toStdString() << endl;
}
else {
data = blockchain.readAll();
}
blockchain.close();
}
Package fromServer = client.talk(ip, port, mode, data);
if (!fromServer.mode) {
if (hashMap.count(bChainHash)) {
for(const Connection& c : hashMap[bChainHash]) {
if ((ip == c.ipAddr) && (port == c.portAddr)) {
return true;
}
}
}
hashMap[bChainHash].push_back(Connection(ip,port));
}
else if (fromServer.mode == -1) {
if (hashMap.count(fromServer.data)) {
for(const Connection& c : hashMap[fromServer.data]) {
if ((ip == c.ipAddr) && (port == c.portAddr)) {
return true;
}
}
}
hashMap[fromServer.data].push_back(Connection(ip,port));
}
else if (fromServer.mode == -2) {
Blockchain<File> importedChain(fromServer.data);
// cerr << "fromServer.data: " << fromServer.data.toStdString() << endl;
QString errors = importedChain.getErrors();
if (errors.isEmpty() && (importedChain.length() >= bChain->length())) {
newBlockchain(importedChain, fromServer.data);
}
else {
if (!(errors.isEmpty())) {
ui->textBrowser->append("Node <b>IP:</b> " + ip + " <b>Port:</b> " + QString::number(port) + " contains the following errors:<br>" + errors);
ui->textBrowser->append("Sending blockchain on this computer to connected node...<br>");
}
else if (importedChain.length() < bChain->length()) {
ui->textBrowser->append("Sending blockchain on this computer to: <b>IP:</b> " + ip + " <b>Port:</b> " + QString::number(port) + "<br>");
}
mode = 4;
setUpConnection(ip, port);
mode = 2;
}
}
else if (fromServer.mode == -100) {
// cerr << "fromServer.mode: " << fromServer.data.toStdString() << endl;
return false;
}
return true;
}
void MainWindow::newBlockchain(const Blockchain<File>& importedChain, const QByteArray &packet) {
// cerr << "In newBlockchain" << endl;
QByteArray importedHash = QCryptographicHash::hash(packet, QCryptographicHash::Sha3_512).toHex();
QByteArray commonHash = checkForUpdates();
// cerr << "ImportedHash: " << importedHash.toStdString() << endl;
// cerr << "CommonHash: " << commonHash.toStdString() << endl;
if (commonHash != bChainHash) {
if ((hashMap[commonHash].size() > 1) || (!mode)) {
if (commonHash == importedHash) {
bChain->operator =(importedChain);
bChain->save();
bChainHash = bChain->hash();
ui->textBrowser->append("<b>Note:</b> Blockchain updated!");
ui->textBrowser->append("Using blockchain from another node!<br>");
}
else {
Connection commonServer = hashMap[commonHash].back();
mode = 0;
setUpConnection(commonServer.ipAddr, commonServer.portAddr);
}
}
else if (bChain->equals(importedChain)) {
bChain->save();
bChainHash = bChain->hash();
ui->textBrowser->append("<b>Note:</b> Blockchain synced with another node.<br>");
}
}
mode = 2;
ui->label->setText("Blockchain Length: " + QString::number(bChain->length()));
}
QByteArray MainWindow::checkForUpdates() {
hashMap.clear();
size_t ctr = 0;
bChainHash = bChain->hash();
qint8 oldMode = mode;
while (ctr < connections.size()) {
mode = 1;
if (setUpConnection(connections[ctr].ipAddr, connections[ctr].portAddr)) {
++ctr;
}
}
mode = oldMode;
QByteArray commonHash;
size_t maxSize = 0;
for (const auto& iter : hashMap) {
// cerr << "iter.first: " << iter.first.toStdString() << endl;
if (iter.second.size() > maxSize) {
maxSize = iter.second.size();
commonHash = iter.first;
}
}
return commonHash;
}
void MainWindow::saveConnection(const QString& ip, quint16 port) {
for(const Connection& c : connections) {
if ((ip == c.ipAddr) && (port == c.portAddr)) {
return;
}
}
connections.push_back(Connection(ip, port));
QString text = "Connected to:<br>";
text += "<b>IP Address:</b> " + ip + "<br><b>Port:</b> ";
text += QString::number(port) + "<br>";
ui->textBrowser->append(text);
emit addNewHost(connections);
}
void MainWindow::addText(const QString& updates) {
ui->textBrowser->append(updates);
}
void MainWindow::displayError(int socketError, const QString &message, const QString& ip, quint16 port)
{
if (!closing) {
QMessageBox messageBox;
switch (socketError) {
case QAbstractSocket::HostNotFoundError:
messageBox.information(this, tr("Blockchain Client"),
("IP: " + ip + " Port: " + QString::number(port) + " not found. Please check the " +
"host and port settings."));
break;
case QAbstractSocket::ConnectionRefusedError:
messageBox.information(this, tr("Blockchain Client"),
("The connection was refused by: IP: " + ip + " Port: " + QString::number(port) +
". Make sure the blockchain server is running, " +
"and check that the host name and port " +
"settings are correct."));
break;
default:
messageBox.information(this, tr("Blockchain Client"),
("Attempted connection: IP: " + ip + " Port: " + QString::number(port) + ". The following error occurred: %1.")
.arg(message));
}
}
// cerr << "still here in display error...\n";
removeConnectection(ip, port);
}
bool MainWindow::removeConnectection(const QString& ip, quint16 port) {
for(size_t i = 0; i < connections.size(); ++i) {
if ((connections[i].ipAddr == ip) && (connections[i].portAddr == port)) {
connections[i] = connections.back();
connections.pop_back();
// cerr << "removing connection...\n";
return true;
}
}
return false;
}
void MainWindow::updateLengthDisplay() {
ui->label->setText("Blockchain Length: " + QString::number(bChain->length()));
}
void MainWindow::changeMode() {
if (!mode) {
ui->Connect->setEnabled(true);
ui->Store->setEnabled(true);
ui->UpdateBlockchain->setEnabled(true);
mode = 2;
}
}