TxValidation.cpp 24.4 KB
Newer Older
1
2
/*
 * This file is part of the flowee project
Tom Zander's avatar
Tom Zander committed
3
 * Copyright (C) 2017-2021 Tom Zander <tom@flowee.org>
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

#include "Engine.h"
20
21
#include "../DoubleSpendProofStorage.h"
#include "../DoubleSpendProof.h"
22
#include <SettingsDefaults.h>
23
#include <primitives/transaction.h>
24
#include <UnspentOutputData.h>
25
26
27
28
29
30
31
32
33
#include "ValidationException.h"
#include "TxValidation_p.h"
#include <Application.h>
#include <main.h>
#include <txorphancache.h>
#include <policy/policy.h>
#include <validationinterface.h>
#include <chainparams.h>
#include <consensus/consensus.h>
34
35
#include <utxo/UnspentOutputDatabase.h>
#include <util.h>
Tom Zander's avatar
Tom Zander committed
36
#include <script/sigcache.h>
37
38
39
40
41

// #define DEBUG_TRANSACTION_VALIDATION
#ifdef DEBUG_TRANSACTION_VALIDATION
# define DEBUGTX logCritical(Log::TxValidation)
#else
42
# define DEBUGTX BCH_NO_DEBUG_MACRO()
43
44
45
46
#endif

using Validation::Exception;

Tom Zander's avatar
Tom Zander committed
47
void ValidationPrivate::validateTransactionInputs(CTransaction &tx, const std::vector<UnspentOutput> &unspents, int blockHeight, ValidationFlags flags, int64_t &fees, uint32_t &txSigChecks, bool &spendsCoinbase, bool requireStandard)
48
{
49
    assert(unspents.size() == tx.vin.size());
Tom Zander's avatar
Tom Zander committed
50
    txSigChecks = 0;
51
52
53

    int64_t valueIn = 0;
    for (size_t i = 0; i < tx.vin.size(); ++i) {
54
        const ValidationPrivate::UnspentOutput &prevout = unspents.at(i);
55
        assert(prevout.amount >= 0);
56
        valueIn += prevout.amount;
57
58
59
60
61
62
63
64
65
66
67
68
69
    }

    if (valueIn < tx.GetValueOut())
        throw Exception("bad-txns-in-belowout");
    if (!MoneyRange(valueIn)) // Check for negative or overflow input values
        throw Exception("bad-txns-inputvalues-outofrange");
    fees = valueIn - tx.GetValueOut();
    if (fees < 0)
        throw Exception("bad-txns-fee-negative");
    if (!MoneyRange(fees))
        throw Exception("bad-txns-fee-outofrange");

    spendsCoinbase = false;
Tom Zander's avatar
Tom Zander committed
70
    const uint32_t scriptValidationFlags = flags.scriptValidationFlags(requireStandard);
71
    for (unsigned int i = 0; i < tx.vin.size(); i++) {
72
73
        const ValidationPrivate::UnspentOutput &prevout = unspents.at(i);
        if (prevout.isCoinbase) { // If prev is coinbase, check that it's matured
74
            spendsCoinbase = true;
75
            if (blockHeight - prevout.blockheight < COINBASE_MATURITY)
76
77
78
                throw Exception("bad-txns-premature-spend-of-coinbase");
        }

79
        if (!MoneyRange(prevout.amount))
80
81
82
            throw Exception("bad-txns-inputvalues-outofrange");

        // Verify signature
Tom Zander's avatar
Tom Zander committed
83
84
85
86
87
88
89
90
91
92
93
        Script::State strict(scriptValidationFlags);
        if (!Script::verify(tx.vin[i].scriptSig, prevout.outputScript,
                            CachingTransactionSignatureChecker(&tx, i, prevout.amount, true), strict)) {
            // Failures of other flags indicate a transaction that is
            // invalid in new blocks, e.g. a invalid P2SH. We DoS ban
            // such nodes as they are not following the protocol. That
            // said during an upgrade careful thought should be taken
            // as to the correct behavior - we may want to continue
            // peering with non-upgraded nodes even after a soft-fork
            // super-majority vote has passed.

94
95
96
97
98
99
100
            if (scriptValidationFlags & STANDARD_NOT_MANDATORY_VERIFY_FLAGS) {
                // Check whether the failure was caused by a
                // non-mandatory script verification check, such as
                // non-standard DER encodings or non-null dummy
                // arguments; if so, don't trigger DoS protection to
                // avoid splitting the network between upgraded and
                // non-upgraded nodes.
Tom Zander's avatar
Tom Zander committed
101
102
103
                Script::State flexible(scriptValidationFlags & ~STANDARD_NOT_MANDATORY_VERIFY_FLAGS);
                if (Script::verify(tx.vin[i].scriptSig, prevout.outputScript, TransactionSignatureChecker(&tx, i, prevout.amount), flexible))
                    throw Exception(strprintf("non-mandatory-script-verify-flag (%s)", strict.errorString()), Validation::RejectNonstandard, 0);
104
            }
Tom Zander's avatar
Tom Zander committed
105
106

            throw Exception(strprintf("mandatory-script-verify-flag-failed (%s)", strict.errorString()));
107
        }
Tom Zander's avatar
Tom Zander committed
108
        txSigChecks += strict.sigCheckCount;
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
    }
}


// static
void Validation::checkTransaction(const CTransaction &tx)
{
    // Basic checks that don't depend on any context
    if (tx.vin.empty())
        throw Exception("bad-txns-vin-empty", 10);
    if (tx.vout.empty())
        throw Exception("bad-txns-vout-empty", 10);
    // Size limits
    if (::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION) > MAX_TX_SIZE)
        throw Exception("bad-txns-oversize", 100);

    // Check for negative or overflow output values
Tom Zander's avatar
Tom Zander committed
126
    int64_t nValueOut = 0;
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
    for (const CTxOut& txout : tx.vout) {
        if (txout.nValue < 0)
            throw Exception("bad-txns-vout-negative", 100);
        if (txout.nValue > MAX_MONEY)
            throw Exception("bad-txns-vout-toolarge", 100);
        nValueOut += txout.nValue;
        if (!MoneyRange(nValueOut))
            throw Exception("bad-txns-txouttotal-toolarge", 100);
    }

    // Check for duplicate inputs
    std::set<COutPoint> vInOutPoints;
    for (const CTxIn& txin : tx.vin) {
        if (vInOutPoints.count(txin.prevout))
            throw Exception("bad-txns-inputs-duplicate", 100);
        vInOutPoints.insert(txin.prevout);
    }

    if (tx.IsCoinBase()) {
        if (tx.vin[0].scriptSig.size() < 2 || tx.vin[0].scriptSig.size() > 100)
            throw Exception("bad-cb-length", 100);
    } else {
        for (const CTxIn& txin : tx.vin) {
            if (txin.prevout.IsNull())
                throw Exception("bad-txns-prevout-null", 10);
        }
    }
}


TxValidationState::TxValidationState(const std::weak_ptr<ValidationEnginePrivate> &parent, const Tx &transaction, uint32_t onValidationFlags)
    : m_parent(parent),
      m_tx(transaction),
      m_validationFlags(onValidationFlags),
      m_originatingNodeId(-1),
      m_originalInsertTime(0)
{
}

TxValidationState::~TxValidationState()
{
    try {
        m_promise.set_value(std::string());
170
    } catch (std::exception &) {}
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
}

void TxValidationState::checkTransaction()
{
    std::shared_ptr<ValidationEnginePrivate> parent = m_parent.lock();
    if (parent.get() == nullptr)
        return;
    const ValidationFlags flags = parent->tipFlags;
    std::string result;
    struct RAII {
        RAII(std::promise<std::string> *promise) : promise(promise) {}
        ~RAII() {
            promise->set_value(result);
        }
        std::promise<std::string> *promise;
        std::string result;
    };
    RAII raii(&m_promise);

190
191
192
    if (flags.hf201811Active && m_tx.size() < 100)
        throw Exception("bad-txns-undersize", 2);

193
194
195
196
197
198
199
200
201
202
203
    const uint256 txid = m_tx.createHash();
    DEBUGTX << "checkTransaction peer:" << m_originatingNodeId << txid;
    auto tx = m_tx.createOldTransaction();
    bool inputsMissing = false;
    try {
        Validation::checkTransaction(tx);

        // Coinbase is only valid in a block, not as a loose transaction
        if (tx.IsCoinBase())
            throw Exception("coinbase", 100);

Justin Holmes's avatar
Justin Holmes committed
204
        // Rather not work on nonstandard transactions (unless -testnet/-testnet4/-scalenet/-regtest)
205
206
207
208
209
210
        std::string reason;
        if (fRequireStandard && !IsStandardTx(tx, reason))
            throw Exception(reason, Validation::RejectNonstandard, 0);

        // Don't relay version 2 transactions until CSV is active, and we can be
        // sure that such transactions will be mined (unless we're on
Justin Holmes's avatar
Justin Holmes committed
211
        // -testnet/-testnet4/-scalenet/-regtest).
212
213
214
215
216
217
218
219
220
221
222
223
        if (fRequireStandard && tx.nVersion >= 2 &&  flags.nLocktimeVerifySequence == false)
            throw Exception("premature-version2-tx", Validation::RejectNonstandard, 0);
        // Only accept nLockTime-using transactions that can be mined in the next
        // block; we don't want our mempool filled up with transactions that can't
        // be mined yet.
        CBlockIndex *tip = parent->tip.load();
        if (tip == nullptr) // don't accept anything before we have a genesis block.
            return;
        if (!IsFinalTx(tx, tip->nHeight + 1, tip->GetMedianTimePast()))
            throw Exception("non-final", Validation::RejectNonstandard, 0);

        CTxMemPoolEntry entry(m_tx);
224
225
        entry.entryHeight = static_cast<std::uint32_t>(tip->nHeight);
        entry.inChainInputValue = 0;
226
227

        {
228
229
230
231
232
233
234
235
236
237
238
            /*
             * Now we iterate over the inputs of the tx and connect them to outputs they spend.
             * We reject when something is fishy.
             *
             * Outputs they spend can come from the mempool or the UTXO. We have a codepath to address each separately.
             * This optimizes for speed, so we don't try to push both usecases though the same codepath. This may mean
             * its a tad harder to follow.  I am only sorry for not being sorry.
             */

            std::vector<Tx> mempoolTransactions;
            mempoolTransactions.resize(tx.vin.size());
