]> Git Repo - VerusCoin.git/blobdiff - src/txmempool.cpp
Additional fixes for currency launch
[VerusCoin.git] / src / txmempool.cpp
index af76b3558328adccf6bff0ce5f93f4df63fd72f4..0262b44b5f2cddf1476d444135b7951a8a102351 100644 (file)
@@ -1,7 +1,7 @@
 // Copyright (c) 2009-2010 Satoshi Nakamoto
 // Copyright (c) 2009-2014 The Bitcoin Core developers
 // Distributed under the MIT software license, see the accompanying
-// file COPYING or http://www.opensource.org/licenses/mit-license.php.
+// file COPYING or https://www.opensource.org/licenses/mit-license.php .
 
 #include "txmempool.h"
 
 #include "timedata.h"
 #include "util.h"
 #include "utilmoneystr.h"
+#include "validationinterface.h"
 #include "version.h"
+#include "cc/CCinclude.h"
+#include "pbaas/pbaas.h"
+#include "pbaas/identity.h"
+#define _COINBASE_MATURITY 100
 
 using namespace std;
 
 CTxMemPoolEntry::CTxMemPoolEntry():
     nFee(0), nTxSize(0), nModSize(0), nUsageSize(0), nTime(0), dPriority(0.0),
-    hadNoDependencies(false), spendsCoinbase(false)
+    hadNoDependencies(false), spendsCoinbase(false), hasReserve(false)
 {
     nHeight = MEMPOOL_HEIGHT;
 }
@@ -28,9 +33,9 @@ CTxMemPoolEntry::CTxMemPoolEntry():
 CTxMemPoolEntry::CTxMemPoolEntry(const CTransaction& _tx, const CAmount& _nFee,
                                  int64_t _nTime, double _dPriority,
                                  unsigned int _nHeight, bool poolHasNoInputsOf,
-                                 bool _spendsCoinbase, uint32_t _nBranchId):
+                                 bool _spendsCoinbase, uint32_t _nBranchId, bool hasreserve):
     tx(_tx), nFee(_nFee), nTime(_nTime), dPriority(_dPriority), nHeight(_nHeight),
-    hadNoDependencies(poolHasNoInputsOf),
+    hadNoDependencies(poolHasNoInputsOf), hasReserve(hasreserve),
     spendsCoinbase(_spendsCoinbase), nBranchId(_nBranchId)
 {
     nTxSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION);
