/
time_locked_mempool.cpp
586 lines (504 loc) · 17.8 KB
/
time_locked_mempool.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
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
// Copyright (c) 2019 Bitcoin Association
// Distributed under the Open BSV software license, see the accompanying file LICENSE.
#include <clientversion.h>
#include <config.h>
#include <logging.h>
#include <memusage.h>
#include <mining/journal_change_set.h>
#include <net/net.h>
#include <policy/policy.h>
#include <scheduler.h>
#include <time_locked_mempool.h>
#include <txn_validator.h>
using namespace mining;
CTimeLockedMempool::CTimeLockedMempool()
{
// Set some sane default values for config
mMaxMemory = DEFAULT_MAX_NONFINAL_MEMPOOL_SIZE * ONE_MEBIBYTE;
mPeriodRunFreq = DEFAULT_NONFINAL_CHECKS_FREQ;
mPurgeAge = DEFAULT_NONFINAL_MEMPOOL_EXPIRY * SECONDS_IN_ONE_HOUR;
}
// Add or update a time-locked transaction
void CTimeLockedMempool::addOrUpdateTransaction(
const TxMempoolInfo& info,
const TxInputDataSPtr& pTxInputData,
CValidationState& state)
{
CTransactionRef txn { info.GetTx() };
std::unique_lock lock { mMtx };
// Update or new addition?
std::set<CTransactionRef> updated { getTransactionsUpdatedByNL(txn) };
if(updated.empty())
{
if(state.IsNonFinal())
{
// New addition
insertNL(info, state);
}
else
{
LogPrint(BCLog::MEMPOOL, "Non-final pool ignoring tx that doesn't finalise any we track: %s\n",
txn->GetId().ToString());
}
}
else if(updated.size() == 1)
{
// Validate update
const CTransactionRef& oldTxn { *updated.begin() };
bool finalised;
if(validateUpdate(txn, oldTxn, state, finalised))
{
// Remove old txn this new one updates
removeNL(oldTxn);
// Do we want to update to another non-final or are we ready to finalise?
if(finalised)
{
LogPrint(BCLog::MEMPOOL, "Finalising non-final tx: %s\n", txn->GetId().ToString());
// For full belt-and-braces safety, resubmit newly final transaction for revalidation
pTxInputData->SetTxSource(TxSource::finalised);
pTxInputData->SetTxStorage(info.GetTxStorage()),
pTxInputData->SetAcceptTime(GetTime());
state.SetResubmitTx();
}
else
{
insertNL(info, state);
}
}
else
{
LogPrint(BCLog::MEMPOOL, "Rejecting non-final tx which failed checks: %s\n", txn->GetId().ToString());
}
}
else
{
LogPrint(BCLog::MEMPOOL, "Rejecting non-final tx which wants to replace multiple txs: %s\n", txn->GetId().ToString());
state.DoS(10, false, REJECT_INVALID, "bad-txn-update");
}
}
// Get IDs of all held transactions
std::vector<TxId> CTimeLockedMempool::getTxnIDs() const
{
std::vector<TxId> res {};
std::shared_lock lock { mMtx };
for(const auto& info : mTransactionMap.get<TagTxID>())
{
res.emplace_back(info.GetTxId());
}
return res;
}
// Does this finalise an existing time-locked transaction?
bool CTimeLockedMempool::finalisesExistingTransaction(const CTransactionRef& txn) const
{
std::set<CTransactionRef> updated {};
{
std::shared_lock lock { mMtx };
if(mTransactionMap.empty())
{
// Can't be an update if we're not tracking any time-locked transactions
return false;
}
// Check if this txn could update exactly 1 of our non-final txns and not anything else
for(const CTxIn& in : txn->vin)
{
if(const auto& it { mUTXOMap.find(in.prevout) }; it != mUTXOMap.end())
{
updated.emplace(it->second);
}
else
{
return false;
}
}
}
if(updated.size() == 1)
{
// Check every input finalises
for(const CTxIn& txin : txn->vin)
{
if(txin.nSequence != CTxIn::SEQUENCE_FINAL)
{
return false;
}
}
return true;
}
return false;
}
// Check the given transaction doesn't try to double spend any of our locked UTXOs.
std::set<CTransactionRef> CTimeLockedMempool::checkForDoubleSpend(const CTransactionRef& txn) const
{
std::shared_lock lock { mMtx };
if(mUTXOMap.empty())
{
return {};
}
std::set<CTransactionRef> conflictsWith;
for(const CTxIn& txin : txn->vin)
{
if(auto it = mUTXOMap.find(txin.prevout); it != mUTXOMap.end())
{
conflictsWith.insert(it->second);
}
}
return conflictsWith;
}
// Is the given txn ID for one currently held?
bool CTimeLockedMempool::exists(const uint256& id) const
{
std::shared_lock lock { mMtx };
const auto& index { mTransactionMap.get<TagRawTxID>() };
return index.find(id) != index.end();
}
// Is the given txn ID for one we held until recently?
bool CTimeLockedMempool::recentlyRemoved(const uint256& id) const
{
std::shared_lock lock { mMtx };
return mRecentlyRemoved.contains(id);
}
// Fetch the full entry we have for the given txn ID
TxMempoolInfo CTimeLockedMempool::getInfo(const uint256& id) const
{
TxMempoolInfo info {};
std::shared_lock lock { mMtx };
const auto& index { mTransactionMap.get<TagRawTxID>() };
if(const auto& it { index.find(id) }; it != index.end())
{
info = *it;
}
return info;
}
// Launch periodic checks for finalised txns
void CTimeLockedMempool::startPeriodicChecks(CScheduler& scheduler)
{
scheduler.scheduleEvery(std::bind(&CTimeLockedMempool::periodicChecks, this), mPeriodRunFreq);
}
// Dump to disk
void CTimeLockedMempool::dumpMempool() const
{
int64_t start { GetTimeMicros() };
std::shared_lock lock { mMtx };
try
{
FILE* filestr { fsbridge::fopen(GetDataDir() / "non-final-mempool.dat.new", "wb") };
if(!filestr)
{
throw std::runtime_error("Failed to create new non-final mempool dump file");
}
CAutoFile file { filestr, SER_DISK, CLIENT_VERSION };
file << DUMP_FILE_VERSION;
const auto& index { mTransactionMap.get<TagTxID>() };
uint64_t numTxns { index.size() };
file << numTxns;
for(const auto& details : index)
{
file << *(details.GetTx());
file << details.nTime;
}
FileCommit(file.Get());
file.reset();
RenameOver(GetDataDir() / "non-final-mempool.dat.new", GetDataDir() / "non-final-mempool.dat");
int64_t last { GetTimeMicros() };
LogPrintf("Dumped %d txns to non-final mempool: %.6fs to dump\n", numTxns, (last - start) * 0.000001);
}
catch(const std::exception& e)
{
LogPrintf("Failed to dump non-final mempool: %s. Continuing anyway.\n", e.what());
}
}
// Load from disk
bool CTimeLockedMempool::loadMempool(const task::CCancellationToken& shutdownToken) const
{
try
{
FILE* filestr { fsbridge::fopen(GetDataDir() / "non-final-mempool.dat", "rb") };
CAutoFile file { filestr, SER_DISK, CLIENT_VERSION };
if(file.IsNull())
{
throw std::runtime_error("Failed to open non-final mempool file from disk");
}
int64_t count {0};
int64_t skipped {0};
int64_t failed {0};
int64_t nNow { GetTime() };
uint64_t version {};
file >> version;
if(version != DUMP_FILE_VERSION)
{
throw std::runtime_error("Bad non-final mempool dump version");
}
// Number of saved txns
uint64_t numTxns {0};
file >> numTxns;
// Take a reference to the validator.
const auto& txValidator { g_connman->getTxnValidator() };
// A pointer to the TxIdTracker.
const TxIdTrackerWPtr& pTxIdTracker = g_connman->GetTxIdTracker();
while(numTxns--)
{
CTransactionRef tx {};
int64_t nTime {};
file >> tx;
file >> nTime;
if(nTime + mPurgeAge > nNow)
{
// Mempool Journal ChangeSet
CJournalChangeSetPtr changeSet {
mempool.getJournalBuilder().getNewChangeSet(JournalUpdateReason::INIT)
};
std::string reason {};
bool standard { IsStandardTx(GlobalConfig::GetConfig(), *tx, chainActive.Tip()->GetHeight() + 1, reason) };
const CValidationState& state {
// Execute txn validation synchronously.
txValidator->processValidation(
std::make_shared<CTxInputData>(
pTxIdTracker, // a pointer to the TxIdTracker
tx, // a pointer to the tx
TxSource::file, // tx source
standard ? TxValidationPriority::high : TxValidationPriority::low,
TxStorage::memory, // tx storage
nTime), // nAcceptTime
changeSet, // an instance of the mempool journal
true) // fLimitMempoolSize
};
// Check results
if(state.IsValid())
{
++count;
}
else
{
++failed;
}
}
else
{
++skipped;
}
if(shutdownToken.IsCanceled())
{
// Abort early
return false;
}
}
LogPrintf("Imported non-final mempool transactions from disk: %i successes, %i "
"failed, %i expired\n", count, failed, skipped);
}
catch(const std::exception& e)
{
LogPrintf("Failed to deserialize non-final mempool data on disk: %s. Continuing anyway.\n", e.what());
return false;
}
return true;
}
// Get number of txns we hold
size_t CTimeLockedMempool::getNumTxns() const
{
std::shared_lock lock { mMtx };
return mTransactionMap.get<TagTxID>().size();
}
// Estimate total memory usage
size_t CTimeLockedMempool::estimateMemoryUsage() const
{
std::shared_lock lock { mMtx };
return estimateMemoryUsageNL();
}
// Load or reload our config
void CTimeLockedMempool::loadConfig()
{
std::unique_lock lock { mMtx };
// Get max memory size in bytes
mMaxMemory = gArgs.GetArgAsBytes("-maxmempoolnonfinal", DEFAULT_MAX_NONFINAL_MEMPOOL_SIZE, ONE_MEBIBYTE);
// Get periodic checks run frequency
mPeriodRunFreq = gArgs.GetArg("-checknonfinalfreq", DEFAULT_NONFINAL_CHECKS_FREQ);
// Get configured purge age (convert hours to seconds)
mPurgeAge = gArgs.GetArg("-mempoolexpirynonfinal", DEFAULT_NONFINAL_MEMPOOL_EXPIRY) * SECONDS_IN_ONE_HOUR;
}
// Fetch all transactions updated by the given new transaction.
// Caller holds mutex.
std::set<CTransactionRef> CTimeLockedMempool::getTransactionsUpdatedByNL(const CTransactionRef& txn) const
{
std::set<CTransactionRef> txns {};
// Find all transactions we're tracking that have any of the same outpoints as this transaction
for(const CTxIn& in : txn->vin)
{
if(const auto& it { mUTXOMap.find(in.prevout) }; it != mUTXOMap.end())
{
txns.emplace(it->second);
}
}
return txns;
}
// Insert a new transaction
void CTimeLockedMempool::insertNL(const TxMempoolInfo& info, CValidationState& state)
{
CTransactionRef txn { info.GetTx() };
// Put new txn in the main index
auto& index { mTransactionMap.get<TagTxID>() };
index.emplace(info);
// Record UTXOs locked by this transaction
for(const CTxIn& input : txn->vin)
{
mUTXOMap[input.prevout] = txn;
}
// Track memory used by this txn
mTxnMemoryUsage += txn->GetTotalSize();
// Check we haven't exceeded max memory
size_t memUsage { estimateMemoryUsageNL() };
if(memUsage > mMaxMemory)
{
LogPrint(BCLog::MEMPOOL, "Dropping non-final tx %s because mempool is full\n",
txn->GetId().ToString());
state.Invalid(false, REJECT_MEMPOOL_FULL, "non-final-pool-full");
removeNL(txn);
}
else
{
LogPrint(BCLog::MEMPOOL, "Added non-final tx: %s, mem: %d\n", txn->GetId().ToString(),
memUsage);
}
}
// Remove an old transaction
void CTimeLockedMempool::removeNL(const CTransactionRef& txn)
{
// Remove from main index
auto& index { mTransactionMap.get<TagTxID>() };
index.erase(txn);
// Track removal in bloom filter
mRecentlyRemoved.insert(txn->GetId());
// Remove UTXOs locked by that transacrion
for(const CTxIn& input : txn->vin)
{
if(mUTXOMap.erase(input.prevout) != 1)
{
LogPrint(BCLog::MEMPOOL, "Warning: Failed to find and remove UTXO from old non-final tx %s\n",
txn->GetId().ToString());
}
}
// Update memory used
auto txnSize { txn->GetTotalSize() };
if(mTxnMemoryUsage <= txnSize)
{
mTxnMemoryUsage = 0;
}
else
{
mTxnMemoryUsage -= txnSize;
}
LogPrint(BCLog::MEMPOOL, "Removed old non-final tx: %s, mem: %d\n", txn->GetId().ToString(),
estimateMemoryUsageNL());
}
// Perform checks on a transaction before allowing an update
bool CTimeLockedMempool::validateUpdate(const CTransactionRef& newTxn,
const CTransactionRef& oldTxn,
CValidationState& state,
bool& finalised) const
{
// Must have same number of inputs
if(newTxn->vin.size() != oldTxn->vin.size())
{
LogPrint(BCLog::MEMPOOL, "Update to non-final txn has different number of inputs\n");
state.DoS(10, false, REJECT_INVALID, "bad-txn-update");
return false;
}
bool seenIncrease {false};
finalised = true;
// Check corresponding inputs on new and old
for(unsigned i = 0; i < newTxn->vin.size(); ++i)
{
const CTxIn& newInput { newTxn->vin[i] };
const CTxIn& oldInput { oldTxn->vin[i] };
// Check each input spends the same outpoint
if(newInput.prevout != oldInput.prevout)
{
LogPrint(BCLog::MEMPOOL, "Update to non-final txn has different inputs\n");
state.DoS(10, false, REJECT_INVALID, "bad-txn-update");
return false;
}
// Check sequence numbers are only ever going forward
if(newInput.nSequence < oldInput.nSequence)
{
LogPrint(BCLog::MEMPOOL, "Update to non-final txn would decrease nSequence\n");
state.DoS(10, false, REJECT_INVALID, "bad-txn-update");
return false;
}
else if(newInput.nSequence > oldInput.nSequence)
{
seenIncrease = true;
if(newInput.nSequence != CTxIn::SEQUENCE_FINAL)
{
// Still not finalised
finalised = false;
}
}
}
// Finally, must have seen at least 1 increase in an nSequence number
if(!seenIncrease)
{
LogPrint(BCLog::MEMPOOL, "Update to non-final txn didn't increase any nSequence\n");
state.DoS(10, false, REJECT_INVALID, "bad-txn-update");
return false;
}
return true;
}
// Estimate our memory usage
size_t CTimeLockedMempool::estimateMemoryUsageNL() const
{
size_t numElements { mTransactionMap.size() };
// Experiment shows that the memory usage of the multi-index container can be
// approximated as:
// 24 bytes overhead (3 pointers) per index per (number of elements + 1)
// + (sizeof(element) * (number of elements + 1))
constexpr size_t numIndexes {3};
constexpr size_t overhead { 3 * numIndexes * sizeof(void*) };
size_t multiIndexUsage { (overhead * (numElements+1)) + (sizeof(TxnMultiIndex::value_type) * (numElements+1)) };
multiIndexUsage += mTxnMemoryUsage;
return memusage::MallocUsage(multiIndexUsage) +
memusage::DynamicUsage(mUTXOMap);
}
// Do periodic checks for finalised txns and txns to purge
void CTimeLockedMempool::periodicChecks()
{
// Get current time
int64_t now { GetTime() };
const CBlockIndex* chainTip = chainActive.Tip();
std::unique_lock lock { mMtx };
// A pointer to the TxIdTracker.
const TxIdTrackerWPtr& pTxIdTracker = g_connman->GetTxIdTracker();
// Iterate over transactions in unlocking time order
auto& index { mTransactionMap.get<TagUnlockingTime>() };
auto it { index.begin() };
while(it != index.end())
{
CTransactionRef txn { it->GetTx() };
int64_t insertionTime { it->nTime };
int64_t timeInPool { now - insertionTime };
// Move iterator on so we don't have to care whether this txn gets removed
++it;
// Lock time passed?
if(IsFinalTx(*txn, chainTip->GetHeight() + 1, chainTip->GetMedianTimePast()))
{
LogPrint(BCLog::MEMPOOL, "Finalising non-final transaction %s at block height %d, mtp %d\n",
txn->GetId().ToString(), chainTip->GetHeight() + 1, chainTip->GetMedianTimePast());
removeNL(txn);
// For full belt-and-braces safety, resubmit newly final transaction for revalidation
std::string reason {};
bool standard { IsStandardTx(GlobalConfig::GetConfig(), *txn, chainTip->GetHeight() + 1, reason) };
g_connman->EnqueueTxnForValidator(
std::make_shared<CTxInputData>(
pTxIdTracker,
txn,
TxSource::finalised,
standard ? TxValidationPriority::high : TxValidationPriority::low,
TxStorage::memory,
GetTime()));
}
// Purge age passed?
else if(timeInPool >= mPurgeAge)
{
LogPrint(BCLog::MEMPOOL, "Purging expired non-final transaction: %s\n",
txn->GetId().ToString());
removeNL(txn);
}
}
}