239
240
            {
                LOCK(parent->mempool->cs);
241
242
                // do we already have the input tx?
                if (parent->mempool->exists(txid))
243
244
                    throw Exception("txn-already-known", Validation::RejectAlreadyKnown, 0);

245
246
                // find the ones in the mempool
                for (size_t i = 0; i < tx.vin.size(); ++i) {
Tom Zander's avatar
Tom Zander committed
247
248
249
                    Tx prevTx;
                    if (parent->mempool->lookup(tx.vin[i].prevout.hash, prevTx))
                        mempoolTransactions[i] = prevTx;
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
                }
            }

            std::vector<ValidationPrivate::UnspentOutput> unspents; // list of outputs
            unspents.resize(tx.vin.size());
            double txPriority = 0;
            for (size_t i = 0; i < tx.vin.size(); ++i) {
                ValidationPrivate::UnspentOutput &prevOut = unspents[i];
                if (mempoolTransactions.at(i).isValid()) { // we found it in the mempool above, in the mempool->lock!
                    // check if the referenced output exists
                    // we do that here, outside of the mempool lock, so we don't have to do that later.
                    Tx::Iterator iter(mempoolTransactions.at(i));
                    uint32_t outputs = 0;
                    const uint32_t prevoutIndex = tx.vin.at(i).prevout.n;
                    while (iter.next(Tx::OutputValue) != Tx::End) { // find all output-value tags.
                        if (outputs++ == prevoutIndex)
                            break;
                    }
                    if (outputs - 1 < prevoutIndex) {
269
                        throw Exception("missing-inputs", 10); // we have a tx it is trying to spend, but the input doesn't exist.
270
                    }
Tom Zander's avatar
Tom Zander committed
271
                    prevOut.amount = static_cast<int64_t>(iter.longData());
272
273
274
275
276
277
278
279
                    auto type = iter.next();
                    assert(type == Tx::OutputScript); // if it made it into the mempool, its supposed to be well formed.
                    prevOut.outputScript = iter.byteData();
                    if (fRequireStandard) {
                        // Check for non-standard pay-to-script-hash in inputs
                        if (!Policy::isInputStandard(prevOut.outputScript, tx.vin.at(i).scriptSig))
                            throw Exception("bad-txns-nonstandard-inputs", Validation::RejectNonstandard, 0);
                    }
280
                }
281
282
283
284
285
286
                else {
                    // prevOut not in mempool, check UTXO
                    assert(tx.vin[i].prevout.n < 0xEFFFFFFF); // utxo db would not like that. 'n' should not get even moderately big, though.
                    UnspentOutputData data(g_utxo->find(tx.vin[i].prevout.hash, static_cast<int>(tx.vin[i].prevout.n)));
                    if (!data.isValid()) {
                        inputsMissing = true;
287
288
                        DEBUGTX << "The output we are trying to spend is unknown to us" << tx.vin[i].prevout.hash << "Me:" << txid;
                        throw Exception("missing-inputs", 0);
289
290
291
292
293
294
295
296
297
298
299
300
301
                    }
                    prevOut.amount = data.outputValue();
                    prevOut.outputScript = data.outputScript();
                    prevOut.isCoinbase = data.isCoinbase();
                    prevOut.blockheight = data.blockHeight();
                    if (fRequireStandard) {
                        // Check for non-standard pay-to-script-hash in inputs
                        if (!Policy::isInputStandard(prevOut.outputScript, tx.vin.at(i).scriptSig))
                            throw Exception("bad-txns-nonstandard-inputs", Validation::RejectNonstandard, 0);
                    }
                    txPriority += prevOut.amount * (entry.entryHeight - data.blockHeight());
                }
                entry.inChainInputValue += prevOut.amount;
302
303
            }