@@ -48,6 +53,12 @@ double
 CTxMemPoolEntry::GetPriority(unsigned int currentHeight) const
 {
     CAmount nValueIn = tx.GetValueOut()+nFee;
+    CCurrencyStateNew currencyState;
+    unsigned int lastHeight = currentHeight < 1 ? 0 : currentHeight - 1;
+    if (hasReserve && (currencyState = ConnectedChains.GetCurrencyState(currentHeight - 1)).IsValid())
+    {
+        nValueIn += currencyState.ReserveToNative(tx.GetReserveValueOut());
+    }
     double deltaPriority = ((double)(currentHeight-nHeight)*nValueIn)/nModSize;
     double dResult = dPriority + deltaPriority;
     return dResult;
@@ -103,8 +114,12 @@ bool CTxMemPool::addUnchecked(const uint256& hash, const CTxMemPoolEntry &entry,
     LOCK(cs);
     mapTx.insert(entry);
     const CTransaction& tx = mapTx.find(hash)->GetTx();
-    for (unsigned int i = 0; i < tx.vin.size(); i++)
-        mapNextTx[tx.vin[i].prevout] = CInPoint(&tx, i);
+    mapRecentlyAddedTx[tx.GetHash()] = &tx;
+    nRecentlyAddedSequence += 1;
+    if (!tx.IsCoinImport()) {
+        for (unsigned int i = 0; i < tx.vin.size(); i++)
+            mapNextTx[tx.vin[i].prevout] = CInPoint(&tx, i);
+    }
     BOOST_FOREACH(const JSDescription &joinsplit, tx.vJoinSplit) {
         BOOST_FOREACH(const uint256 &nf, joinsplit.nullifiers) {
             mapSproutNullifiers[nf] = &tx;
@@ -121,6 +136,152 @@ bool CTxMemPool::addUnchecked(const uint256& hash, const CTxMemPoolEntry &entry,
     return true;
 }
 
+void CTxMemPool::addAddressIndex(const CTxMemPoolEntry &entry, const CCoinsViewCache &view)
+{
+    LOCK(cs);
+    const CTransaction& tx = entry.GetTx();
+    std::vector<CMempoolAddressDeltaKey> inserted;
+
+    uint256 txhash = tx.GetHash();
+    if (!tx.IsCoinBase())
+    {
+        for (unsigned int j = 0; j < tx.vin.size(); j++) {
+            const CTxIn input = tx.vin[j];
+            const CTxOut &prevout = view.GetOutputFor(input);
+            CScript::ScriptType type = prevout.scriptPubKey.GetType();
+            if (type == CScript::UNKNOWN)
+                continue;
+
+            if (type == CScript::P2CC)
+            {
+                std::vector<CTxDestination> dests = prevout.scriptPubKey.GetDestinations();
+                for (auto dest : dests)
+                {
+                    if (dest.which() != COptCCParams::ADDRTYPE_INVALID)
+                    {
+                        CMempoolAddressDeltaKey key(AddressTypeFromDest(dest), GetDestinationID(dest), txhash, j, 1);
+                        CMempoolAddressDelta delta(entry.GetTime(), prevout.nValue * -1, input.prevout.hash, input.prevout.n);
+                        mapAddress.insert(make_pair(key, delta));
+                        inserted.push_back(key);
+                    }
+                }
+            }
+            else
+            {
+                CMempoolAddressDeltaKey key(type, prevout.scriptPubKey.AddressHash(), txhash, j, 1);
+                CMempoolAddressDelta delta(entry.GetTime(), prevout.nValue * -1, input.prevout.hash, input.prevout.n);
+                mapAddress.insert(make_pair(key, delta));
+                inserted.push_back(key);
+            }
+        }
+    }
+
+    for (unsigned int j = 0; j < tx.vout.size(); j++) {
+        const CTxOut &out = tx.vout[j];
+        CScript::ScriptType type = out.scriptPubKey.GetType();
+        if (type == CScript::UNKNOWN)
+            continue;
+
+
+        if (type == CScript::P2CC)
+        {
+            std::vector<CTxDestination> dests = out.scriptPubKey.GetDestinations();
+            for (auto dest : dests)
+            {
+                if (dest.which() != COptCCParams::ADDRTYPE_INVALID)
+                {
+                    CMempoolAddressDeltaKey key(AddressTypeFromDest(dest), GetDestinationID(dest), txhash, j, 0);
+                    mapAddress.insert(make_pair(key, CMempoolAddressDelta(entry.GetTime(), out.nValue)));
+                    inserted.push_back(key);
+                }
+            }
+        }
+        else
+        {
+            CMempoolAddressDeltaKey key(type, out.scriptPubKey.AddressHash(), txhash, j, 0);
+            mapAddress.insert(make_pair(key, CMempoolAddressDelta(entry.GetTime(), out.nValue)));
+            inserted.push_back(key);
+        }
+    }
+
+    mapAddressInserted.insert(make_pair(txhash, inserted));
+}
+
+bool CTxMemPool::getAddressIndex(const std::vector<std::pair<uint160, int> > &addresses, std::vector<std::pair<CMempoolAddressDeltaKey, CMempoolAddressDelta> > &results)
+{
+    LOCK(cs);
+    for (std::vector<std::pair<uint160, int> >::const_iterator it = addresses.begin(); it != addresses.end(); it++) {
+        auto ait = mapAddress.lower_bound(CMempoolAddressDeltaKey((*it).second, (*it).first));
+        while (ait != mapAddress.end() && (*ait).first.addressBytes == (*it).first && (*ait).first.type == (*it).second) {
+            results.push_back(*ait);
+            ait++;
+        }
+    }
+    return true;
+}
+
+bool CTxMemPool::removeAddressIndex(const uint256 txhash)
+{
+    LOCK(cs);
+    auto it = mapAddressInserted.find(txhash);
+
+    if (it != mapAddressInserted.end()) {
+        std::vector<CMempoolAddressDeltaKey> keys = (*it).second;
+        for (std::vector<CMempoolAddressDeltaKey>::iterator mit = keys.begin(); mit != keys.end(); mit++) {
+            mapAddress.erase(*mit);
+        }
+        mapAddressInserted.erase(it);
+    }
+
+    return true;
+}
+
+void CTxMemPool::addSpentIndex(const CTxMemPoolEntry &entry, const CCoinsViewCache &view)
+{
+    LOCK(cs);
+    const CTransaction& tx = entry.GetTx();
+    uint256 txhash = tx.GetHash();
+    std::vector<CSpentIndexKey> inserted;
+
+    for (unsigned int j = 0; j < tx.vin.size(); j++) {
+        const CTxIn input = tx.vin[j];
+        const CTxOut &prevout = view.GetOutputFor(input);
+        CSpentIndexKey key = CSpentIndexKey(input.prevout.hash, input.prevout.n);
+        CSpentIndexValue value = CSpentIndexValue(txhash, j, -1, prevout.nValue,
+            prevout.scriptPubKey.GetType(),
+            prevout.scriptPubKey.AddressHash());
+        mapSpent.insert(make_pair(key, value));
+        inserted.push_back(key);
+    }
+    mapSpentInserted.insert(make_pair(txhash, inserted));
+}
+
+bool CTxMemPool::getSpentIndex(const CSpentIndexKey &key, CSpentIndexValue &value)
+{
+    LOCK(cs);
+    std::map<CSpentIndexKey, CSpentIndexValue, CSpentIndexKeyCompare>::iterator it = mapSpent.find(key);
+    if (it != mapSpent.end()) {
+        value = it->second;
+        return true;
+    }
+    return false;
+}
+
+bool CTxMemPool::removeSpentIndex(const uint256 txhash)
+{
+    LOCK(cs);
+    auto it = mapSpentInserted.find(txhash);
+
+    if (it != mapSpentInserted.end()) {
+        std::vector<CSpentIndexKey> keys = (*it).second;
+        for (std::vector<CSpentIndexKey>::iterator mit = keys.begin(); mit != keys.end(); mit++) {
+            mapSpent.erase(*mit);
+        }
+        mapSpentInserted.erase(it);
+    }
+
+    return true;
+}
 
 void CTxMemPool::remove(const CTransaction &origTx, std::list<CTransaction>& removed, bool fRecursive)
 {
@@ -156,6 +317,7 @@ void CTxMemPool::remove(const CTransaction &origTx, std::list<CTransaction>& rem
                     txToRemove.push_back(it->second.ptx->GetHash());
                 }
             }
+            mapRecentlyAddedTx.erase(hash);
             BOOST_FOREACH(const CTxIn& txin, tx.vin)
                 mapNextTx.erase(txin.prevout);
             BOOST_FOREACH(const JSDescription& joinsplit, tx.vJoinSplit) {
@@ -172,12 +334,26 @@ void CTxMemPool::remove(const CTransaction &origTx, std::list<CTransaction>& rem
             mapTx.erase(hash);
             nTransactionsUpdated++;
             minerPolicyEstimator->removeTx(hash);
+            if (fAddressIndex)
+                removeAddressIndex(hash);
+            if (fSpentIndex)
+                removeSpentIndex(hash);
+            ClearPrioritisation(tx.GetHash());
         }
     }
 }
 
+extern uint64_t ASSETCHAINS_TIMELOCKGTE;
+int64_t komodo_block_unlocktime(uint32_t nHeight);
+
 void CTxMemPool::removeForReorg(const CCoinsViewCache *pcoins, unsigned int nMemPoolHeight, int flags)
 {
+    // Remove transactions spending a coinbase which are now immature
+    extern char ASSETCHAINS_SYMBOL[KOMODO_ASSETCHAIN_MAXLEN];
+
+    if ( ASSETCHAINS_SYMBOL[0] == 0 )
+        COINBASE_MATURITY = _COINBASE_MATURITY;
+
     // Remove transactions spending a coinbase which are now immature and no-longer-final transactions
     LOCK(cs);
     list<CTransaction> transactionsToRemove;
@@ -191,8 +367,12 @@ void CTxMemPool::removeForReorg(const CCoinsViewCache *pcoins, unsigned int nMem
                 if (it2 != mapTx.end())
                     continue;
                 const CCoins *coins = pcoins->AccessCoins(txin.prevout.hash);
-               if (nCheckFrequency != 0) assert(coins);
-                if (!coins || (coins->IsCoinBase() && ((signed long)nMemPoolHeight) - coins->nHeight < COINBASE_MATURITY)) {
+                       if (nCheckFrequency != 0) assert(coins);
+
+                if (!coins || (coins->IsCoinBase() &&
+                               (((signed long)nMemPoolHeight) - coins->nHeight < COINBASE_MATURITY) || 
+                                    ((signed long)nMemPoolHeight < komodo_block_unlocktime(coins->nHeight) && 
+                                        coins->IsAvailable(0) && coins->vout[0].nValue >= ASSETCHAINS_TIMELOCKGTE))) {
                     transactionsToRemove.push_back(tx);
                     break;
                 }
@@ -246,11 +426,108 @@ void CTxMemPool::removeWithAnchor(const uint256 &invalidRoot, ShieldedType type)
     }
 }
 
+bool CTxMemPool::checkNameConflicts(const CTransaction &tx, std::list<CTransaction> &conflicting)
+{
+    LOCK(cs);
+
+    // easy way to check if there are any transactions in the memory pool that define the name specified but are not the same as tx
+    conflicting.clear();
+
+    // first, be sure that this is a name definition. if so, it will have both a definition and reservation output. if it is a name definition,
+    // our only concern is whether or not there is a conflicting definition in the mempool. we assume that a check for any conflicting definition
+    // in the blockchain has already taken place.
+    CIdentity identity;
+    CNameReservation reservation;
+    for (auto output : tx.vout)
+    {
+        COptCCParams p;
+        if (output.scriptPubKey.IsPayToCryptoCondition(p) && p.IsValid() && p.version >= p.VERSION_V3)
+        {
+            if (p.evalCode == EVAL_IDENTITY_PRIMARY && p.vData.size() > 1)
+            {
+                if (identity.IsValid())
+                {
+                    identity = CIdentity();
+                    break;
+                }
+                else
+                {
+                    identity = CIdentity(p.vData[0]);
+                }
+            }
+            else if (p.evalCode == EVAL_IDENTITY_RESERVATION && p.vData.size() > 1)
+            {
+                if (reservation.IsValid())
+                {
+                    reservation = CNameReservation();
+                    break;
+                }
+                else
+                {
+                    reservation = CNameReservation(p.vData[0]);
+                }
+            }
+        }
+    }
+
+    // it can't conflict if it's not a definition
+    if (!(identity.IsValid() && reservation.IsValid()))
+    {
+        return false;
+    }
+
+    std::vector<std::pair<uint160, int>> addresses = std::vector<std::pair<uint160, int>>({{identity.GetID(), CScript::P2ID}});
+    std::vector<std::pair<CMempoolAddressDeltaKey, CMempoolAddressDelta>> results;
+    if (mempool.getAddressIndex(addresses, results) && results.size())
+    {
+        std::map<uint256, std::pair<CTransaction, int>> txesAndSources;   // first hash is transaction of input of prior identity or commitment output in the mempool, second pair is tx and ID output num if identity
+
+        uint256 txHash = tx.GetHash();
+        CNameReservation conflictingRes;
+        for (auto r : results)
+        {
+            if (r.first.txhash == txHash)
+            {
+                continue;
+            }
+            CTransaction mpTx;
+            if (lookup(r.first.txhash, mpTx))
+            {
+                COptCCParams p;
+                if (mpTx.vout[r.first.index].scriptPubKey.IsPayToCryptoCondition(p) && 
+                    p.IsValid() && 
+                    p.evalCode == EVAL_IDENTITY_RESERVATION && 
+                    p.vData.size() > 1 && 
+                    (conflictingRes = CNameReservation(p.vData[0])).IsValid() &&
+                    CIdentity(mpTx).IsValid())
+                {
+                    conflicting.push_back(mpTx);
+                }
+            }
+        }
+    }
+
+    return conflicting.size();
+}
+
 void CTxMemPool::removeConflicts(const CTransaction &tx, std::list<CTransaction>& removed)
 {
+    LOCK(cs);
+
+    // names are enforced as unique without requiring related spends.
+    // if this is a definition that conflicts with an existing, unrelated name definition, remove the
+    // definition that exists in the mempool
+    std::list<CTransaction> conflicting;
+    if (checkNameConflicts(tx, conflicting))
+    {
+        for (auto &remTx : conflicting)
+        {
+            remove(remTx, removed, true);
+        }
+    }
+
     // Remove transactions which depend on inputs of tx, recursively
     list<CTransaction> result;
-    LOCK(cs);
     BOOST_FOREACH(const CTxIn &txin, tx.vin) {
         std::map<COutPoint, CInPoint>::iterator it = mapNextTx.find(txin.prevout);
         if (it != mapNextTx.end()) {
@@ -284,15 +561,21 @@ void CTxMemPool::removeConflicts(const CTransaction &tx, std::list<CTransaction>
     }
 }
 
+int32_t komodo_validate_interest(const CTransaction &tx,int32_t txheight,uint32_t nTime,int32_t dispflag);
+extern char ASSETCHAINS_SYMBOL[];
+
 void CTxMemPool::removeExpired(unsigned int nBlockHeight)
 {
-    // Remove expired txs from the mempool
+    CBlockIndex *tipindex;
+    // Remove expired txs and leftover coinbases from the mempool
     LOCK(cs);
     list<CTransaction> transactionsToRemove;
     for (indexed_transaction_set::const_iterator it = mapTx.begin(); it != mapTx.end(); it++)
     {
         const CTransaction& tx = it->GetTx();
-        if (IsExpiredTx(tx, nBlockHeight)) {
+        tipindex = chainActive.LastTip();
+        if (tx.IsCoinBase() || IsExpiredTx(tx, nBlockHeight))
+        {
             transactionsToRemove.push_back(tx);
         }
     }
@@ -564,7 +847,7 @@ CTxMemPool::ReadFeeEstimates(CAutoFile& filein)
     return true;
 }
 
-void CTxMemPool::PrioritiseTransaction(const uint256 hash, const string strHash, double dPriorityDelta, const CAmount& nFeeDelta)
+void CTxMemPool::PrioritiseTransaction(const uint256 &hash, const string strHash, double dPriorityDelta, const CAmount& nFeeDelta)
 {
     {
         LOCK(cs);
@@ -572,7 +855,10 @@ void CTxMemPool::PrioritiseTransaction(const uint256 hash, const string strHash,
         deltas.first += dPriorityDelta;
         deltas.second += nFeeDelta;
     }
-    LogPrintf("PrioritiseTransaction: %s priority += %f, fee += %d\n", strHash, dPriorityDelta, FormatMoney(nFeeDelta));
+    if (fDebug)
+    {
+        LogPrintf("PrioritiseTransaction: %s priority += %f, fee += %d\n", strHash, dPriorityDelta, FormatMoney(nFeeDelta));
+    }
 }
 
 void CTxMemPool::ApplyDeltas(const uint256 hash, double &dPriorityDelta, CAmount &nFeeDelta)
@@ -590,6 +876,45 @@ void CTxMemPool::ClearPrioritisation(const uint256 hash)
 {
     LOCK(cs);
     mapDeltas.erase(hash);
+    mapReserveTransactions.erase(hash);
+}
+
+bool CTxMemPool::PrioritiseReserveTransaction(const CReserveTransactionDescriptor &txDesc, const CCurrencyStateNew &currencyState)
+{
+    LOCK(cs);
+    uint256 hash = txDesc.ptx->GetHash();
+    auto it = mapReserveTransactions.find(hash);
+    if (txDesc.IsValid())
+    {
+        mapReserveTransactions[hash] = txDesc;
+        CAmount feeDelta = txDesc.AllFeesAsNative(currencyState);
+        PrioritiseTransaction(hash, hash.GetHex().c_str(), (double)feeDelta * 100.0, feeDelta);
+        return true;
+    }
+    return false;
+}
+
+bool CTxMemPool::IsKnownReserveTransaction(const uint256 &hash, CReserveTransactionDescriptor &txDesc)
+{
+    LOCK(cs);
+    auto it = mapReserveTransactions.find(hash);
+    if (it != mapReserveTransactions.end() && it->second.IsValid())
+    {
+        // refresh transaction from mempool or delete it if not found (we may not need this at all)
+        indexed_transaction_set::const_iterator i = mapTx.find(hash);
+        if (i == mapTx.end())
+        {
+            ClearPrioritisation(hash);
+        }
+        else
+        {
+            it->second.ptx = &(i->GetTx());
+
+            txDesc = it->second;
+            return true;
+        }
+    }
+    return false;
 }
 
 bool CTxMemPool::HasNoInputsOf(const CTransaction &tx) const
@@ -612,6 +937,49 @@ bool CTxMemPool::nullifierExists(const uint256& nullifier, ShieldedType type) co
     }
 }
 
+void CTxMemPool::NotifyRecentlyAdded()
+{
+    uint64_t recentlyAddedSequence;
+    std::vector<CTransaction> txs;
+    {
+        LOCK(cs);
+        recentlyAddedSequence = nRecentlyAddedSequence;
+        for (const auto& kv : mapRecentlyAddedTx) {
+            txs.push_back(*(kv.second));
+        }
+        mapRecentlyAddedTx.clear();
+    }
+
+    // A race condition can occur here between these SyncWithWallets calls, and
+    // the ones triggered by block logic (in ConnectTip and DisconnectTip). It
+    // is harmless because calling SyncWithWallets(_, NULL) does not alter the
+    // wallet transaction's block information.
+    for (auto tx : txs) {
+        try {
+            SyncWithWallets(tx, NULL);
+        } catch (const boost::thread_interrupted&) {
+            throw;
+        } catch (const std::exception& e) {
+            PrintExceptionContinue(&e, "CTxMemPool::NotifyRecentlyAdded()");
+        } catch (...) {
+            PrintExceptionContinue(NULL, "CTxMemPool::NotifyRecentlyAdded()");
+        }
+    }
+
+    // Update the notified sequence number. We only need this in regtest mode,
+    // and should not lock on cs after calling SyncWithWallets otherwise.
+    if (Params().NetworkIDString() == "regtest") {
+        LOCK(cs);
+        nNotifiedSequence = recentlyAddedSequence;
+    }
+}
+
+bool CTxMemPool::IsFullyNotified() {
+    assert(Params().NetworkIDString() == "regtest");
+    LOCK(cs);
+    return nRecentlyAddedSequence == nNotifiedSequence;
+}
+
 CCoinsViewMemPool::CCoinsViewMemPool(CCoinsView *baseIn, CTxMemPool &mempoolIn) : CCoinsViewBacked(baseIn), mempool(mempoolIn) { }
 
 bool CCoinsViewMemPool::GetNullifier(const uint256 &nf, ShieldedType type) const
@@ -638,5 +1006,5 @@ bool CCoinsViewMemPool::HaveCoins(const uint256 &txid) const {
 size_t CTxMemPool::DynamicMemoryUsage() const {
     LOCK(cs);
     // Estimate the overhead of mapTx to be 6 pointers + an allocation, as no exact formula for boost::multi_index_contained is implemented.
-    return memusage::MallocUsage(sizeof(CTxMemPoolEntry) + 6 * sizeof(void*)) * mapTx.size() + memusage::DynamicUsage(mapNextTx) + memusage::DynamicUsage(mapDeltas) + cachedInnerUsage;
+    return memusage::MallocUsage(sizeof(CTxMemPoolEntry) + 6 * sizeof(void*)) * mapTx.size() + memusage::DynamicUsage(mapNextTx) + memusage::DynamicUsage(mapDeltas) + memusage::DynamicUsage(mapDeltas) + memusage::DynamicUsage(mapDeltas) + cachedInnerUsage;
 }
This page took 0.03787 seconds and 4 git commands to generate.