forked from etotheipi/BitcoinArmory
-
Notifications
You must be signed in to change notification settings - Fork 170
/
BDM_supportClasses.h
633 lines (489 loc) · 17.1 KB
/
BDM_supportClasses.h
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
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
////////////////////////////////////////////////////////////////////////////////
// //
// Copyright (C) 2011-2015, Armory Technologies, Inc. //
// Distributed under the GNU Affero General Public License (AGPL v3) //
// See LICENSE-ATI or http://www.gnu.org/licenses/agpl.html //
// //
// //
// Copyright (C) 2016, goatpig //
// Distributed under the MIT license //
// See LICENSE-MIT or https://opensource.org/licenses/MIT //
// //
////////////////////////////////////////////////////////////////////////////////
#ifndef _BDM_SUPPORTCLASSES_H_
#define _BDM_SUPPORTCLASSES_H_
#include <vector>
#include <atomic>
#include <functional>
#include <memory>
#include "ThreadSafeClasses.h"
#include "BitcoinP2p.h"
#include "BinaryData.h"
#include "ScrAddrObj.h"
#include "BtcWallet.h"
#define GETZC_THREADCOUNT 5
enum ZcAction
{
Zc_NewTx,
Zc_Purge,
Zc_Shutdown
};
class ZeroConfContainer;
struct ZeroConfData
{
Tx txobj_;
uint32_t txtime_;
bool operator==(const ZeroConfData& rhs) const
{
return (this->txobj_ == rhs.txobj_) && (this->txtime_ == rhs.txtime_);
}
};
class ScrAddrFilter
{
/***
This class keeps track of all registered scrAddr to be scanned by the DB.
If the DB isn't running in supernode, this class also acts as a helper to
filter transactions, which is required in order to save only relevant ssh
The transaction filter isn't exact however. It gets more efficient as it
encounters more UTxO.
The basic principle of the filter is that it expect to have a complete
list of UTxO's starting a given height, usually where the DB picked up
at initial load. It can then guarantee a TxIn isn't spending a tracked
UTxO by checking the UTxO DBkey instead of fetching the entire stored TxOut.
If the DBkey carries a height lower than the cut off, the filter will
fail to give a definitive answer, in which case the TxOut script will be
pulled from the DB, using the DBkey, as it would have otherwise.
Registering addresses while the BDM isn't initialized will return instantly
Otherwise, the following steps are taken:
1) Check ssh entries in the DB for this scrAddr. If there is none, this
DB never saw this address (full/lite node). Else mark the top scanned block.
-- Non supernode operations --
2.a) If the address is new, create an empty ssh header for that scrAddr
in the DB, marked at the current top height
2.b) If the address isn't new, scan it from its last seen block, or its
block creation, or 0 if none of the above is available. This will create
the ssh entries for the address, which will have the current top height as
its scanned height.
--
3) Add address to scrAddrMap_
4) Signal the wallet that the address is ready. Wallet object will take it
up from there.
***/
friend class BlockDataViewer;
public:
struct WalletInfo
{
static atomic<unsigned> idCounter_; //no need to init this
function<void(bool)> callback_;
set<BinaryData> scrAddrSet_;
string ID_;
const unsigned intID_;
WalletInfo(void) :
intID_(idCounter_.fetch_add(1, memory_order_relaxed))
{}
bool operator<(const ScrAddrFilter::WalletInfo& rhs) const
{
return intID_ < rhs.intID_;
}
};
struct ScrAddrSideScanData
{
int32_t startScanFrom_= -1;
vector<shared_ptr<WalletInfo>> wltInfoVec_;
bool doScan_ = true;
unsigned uniqueID_ = UINT32_MAX;
BinaryData lastScannedBlkHash_;
ScrAddrSideScanData(void) {}
ScrAddrSideScanData(uint32_t height) :
startScanFrom_(height) {}
vector<string> getWalletIDString(void)
{
vector<string> strVec;
for (auto& wltInfo : wltInfoVec_)
{
if (wltInfo->ID_.size() == 0)
continue;
strVec.push_back(wltInfo->ID_);
}
return strVec;
}
};
struct AddrSyncState
{
private:
mutable BinaryData addrHash_;
public:
const BinaryData scrAddr_;
int32_t syncHeight_ = -1;
public:
AddrSyncState(const BinaryData& addr) :
scrAddr_(addr)
{}
AddrSyncState(const BinaryDataRef& addrref) :
scrAddr_(addrref)
{}
const BinaryData& getHash(void) const
{
if (addrHash_.getSize() == 0)
addrHash_ = move(BtcUtils::getHash256(scrAddr_));
return addrHash_;
}
bool operator<(const AddrSyncState& rhs) const
{
return this->scrAddr_ < rhs.scrAddr_;
}
bool operator<(const BinaryDataRef& rhs) const
{
return this->scrAddr_.getRef() < rhs;
}
};
public:
mutex mergeLock_;
BinaryData lastScannedHash_;
const ARMORY_DB_TYPE armoryDbType_;
private:
static atomic<unsigned> keyCounter_;
static atomic<bool> run_;
//TODO: avoid std::set, results in too many implicit copies on searches
shared_ptr<set<AddrSyncState>> scrAddrSet_;
LMDBBlockDatabase *const lmdb_;
const unsigned uniqueKey_;
//
ScrAddrFilter* parent_;
ScrAddrSideScanData scrAddrDataForSideScan_;
//false: dont scan
//true: wipe existing ssh then scan
bool isScanning_ = false;
Pile<ScrAddrSideScanData> scanDataPile_;
set<shared_ptr<WalletInfo>> scanningAddresses_;
private:
void setScrAddrLastScanned(const BinaryData& scrAddr, int32_t blkHgt)
{
auto scrAddrIter = scrAddrSet_->find(scrAddr);
if (scrAddrIter != scrAddrSet_->end())
{
auto& sa = (AddrSyncState&)*scrAddrIter;
sa.syncHeight_ = blkHgt;
}
}
static void cleanUpPreviousChildren(LMDBBlockDatabase* lmdb);
protected:
function<void(const vector<string>& wltIDs, double prog, unsigned time)>
scanThreadProgressCallback_;
static unsigned getUniqueKey(void)
{
return keyCounter_.fetch_add(1, memory_order_relaxed);
}
public:
static void init(void);
ScrAddrFilter(LMDBBlockDatabase* lmdb, ARMORY_DB_TYPE armoryDbType)
: lmdb_(lmdb), armoryDbType_(armoryDbType),
uniqueKey_(getUniqueKey())
{
//make sure we are running off of a clean SDBI set when instantiating the first
//SAF object (held by the BDM object)
if (uniqueKey_ == 0)
cleanUpPreviousChildren(lmdb);
scrAddrSet_ = make_shared<set<AddrSyncState>>();
scanThreadProgressCallback_ =
[](const vector<string>&, double, unsigned)->void {};
}
ScrAddrFilter(const ScrAddrFilter& sca) //copy constructor
: lmdb_(sca.lmdb_), armoryDbType_(sca.armoryDbType_),
uniqueKey_(getUniqueKey()) //even copies' keys are unique
{}
virtual ~ScrAddrFilter() { }
LMDBBlockDatabase* lmdb() { return lmdb_; }
const shared_ptr<set<AddrSyncState>>& getScrAddrSet(void) const
{
if (!run_.load(memory_order_relaxed))
{
LOGERR << "ScrAddrFilter flagged for termination";
throw runtime_error("ScrAddrFilter flagged for termination");
}
return scrAddrSet_;
}
map<TxOutScriptRef, int> getOutScrRefMap(void)
{
getScrAddrCurrentSyncState();
map<TxOutScriptRef, int> outset;
auto scrAddrSet = scrAddrSet_;
for (auto& scrAddr : *scrAddrSet_)
{
TxOutScriptRef scrRef;
scrRef.setRef(scrAddr.scrAddr_);
outset.insert(move(make_pair(scrRef, scrAddr.syncHeight_)));
}
return outset;
}
size_t numScrAddr(void) const
{ return scrAddrSet_->size(); }
int32_t scanFrom(void) const;
bool registerAddresses(const set<BinaryData>&, string, bool,
function<void(bool)>);
bool registerAddressBatch(
vector<shared_ptr<WalletInfo>>&& wltInfoVec, bool areNew);
void clear(void);
void getScrAddrCurrentSyncState();
void getScrAddrCurrentSyncState(BinaryData const & scrAddr);
void setSSHLastScanned(uint32_t height);
void regScrAddrForScan(const BinaryData& scrAddr, uint32_t scanFrom)
{
auto addrIter = scrAddrSet_->find(scrAddr);
if (addrIter == scrAddrSet_->end())
{
AddrSyncState acs(scrAddr);
acs.syncHeight_ = scanFrom;
scrAddrSet_->insert(move(acs));
return;
}
auto& acsRef = (AddrSyncState&)*addrIter;
acsRef.syncHeight_ = scanFrom;
}
static void scanFilterInNewThread(shared_ptr<ScrAddrFilter> sca);
//pointer to the SAF object held by the bdm
void setParent(ScrAddrFilter* sca) { parent_ = sca; }
void addToMergePile(const BinaryData& lastScannedBlkHash);
void mergeSideScanPile(void);
void getAllScrAddrInDB(void);
void putAddrMapInDB(void);
BinaryData getAddressMapMerkle(void) const;
bool hasNewAddresses(void) const;
void updateAddressMerkleInDB(void);
StoredDBInfo getSubSshSDBI(void) const;
void putSubSshSDBI(const StoredDBInfo&);
StoredDBInfo getSshSDBI(void) const;
void putSshSDBI(const StoredDBInfo&);
set<BinaryData> getMissingHashes(void) const;
void putMissingHashes(const set<BinaryData>&);
static void shutdown(void)
{
run_.store(false, memory_order_relaxed);
}
public:
virtual shared_ptr<ScrAddrFilter> copy()=0;
protected:
virtual bool bdmIsRunning() const=0;
virtual BinaryData applyBlockRangeToDB(
uint32_t startBlock, uint32_t endBlock, const vector<string>& wltIDs
)=0;
virtual uint32_t currentTopBlockHeight() const=0;
virtual void wipeScrAddrsSSH(const vector<BinaryData>& saVec) = 0;
virtual shared_ptr<Blockchain> blockchain(void) = 0;
virtual BlockDataManagerConfig config(void) = 0;
private:
void scanScrAddrThread(void);
void buildSideScanData(
const vector<shared_ptr<WalletInfo>>& wltInfoSet, bool areNew);
};
////////////////////////////////////////////////////////////////////////////////
class ZeroConfContainer
{
private:
struct BulkFilterData
{
map<BinaryData, shared_ptr<map<BinaryData, TxIOPair>>> scrAddrTxioMap_;
map<BinaryData, map<unsigned, BinaryData>> outPointsSpentByKey_;
set<BinaryData> txOutsSpentByZC_;
map<BinaryData, set<BinaryData>> keyToSpentScrAddr_;
map<BinaryData, set<BinaryData>> keyToFundedScrAddr_;
map<string, set<BinaryData>> flaggedBDVs_;
bool isEmpty(void) { return scrAddrTxioMap_.size() == 0; }
};
public:
struct BDV_Callbacks
{
function<void(
map<BinaryData, shared_ptr<map<BinaryData, TxIOPair>>>
)> newZcCallback_;
function<bool(const BinaryData&)> addressFilter_;
function<void(string&, string&)> zcErrorCallback_;
};
struct ZcActionStruct
{
ZcAction action_;
map<BinaryData, Tx> zcMap_;
shared_ptr<promise<bool>> finishedPromise_ = nullptr;
void setData(map<BinaryData, Tx> zcmap)
{
zcMap_ = move(zcmap);
}
};
private:
TransactionalMap<HashString, HashString> txHashToDBKey_; //<txHash, dbKey>
TransactionalMap<HashString, Tx> txMap_; //<zcKey, zcTx>
TransactionalSet<HashString> txOutsSpentByZC_; //<txOutDbKeys>
set<HashString> allZcTxHashes_;
map<BinaryData, map<unsigned, BinaryData>> outPointsSpentByKey_; //<txHash, map<opId, ZcKeys>>
//<scrAddr, <dbKeyOfOutput, TxIOPair>>
TransactionalMap<BinaryData, shared_ptr<map<BinaryData, TxIOPair>>> txioMap_;
//<zcKey, vector<ScrAddr>>
TransactionalMap<HashString, set<HashString>> keyToSpentScrAddr_;
map<BinaryData, set<BinaryData>> keyToFundedScrAddr_;
BinaryData lastParsedBlockHash_;
std::atomic<uint32_t> topId_;
LMDBBlockDatabase* db_;
static map<BinaryData, TxIOPair> emptyTxioMap_;
bool enabled_ = false;
set<BinaryData> emptySetBinData_;
//stacks inv tx packets from node
shared_ptr<BitcoinP2P> networkNode_;
Stack<promise<InvEntry>> newInvTxStack_;
TransactionalMap<string, BDV_Callbacks> bdvCallbacks_;
function<shared_ptr<set<ScrAddrFilter::AddrSyncState>>(void)> getMainAddressSet_;
mutex parserMutex_;
Stack<thread> parserThreads_;
atomic<bool> zcEnabled_;
private:
BulkFilterData ZCisMineBulkFilter(const Tx & tx,
const BinaryData& ZCkey,
uint32_t txtime,
function<bool(const BinaryData&, BinaryData&)> getzckeyfortxhash,
function<const Tx&(const BinaryData&)> getzctxbykey);
void loadZeroConfMempool(bool clearMempool);
set<BinaryData> purge(void);
void processInvTxThread(void);
bool processInvTxThread(InvEntry);
public:
//stacks new zc Tx objects from node
BinaryData getNewZCkey(void);
BlockingStack<ZcActionStruct> newZcStack_;
public:
ZeroConfContainer(LMDBBlockDatabase* db,
shared_ptr<BitcoinP2P> node) :
topId_(0), db_(db),
networkNode_(node)
{
zcEnabled_.store(false, memory_order_relaxed);
//register ZC callback
auto processInvTx = [this](vector<InvEntry> entryVec)->void
{
this->processInvTxVec(entryVec);
};
networkNode_->registerInvTxLambda(processInvTx);
}
bool hasTxByHash(const BinaryData& txHash) const;
Tx getTxByHash(const BinaryData& txHash) const;
shared_ptr<map<BinaryData, shared_ptr<map<BinaryData, TxIOPair>>>>
getFullTxioMap(void) const { return txioMap_.get(); }
void dropZC(const set<BinaryData>& txHashes);
void parseNewZC(void);
void parseNewZC(map<BinaryData, Tx> zcMap, bool updateDB, bool notify);
bool isTxOutSpentByZC(const BinaryData& dbKey) const;
void clear(void);
map<BinaryData, TxIOPair> getUnspentZCforScrAddr(BinaryData scrAddr) const;
map<BinaryData, TxIOPair> getRBFTxIOsforScrAddr(BinaryData scrAddr) const;
vector<TxOut> getZcTxOutsForKey(const set<BinaryData>&) const;
const set<BinaryData>& getSpentSAforZCKey(const BinaryData& zcKey) const;
const shared_ptr<map<BinaryData, set<HashString>>> getKeyToSpentScrAddrMap(void) const;
void updateZCinDB(
const vector<BinaryData>& keysToWrite, const vector<BinaryData>& keysToDel);
void processInvTxVec(vector<InvEntry>, bool extend = true);
void init(function<shared_ptr<set<ScrAddrFilter::AddrSyncState>>(void)>,
bool clearMempool);
void shutdown();
void insertBDVcallback(string, BDV_Callbacks);
void eraseBDVcallback(string);
void broadcastZC(const BinaryData& rawzc,
const string& bdvId, uint32_t timeout_sec = 5);
bool isEnabled(void) const { return zcEnabled_.load(memory_order_relaxed); }
};
//////
struct BDV_Notification
{
virtual ~BDV_Notification(void)
{}
virtual BDV_Action action_type(void) = 0;
};
struct BDV_Notification_Init : public BDV_Notification
{
BDV_Notification_Init(void)
{}
BDV_Action action_type(void)
{
return BDV_Init;
}
};
struct BDV_Notification_NewBlock : public BDV_Notification
{
Blockchain::ReorganizationState reorgState_;
BDV_Notification_NewBlock(
const Blockchain::ReorganizationState& ref) :
reorgState_(ref)
{}
BDV_Action action_type(void)
{
return BDV_NewBlock;
}
};
struct BDV_Notification_ZC : public BDV_Notification
{
typedef map<BinaryData, shared_ptr<map<BinaryData, TxIOPair>>> zcMapType;
zcMapType scrAddrZcMap_;
map<BinaryData, LedgerEntry> leMap_;
BDV_Notification_ZC(zcMapType&& mv) :
scrAddrZcMap_(move(mv))
{}
BDV_Action action_type(void)
{
return BDV_ZC;
}
};
struct BDV_Notification_Refresh : public BDV_Notification
{
const BDV_refresh refresh_;
const BinaryData refreshID_;
BDV_Notification_Refresh(
BDV_refresh refresh, const BinaryData& refreshID) :
refresh_(refresh), refreshID_(refreshID)
{}
BDV_Action action_type(void)
{
return BDV_Refresh;
}
};
struct BDV_Notification_Progress : public BDV_Notification
{
BDMPhase phase_;
double progress_;
unsigned time_;
unsigned numericProgress_;
const vector<string> walletIDs_;
BDV_Notification_Progress(BDMPhase phase, double prog,
unsigned time, unsigned numProg, const vector<string>& walletIDs) :
phase_(phase), progress_(prog), time_(time),
numericProgress_(numProg), walletIDs_(walletIDs)
{}
BDV_Action action_type(void)
{
return BDV_Progress;
}
};
struct BDV_Notification_NodeStatus : public BDV_Notification
{
const NodeStatusStruct status_;
BDV_Notification_NodeStatus(NodeStatusStruct nss) :
status_(nss)
{}
BDV_Action action_type(void)
{
return BDV_NodeStatus;
}
};
struct BDV_Notification_Error : public BDV_Notification
{
BDV_Error_Struct errStruct;
BDV_Notification_Error(
BDV_ErrorType errt, string errstr, string extra)
{
errStruct.errType_ = errt;
errStruct.errorStr_ = errstr;
errStruct.extraMsg_ = extra;
}
BDV_Action action_type(void)
{
return BDV_Error;
}
};
#endif
// kate: indent-width 3; replace-tabs on;