304
305
306
307
308
309

            // Only accept BIP68 sequence locked transactions that can be mined in the next
            // block; we don't want our mempool filled up with transactions that can't
            // be mined yet.
            if (!CheckSequenceLocks(*parent->mempool, tx, STANDARD_LOCKTIME_VERIFY_FLAGS, &entry.lockPoints, false, tip))
                throw Exception("non-BIP68-final", Validation::RejectNonstandard, 0);
310

Tom Zander's avatar
Tom Zander committed
311
312
313
314
315
            uint32_t txSigChecks = 0;
            ValidationPrivate::validateTransactionInputs(tx, unspents, static_cast<int>(entry.entryHeight) + 1, flags, entry.nFee, txSigChecks , entry.spendsCoinbase, fRequireStandard);
            if (fRequireStandard && txSigChecks > Policy::MAX_SIGCHEKCS_PER_TX) {
                throw Exception("bad-blk-sigcheck", Validation::RejectNonstandard, 0);
            }
316
317

            // nModifiedFees includes any fee deltas from PrioritiseTransaction
Tom Zander's avatar
Tom Zander committed
318
            int64_t nModifiedFees = entry.nFee;
319
320
            double nPriorityDummy = 0;
            parent->mempool->ApplyDeltas(txid, nPriorityDummy, nModifiedFees);
