LCOV - code coverage report
Current view: top level - src/policy - policy.cpp (source / functions) Hit Total Coverage
Test: fuzz_coverage.info Lines: 144 147 98.0 %
Date: 2023-10-05 15:40:34 Functions: 11 11 100.0 %
Branches: 134 160 83.8 %

           Branch data     Line data    Source code
       1                 :            : // Copyright (c) 2009-2010 Satoshi Nakamoto
       2                 :            : // Copyright (c) 2009-2022 The Bitcoin Core developers
       3                 :            : // Distributed under the MIT software license, see the accompanying
       4                 :            : // file COPYING or http://www.opensource.org/licenses/mit-license.php.
       5                 :            : 
       6                 :            : // NOTE: This file is intended to be customised by the end user, and includes only local node policy logic
       7                 :            : 
       8                 :            : #include <policy/policy.h>
       9                 :            : 
      10                 :            : #include <coins.h>
      11                 :            : #include <consensus/amount.h>
      12                 :            : #include <consensus/consensus.h>
      13                 :            : #include <consensus/validation.h>
      14                 :            : #include <policy/feerate.h>
      15                 :            : #include <primitives/transaction.h>
      16                 :            : #include <script/interpreter.h>
      17         [ +  - ]:        173 : #include <script/script.h>
      18         [ +  - ]:        173 : #include <script/solver.h>
      19                 :            : #include <serialize.h>
      20                 :            : #include <span.h>
      21                 :            : 
      22                 :            : #include <algorithm>
      23                 :            : #include <cstddef>
      24                 :            : #include <vector>
      25                 :            : 
      26                 :    8854773 : CAmount GetDustThreshold(const CTxOut& txout, const CFeeRate& dustRelayFeeIn)
      27                 :            : {
      28                 :            :     // "Dust" is defined in terms of dustRelayFee,
      29                 :            :     // which has units satoshis-per-kilobyte.
      30                 :            :     // If you'd pay more in fees than the value of the output
      31                 :            :     // to spend something, then we consider it dust.
      32                 :            :     // A typical spendable non-segwit txout is 34 bytes big, and will
      33                 :            :     // need a CTxIn of at least 148 bytes to spend:
      34                 :            :     // so dust is a spendable txout less than
      35                 :            :     // 182*dustRelayFee/1000 (in satoshis).
      36                 :            :     // 546 satoshis at the default rate of 3000 sat/kvB.
      37                 :            :     // A typical spendable segwit P2WPKH txout is 31 bytes big, and will
      38                 :            :     // need a CTxIn of at least 67 bytes to spend:
      39                 :            :     // so dust is a spendable txout less than
      40                 :            :     // 98*dustRelayFee/1000 (in satoshis).
      41                 :            :     // 294 satoshis at the default rate of 3000 sat/kvB.
      42         [ +  + ]:    8854773 :     if (txout.scriptPubKey.IsUnspendable())
      43                 :          4 :         return 0;
      44                 :            : 
      45                 :    8854769 :     size_t nSize = GetSerializeSize(txout);
      46                 :    8854769 :     int witnessversion = 0;
      47                 :    8854769 :     std::vector<unsigned char> witnessprogram;
      48                 :            : 
      49                 :            :     // Note this computation is for spending a Segwit v0 P2WPKH output (a 33 bytes
      50                 :            :     // public key + an ECDSA signature). For Segwit v1 Taproot outputs the minimum
      51                 :            :     // satisfaction is lower (a single BIP340 signature) but this computation was
      52                 :            :     // kept to not further reduce the dust level.
      53                 :            :     // See discussion in https://github.com/bitcoin/bitcoin/pull/22779 for details.
      54   [ +  -  +  + ]:    8854769 :     if (txout.scriptPubKey.IsWitnessProgram(witnessversion, witnessprogram)) {
      55                 :            :         // sum the sizes of the parts of a transaction input
      56                 :            :         // with 75% segwit discount applied to the script size.
      57                 :    8850592 :         nSize += (32 + 4 + 1 + (107 / WITNESS_SCALE_FACTOR) + 4);
      58                 :    8850592 :     } else {
      59                 :       4177 :         nSize += (32 + 4 + 1 + 107 + 4); // the 148 mentioned above
      60                 :            :     }
      61                 :            : 
      62         [ +  - ]:    8854769 :     return dustRelayFeeIn.GetFee(nSize);
      63                 :    8854773 : }
      64                 :            : 
      65                 :    8854761 : bool IsDust(const CTxOut& txout, const CFeeRate& dustRelayFeeIn)
      66                 :            : {
      67                 :    8854761 :     return (txout.nValue < GetDustThreshold(txout, dustRelayFeeIn));
      68                 :            : }
      69                 :            : 
      70                 :    8875682 : bool IsStandard(const CScript& scriptPubKey, const std::optional<unsigned>& max_datacarrier_bytes, TxoutType& whichType)
      71                 :            : {
      72                 :    8875682 :     std::vector<std::vector<unsigned char> > vSolutions;
      73         [ +  - ]:    8875682 :     whichType = Solver(scriptPubKey, vSolutions);
      74                 :            : 
      75         [ +  + ]:    8875682 :     if (whichType == TxoutType::NONSTANDARD) {
      76                 :       7755 :         return false;
      77         [ +  + ]:    8867927 :     } else if (whichType == TxoutType::MULTISIG) {
      78                 :        354 :         unsigned char m = vSolutions.front()[0];
      79                 :        354 :         unsigned char n = vSolutions.back()[0];
      80                 :            :         // Support up to x-of-3 multisig txns as standard
      81   [ +  -  +  + ]:        354 :         if (n < 1 || n > 3)
      82                 :         29 :             return false;
      83   [ +  -  -  + ]:        325 :         if (m < 1 || m > n)
      84                 :          0 :             return false;
      85         [ +  + ]:    8867898 :     } else if (whichType == TxoutType::NULL_DATA) {
      86   [ +  +  +  -  :      12959 :         if (!max_datacarrier_bytes || scriptPubKey.size() > *max_datacarrier_bytes) {
             +  -  +  + ]
      87                 :         62 :             return false;
      88                 :            :         }
      89                 :      12897 :     }
      90                 :            : 
      91                 :    8867836 :     return true;
      92                 :    8875682 : }
      93                 :            : 
      94                 :     179759 : bool IsStandardTx(const CTransaction& tx, const std::optional<unsigned>& max_datacarrier_bytes, bool permit_bare_multisig, const CFeeRate& dust_relay_fee, std::string& reason)
      95                 :            : {
      96   [ +  +  +  + ]:     179759 :     if (tx.nVersion > TX_MAX_STANDARD_VERSION || tx.nVersion < 1) {
      97                 :       3563 :         reason = "version";
      98                 :       3563 :         return false;
      99                 :            :     }
     100                 :            : 
     101                 :            :     // Extremely large transactions with lots of inputs can cost the network
     102                 :            :     // almost as much to process as they cost the sender in fees, because
     103                 :            :     // computing signature hashes is O(ninputs*txsize). Limiting transactions
     104                 :            :     // to MAX_STANDARD_TX_WEIGHT mitigates CPU exhaustion attacks.
     105                 :     176196 :     unsigned int sz = GetTransactionWeight(tx);
     106         [ +  + ]:     176196 :     if (sz > MAX_STANDARD_TX_WEIGHT) {
     107                 :       1153 :         reason = "tx-size";
     108                 :       1153 :         return false;
     109                 :            :     }
     110                 :            : 
     111         [ +  + ]:    3348242 :     for (const CTxIn& txin : tx.vin)
     112                 :            :     {
     113                 :            :         // Biggest 'standard' txin involving only keys is a 15-of-15 P2SH
     114                 :            :         // multisig with compressed keys (remember the 520 byte limit on
     115                 :            :         // redeemScript size). That works out to a (15*(33+1))+3=513 byte
     116                 :            :         // redeemScript, 513+1+15*(73+1)+3=1627 bytes of scriptSig, which
     117                 :            :         // we round off to 1650(MAX_STANDARD_SCRIPTSIG_SIZE) bytes for
     118                 :            :         // some minor future-proofing. That's also enough to spend a
     119                 :            :         // 20-of-20 CHECKMULTISIG scriptPubKey, though such a scriptPubKey
     120                 :            :         // is not considered standard.
     121         [ +  + ]:    3174441 :         if (txin.scriptSig.size() > MAX_STANDARD_SCRIPTSIG_SIZE) {
     122                 :          9 :             reason = "scriptsig-size";
     123                 :          9 :             return false;
     124                 :            :         }
     125         [ +  + ]:    3174432 :         if (!txin.scriptSig.IsPushOnly()) {
     126                 :       1233 :             reason = "scriptsig-not-pushonly";
     127                 :       1233 :             return false;
     128                 :            :         }
     129                 :            :     }
     130                 :            : 
     131                 :     173801 :     unsigned int nDataOut = 0;
     132                 :            :     TxoutType whichType;
     133         [ +  + ]:    9040975 :     for (const CTxOut& txout : tx.vout) {
     134         [ +  + ]:    8875031 :         if (!::IsStandard(txout.scriptPubKey, max_datacarrier_bytes, whichType)) {
     135                 :       7309 :             reason = "scriptpubkey";
     136                 :       7309 :             return false;
     137                 :            :         }
     138                 :            : 
     139         [ +  + ]:    8867722 :         if (whichType == TxoutType::NULL_DATA)
     140                 :      12897 :             nDataOut++;
     141   [ +  +  +  + ]:    8854825 :         else if ((whichType == TxoutType::MULTISIG) && (!permit_bare_multisig)) {
     142                 :         76 :             reason = "bare-multisig";
     143                 :         76 :             return false;
     144         [ +  + ]:    8854749 :         } else if (IsDust(txout, dust_relay_fee)) {
     145                 :        472 :             reason = "dust";
     146                 :        472 :             return false;
     147                 :            :         }
     148                 :            :     }
     149                 :            : 
     150                 :            :     // only one OP_RETURN txout is permitted
     151         [ +  + ]:     165944 :     if (nDataOut > 1) {
     152                 :         28 :         reason = "multi-op-return";
     153                 :         28 :         return false;
     154                 :            :     }
     155                 :            : 
     156                 :     165916 :     return true;
     157                 :     179759 : }
     158                 :            : 
     159                 :            : /**
     160                 :            :  * Check transaction inputs to mitigate two
     161                 :            :  * potential denial-of-service attacks:
     162                 :            :  *
     163                 :            :  * 1. scriptSigs with extra data stuffed into them,
     164                 :            :  *    not consumed by scriptPubKey (or P2SH script)
     165                 :            :  * 2. P2SH scripts with a crazy number of expensive
     166                 :            :  *    CHECKSIG/CHECKMULTISIG operations
     167                 :            :  *
     168                 :            :  * Why bother? To avoid denial-of-service attacks; an attacker
     169                 :            :  * can submit a standard HASH... OP_EQUAL transaction,
     170                 :            :  * which will get accepted into blocks. The redemption
     171                 :            :  * script can be anything; an attacker could use a very
     172                 :            :  * expensive-to-check-upon-redemption script like:
     173                 :            :  *   DUP CHECKSIG DROP ... repeated 100 times... OP_1
     174                 :            :  *
     175                 :            :  * Note that only the non-witness portion of the transaction is checked here.
     176                 :            :  */
     177                 :      57184 : bool AreInputsStandard(const CTransaction& tx, const CCoinsViewCache& mapInputs)
     178                 :            : {
     179         [ +  + ]:      57184 :     if (tx.IsCoinBase()) {
     180                 :          7 :         return true; // Coinbases don't use vin normally
     181                 :            :     }
     182                 :            : 
     183         [ +  + ]:     415646 :     for (unsigned int i = 0; i < tx.vin.size(); i++) {
     184                 :     359689 :         const CTxOut& prev = mapInputs.AccessCoin(tx.vin[i].prevout).out;
     185                 :            : 
     186                 :     359689 :         std::vector<std::vector<unsigned char> > vSolutions;
     187         [ +  - ]:     359689 :         TxoutType whichType = Solver(prev.scriptPubKey, vSolutions);
     188   [ +  +  +  + ]:     359689 :         if (whichType == TxoutType::NONSTANDARD || whichType == TxoutType::WITNESS_UNKNOWN) {
     189                 :            :             // WITNESS_UNKNOWN failures are typically also caught with a policy
     190                 :            :             // flag in the script interpreter, but it can be helpful to catch
     191                 :            :             // this type of NONSTANDARD transaction earlier in transaction
     192                 :            :             // validation.
     193                 :        766 :             return false;
     194         [ +  + ]:     358923 :         } else if (whichType == TxoutType::SCRIPTHASH) {
     195                 :        543 :             std::vector<std::vector<unsigned char> > stack;
     196                 :            :             // convert the scriptSig into a stack, so we can inspect the redeemScript
     197   [ +  -  +  + ]:        543 :             if (!EvalScript(stack, tx.vin[i].scriptSig, SCRIPT_VERIFY_NONE, BaseSignatureChecker(), SigVersion::BASE))
     198                 :        445 :                 return false;
     199         [ +  + ]:         98 :             if (stack.empty())
     200                 :          1 :                 return false;
     201         [ +  - ]:         97 :             CScript subscript(stack.back().begin(), stack.back().end());
     202   [ +  -  +  + ]:         97 :             if (subscript.GetSigOpCount(true) > MAX_P2SH_SIGOPS) {
     203                 :          8 :                 return false;
     204                 :            :             }
     205         [ +  + ]:        543 :         }
     206      [ -  +  + ]:     359689 :     }
     207                 :            : 
     208                 :      55957 :     return true;
     209                 :      57184 : }
     210                 :            : 
     211                 :      56399 : bool IsWitnessStandard(const CTransaction& tx, const CCoinsViewCache& mapInputs)
     212                 :            : {
     213         [ +  + ]:      56399 :     if (tx.IsCoinBase())
     214                 :          7 :         return true; // Coinbases are skipped
     215                 :            : 
     216         [ +  + ]:     538636 :     for (unsigned int i = 0; i < tx.vin.size(); i++)
     217                 :            :     {
     218                 :            :         // We don't care if witness for this input is empty, since it must not be bloated.
     219                 :            :         // If the script is invalid without witness, it would be caught sooner or later during validation.
     220         [ +  + ]:     482577 :         if (tx.vin[i].scriptWitness.IsNull())
     221                 :     125006 :             continue;
     222                 :            : 
     223                 :     357571 :         const CTxOut &prev = mapInputs.AccessCoin(tx.vin[i].prevout).out;
     224                 :            : 
     225                 :            :         // get the scriptPubKey corresponding to this input:
     226                 :     357571 :         CScript prevScript = prev.scriptPubKey;
     227                 :            : 
     228                 :     357571 :         bool p2sh = false;
     229   [ +  -  +  + ]:     357571 :         if (prevScript.IsPayToScriptHash()) {
     230                 :         17 :             std::vector <std::vector<unsigned char> > stack;
     231                 :            :             // If the scriptPubKey is P2SH, we try to extract the redeemScript casually by converting the scriptSig
     232                 :            :             // into a stack. We do not check IsPushOnly nor compare the hash as these will be done later anyway.
     233                 :            :             // If the check fails at this stage, we know that this txid must be a bad one.
     234   [ +  -  +  + ]:         17 :             if (!EvalScript(stack, tx.vin[i].scriptSig, SCRIPT_VERIFY_NONE, BaseSignatureChecker(), SigVersion::BASE))
     235                 :          2 :                 return false;
     236         [ +  + ]:         15 :             if (stack.empty())
     237                 :          1 :                 return false;
     238         [ +  - ]:         14 :             prevScript = CScript(stack.back().begin(), stack.back().end());
     239                 :         14 :             p2sh = true;
     240         [ +  + ]:         17 :         }
     241                 :            : 
     242                 :     357568 :         int witnessversion = 0;
     243                 :     357568 :         std::vector<unsigned char> witnessprogram;
     244                 :            : 
     245                 :            :         // Non-witness program must not be associated with any witness
     246   [ +  -  +  + ]:     357568 :         if (!prevScript.IsWitnessProgram(witnessversion, witnessprogram))
     247                 :        295 :             return false;
     248                 :            : 
     249                 :            :         // Check P2WSH standard limits
     250   [ +  +  +  + ]:     357273 :         if (witnessversion == 0 && witnessprogram.size() == WITNESS_V0_SCRIPTHASH_SIZE) {
     251         [ +  + ]:     357104 :             if (tx.vin[i].scriptWitness.stack.back().size() > MAX_STANDARD_P2WSH_SCRIPT_SIZE)
     252                 :          2 :                 return false;
     253                 :     357102 :             size_t sizeWitnessStack = tx.vin[i].scriptWitness.stack.size() - 1;
     254         [ +  + ]:     357102 :             if (sizeWitnessStack > MAX_STANDARD_P2WSH_STACK_ITEMS)
     255                 :          1 :                 return false;
     256         [ +  + ]:     359457 :             for (unsigned int j = 0; j < sizeWitnessStack; j++) {
     257         [ +  + ]:       2383 :                 if (tx.vin[i].scriptWitness.stack[j].size() > MAX_STANDARD_P2WSH_STACK_ITEM_SIZE)
     258                 :         27 :                     return false;
     259                 :       2356 :             }
     260                 :     357074 :         }
     261                 :            : 
     262                 :            :         // Check policy limits for Taproot spends:
     263                 :            :         // - MAX_STANDARD_TAPSCRIPT_STACK_ITEM_SIZE limit for stack item size
     264                 :            :         // - No annexes
     265   [ +  +  +  +  :     357243 :         if (witnessversion == 1 && witnessprogram.size() == WITNESS_V1_TAPROOT_SIZE && !p2sh) {
                   +  - ]
     266                 :            :             // Taproot spend (non-P2SH-wrapped, version 1, witness program size 32; see BIP 341)
     267         [ +  - ]:         26 :             Span stack{tx.vin[i].scriptWitness.stack};
     268   [ +  +  +  +  :         26 :             if (stack.size() >= 2 && !stack.back().empty() && stack.back()[0] == ANNEX_TAG) {
                   +  + ]
     269                 :            :                 // Annexes are nonstandard as long as no semantics are defined for them.
     270                 :          1 :                 return false;
     271                 :            :             }
     272         [ +  + ]:         25 :             if (stack.size() >= 2) {
     273                 :            :                 // Script path spend (2 or more stack elements after removing optional annex)
     274         [ +  - ]:         14 :                 const auto& control_block = SpanPopBack(stack);
     275         [ +  - ]:         14 :                 SpanPopBack(stack); // Ignore script
     276         [ +  + ]:         14 :                 if (control_block.empty()) return false; // Empty control block is invalid
     277         [ +  + ]:         13 :                 if ((control_block[0] & TAPROOT_LEAF_MASK) == TAPROOT_LEAF_TAPSCRIPT) {
     278                 :            :                     // Leaf version 0xc0 (aka Tapscript, see BIP 342)
     279         [ +  - ]:         11 :                     for (const auto& item : stack) {
     280         [ +  + ]:         11 :                         if (item.size() > MAX_STANDARD_TAPSCRIPT_STACK_ITEM_SIZE) return false;
     281                 :            :                     }
     282                 :          0 :                 }
     283         [ +  - ]:         21 :             } else if (stack.size() == 1) {
     284                 :            :                 // Key path spend (1 stack element after removing optional annex)
     285                 :            :                 // (no policy rules apply)
     286                 :         11 :             } else {
     287                 :            :                 // 0 stack elements; this is already invalid by consensus rules
     288                 :          0 :                 return false;
     289                 :            :             }
     290                 :         21 :         }
     291      [ -  +  + ]:     357571 :     }
     292                 :      56059 :     return true;
     293                 :      56399 : }
     294                 :            : 
     295                 :  312552377 : int64_t GetVirtualTransactionSize(int64_t nWeight, int64_t nSigOpCost, unsigned int bytes_per_sigop)
     296                 :            : {
     297                 :  312552377 :     return (std::max(nWeight, nSigOpCost * bytes_per_sigop) + WITNESS_SCALE_FACTOR - 1) / WITNESS_SCALE_FACTOR;
     298                 :            : }
     299                 :            : 
     300                 :      24651 : int64_t GetVirtualTransactionSize(const CTransaction& tx, int64_t nSigOpCost, unsigned int bytes_per_sigop)
     301                 :            : {
     302                 :      24651 :     return GetVirtualTransactionSize(GetTransactionWeight(tx), nSigOpCost, bytes_per_sigop);
     303                 :            : }
     304                 :            : 
     305                 :          8 : int64_t GetVirtualTransactionInputSize(const CTxIn& txin, int64_t nSigOpCost, unsigned int bytes_per_sigop)
     306                 :            : {
     307                 :          8 :     return GetVirtualTransactionSize(GetTransactionInputWeight(txin), nSigOpCost, bytes_per_sigop);
     308                 :            : }

Generated by: LCOV version 1.14