-
Notifications
You must be signed in to change notification settings - Fork 617
/
ScrAddrObj.cpp
563 lines (459 loc) · 17.4 KB
/
ScrAddrObj.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
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
////////////////////////////////////////////////////////////////////////////////
// //
// 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 "ScrAddrObj.h"
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
//
// ScrAddrObj Methods
//
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
ScrAddrObj::ScrAddrObj(LMDBBlockDatabase *db, Blockchain *bc,
HashString addr,
uint32_t firstBlockNum,
uint32_t firstTimestamp,
uint32_t lastBlockNum,
uint32_t lastTimestamp) :
db_(db),
bc_(bc),
scrAddr_(addr),
firstBlockNum_(firstBlockNum),
firstTimestamp_(firstTimestamp),
lastBlockNum_(lastBlockNum),
lastTimestamp_(lastTimestamp),
utxos_(this)
{
relevantTxIO_.clear();
}
////////////////////////////////////////////////////////////////////////////////
uint64_t ScrAddrObj::getSpendableBalance(
uint32_t currBlk, bool ignoreAllZC
) const
{
//ignoreing the currBlk for now, until the partial history loading is solid
uint64_t balance = getFullBalance();
for (auto txio : relevantTxIO_)
{
if (!txio.second.hasTxIn() &&
!txio.second.isSpendable(db_, currBlk, ignoreAllZC))
balance -= txio.second.getValue();
}
return balance;
}
////////////////////////////////////////////////////////////////////////////////
uint64_t ScrAddrObj::getUnconfirmedBalance(
uint32_t currBlk, bool inclAllZC
) const
{
/***may need some help with the paging system in place***/
if (!db_->isReady())
throw runtime_error("DB isnt ready");
uint64_t balance = 0;
for (auto txio : relevantTxIO_)
{
if(txio.second.isMineButUnconfirmed(db_, currBlk, inclAllZC))
balance += txio.second.getValue();
}
return balance;
}
////////////////////////////////////////////////////////////////////////////////
uint64_t ScrAddrObj::getFullBalance() const
{
if (!db_->isReady())
throw runtime_error("DB isnt ready");
StoredScriptHistory ssh;
db_->getStoredScriptHistorySummary(ssh, scrAddr_);
uint64_t balance = ssh.getScriptBalance(false);
for (auto txio : relevantTxIO_)
{
if (txio.second.hasTxOutZC())
balance += txio.second.getValue();
if (txio.second.hasTxInZC())
balance -= txio.second.getValue();
}
return balance;
}
////////////////////////////////////////////////////////////////////////////////
void ScrAddrObj::addTxIO(TxIOPair& txio, bool isZeroConf)
{
relevantTxIO_[txio.getDBKeyOfOutput()] = txio;
}
////////////////////////////////////////////////////////////////////////////////
void ScrAddrObj::pprintLedger() const
{
cout << "Address Ledger: " << getScrAddr().toHexStr() << endl;
for(const auto ledger : *ledger_)
ledger.second.pprintOneLine();
}
////////////////////////////////////////////////////////////////////////////////
void ScrAddrObj::clearBlkData(void)
{
relevantTxIO_.clear();
hist_.reset();
ledger_ = &LedgerEntry::EmptyLedgerMap_;
totalTxioCount_ = 0;
}
////////////////////////////////////////////////////////////////////////////////
void ScrAddrObj::updateTxIOMap(map<BinaryData, TxIOPair>& txio_map)
{
for (auto txio : txio_map)
relevantTxIO_[txio.first] = txio.second;
}
////////////////////////////////////////////////////////////////////////////////
void ScrAddrObj::scanZC(const map<HashString, TxIOPair>& zcTxIOMap,
function<bool(const BinaryData&)> isZcFromWallet)
{
//Dont use a reference for this loop. We check and set the isFromSelf flag
//in this operation, which is based on the wallet this scrAddr belongs to.
//The txio comes straight from the ZC container object, which only deals
//with scrAddr. Since several wallets may reference the same scrAddr, we
//can't modify original txio, so we use a copy.
for (auto txioPair : zcTxIOMap)
{
if (txioPair.second.hasTxOutZC() &&
isZcFromWallet(txioPair.second.getDBKeyOfOutput().getSliceCopy(0, 6)))
txioPair.second.setTxOutFromSelf(true);
txioPair.second.setScrAddrLambda(
[this](void)->const BinaryData&{ return this->getScrAddr(); });
relevantTxIO_[txioPair.first] = txioPair.second;
}
updateLedgers(*ledger_, zcTxIOMap, 0, UINT32_MAX, false);
}
////////////////////////////////////////////////////////////////////////////////
void ScrAddrObj::purgeZC(const vector<BinaryData>& invalidatedTxOutKeys)
{
for (auto zc : invalidatedTxOutKeys)
{
auto txioIter = relevantTxIO_.find(zc);
if (ITER_IN_MAP(txioIter, relevantTxIO_))
{
TxIOPair& txio = txioIter->second;
if (txio.hasTxInZC())
{
//since the txio has a ZC txin, there is a scrAddr ledger entry for that key
ledger_->erase(txio.getTxRefOfInput().getDBKey());
txio.setTxIn(BinaryData(0));
txio.setTxHashOfInput(BinaryData(0));
}
if (txio.hasTxOutZC())
{
//purged ZC chain, remove the TxIO
relevantTxIO_.erase(txioIter);
ledger_->erase(zc.getSliceRef(0, 6));
}
}
}
}
////////////////////////////////////////////////////////////////////////////////
void ScrAddrObj::updateAfterReorg(uint32_t lastValidBlockHeight)
{
auto txioIter = relevantTxIO_.begin();
uint32_t height;
while (txioIter != relevantTxIO_.end())
{
//txio pairs are saved by TxOut DBkey, if the key points to a block
//higher than the reorg point, delete the txio
height = DBUtils::hgtxToHeight(txioIter->first.getSliceCopy(0, 4));
if (height >= 0xFF000000)
{
//ZC chain, already dealt with by the call to purgeZC from
//readBlkFileUpdate
continue;
}
else if (height <= lastValidBlockHeight)
{
TxIOPair& txio = txioIter->second;
if (txio.hasTxIn())
{
//if the txio is spent, check the block of the txin
height = DBUtils::hgtxToHeight(
txio.getDBKeyOfInput().getSliceCopy(0, 4));
if (height > lastValidBlockHeight && height < 0xFF000000)
{
//clear the TxIn by setting it to an empty BinaryData
txio.setTxIn(BinaryData(0));
txio.setTxHashOfInput(BinaryData(0));
}
}
++txioIter;
}
else
relevantTxIO_.erase(txioIter++);
}
//clean up ledgers
BinaryData cutOffHghtX = DBUtils::heightAndDupToHgtx(lastValidBlockHeight + 1, 0);
uint16_t zero = 0;
cutOffHghtX.append((uint8_t*)&zero, 2);
auto leRange = ledger_->equal_range(cutOffHghtX);
ledger_->erase(leRange.first, ledger_->end());
}
////////////////////////////////////////////////////////////////////////////////
void ScrAddrObj::updateLedgers(map<BinaryData, LedgerEntry>& leMap,
const map<BinaryData, TxIOPair>& txioMap,
uint32_t startBlock, uint32_t endBlock,
bool purge) const
{
LedgerEntry::computeLedgerMap(leMap, txioMap, startBlock, endBlock,
scrAddr_, db_, bc_, purge);
}
////////////////////////////////////////////////////////////////////////////////
uint64_t ScrAddrObj::getTxioCountFromSSH(void) const
{
if (!db_->isReady())
throw runtime_error("DB isnt ready");
StoredScriptHistory ssh;
db_->getStoredScriptHistorySummary(ssh, scrAddr_);
return ssh.totalTxioCount_;
}
////////////////////////////////////////////////////////////////////////////////
void ScrAddrObj::fetchDBScrAddrData(uint32_t startBlock,
uint32_t endBlock)
{
//maintains first page worth of TxIO in RAM. This call purges ZC, so you
//should rescan ZC right after
map<BinaryData, TxIOPair> hist;
getHistoryForScrAddr(startBlock, endBlock, hist, true);
updateTxIOMap(hist);
updateLedgers(*ledger_, hist, startBlock, endBlock, false);
}
///////////////////////////////////////////////////////////////////////////////
void ScrAddrObj::getHistoryForScrAddr(
uint32_t startBlock, uint32_t endBlock,
map<BinaryData, TxIOPair>& outMap,
bool update,
bool withMultisig) const
{
//check relevantTxio_ first to see if it has some of the TxIOs
uint32_t localTxioBottom = hist_.getPageBottom(0);
if (update==false && endBlock > localTxioBottom)
{
if (startBlock <= localTxioBottom)
{
for (auto txioPair : relevantTxIO_)
{
auto& txio = outMap[txioPair.first];
txio = txioPair.second;
txio.setScrAddrLambda(
[this](void)->const BinaryData&
{ return this->getScrAddr(); });
}
}
else
{
BinaryData startHeight = DBUtils::heightAndDupToHgtx(startBlock, 0);
startHeight.append(WRITE_UINT16_BE(0));
for (auto txioPair : relevantTxIO_)
{
if (txioPair.second >= startHeight)
{
auto& txio = outMap[txioPair.first];
txio = txioPair.second;
txio.setScrAddrLambda(
[this](void)->const BinaryData&
{ return this->getScrAddr(); });
}
}
}
if (startBlock >= localTxioBottom)
return;
endBlock = localTxioBottom -1;
}
//grab txio range from SSH
StoredScriptHistory ssh;
db_->getStoredScriptHistory(ssh, scrAddr_, startBlock, endBlock);
//update scrAddrObj containers
totalTxioCount_ = ssh.totalTxioCount_;
lastSeenBlock_ = endBlock;
if (scrAddr_[0] == SCRIPT_PREFIX_MULTISIG)
withMultisig = true;
if (!ssh.isInitialized())
return;
//Serve content as a map. Do not overwrite existing TxIOs to avoid wiping ZC
//data, Since the data isn't overwritten, iterate the map from its end to make
//sure newer txio aren't ignored due to older ones being inserted first.
auto subSSHiter = ssh.subHistMap_.rbegin();
while (subSSHiter != ssh.subHistMap_.rend())
{
StoredSubHistory & subssh = subSSHiter->second;
for (auto &txiop : subssh.txioMap_)
{
if (withMultisig || !txiop.second.isMultisig())
{
auto& txio = outMap[txiop.first];
txio.setScrAddrLambda(
[this](void)->const BinaryData&
{ return this->getScrAddr(); });
if (!txio.hasValue())
txio = txiop.second;
}
}
++subSSHiter;
}
}
////////////////////////////////////////////////////////////////////////////////
vector<LedgerEntry> ScrAddrObj::getHistoryPageById(uint32_t id)
{
if (id < 0 || id > hist_.getPageCount())
throw std::range_error("pageId out of range");
auto getTxio = [this](uint32_t start,
uint32_t end,
map<BinaryData, TxIOPair>& outMap)->void
{ this->getHistoryForScrAddr(start, end, outMap, false); };
auto buildLedgers = [this](map<BinaryData, LedgerEntry>& leMap,
const map<BinaryData, TxIOPair>& txioMap,
uint32_t cutoff)->void
{ this->updateLedgers(leMap, txioMap, cutoff, UINT32_MAX, false); };
return getTxLedgerAsVector(hist_.getPageLedgerMap(getTxio, buildLedgers, id));
}
////////////////////////////////////////////////////////////////////////////////
void ScrAddrObj::mapHistory()
{
ledger_ = &LedgerEntry::EmptyLedgerMap_;
//create history map
auto getSummary = [this](bool)->map<uint32_t, uint32_t>
{ return db_->getSSHSummary(this->getScrAddr(), UINT32_MAX); };
hist_.mapHistory(getSummary);
//grab first page and point ScrAddrObj's ledger at it
auto getTxio = [this](uint32_t start,
uint32_t end,
map<BinaryData, TxIOPair>& outMap)->void
{ this->getHistoryForScrAddr(start, end, outMap, true); };
auto buildLedgers = [this](map<BinaryData, LedgerEntry>& leMap,
const map<BinaryData, TxIOPair>& txioMap,
uint32_t cutoff)->void
{ this->updateLedgers(leMap, txioMap, cutoff, UINT32_MAX, false); };
ledger_ = &hist_.getPageLedgerMap(getTxio, buildLedgers, 0, &relevantTxIO_);
}
////////////////////////////////////////////////////////////////////////////////
ScrAddrObj& ScrAddrObj::operator= (const ScrAddrObj& rhs)
{
if (&rhs == this)
return *this;
this->db_ = rhs.db_;
this->bc_ = rhs.bc_;
this->scrAddr_ = rhs.scrAddr_;
this->firstBlockNum_ = rhs.firstBlockNum_;
this->firstTimestamp_ = rhs.firstTimestamp_;
this->lastBlockNum_ = rhs.lastBlockNum_;
this->lastTimestamp_ = rhs.lastTimestamp_;
this->hasMultisigEntries_ = rhs.hasMultisigEntries_;
this->relevantTxIO_ = rhs.relevantTxIO_;
this->totalTxioCount_ = rhs.totalTxioCount_;
this->lastSeenBlock_ = rhs.lastSeenBlock_;
//prebuild history indexes for quick fetch from SSH
this->hist_ = rhs.hist_;
this->utxos_.reset();
this->utxos_.scrAddrObj_ = this;
this->ledger_ = &LedgerEntry::EmptyLedgerMap_;
if (this->hist_.getPageCount() != 0)
this->ledger_ = &this->hist_.getPageLedgerMap(0);
return *this;
}
////////////////////////////////////////////////////////////////////////////////
vector<LedgerEntry> ScrAddrObj::getTxLedgerAsVector(
map<BinaryData, LedgerEntry>& leMap) const
{
vector<LedgerEntry>le;
for (auto& lePair : leMap)
le.push_back(lePair.second);
return le;
}
////////////////////////////////////////////////////////////////////////////////
LedgerEntry ScrAddrObj::getFirstLedger() const
{
auto getTxio = [this](uint32_t start,
uint32_t end,
map<BinaryData, TxIOPair>& outMap)->void
{ this->getHistoryForScrAddr(start, end, outMap, true); };
auto buildLedgers = [this](map<BinaryData, LedgerEntry>& leMap,
const map<BinaryData, TxIOPair>& txioMap,
uint32_t bottom, uint32_t top)->void
{ this->updateLedgers(leMap, txioMap, bottom, top, false); };
map<BinaryData, LedgerEntry> leMap;
size_t lastPage = hist_.getPageCount();
hist_.getPageLedgerMap(getTxio, buildLedgers, lastPage-1, leMap);
LedgerEntry le;
if (leMap.size())
le = leMap.begin()->second;
return le;
}
////////////////////////////////////////////////////////////////////////////////
bool ScrAddrObj::getMoreUTXOs(function<bool(const BinaryData&)> spentByZC)
{
return utxos_.fetchMoreUTXO(spentByZC);
}
////////////////////////////////////////////////////////////////////////////////
vector<UnspentTxOut> ScrAddrObj::getFullTxOutList(uint32_t currBlk,
bool ignoreZc) const
{
if (currBlk == 0)
currBlk = UINT32_MAX;
if (currBlk != UINT32_MAX)
ignoreZc = true;
auto utxoVec = getSpendableTxOutList(ignoreZc);
auto utxoIter = utxoVec.rbegin();
uint32_t cutOff = UINT32_MAX;
while (utxoIter != utxoVec.rend())
{
if (utxoIter->getTxHeight() <= currBlk)
{
cutOff = utxoVec.size() - (utxoIter - utxoVec.rbegin());
break;
}
}
utxoVec.erase(utxoVec.begin() + cutOff, utxoVec.end());
return utxoVec;
}
////////////////////////////////////////////////////////////////////////////////
vector<UnspentTxOut> ScrAddrObj::getSpendableTxOutList(
bool ignoreZc) const
{
//deliberately slow, only trying to support the old bdm behavior until the
//Python side has been reworked to ask for paged UTXO history
StoredScriptHistory ssh;
map<BinaryData, UnspentTxOut> utxoMap;
db_->getStoredScriptHistory(ssh, scrAddr_);
db_->getFullUTXOMapForSSH(ssh, utxoMap, false);
vector<UnspentTxOut> utxoVec;
for (auto& utxo : utxoMap)
{
auto txioIter = relevantTxIO_.find(utxo.first);
if (txioIter != relevantTxIO_.end())
if (txioIter->second.hasTxInZC())
continue;
utxoVec.push_back(utxo.second);
}
if (ignoreZc)
return utxoVec;
LMDBEnv::Transaction tx(db_->dbEnv_[db_->getDbSelect(HISTORY)].get(), LMDB::ReadOnly);
for (auto& txio : relevantTxIO_)
{
if (!txio.second.hasTxOutZC())
continue;
if (txio.second.hasTxInZC())
continue;
TxOut txout = txio.second.getTxOutCopy(db_);
uint32_t blk = DBUtils::hgtxToHeight(
txio.second.getDBKeyOfOutput().getSliceCopy(0, 4));
UnspentTxOut UTXO = UnspentTxOut(db_, txout, blk);
utxoVec.push_back(UTXO);
}
return utxoVec;
}
////////////////////////////////////////////////////////////////////////////////
uint32_t ScrAddrObj::getBlockInVicinity(uint32_t blk) const
{
//expect history has been computed, it will throw otherwise
return hist_.getBlockInVicinity(blk);
}
////////////////////////////////////////////////////////////////////////////////
uint32_t ScrAddrObj::getPageIdForBlockHeight(uint32_t blk) const
{
//same as above
return hist_.getPageIdForBlockHeight(blk);
}