321
            entry.entryPriority = entry.oldTx.ComputePriority(txPriority, entry.tx.size());
322
323
            entry.hadNoDependencies = parent->mempool->HasNoInputsOf(tx);

324
            const size_t nSize = entry.GetTxSize();
325

Tom Zander's avatar
Tom Zander committed
326
            int64_t mempoolRejectFee = parent->mempool->GetMinFee().GetFee(nSize);
327
            if (mempoolRejectFee > 0 && nModifiedFees < mempoolRejectFee) {
Tom Zander's avatar
Tom Zander committed
328
                logInfo(Log::Mempool) << "transaction rejected, low fee:" << nModifiedFees << "<" << mempoolRejectFee << "sat";
329
                throw Exception("mempool min fee not met", Validation::RejectInsufficientFee, 0);
330
            } else if (GetBoolArg("-relaypriority", Settings::DefaultRelayPriority) && nModifiedFees < ::minRelayTxFee.GetFee(nSize)
331
                       && !AllowFree(entry.GetPriority(static_cast<uint32_t>(tip->nHeight + 1)))) {
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
                // Require that free transactions have sufficient priority to be mined in the next block.
                raii.result = std::string("insufficient priority");
                return;
            }

            // Continuously rate-limit free and very-low-fee transactions
            // This mitigates 'penny-flooding' -- sending thousands of free transactions just to
            // be annoying or make others' transactions take longer to confirm.
            if ((m_validationFlags & Validation::RateLimitFreeTx) && nModifiedFees < ::minRelayTxFee.GetFee(nSize)) {
                static CCriticalSection csFreeLimiter;
                static double dFreeCount;
                static int64_t nLastTime;
                int64_t nNow = GetTime();

                LOCK(csFreeLimiter);

                // Use an exponentially decaying ~10-minute window:
349
                dFreeCount *= pow(1.0 - 1.0/600.0, static_cast<double>(nNow - nLastTime));
350
351
352
                nLastTime = nNow;
                // -limitfreerelay unit is thousand-bytes-per-minute
                // At default rate it would take over a month to fill 1GB
353
                if (dFreeCount >= GetArg("-limitfreerelay", Settings::DefaultLimitFreeRelay) * 10 * 1000)
354
355
356
357
358
359
360
361
362
363
                    throw Exception("rate limited free transaction", Validation::RejectInsufficientFee, 0);
                logInfo(Log::TxValidation) << "Rate limit dFreeCount:" << dFreeCount << "=>" << dFreeCount + nSize;
                dFreeCount += nSize;
            }

            if ((m_validationFlags & Validation::RejectAbsurdFeeTx) && entry.nFee > ::minRelayTxFee.GetFee(nSize) * 10000)
                throw Exception("absurdly-high-fee", 0);

            // Calculate in-mempool ancestors, up to a limit.
            CTxMemPool::setEntries setAncestors;
