-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy pathChain.cpp
executable file
·377 lines (309 loc) · 13.7 KB
/
Chain.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
#include "Chain.h"
#include "Block/BlockStore.h"
#include "Tools/Log.h"
#include "FS/FS.h"
#include "DB/DB.h"
#include "TxPool.h"
#include "Network/BanList.h"
#include "Network/BlockCache.h"
#include "App.h"
#include "Network/Network.h"
std::mutex Chain::connectBlockMutex;
void Chain::setBlockHashAndHeightMap(uint64_t position, std::vector<unsigned char> headerHash) {
DB &db = DB::Instance();
db.putInDB(DB_BLOCK_HEADERS, position, headerHash);
}
bool Chain::disconnectBlock(std::vector<unsigned char> blockHeaderHash) {
TxPool& txPool = TxPool::Instance();
Block* block = BlockStore::getBlock(blockHeaderHash);
if(block == nullptr) {
Log(LOG_LEVEL_ERROR) << "Cannot disconnect block:" << blockHeaderHash << " because block was not found in block store";
return false;
}
bool success = BlockHelper::undoBlock(block);
// put transactions from Block back into TxPool
txPool.appendTransactionsFromBlock(block);
return success;
}
bool Chain::connectBlock(Block* block) {
return Chain::connectBlock(block, false);
}
bool Chain::connectBlock(Block* block, bool isRecursion) {
App& app = App::Instance();
if(app.getTerminateSignal()) {
Log(LOG_LEVEL_INFO) << "cannot connect a new block, received terminate signal";
return false;
}
if(!isRecursion) {
connectBlockMutex.lock();
}
DB &db = DB::Instance();
BlockHeader* header = block->getHeader();
Log(LOG_LEVEL_INFO) << "attempting to add block with hash "
<< header->getHeaderHash()
<< "\n"
<< " and height "
<< "\n"
<< header->getBlockHeight()
<< " to the chain"
<< "\n"
<< "Payout:"
<< header->getPayout()
<< "\n"
<< "PayoutRemainder:"
<< header->getPayoutRemainder()
<< "\n"
<< "UbiReceiverCount:"
<< header->getUbiReceiverCount()
<< "\n"
<< "transaction count:"
<< (uint32_t)block->getTransactions().size();
BlockHeader* previousHeader = getBlockHeader(header->getPreviousHeaderHash());
if(previousHeader == nullptr) {
if(header->getPreviousHeaderHash().empty()) {
if(header->getBlockHeight() != 1) {
Log(LOG_LEVEL_ERROR) << "Genesis block should be of height 1";
connectBlockMutex.unlock();
return false;
}
// genesis block
} else {
Log(LOG_LEVEL_ERROR) << "couldn't connect block " << header->getHeaderHash() << " to chain, previous block not found";
connectBlockMutex.unlock();
return false;
}
} else {
if(header->getBlockHeight() != previousHeader->getBlockHeight() + 1) {
Log(LOG_LEVEL_ERROR) << "previous blockheight is "
<< previousHeader->getBlockHeight()
<< " but expected to be "
<< header->getBlockHeight() - 1;
connectBlockMutex.unlock();
return false;
}
delete previousHeader;
}
BlockHeader* bestBlockHeader = this->getBestBlockHeader();
if(this->bestBlockHeight >= header->getBlockHeight()) {
// fork without consequences
Log(LOG_LEVEL_INFO) << "Detected a fork, block: " << header->getHeaderHash() << " at height: " << header->getBlockHeight();
//add block to chain
BlockStore::insertBlock(block);
db.serializeToDb(DB_BLOCK_HEADERS, header->getHeaderHash(), *header);
// If block has the same height as the other highest block
if(this->bestBlockHeight == header->getBlockHeight()) {
this->bestBlocks.emplace_back(*header);
}
connectBlockMutex.unlock();
return true;
} else if(bestBlockHeader != nullptr && !block->getHeader()->getPreviousHeaderHash().empty()) {
if (bestBlockHeader->getHeaderHash() != block->getHeader()->getPreviousHeaderHash()) {
// fork with consequences
// Need to solve the fork
Log(LOG_LEVEL_INFO) << "Started trying to solve a fork";
bool forkFailed = false;
std::vector<std::vector<unsigned char> > toUndo;
std::vector<std::vector<unsigned char> > toDo;
std::vector<unsigned char> currentChainHeaderHash = bestBlockHeader->getHeaderHash();
std::vector<unsigned char> newChainHeaderHash = block->getHeader()->getPreviousHeaderHash();
std::vector<unsigned char> commonHeaderHash;
bool foundCommonHeader = false;
while (!foundCommonHeader) {
Log(LOG_LEVEL_INFO) << "currentChainHeaderHash: " << currentChainHeaderHash;
toUndo.emplace_back(currentChainHeaderHash);
toDo.emplace_back(newChainHeaderHash);
BlockHeader* currentChainHeader = this->getBlockHeader(currentChainHeaderHash);
BlockHeader* newChainHeader = this->getBlockHeader(newChainHeaderHash);
if(currentChainHeader == nullptr || newChainHeader == nullptr) {
Log(LOG_LEVEL_ERROR) << "Something went wrong, reverting fork";
forkFailed = true;
break;
}
currentChainHeaderHash = currentChainHeader->getPreviousHeaderHash();
newChainHeaderHash = newChainHeader->getPreviousHeaderHash();
delete newChainHeader;
delete currentChainHeader;
for(auto toDoHeaderHash : toDo) {
auto found = std::find(toUndo.begin(), toUndo.end(), toDoHeaderHash);
if (found != toUndo.end()) {
foundCommonHeader = true;
commonHeaderHash = *found;
}
}
}
Log(LOG_LEVEL_INFO) << "Found common header:" << commonHeaderHash;
// Undo common header as well as all previous headers
bool reachedCommonHeader = false;
for(std::vector<std::vector<unsigned char> >::iterator it = toDo.begin(); it != toDo.end();) {
if(*it == commonHeaderHash) {
reachedCommonHeader = true;
}
if(reachedCommonHeader) {
it = toDo.erase(it);
} else {
it++;
}
}
// for undo too
reachedCommonHeader = false;
for(std::vector<std::vector<unsigned char> >::iterator it = toUndo.begin(); it != toUndo.end();) {
if(*it == commonHeaderHash) {
reachedCommonHeader = true;
}
if(reachedCommonHeader) {
it = toUndo.erase(it);
} else {
it++;
}
}
Log(LOG_LEVEL_INFO) << "Need to disconnect " << (uint64_t)toUndo.size() << " blocks";
// disconnect all blocks until last common block
for (std::vector<std::vector<unsigned char>>::iterator it = toUndo.begin(); it != toUndo.end(); it++) {
Log(LOG_LEVEL_INFO) << "Disconnecting: " << *it;
this->disconnectBlock(*it);
}
std::vector<BlockHeader> newBestBlockHeader;
BlockHeader commonBlock = *this->getBlockHeader(commonHeaderHash);
newBestBlockHeader.emplace_back(commonBlock);
this->setBestBlockHeaders(newBestBlockHeader);
this->bestBlockHeight = commonBlock.getBlockHeight();
Log(LOG_LEVEL_INFO) << "Blocks are now disconnected";
Log(LOG_LEVEL_INFO) << "Will apply " << (uint64_t)toDo.size() << " new blocks";
std::vector<std::vector<unsigned char> > appliedTodos;
BanList& banList = BanList::Instance();
BlockCache& blockCache = BlockCache::Instance();
// apply blocks from new best chain
for (std::vector<std::vector<unsigned char>>::reverse_iterator it = toDo.rbegin();
it != toDo.rend(); it++) {
Block *blockFromStore = BlockStore::getBlock(*it);
if (BlockHelper::verifyBlock(blockFromStore)) {
if(this->connectBlock(blockFromStore, true)) {
appliedTodos.emplace_back(*it);
} else {
banList.appendBan(blockCache.getIpForBlock(*it), BAN_INC_INSTA_BAN);
forkFailed = true;
}
} else {
banList.appendBan(blockCache.getIpForBlock(*it), BAN_INC_INSTA_BAN);
forkFailed = true;
}
}
if(!forkFailed) {
Log(LOG_LEVEL_INFO) << "New blocks applied, fork success";
}
// fork failed because it contains invalid block(s), rollback and delete this evil fork
if (forkFailed) {
Log(LOG_LEVEL_INFO) << "Fork failed, need to rollback!";
// rollback all applied todos
for (std::vector<std::vector<unsigned char>>::iterator it = appliedTodos.begin(); it != appliedTodos.end(); it++) {
Log(LOG_LEVEL_INFO) << "Rollback: " << *it;
this->disconnectBlock(*it);
}
// reapply all untodos
for (std::vector<std::vector<unsigned char>>::reverse_iterator it = toUndo.rbegin(); it != toUndo.rend(); it++) {
Log(LOG_LEVEL_INFO) << "Connecting: " << *it;
Block *blockFromStore = BlockStore::getBlock(*it);
if (BlockHelper::verifyBlock(blockFromStore)) {
this->connectBlock(blockFromStore);
} else {
Log(LOG_LEVEL_CRITICAL_ERROR) << "Rollback failed after a bad fork";
// terminate app to avoid more damage
App& app = App::Instance();
app.terminate();
return false;
}
}
}
}
}
//verify block
if(!BlockHelper::verifyBlock(block)) {
Log(LOG_LEVEL_ERROR) << "couldn't connect block " << header->getHeaderHash() << " to chain, verification failed";
connectBlockMutex.unlock();
return false;
}
//add block to chain
BlockStore::insertBlock(block);
db.serializeToDb(DB_BLOCK_HEADERS, header->getHeaderHash(), *header);
// Apply blocks
BlockHelper::applyBlock(block);
//update best blocks
this->bestBlockHeight = header->getBlockHeight();
std::vector<BlockHeader> newBestBlocks = std::vector<BlockHeader>();
newBestBlocks.emplace_back(*header);
this->setBestBlockHeaders(newBestBlocks);
db.putInDB(DB_BLOCK_HEADERS, header->getBlockHeight(), header->getHeaderHash());
FS::clearFile(FS::getBestBlockHeadersPath());
for(BlockHeader bestHeader: this->bestBlocks) {
FS::serializeToFile(FS::getBestBlockHeadersPath(), bestHeader);
}
Log(LOG_LEVEL_INFO) << "added block with hash "
<< header->getHeaderHash()
<< " and height "
<< header->getBlockHeight()
<< " to the chain";
connectBlockMutex.unlock();
std::thread t1(&Network::broadCastNewBlockHeight, header->getBlockHeight(), header->getHeaderHash());
t1.detach();
return true;
}
uint32_t Chain::getBlockHeight(std::vector<unsigned char> blockHeaderHash) {
BlockHeader* blockHeader = this->getBlockHeader(blockHeaderHash);
if(blockHeader != nullptr) {
uint32_t height = blockHeader->getBlockHeight();
delete blockHeader;
return height;
}
return 0;
}
BlockHeader* Chain::getBlockHeader(std::vector<unsigned char> blockHeaderHash) {
if(blockHeaderHash.empty()) {
return nullptr;
}
DB &db = DB::Instance();
BlockHeader* blockHeader = new BlockHeader();
if(db.deserializeFromDb(DB_BLOCK_HEADERS, blockHeaderHash, *blockHeader)) {
return blockHeader;
}
delete blockHeader;
return nullptr;
}
BlockHeader* Chain::getBlockHeader(uint64_t height) {
DB &db = DB::Instance();
std::vector<unsigned char> blockHeaderHash = db.getFromDB(DB_BLOCK_HEADERS, height);
if(!blockHeaderHash.empty()) {
return this->getBlockHeader(blockHeaderHash);
}
return nullptr;
}
bool Chain::doesBlockExist(uint64_t height) {
DB &db = DB::Instance();
std::vector<unsigned char> blockHeaderHash = db.getFromDB(DB_BLOCK_HEADERS, height);
return !blockHeaderHash.empty();
}
bool Chain::doesBlockExist(std::vector<unsigned char> blockHeaderHash) {
DB &db = DB::Instance();
return db.isInDB(DB_BLOCK_HEADERS, blockHeaderHash);
}
uint32_t Chain::getCurrentBlockchainHeight() {
return this->bestBlockHeight;
}
void Chain::setCurrentBlockchainHeight(uint32_t bestHeight) {
this->bestBlockHeight = bestHeight;
}
void Chain::setBestBlockHeaders(std::vector<BlockHeader> newBestBlocks) {
this->bestBlocks = newBestBlocks;
}
std::vector<BlockHeader> Chain::getBestBlockHeaders() {
return this->bestBlocks;
}
BlockHeader* Chain::getBestBlockHeader() {
if(this->bestBlocks.size() == 0) {
return nullptr;
}
return &this->bestBlocks[0];
}
void Chain::insertBlockHeader(BlockHeader blockHeader) {
DB &db = DB::Instance();
db.serializeToDb(DB_BLOCK_HEADERS, blockHeader.getHeaderHash(), blockHeader);
}