LCOV - code coverage report
Current view: top level - src/consensus - tx_verify.cpp (source / functions) Hit Total Coverage
Test: fuzz_coverage.info Lines: 102 103 99.0 %
Date: 2023-10-05 15:40:34 Functions: 9 9 100.0 %
Branches: 73 100 73.0 %

           Branch data     Line data    Source code
       1                 :            : // Copyright (c) 2017-2021 The Bitcoin Core developers
       2                 :            : // Distributed under the MIT software license, see the accompanying
       3                 :            : // file COPYING or http://www.opensource.org/licenses/mit-license.php.
       4                 :            : 
       5                 :            : #include <consensus/tx_verify.h>
       6                 :            : 
       7                 :            : #include <chain.h>
       8                 :            : #include <coins.h>
       9                 :            : #include <consensus/amount.h>
      10                 :            : #include <consensus/consensus.h>
      11                 :            : #include <consensus/validation.h>
      12                 :            : #include <primitives/transaction.h>
      13                 :            : #include <script/interpreter.h>
      14                 :            : #include <util/check.h>
      15                 :            : #include <util/moneystr.h>
      16                 :            : 
      17                 :     377000 : bool IsFinalTx(const CTransaction &tx, int nBlockHeight, int64_t nBlockTime)
      18                 :            : {
      19         [ +  + ]:     377000 :     if (tx.nLockTime == 0)
      20                 :     261269 :         return true;
      21   [ +  +  +  + ]:     115731 :     if ((int64_t)tx.nLockTime < ((int64_t)tx.nLockTime < LOCKTIME_THRESHOLD ? (int64_t)nBlockHeight : nBlockTime))
      22                 :      41112 :         return true;
      23                 :            : 
      24                 :            :     // Even if tx.nLockTime isn't satisfied by nBlockHeight/nBlockTime, a
      25                 :            :     // transaction is still considered final if all inputs' nSequence ==
      26                 :            :     // SEQUENCE_FINAL (0xffffffff), in which case nLockTime is ignored.
      27                 :            :     //
      28                 :            :     // Because of this behavior OP_CHECKLOCKTIMEVERIFY/CheckLockTime() will
      29                 :            :     // also check that the spending input's nSequence != SEQUENCE_FINAL,
      30                 :            :     // ensuring that an unsatisfied nLockTime value will actually cause
      31                 :            :     // IsFinalTx() to return false here:
      32         [ +  + ]:     148357 :     for (const auto& txin : tx.vin) {
      33         [ +  + ]:      86038 :         if (!(txin.nSequence == CTxIn::SEQUENCE_FINAL))
      34                 :      12300 :             return false;
      35                 :            :     }
      36                 :      62319 :     return true;
      37                 :     377000 : }
      38                 :            : 
      39                 :     112886 : std::pair<int, int64_t> CalculateSequenceLocks(const CTransaction &tx, int flags, std::vector<int>& prevHeights, const CBlockIndex& block)
      40                 :            : {
      41         [ +  - ]:     112886 :     assert(prevHeights.size() == tx.vin.size());
      42                 :            : 
      43                 :            :     // Will be set to the equivalent height- and time-based nLockTime
      44                 :            :     // values that would be necessary to satisfy all relative lock-
      45                 :            :     // time constraints given our view of block chain history.
      46                 :            :     // The semantics of nLockTime are the last invalid height/time, so
      47                 :            :     // use -1 to have the effect of any height or time being valid.
      48                 :     112886 :     int nMinHeight = -1;
      49                 :     112886 :     int64_t nMinTime = -1;
      50                 :            : 
      51                 :            :     // tx.nVersion is signed integer so requires cast to unsigned otherwise
      52                 :            :     // we would be doing a signed comparison and half the range of nVersion
      53                 :            :     // wouldn't support BIP 68.
      54                 :     225414 :     bool fEnforceBIP68 = static_cast<uint32_t>(tx.nVersion) >= 2
      55         [ +  + ]:     112886 :                       && flags & LOCKTIME_VERIFY_SEQUENCE;
      56                 :            : 
      57                 :            :     // Do not enforce sequence numbers as a relative lock time
      58                 :            :     // unless we have been instructed to
      59         [ +  + ]:     112886 :     if (!fEnforceBIP68) {
      60                 :        358 :         return std::make_pair(nMinHeight, nMinTime);
      61                 :            :     }
      62                 :            : 
      63         [ +  + ]:    1119923 :     for (size_t txinIndex = 0; txinIndex < tx.vin.size(); txinIndex++) {
      64                 :    1007395 :         const CTxIn& txin = tx.vin[txinIndex];
      65                 :            : 
      66                 :            :         // Sequence numbers with the most significant bit set are not
      67                 :            :         // treated as relative lock-times, nor are they given any
      68                 :            :         // consensus-enforced meaning at this point.
      69         [ +  + ]:    1007395 :         if (txin.nSequence & CTxIn::SEQUENCE_LOCKTIME_DISABLE_FLAG) {
      70                 :            :             // The height of this input is not relevant for sequence locks
      71                 :     878751 :             prevHeights[txinIndex] = 0;
      72                 :     878751 :             continue;
      73                 :            :         }
      74                 :        173 : 
      75                 :     128644 :         int nCoinHeight = prevHeights[txinIndex];
      76                 :            : 
      77         [ +  + ]:     128644 :         if (txin.nSequence & CTxIn::SEQUENCE_LOCKTIME_TYPE_FLAG) {
      78                 :      30570 :             const int64_t nCoinTime{Assert(block.GetAncestor(std::max(nCoinHeight - 1, 0)))->GetMedianTimePast()};
      79                 :            :             // NOTE: Subtract 1 to maintain nLockTime semantics
      80                 :            :             // BIP 68 relative lock times have the semantics of calculating
      81                 :            :             // the first block or time at which the transaction would be
      82                 :            :             // valid. When calculating the effective block time or height
      83                 :            :             // for the entire transaction, we switch to using the
      84                 :            :             // semantics of nLockTime which is the last invalid block
      85                 :            :             // time or height.  Thus we subtract 1 from the calculated
      86                 :            :             // time or height.
      87                 :            : 
      88                 :            :             // Time-based relative lock-times are measured from the
      89                 :            :             // smallest allowed timestamp of the block containing the
      90                 :            :             // txout being spent, which is the median time past of the
      91                 :            :             // block prior.
      92                 :      30570 :             nMinTime = std::max(nMinTime, nCoinTime + (int64_t)((txin.nSequence & CTxIn::SEQUENCE_LOCKTIME_MASK) << CTxIn::SEQUENCE_LOCKTIME_GRANULARITY) - 1);
      93                 :      30570 :         } else {
      94                 :      98074 :             nMinHeight = std::max(nMinHeight, nCoinHeight + (int)(txin.nSequence & CTxIn::SEQUENCE_LOCKTIME_MASK) - 1);
      95                 :            :         }
      96                 :     128644 :     }
      97                 :            : 
      98                 :     112528 :     return std::make_pair(nMinHeight, nMinTime);
      99                 :     112886 : }
     100                 :            : 
     101                 :     112886 : bool EvaluateSequenceLocks(const CBlockIndex& block, std::pair<int, int64_t> lockPair)
     102                 :            : {
     103         [ +  - ]:     112886 :     assert(block.pprev);
     104                 :     112886 :     int64_t nBlockTime = block.pprev->GetMedianTimePast();
     105   [ +  +  +  + ]:     112886 :     if (lockPair.first >= block.nHeight || lockPair.second >= nBlockTime)
     106                 :       7780 :         return false;
     107                 :            : 
     108                 :     105106 :     return true;
     109                 :     112886 : }
     110                 :            : 
     111                 :       9758 : bool SequenceLocks(const CTransaction &tx, int flags, std::vector<int>& prevHeights, const CBlockIndex& block)
     112                 :            : {
     113                 :       9758 :     return EvaluateSequenceLocks(block, CalculateSequenceLocks(tx, flags, prevHeights, block));
     114                 :            : }
     115                 :            : 
     116                 :     448596 : unsigned int GetLegacySigOpCount(const CTransaction& tx)
     117                 :            : {
     118                 :     448596 :     unsigned int nSigOps = 0;
     119         [ +  + ]:    1486309 :     for (const auto& txin : tx.vin)
     120                 :            :     {
     121                 :    1037713 :         nSigOps += txin.scriptSig.GetSigOpCount(false);
     122                 :            :     }
     123         [ +  + ]:    7637586 :     for (const auto& txout : tx.vout)
     124                 :            :     {
     125                 :    7188990 :         nSigOps += txout.scriptPubKey.GetSigOpCount(false);
     126                 :            :     }
     127                 :     448596 :     return nSigOps;
     128                 :            : }
     129                 :            : 
     130                 :     102835 : unsigned int GetP2SHSigOpCount(const CTransaction& tx, const CCoinsViewCache& inputs)
     131                 :            : {
     132         [ +  + ]:     102835 :     if (tx.IsCoinBase())
     133                 :          1 :         return 0;
     134                 :            : 
     135                 :     102834 :     unsigned int nSigOps = 0;
     136         [ +  + ]:     567790 :     for (unsigned int i = 0; i < tx.vin.size(); i++)
     137                 :            :     {
     138                 :     464956 :         const Coin& coin = inputs.AccessCoin(tx.vin[i].prevout);
     139         [ +  - ]:     464956 :         assert(!coin.IsSpent());
     140                 :     464956 :         const CTxOut &prevout = coin.out;
     141         [ +  + ]:     464956 :         if (prevout.scriptPubKey.IsPayToScriptHash())
     142                 :        273 :             nSigOps += prevout.scriptPubKey.GetSigOpCount(tx.vin[i].scriptSig);
     143                 :     464956 :     }
     144                 :     102834 :     return nSigOps;
     145                 :     102835 : }
     146                 :            : 
     147                 :     201023 : int64_t GetTransactionSigOpCost(const CTransaction& tx, const CCoinsViewCache& inputs, uint32_t flags)
     148                 :            : {
     149                 :     201023 :     int64_t nSigOps = GetLegacySigOpCount(tx) * WITNESS_SCALE_FACTOR;
     150                 :            : 
     151         [ +  + ]:     201023 :     if (tx.IsCoinBase())
     152                 :      98200 :         return nSigOps;
     153                 :            : 
     154         [ +  + ]:     102823 :     if (flags & SCRIPT_VERIFY_P2SH) {
     155                 :     102820 :         nSigOps += GetP2SHSigOpCount(tx, inputs) * WITNESS_SCALE_FACTOR;
     156                 :     102820 :     }
     157                 :            : 
     158         [ +  + ]:     567658 :     for (unsigned int i = 0; i < tx.vin.size(); i++)
     159                 :            :     {
     160                 :     464835 :         const Coin& coin = inputs.AccessCoin(tx.vin[i].prevout);
     161         [ +  - ]:     464835 :         assert(!coin.IsSpent());
     162                 :     464835 :         const CTxOut &prevout = coin.out;
     163                 :     464835 :         nSigOps += CountWitnessSigOps(tx.vin[i].scriptSig, prevout.scriptPubKey, &tx.vin[i].scriptWitness, flags);
     164                 :     464835 :     }
     165                 :     102823 :     return nSigOps;
     166                 :     201023 : }
     167                 :            : 
     168                 :     141267 : bool Consensus::CheckTxInputs(const CTransaction& tx, TxValidationState& state, const CCoinsViewCache& inputs, int nSpendHeight, CAmount& txfee)
     169                 :            : {
     170                 :            :     // are the actual inputs available?
     171         [ +  + ]:     141267 :     if (!inputs.HaveInputs(tx)) {
     172   [ +  -  +  - ]:       6238 :         return state.Invalid(TxValidationResult::TX_MISSING_INPUTS, "bad-txns-inputs-missingorspent",
     173         [ +  - ]:       3119 :                          strprintf("%s: inputs missing/spent", __func__));
     174                 :            :     }
     175                 :            : 
     176                 :     138148 :     CAmount nValueIn = 0;
     177         [ +  + ]:     686136 :     for (unsigned int i = 0; i < tx.vin.size(); ++i) {
     178                 :     549376 :         const COutPoint &prevout = tx.vin[i].prevout;
     179                 :     549376 :         const Coin& coin = inputs.AccessCoin(prevout);
     180         [ +  - ]:     549376 :         assert(!coin.IsSpent());
     181                 :            : 
     182                 :            :         // If prev is coinbase, check that it's matured
     183   [ +  +  +  + ]:     549376 :         if (coin.IsCoinBase() && nSpendHeight - coin.nHeight < COINBASE_MATURITY) {
     184   [ +  -  +  - ]:       2774 :             return state.Invalid(TxValidationResult::TX_PREMATURE_SPEND, "bad-txns-premature-spend-of-coinbase",
     185         [ +  - ]:       1387 :                 strprintf("tried to spend coinbase at depth %d", nSpendHeight - coin.nHeight));
     186                 :            :         }
     187                 :            : 
     188                 :            :         // Check for negative or overflow input values
     189                 :     547989 :         nValueIn += coin.out.nValue;
     190   [ +  +  -  + ]:     547989 :         if (!MoneyRange(coin.out.nValue) || !MoneyRange(nValueIn)) {
     191   [ +  -  +  -  :          1 :             return state.Invalid(TxValidationResult::TX_CONSENSUS, "bad-txns-inputvalues-outofrange");
                   +  - ]
     192                 :            :         }
     193                 :     547988 :     }
     194                 :            : 
     195                 :     136760 :     const CAmount value_out = tx.GetValueOut();
     196         [ +  + ]:     136760 :     if (nValueIn < value_out) {
     197   [ +  -  +  - ]:       3590 :         return state.Invalid(TxValidationResult::TX_CONSENSUS, "bad-txns-in-belowout",
     198   [ +  -  -  +  :       1795 :             strprintf("value in (%s) < value out (%s)", FormatMoney(nValueIn), FormatMoney(value_out)));
                   +  - ]
     199                 :            :     }
     200                 :            : 
     201                 :            :     // Tally transaction fees
     202                 :     134965 :     const CAmount txfee_aux = nValueIn - value_out;
     203         [ +  - ]:     134965 :     if (!MoneyRange(txfee_aux)) {
     204   [ #  #  #  #  :          0 :         return state.Invalid(TxValidationResult::TX_CONSENSUS, "bad-txns-fee-outofrange");
                   #  # ]
     205                 :            :     }
     206                 :            : 
     207                 :     134965 :     txfee = txfee_aux;
     208                 :     134965 :     return true;
     209                 :     141267 : }

Generated by: LCOV version 1.14