364
365
366
367
            int64_t nLimitAncestors = GetArg("-limitancestorcount", Settings::DefaultAncestorLimit);
            int64_t nLimitAncestorSize = GetArg("-limitancestorsize", Settings::DefaultAncestorSizeLimit)*1000;
            int64_t nLimitDescendants = GetArg("-limitdescendantcount", Settings::DefaultDescendantLimit);
            int64_t nLimitDescendantSize = GetArg("-limitdescendantsize", Settings::DefaultDescendantSizeLimit)*1000;
368
369
370
            std::string errString;
            if (!parent->mempool->CalculateMemPoolAncestors(entry, setAncestors, nLimitAncestors, nLimitAncestorSize,
                                                            nLimitDescendants, nLimitDescendantSize, errString)) {
371
                logInfo(Log::TxValidation) << "Tx rejected from mempool (too-long-mempool-chain). Reason:" << errString;
372
373
374
375
376
377
378
379
                throw Exception("too-long-mempool-chain", Validation::RejectNonstandard, 0);
            }

            if (!parent->mempool->insertTx(entry)) {
                raii.result = "bad-txns-inputs-spent";
                DEBUGTX << "Mempool did not accept tx entry, returned false";
                return;
            }
Tom Zander's avatar
Tom Zander committed
380
381
382
383
384
385
            if (entry.dsproof != -1) {
                m_doubleSpendTx = entry.tx;
                m_doubleSpendProofId = entry.dsproof;

                parent->strand.post(std::bind(&TxValidationState::notifyDoubleSpend, shared_from_this()));
            }
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
        }

        logDebug(Log::TxValidation) << "accepted:"<< txid << "peer:" << m_originatingNodeId
                               << "(poolsz" << parent->mempool->size() << "txn," << (parent->mempool->DynamicMemoryUsage() / 1000) << "kB)";


        if (m_validationFlags & FromMempool) {
            // AcceptToMemoryPool/addUnchecked all assume that new mempool entries have
            // no in-mempool children, which is generally not true when adding
            // previously-confirmed transactions back to the mempool.
            // UpdateTransactionsFromBlock finds descendants of any transactions in this
            // block that were added back and cleans up the mempool state.
            std::vector<uint256> me;
            me.push_back(txid);
            parent->mempool->UpdateTransactionsFromBlock(me);
        }

