forked from etotheipi/BitcoinArmory
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBDM_mainthread.cpp
More file actions
452 lines (371 loc) · 11.7 KB
/
BDM_mainthread.cpp
File metadata and controls
452 lines (371 loc) · 11.7 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
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
////////////////////////////////////////////////////////////////////////////////
// //
// Copyright (C) 2011-2015, Armory Technologies, Inc. //
// Distributed under the GNU Affero General Public License (AGPL v3) //
// See LICENSE or http://www.gnu.org/licenses/agpl.html //
// //
////////////////////////////////////////////////////////////////////////////////
#include "BDM_mainthread.h"
#include "BlockUtils.h"
#include "BlockDataViewer.h"
#include <ctime>
#include <unistd.h>
#include "pthread.h"
BDM_CallBack::~BDM_CallBack()
{}
struct BDM_Inject::BDM_Inject_Impl
{
pthread_mutex_t notifierLock;
pthread_cond_t notifier;
bool wantsToRun=false, failure=false;
};
BDM_Inject::BDM_Inject()
{
pimpl = new BDM_Inject_Impl;
pthread_mutex_init(&pimpl->notifierLock, 0);
pthread_cond_init(&pimpl->notifier, 0);
}
BDM_Inject::~BDM_Inject()
{
pthread_mutex_destroy(&pimpl->notifierLock);
pthread_cond_destroy(&pimpl->notifier);
delete pimpl;
}
void BDM_Inject::notify()
{
pthread_mutex_lock(&pimpl->notifierLock);
pimpl->wantsToRun=true;
pthread_cond_signal(&pimpl->notifier);
pthread_mutex_unlock(&pimpl->notifierLock);
}
void BDM_Inject::wait(unsigned ms)
{
#ifdef _WIN32_
ULONGLONG abstime = GetTickCount64();
abstime += ms;
pthread_mutex_lock(&pimpl->notifierLock);
while (!pimpl->wantsToRun)
{
pthread_cond_timedwait(&pimpl->notifier, &pimpl->notifierLock, &abstime);
ULONGLONG latertime = GetTickCount64();
if (latertime >= abstime)
break;
}
if (pimpl->wantsToRun)
run();
pimpl->wantsToRun=false;
pthread_cond_signal(&pimpl->notifier);
pthread_mutex_unlock(&pimpl->notifierLock);
#else
struct timeval abstime;
gettimeofday(&abstime, 0);
abstime.tv_sec += ms/1000;
pthread_mutex_lock(&pimpl->notifierLock);
while (!pimpl->wantsToRun)
{
struct timespec abstimets;
abstimets.tv_sec = abstime.tv_sec;
abstimets.tv_nsec = abstime.tv_usec*1000;
pthread_cond_timedwait(&pimpl->notifier, &pimpl->notifierLock, &abstimets);
struct timeval latertime;
gettimeofday(&latertime, 0);
if (latertime.tv_sec >= abstime.tv_sec && latertime.tv_usec >= abstime.tv_usec)
break;
}
if (pimpl->wantsToRun)
run();
pimpl->wantsToRun=false;
pthread_cond_signal(&pimpl->notifier);
pthread_mutex_unlock(&pimpl->notifierLock);
#endif
}
void BDM_Inject::waitRun()
{
pthread_mutex_lock(&pimpl->notifierLock);
while (pimpl->wantsToRun)
{
pthread_cond_wait(&pimpl->notifier, &pimpl->notifierLock);
}
const bool f = pimpl->failure;
pthread_mutex_unlock(&pimpl->notifierLock);
if (f)
throw BDMFailure();
}
void BDM_Inject::setFailureFlag()
{
pimpl->failure = true;
}
struct BlockDataManagerThread::BlockDataManagerThreadImpl
{
BlockDataManager_LevelDB *bdm=nullptr;
BlockDataViewer *bdv = nullptr;
BDM_CallBack *callback=nullptr;
BDM_Inject *inject=nullptr;
pthread_t tID=0;
int mode=0;
volatile bool run=false;
bool failure=false;
~BlockDataManagerThreadImpl()
{
delete bdm;
delete bdv;
}
};
BlockDataManagerThread::BlockDataManagerThread(const BlockDataManagerConfig &config)
{
pimpl = new BlockDataManagerThreadImpl;
pimpl->bdm = new BlockDataManager_LevelDB(config);
pimpl->bdv = new BlockDataViewer(pimpl->bdm);
}
BlockDataManagerThread::~BlockDataManagerThread()
{
if (pimpl->run)
{
LOGERR << "Destroying BlockDataManagerThread without shutting down first";
}
else
{
delete pimpl;
}
}
void BlockDataManagerThread::start(int mode, BDM_CallBack *callback, BDM_Inject *inject)
{
pimpl->callback = callback;
pimpl->inject = inject;
pimpl->mode = mode;
pimpl->run = true;
if (0 != pthread_create(&pimpl->tID, nullptr, thrun, this))
throw std::runtime_error("Failed to start BDM thread");
}
BlockDataManager_LevelDB *BlockDataManagerThread::bdm()
{
return pimpl->bdm;
}
BlockDataViewer* BlockDataManagerThread::bdv()
{
return pimpl->bdv;
}
void BlockDataManagerThread::setConfig(const BlockDataManagerConfig &config)
{
pimpl->bdm->setConfig(config);
}
// stop the BDM thread
void BlockDataManagerThread::shutdownAndWait()
{
requestShutdown();
if (pimpl->tID)
{
pthread_join(pimpl->tID, nullptr);
pimpl->tID=0;
}
}
bool BlockDataManagerThread::requestShutdown()
{
if (pimpl->run)
{
pimpl->run = false;
pimpl->inject->notify();
return true;
}
return false;
}
namespace
{
class OnFinish
{
const function<void()> fn;
public:
OnFinish(const function<void()> &fn)
: fn(fn) { }
~OnFinish()
{
fn();
}
};
}
void BlockDataManagerThread::run()
try
{
BlockDataManager_LevelDB *const bdm = this->bdm();
BlockDataViewer *const bdv = this->bdv();
BDM_CallBack *const callback = pimpl->callback;
OnFinish onFinish(
[callback] () { callback->run(BDMAction_Exited, nullptr); }
);
{
tuple<BDMPhase, double, unsigned, unsigned> lastvalues;
time_t lastProgressTime=0;
class BDMStopRequest
{
public:
virtual ~BDMStopRequest() { }
};
const auto loadProgress
= [&] (BDMPhase phase, double prog,unsigned time, unsigned numericProgress)
{
const tuple<BDMPhase, double, unsigned, unsigned> currentvalues
{ phase, prog, time, numericProgress };
if (currentvalues == lastvalues)
return; // don't go to python if nothing's changed
// also, don't go to the python if the phase is the same and it's been
// less than 1 second since the last time this has been called
// python is a lot slower than C++, so we don't want to invoke
// the python interpreter to frequently
const time_t currentProgressTime = std::time(nullptr);
if (phase == get<0>(lastvalues)
&& currentProgressTime <= lastProgressTime+1
&& fabs(get<1>(lastvalues)-get<1>(currentvalues)) <= .01 )
return;
lastProgressTime = currentProgressTime;
lastvalues = currentvalues;
//pass empty walletID for main build&scan calls
callback->progress(phase, vector<string>(), prog, time, numericProgress);
if (!pimpl->run)
{
LOGINFO << "Stop requested detected";
throw BDMStopRequest();
}
};
try
{
//don't call this unless you're trying to get online
pimpl->bdm->setNotifier(pimpl->inject);
bdm->openDatabase();
unsigned mode = pimpl->mode & 0x00000003;
bool clearZc = pimpl->mode & 0x00000004;
if (mode == 0) bdm->doInitialSyncOnLoad(loadProgress);
else if (mode == 1) bdm->doInitialSyncOnLoad_Rescan(loadProgress);
else if (mode == 2) bdm->doInitialSyncOnLoad_Rebuild(loadProgress);
if (bdm->missingBlockHashes().size() || bdm->missingBlockHeaderHashes().size())
{
string errorMsg(
"Armory has detected an error in the blockchain database "
"maintained by the third-party Bitcoin software (Bitcoin-Qt "
"or bitcoind). This error is not fatal, but may lead to "
"incorrect balances, inability to send coins, or application "
"instability."
"<br><br> "
"It is unlikely that the error affects your wallets, "
"but it <i>is</i> possible. If you experience crashing, "
"or see incorrect balances on any wallets, it is strongly "
"recommended you re-download the blockchain using: "
"<i>Help</i>\"\xe2\x86\x92\"<i>Factory Reset</i>\".");
callback->run(BDMAction_ErrorMsg, &errorMsg, bdm->missingBlockHashes().size());
throw;
}
bdv->enableZeroConf(clearZc);
bdv->scanWallets();
}
catch (BDMStopRequest&)
{
LOGINFO << "UI asked build/scan thread to finish";
return;
}
}
double lastprog=0;
unsigned lasttime=0;
const auto rescanProgress
= [&] (const vector<string>& wltIdVec, double prog,unsigned time)
{
if (prog == lastprog && time==lasttime)
return; // don't go to python if nothing's changed
//callback->progress("blk", prog, time);
lastprog = prog;
lasttime = time;
callback->progress(
BDMPhase_Rescan,
wltIdVec,
lastprog, lasttime, 0
);
};
//push 'bdm is ready' to Python
callback->run(BDMAction_Ready, nullptr, bdm->getTopBlockHeight());
while(pimpl->run)
{
bdm->getScrAddrFilter()->checkForMerge();
if (bdm->sideScanFlag_ == true)
{
bdm->sideScanFlag_ = false;
bool doScan = bdm->startSideScan(rescanProgress);
vector<string> wltIDs = bdm->getNextWalletIDToScan();
if (wltIDs.size() && doScan)
{
callback->run(BDMAction_StartedWalletScan, &wltIDs);
}
}
if (bdm->criticalError_.size())
{
throw runtime_error(bdm->criticalError_.c_str());
}
if(bdv->getZCflag())
{
bdv->flagRescanZC(false);
if (bdv->parseNewZeroConfTx() == true)
{
set<BinaryData> newZCTxHash = bdv->getNewZCTxHash();
bdv->scanWallets();
vector<LedgerEntry> newZCLedgers;
for (const auto& txHash : newZCTxHash)
{
auto& le_w = bdv->getTxLedgerByHash_FromWallets(txHash);
if (le_w.getTxTime() != 0)
newZCLedgers.push_back(le_w);
auto& le_lb = bdv->getTxLedgerByHash_FromLockboxes(txHash);
if (le_lb.getTxTime() != 0)
newZCLedgers.push_back(le_lb);
}
LOGINFO << newZCLedgers.size() << " new ZC Txn";
//notify ZC
callback->run(BDMAction_ZC, &newZCLedgers);
}
}
if (bdv->refresh_ != BDV_dontRefresh)
{
unique_lock<mutex> lock(bdv->refreshLock_);
BDV_refresh refresh = bdv->refresh_;
bdv->refresh_ = BDV_dontRefresh;
bdv->scanWallets(UINT32_MAX, UINT32_MAX, refresh);
vector<BinaryData> refreshIDVec;
for (const auto& refreshID : bdv->refreshIDSet_)
refreshIDVec.push_back(refreshID);
bdv->refreshIDSet_.clear();
callback->run(BDMAction_Refresh, &refreshIDVec);
}
const uint32_t prevTopBlk = bdm->readBlkFileUpdate();
if(prevTopBlk > 0)
{
bdv->scanWallets(prevTopBlk);
//notify Python that new blocks have been parsed
int nNewBlocks = bdm->blockchain().top().getBlockHeight() + 1
- prevTopBlk;
callback->run(BDMAction_NewBlock, &nNewBlocks,
bdm->getTopBlockHeight()
);
}
#ifndef _DEBUG_REPLAY_BLOCKS
pimpl->inject->wait(1000);
#endif
}
}
catch (std::exception &e)
{
LOGERR << "BDM thread failed: " << e.what();
string errstr(e.what());
pimpl->callback->run(BDMAction_ErrorMsg, &errstr);
pimpl->inject->setFailureFlag();
pimpl->inject->notify();
}
catch (...)
{
LOGERR << "BDM thread failed: (unknown exception)";
pimpl->inject->setFailureFlag();
pimpl->inject->notify();
}
void* BlockDataManagerThread::thrun(void *_self)
{
BlockDataManagerThread *const self
= static_cast<BlockDataManagerThread*>(_self);
self->run();
return 0;
}
// kate: indent-width 3; replace-tabs on;