403
        if ((m_validationFlags & Validation::TxValidateOnly) == 0)
404
405
406
407
408
409
410
411
412
413
414
415
416
            RelayTransaction(tx);

        auto orphans = CTxOrphanCache::instance()->fetchTransactionsByPrev(txid);
        std::vector<uint256> scheduled;
        scheduled.reserve(orphans.size());
        for (auto orphan : orphans) {
            std::shared_ptr<TxValidationState> state(new TxValidationState(m_parent, Tx::fromOldTransaction(orphan.tx), orphan.onResultFlags));
            state->m_originatingNodeId = orphan.fromPeer;
            state->m_originalInsertTime = orphan.nEntryTime;
            scheduled.push_back(state->m_tx.createHash());
            Application::instance()->ioService().post(std::bind(&TxValidationState::checkTransaction, state));
        }

417
418
        CTxOrphanCache::instance()->eraseOrphans(scheduled);
        CTxOrphanCache::instance()->eraseOrphansByTime();
419
420

        parent->strand.post(std::bind(&TxValidationState::sync, shared_from_this()));
421
422
    } catch (const Validation::DoubleSpendException &ex) {
        raii.result = strprintf("%i: %s", Validation::RejectConflict, "txn-mempool-conflict");
Tom Zander's avatar
Tom Zander committed
423
424
        if (ex.id != -1) // to avoid log file confusion, don't mention this for anything but the first DS
            logWarning(Log::TxValidation) << "Tx-Validation found a double spend";
425

426
427
428
429
        if ((m_validationFlags & Validation::TxValidateOnly) == 0) {
            m_doubleSpendTx = ex.otherTx;
            m_doubleSpendProofId = ex.id;
            parent->strand.post(std::bind(&TxValidationState::notifyDoubleSpend, shared_from_this()));
430

431
432
433
            std::lock_guard<std::mutex> rejects(parent->recentRejectsLock);
            parent->recentTxRejects.insert(txid);
        }
434
435
436
437
    } catch (const Exception &ex) {
        raii.result = strprintf("%i: %s", ex.rejectCode(), ex.what());
        if (inputsMissing) {// if missing inputs, add to orphan cache
            DEBUGTX << "Tx missed inputs, can't add to mempool" << txid;
438
            if ((m_validationFlags & Validation::TxValidateOnly) || m_originatingNodeId < 0)
439
440
441
                return;
            CTxOrphanCache *cache = CTxOrphanCache::instance();
            // DoS prevention: do not allow CTxOrphanCache to grow unbounded
442
443
            cache->addOrphanTx(tx, m_originatingNodeId, m_validationFlags, m_originalInsertTime);
            std::uint32_t nEvicted = cache->limitOrphanTxSize();
444
445
446
            if (nEvicted > 0)
                logDebug(Log::TxValidation) << "mapOrphan overflow, removed" << nEvicted << "tx";
        }
447
        logInfo(Log::TxValidation) << "Tx-Validation failed" << ex << "peer:" << m_originatingNodeId;
448
449
450
451
452
453

        if (ex.punishment() > 0 && (m_validationFlags & Validation::PunishBadNode)) {
            assert(m_originatingNodeId >= 0);
            LOCK(cs_main);
            CNode *node = FindNode(m_originatingNodeId);
            if (node) {
454
455
                node->PushMessage(NetMsgType::REJECT, std::string(NetMsgType::TX),
                                      static_cast<uint8_t>(ex.rejectCode()),
456
457
458
459
460
461
462
463
464
465
                                      std::string(ex.what()).substr(0, MAX_REJECT_MESSAGE_LENGTH), txid);
               if (ex.punishment() > 0)
                   Misbehaving(m_originatingNodeId, ex.punishment());
            }
        }

        std::lock_guard<std::mutex> rejects(parent->recentRejectsLock);
        parent->recentTxRejects.insert(txid);
    } catch (const std::runtime_error &ex) {
        raii.result = std::string(ex.what());
Tom Zander's avatar
Tom Zander committed
466
467
        logFatal(Log::TxValidation) << "TxValidation" << txid << "got exception:" << ex;
        logFatal(Log::TxValidation) << "  size" << m_tx.size() << m_tx.createHash();
468
469
470
471
472
473
474
475
476
477
478
        assert(false);
    }
}

void TxValidationState::sync()
{
    std::shared_ptr<ValidationEnginePrivate> parent = m_parent.lock();
    if (parent.get() == nullptr)
        return;
    assert(parent->strand.running_in_this_thread());

479
480
    LimitMempoolSize(*parent->mempool, GetArg("-maxmempool", Settings::DefaultMaxMempoolSize) * 1000000,
                     GetArg("-mempoolexpiry", Settings::DefaultMempoolExpiry) * 60 * 60);
481

482
483
    ValidationNotifier().syncTransaction(m_tx.createOldTransaction());
    ValidationNotifier().syncTx(m_tx);
484
485
}

486
487
488
489
490
491
492
493
494
495
496
497
void TxValidationState::notifyDoubleSpend()
{
    std::shared_ptr<ValidationEnginePrivate> parent = m_parent.lock();
    if (parent.get() == nullptr)
        return;
    assert(parent->strand.running_in_this_thread());

    // send INV to all peers
    if (m_doubleSpendProofId != -1) {
        auto dsp = mempool.doubleSpendProofStorage()->proof(m_doubleSpendProofId);
        if (!dsp.isEmpty()) {
            CInv inv(MSG_DOUBLESPENDPROOF, dsp.createHash());
Tom Zander's avatar
Tom Zander committed
498
            const CTransaction dspTx = m_doubleSpendTx.createOldTransaction();
Tom Zander's avatar
Tom Zander committed
499
            logDebug(Log::DSProof) << "Broadcasting DSP" << inv;
500
501
502

            LOCK(cs_vNodes);
            for (CNode* pnode : vNodes) {
Tom Zander's avatar
Tom Zander committed
503
                if (!pnode->fRelayTxes)
504
505
506
507
                    continue;
                LOCK(pnode->cs_filter);
                if (pnode->pfilter) {
                    // For nodes that we sent this Tx before, send a proof.
Tom Zander's avatar
Tom Zander committed
508
                    if (pnode->pfilter->isRelevantAndUpdate(dspTx)) {
Tom Zander's avatar
Tom Zander committed
509
                        logDebug(Log::DSProof) << "  peer:" << pnode->id;
510
                        pnode->PushInventory(inv);
Tom Zander's avatar
Tom Zander committed
511
                    }
512
                } else {
Tom Zander's avatar
Tom Zander committed
513
                    logDebug(Log::DSProof) << "  peer:" << pnode->id;
514
515
516
517
518
519
                    pnode->PushInventory(inv);
                }
            }
        }
    }

520
    ValidationNotifier().doubleSpendFound(m_doubleSpendTx, m_tx);
521
}