LCOV - code coverage report
Current view: top level - src/primitives - transaction.h (source / functions) Hit Total Coverage
Test: fuzz_coverage.info Lines: 110 134 82.1 %
Date: 2023-11-10 23:46:46 Functions: 110 227 48.5 %
Branches: 61 164 37.2 %

           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                 :            : #ifndef BITCOIN_PRIMITIVES_TRANSACTION_H
       7                 :            : #define BITCOIN_PRIMITIVES_TRANSACTION_H
       8                 :            : 
       9                 :            : #include <attributes.h>
      10                 :            : #include <consensus/amount.h>
      11                 :            : #include <script/script.h>
      12                 :            : #include <serialize.h>
      13                 :            : #include <uint256.h>
      14                 :            : #include <util/transaction_identifier.h> // IWYU pragma: export
      15                 :            : 
      16                 :            : #include <cstddef>
      17                 :            : #include <cstdint>
      18                 :            : #include <ios>
      19                 :            : #include <limits>
      20                 :            : #include <memory>
      21                 :            : #include <numeric>
      22                 :            : #include <string>
      23                 :            : #include <tuple>
      24                 :            : #include <utility>
      25                 :            : #include <vector>
      26                 :            : 
      27                 :            : /**
      28                 :            :  * A flag that is ORed into the protocol version to designate that a transaction
      29                 :            :  * should be (un)serialized without witness data.
      30                 :            :  * Make sure that this does not collide with any of the values in `version.h`
      31                 :            :  * or with `ADDRV2_FORMAT`.
      32                 :            :  */
      33                 :            : static const int SERIALIZE_TRANSACTION_NO_WITNESS = 0x40000000;
      34                 :            : 
      35                 :            : /** An outpoint - a combination of a transaction hash and an index n into its vout */
      36                 :            : class COutPoint
      37                 :            : {
      38                 :            : public:
      39                 :            :     uint256 hash;
      40                 :            :     uint32_t n;
      41                 :            : 
      42                 :            :     static constexpr uint32_t NULL_INDEX = std::numeric_limits<uint32_t>::max();
      43                 :            : 
      44                 :     370289 :     COutPoint(): n(NULL_INDEX) { }
      45                 :     505800 :     COutPoint(const uint256& hashIn, uint32_t nIn): hash(hashIn), n(nIn) { }
      46                 :            : 
      47                 :    2791425 :     SERIALIZE_METHODS(COutPoint, obj) { READWRITE(obj.hash, obj.n); }
      48                 :            : 
      49                 :        150 :     void SetNull() { hash.SetNull(); n = NULL_INDEX; }
      50         [ -  + ]:     765630 :     bool IsNull() const { return (hash.IsNull() && n == NULL_INDEX); }
      51                 :            : 
      52                 :    6369139 :     friend bool operator<(const COutPoint& a, const COutPoint& b)
      53                 :            :     {
      54                 :    6369139 :         int cmp = a.hash.Compare(b.hash);
      55 [ +  + ][ +  + ]:    6369139 :         return cmp < 0 || (cmp == 0 && a.n < b.n);
      56                 :            :     }
      57                 :            : 
      58                 :      48626 :     friend bool operator==(const COutPoint& a, const COutPoint& b)
      59                 :            :     {
      60         [ +  + ]:      48626 :         return (a.hash == b.hash && a.n == b.n);
      61                 :            :     }
      62                 :            : 
      63                 :            :     friend bool operator!=(const COutPoint& a, const COutPoint& b)
      64                 :            :     {
      65                 :            :         return !(a == b);
      66                 :            :     }
      67                 :            : 
      68                 :            :     std::string ToString() const;
      69                 :            : };
      70                 :            : 
      71                 :            : /** An input of a transaction.  It contains the location of the previous
      72                 :            :  * transaction's output that it claims and a signature that matches the
      73                 :            :  * output's public key.
      74                 :            :  */
      75                 :     165371 : class CTxIn
      76                 :            : {
      77                 :            : public:
      78                 :            :     COutPoint prevout;
      79                 :            :     CScript scriptSig;
      80                 :            :     uint32_t nSequence;
      81                 :            :     CScriptWitness scriptWitness; //!< Only serialized through CTransaction
      82                 :            : 
      83                 :            :     /**
      84                 :            :      * Setting nSequence to this value for every input in a transaction
      85                 :            :      * disables nLockTime/IsFinalTx().
      86                 :            :      * It fails OP_CHECKLOCKTIMEVERIFY/CheckLockTime() for any input that has
      87                 :            :      * it set (BIP 65).
      88                 :            :      * It has SEQUENCE_LOCKTIME_DISABLE_FLAG set (BIP 68/112).
      89                 :            :      */
      90                 :            :     static const uint32_t SEQUENCE_FINAL = 0xffffffff;
      91                 :            :     /**
      92                 :            :      * This is the maximum sequence number that enables both nLockTime and
      93                 :            :      * OP_CHECKLOCKTIMEVERIFY (BIP 65).
      94                 :            :      * It has SEQUENCE_LOCKTIME_DISABLE_FLAG set (BIP 68/112).
      95                 :            :      */
      96                 :            :     static const uint32_t MAX_SEQUENCE_NONFINAL{SEQUENCE_FINAL - 1};
      97                 :            : 
      98                 :            :     // Below flags apply in the context of BIP 68. BIP 68 requires the tx
      99                 :            :     // version to be set to 2, or higher.
     100                 :            :     /**
     101                 :            :      * If this flag is set, CTxIn::nSequence is NOT interpreted as a
     102                 :            :      * relative lock-time.
     103                 :            :      * It skips SequenceLocks() for any input that has it set (BIP 68).
     104                 :            :      * It fails OP_CHECKSEQUENCEVERIFY/CheckSequence() for any input that has
     105                 :            :      * it set (BIP 112).
     106                 :            :      */
     107                 :            :     static const uint32_t SEQUENCE_LOCKTIME_DISABLE_FLAG = (1U << 31);
     108                 :            : 
     109                 :            :     /**
     110                 :            :      * If CTxIn::nSequence encodes a relative lock-time and this flag
     111                 :            :      * is set, the relative lock-time has units of 512 seconds,
     112                 :            :      * otherwise it specifies blocks with a granularity of 1. */
     113                 :            :     static const uint32_t SEQUENCE_LOCKTIME_TYPE_FLAG = (1 << 22);
     114                 :            : 
     115                 :            :     /**
     116                 :            :      * If CTxIn::nSequence encodes a relative lock-time, this mask is
     117                 :            :      * applied to extract that lock-time from the sequence field. */
     118                 :            :     static const uint32_t SEQUENCE_LOCKTIME_MASK = 0x0000ffff;
     119                 :            : 
     120                 :            :     /**
     121                 :            :      * In order to use the same number of bits to encode roughly the
     122                 :            :      * same wall-clock duration, and because blocks are naturally
     123                 :            :      * limited to occur every 600s on average, the minimum granularity
     124                 :            :      * for time-based relative lock-time is fixed at 512 seconds.
     125                 :            :      * Converting from CTxIn::nSequence to seconds is performed by
     126                 :            :      * multiplying by 512 = 2^9, or equivalently shifting up by
     127                 :            :      * 9 bits. */
     128                 :            :     static const int SEQUENCE_LOCKTIME_GRANULARITY = 9;
     129                 :            : 
     130         [ +  - ]:       2497 :     CTxIn()
     131                 :            :     {
     132                 :       2497 :         nSequence = SEQUENCE_FINAL;
     133                 :       2497 :     }
     134                 :            : 
     135                 :            :     explicit CTxIn(COutPoint prevoutIn, CScript scriptSigIn=CScript(), uint32_t nSequenceIn=SEQUENCE_FINAL);
     136                 :            :     CTxIn(uint256 hashPrevTx, uint32_t nOut, CScript scriptSigIn=CScript(), uint32_t nSequenceIn=SEQUENCE_FINAL);
     137                 :            : 
     138                 :     782061 :     SERIALIZE_METHODS(CTxIn, obj) { READWRITE(obj.prevout, obj.scriptSig, obj.nSequence); }
     139                 :            : 
     140                 :          0 :     friend bool operator==(const CTxIn& a, const CTxIn& b)
     141                 :            :     {
     142         [ #  # ]:          0 :         return (a.prevout   == b.prevout &&
     143         [ #  # ]:          0 :                 a.scriptSig == b.scriptSig &&
     144                 :          0 :                 a.nSequence == b.nSequence);
     145                 :            :     }
     146                 :            : 
     147                 :            :     friend bool operator!=(const CTxIn& a, const CTxIn& b)
     148                 :            :     {
     149                 :            :         return !(a == b);
     150                 :            :     }
     151                 :            : 
     152                 :            :     std::string ToString() const;
     153                 :            : };
     154                 :            : 
     155                 :            : /** An output of a transaction.  It contains the public key that the next input
     156                 :            :  * must be able to sign with to claim it.
     157                 :            :  */
     158                 :          0 : class CTxOut
     159                 :            : {
     160                 :            : public:
     161                 :            :     CAmount nValue;
     162                 :            :     CScript scriptPubKey;
     163                 :            : 
     164                 :     157286 :     CTxOut()
     165                 :            :     {
     166         [ +  - ]:     157286 :         SetNull();
     167                 :     157286 :     }
     168                 :            : 
     169                 :            :     CTxOut(const CAmount& nValueIn, CScript scriptPubKeyIn);
     170                 :            : 
     171                 :     525687 :     SERIALIZE_METHODS(CTxOut, obj) { READWRITE(obj.nValue, obj.scriptPubKey); }
     172                 :            : 
     173                 :     166670 :     void SetNull()
     174                 :            :     {
     175                 :     166670 :         nValue = -1;
     176                 :     166670 :         scriptPubKey.clear();
     177                 :     166670 :     }
     178                 :            : 
     179                 :     146566 :     bool IsNull() const
     180                 :            :     {
     181                 :     146566 :         return (nValue == -1);
     182                 :            :     }
     183                 :            : 
     184                 :          0 :     friend bool operator==(const CTxOut& a, const CTxOut& b)
     185                 :            :     {
     186         [ #  # ]:          0 :         return (a.nValue       == b.nValue &&
     187                 :          0 :                 a.scriptPubKey == b.scriptPubKey);
     188                 :            :     }
     189                 :            : 
     190                 :          0 :     friend bool operator!=(const CTxOut& a, const CTxOut& b)
     191                 :            :     {
     192                 :          0 :         return !(a == b);
     193                 :            :     }
     194                 :            : 
     195                 :            :     std::string ToString() const;
     196                 :            : };
     197                 :            : 
     198                 :            : struct CMutableTransaction;
     199                 :            : 
     200                 :            : /**
     201                 :            :  * Basic transaction serialization format:
     202                 :            :  * - int32_t nVersion
     203                 :            :  * - std::vector<CTxIn> vin
     204                 :            :  * - std::vector<CTxOut> vout
     205                 :            :  * - uint32_t nLockTime
     206                 :            :  *
     207                 :            :  * Extended transaction serialization format:
     208                 :            :  * - int32_t nVersion
     209                 :            :  * - unsigned char dummy = 0x00
     210                 :            :  * - unsigned char flags (!= 0)
     211                 :            :  * - std::vector<CTxIn> vin
     212                 :            :  * - std::vector<CTxOut> vout
     213                 :            :  * - if (flags & 1):
     214                 :            :  *   - CScriptWitness scriptWitness; (deserialized into CTxIn)
     215                 :            :  * - uint32_t nLockTime
     216                 :            :  */
     217                 :            : template<typename Stream, typename TxType>
     218                 :        592 : inline void UnserializeTransaction(TxType& tx, Stream& s) {
     219                 :        592 :     const bool fAllowWitness = !(s.GetVersion() & SERIALIZE_TRANSACTION_NO_WITNESS);
     220                 :            : 
     221                 :        592 :     s >> tx.nVersion;
     222                 :        592 :     unsigned char flags = 0;
     223                 :        592 :     tx.vin.clear();
     224                 :        592 :     tx.vout.clear();
     225                 :            :     /* Try to read the vin. In case the dummy is there, this will be read as an empty vector. */
     226                 :        592 :     s >> tx.vin;
     227 [ +  + ][ +  + ]:        592 :     if (tx.vin.size() == 0 && fAllowWitness) {
         [ #  # ][ #  # ]
     228                 :            :         /* We read a dummy or an empty vin. */
     229                 :        226 :         s >> flags;
     230 [ +  + ][ #  # ]:        226 :         if (flags != 0) {
     231                 :        211 :             s >> tx.vin;
     232                 :        211 :             s >> tx.vout;
     233                 :        211 :         }
     234                 :        226 :     } else {
     235                 :            :         /* We read a non-empty vin. Assume a normal vout follows. */
     236                 :        366 :         s >> tx.vout;
     237                 :            :     }
     238 [ +  + ][ +  + ]:        592 :     if ((flags & 1) && fAllowWitness) {
         [ #  # ][ #  # ]
     239                 :            :         /* The witness flag is present, and we support witnesses. */
     240                 :        180 :         flags ^= 1;
     241 [ +  + ][ #  # ]:        750 :         for (size_t i = 0; i < tx.vin.size(); i++) {
     242                 :        570 :             s >> tx.vin[i].scriptWitness.stack;
     243                 :        570 :         }
     244 [ +  + ][ #  # ]:        180 :         if (!tx.HasWitness()) {
     245                 :            :             /* It's illegal to encode witnesses when all witness stacks are empty. */
     246 [ +  - ][ #  # ]:          5 :             throw std::ios_base::failure("Superfluous witness record");
     247                 :            :         }
     248                 :        175 :     }
     249 [ +  + ][ #  # ]:        587 :     if (flags) {
     250                 :            :         /* Unknown flag in the serialization */
     251 [ +  - ][ #  # ]:          5 :         throw std::ios_base::failure("Unknown transaction optional data");
     252                 :            :     }
     253                 :        582 :     s >> tx.nLockTime;
     254                 :        582 : }
     255                 :            : 
     256                 :            : template<typename Stream, typename TxType>
     257                 :      24747 : inline void SerializeTransaction(const TxType& tx, Stream& s) {
     258                 :      24747 :     const bool fAllowWitness = !(s.GetVersion() & SERIALIZE_TRANSACTION_NO_WITNESS);
     259                 :            : 
     260                 :      24747 :     s << tx.nVersion;
     261                 :      24747 :     unsigned char flags = 0;
     262                 :            :     // Consistency check
     263 [ +  + ][ +  + ]:      24747 :     if (fAllowWitness) {
         [ #  # ][ #  # ]
         [ #  # ][ #  # ]
     264                 :            :         /* Check whether witnesses need to be serialized. */
     265 [ +  + ][ -  + ]:       5856 :         if (tx.HasWitness()) {
         [ #  # ][ #  # ]
         [ #  # ][ #  # ]
     266                 :       1990 :             flags |= 1;
     267                 :       1990 :         }
     268                 :       5856 :     }
     269 [ +  + ][ +  + ]:      24747 :     if (flags) {
         [ #  # ][ #  # ]
         [ #  # ][ #  # ]
     270                 :            :         /* Use extended format in case witnesses are to be serialized. */
     271                 :       1990 :         std::vector<CTxIn> vinDummy;
     272 [ +  - ][ +  - ]:       1990 :         s << vinDummy;
         [ #  # ][ #  # ]
         [ #  # ][ #  # ]
     273 [ +  - ][ +  - ]:       1990 :         s << flags;
         [ #  # ][ #  # ]
         [ #  # ][ #  # ]
     274                 :       1990 :     }
     275                 :      24747 :     s << tx.vin;
     276                 :      24747 :     s << tx.vout;
     277 [ +  + ][ +  + ]:      24747 :     if (flags & 1) {
         [ #  # ][ #  # ]
         [ #  # ][ #  # ]
     278 [ +  + ][ +  + ]:       3980 :         for (size_t i = 0; i < tx.vin.size(); i++) {
         [ #  # ][ #  # ]
         [ #  # ][ #  # ]
     279                 :       1990 :             s << tx.vin[i].scriptWitness.stack;
     280                 :       1990 :         }
     281                 :       1990 :     }
     282                 :      24747 :     s << tx.nLockTime;
     283                 :      24747 : }
     284                 :            : 
     285                 :            : template<typename TxType>
     286                 :       7027 : inline CAmount CalculateOutputValue(const TxType& tx)
     287                 :            : {
     288                 :      23784 :     return std::accumulate(tx.vout.cbegin(), tx.vout.cend(), CAmount{0}, [](CAmount sum, const auto& txout) { return sum + txout.nValue; });
     289                 :            : }
     290                 :            : 
     291                 :            : 
     292                 :            : /** The basic transaction that is broadcasted on the network and contained in
     293                 :            :  * blocks.  A transaction can contain multiple inputs and outputs.
     294                 :            :  */
     295                 :        150 : class CTransaction
     296                 :            : {
     297                 :            : public:
     298                 :            :     // Default transaction version.
     299                 :            :     static const int32_t CURRENT_VERSION=2;
     300                 :            : 
     301                 :            :     // The local variables are made const to prevent unintended modification
     302                 :            :     // without updating the cached hash value. However, CTransaction is not
     303                 :            :     // actually immutable; deserialization and assignment are implemented,
     304                 :            :     // and bypass the constness. This is safe, as they update the entire
     305                 :            :     // structure, including the hash.
     306                 :            :     const std::vector<CTxIn> vin;
     307                 :            :     const std::vector<CTxOut> vout;
     308                 :            :     const int32_t nVersion;
     309                 :            :     const uint32_t nLockTime;
     310                 :            : 
     311                 :            : private:
     312                 :            :     /** Memory only. */
     313                 :            :     const Txid hash;
     314                 :            :     const Wtxid m_witness_hash;
     315                 :            : 
     316                 :            :     Txid ComputeHash() const;
     317                 :            :     Wtxid ComputeWitnessHash() const;
     318                 :            : 
     319                 :            : public:
     320                 :            :     /** Convert a CMutableTransaction into a CTransaction. */
     321                 :            :     explicit CTransaction(const CMutableTransaction& tx);
     322                 :            :     explicit CTransaction(CMutableTransaction&& tx);
     323                 :            : 
     324                 :            :     template <typename Stream>
     325                 :      24747 :     inline void Serialize(Stream& s) const {
     326                 :      24747 :         SerializeTransaction(*this, s);
     327                 :      24747 :     }
     328                 :            : 
     329                 :            :     /** This deserializing constructor is provided instead of an Unserialize method.
     330                 :            :      *  Unserialize is not possible, since it would require overwriting const fields. */
     331                 :            :     template <typename Stream>
     332 [ +  - ][ #  # ]:        152 :     CTransaction(deserialize_type, Stream& s) : CTransaction(CMutableTransaction(deserialize, s)) {}
     333                 :            : 
     334                 :          0 :     bool IsNull() const {
     335         [ #  # ]:          0 :         return vin.empty() && vout.empty();
     336                 :            :     }
     337                 :            : 
     338                 :       2110 :     const Txid& GetHash() const LIFETIMEBOUND { return hash; }
     339                 :          0 :     const Wtxid& GetWitnessHash() const LIFETIMEBOUND { return m_witness_hash; };
     340                 :            : 
     341                 :            :     // Return sum of txouts.
     342                 :            :     CAmount GetValueOut() const;
     343                 :            : 
     344                 :            :     /**
     345                 :            :      * Get the total transaction size in bytes, including witness data.
     346                 :            :      * "Total Size" defined in BIP141 and BIP144.
     347                 :            :      * @return Total transaction size in bytes
     348                 :            :      */
     349                 :            :     unsigned int GetTotalSize() const;
     350                 :            : 
     351                 :     765630 :     bool IsCoinBase() const
     352                 :            :     {
     353         [ -  + ]:     765630 :         return (vin.size() == 1 && vin[0].prevout.IsNull());
     354                 :            :     }
     355                 :            : 
     356                 :          0 :     friend bool operator==(const CTransaction& a, const CTransaction& b)
     357                 :            :     {
     358                 :          0 :         return a.hash == b.hash;
     359                 :            :     }
     360                 :            : 
     361                 :          0 :     friend bool operator!=(const CTransaction& a, const CTransaction& b)
     362                 :            :     {
     363                 :          0 :         return a.hash != b.hash;
     364                 :            :     }
     365                 :            : 
     366                 :            :     std::string ToString() const;
     367                 :            : 
     368                 :      19832 :     bool HasWitness() const
     369                 :            :     {
     370         [ +  + ]:     223337 :         for (size_t i = 0; i < vin.size(); i++) {
     371         [ +  + ]:     206585 :             if (!vin[i].scriptWitness.IsNull()) {
     372                 :       3080 :                 return true;
     373                 :            :             }
     374                 :     203505 :         }
     375                 :      16752 :         return false;
     376                 :      19832 :     }
     377                 :            : };
     378                 :            : 
     379                 :            : /** A mutable version of CTransaction. */
     380                 :          0 : struct CMutableTransaction
     381                 :            : {
     382                 :            :     std::vector<CTxIn> vin;
     383                 :            :     std::vector<CTxOut> vout;
     384                 :            :     int32_t nVersion;
     385                 :            :     uint32_t nLockTime;
     386                 :            : 
     387                 :            :     explicit CMutableTransaction();
     388                 :            :     explicit CMutableTransaction(const CTransaction& tx);
     389                 :            : 
     390                 :            :     template <typename Stream>
     391                 :          0 :     inline void Serialize(Stream& s) const {
     392                 :          0 :         SerializeTransaction(*this, s);
     393                 :          0 :     }
     394                 :            : 
     395                 :            : 
     396                 :            :     template <typename Stream>
     397                 :        941 :     inline void Unserialize(Stream& s) {
     398                 :        941 :         UnserializeTransaction(*this, s);
     399                 :        941 :     }
     400                 :            : 
     401                 :            :     template <typename Stream>
     402                 :        152 :     CMutableTransaction(deserialize_type, Stream& s) {
     403 [ +  - ][ #  # ]:        152 :         Unserialize(s);
     404                 :        152 :     }
     405                 :            : 
     406                 :            :     /** Compute the hash of this CMutableTransaction. This is computed on the
     407                 :            :      * fly, as opposed to GetHash() in CTransaction, which uses a cached result.
     408                 :            :      */
     409                 :            :     Txid GetHash() const;
     410                 :            : 
     411                 :        180 :     bool HasWitness() const
     412                 :            :     {
     413         [ +  + ]:        183 :         for (size_t i = 0; i < vin.size(); i++) {
     414         [ +  + ]:        178 :             if (!vin[i].scriptWitness.IsNull()) {
     415                 :        175 :                 return true;
     416                 :            :             }
     417                 :          3 :         }
     418                 :          5 :         return false;
     419                 :        180 :     }
     420                 :            : };
     421                 :            : 
     422                 :            : typedef std::shared_ptr<const CTransaction> CTransactionRef;
     423                 :       4480 : template <typename Tx> static inline CTransactionRef MakeTransactionRef(Tx&& txIn) { return std::make_shared<const CTransaction>(std::forward<Tx>(txIn)); }
     424                 :            : 
     425                 :            : /** A generic txid reference (txid or wtxid). */
     426                 :            : class GenTxid
     427                 :            : {
     428                 :            :     bool m_is_wtxid;
     429                 :            :     uint256 m_hash;
     430                 :     328825 :     GenTxid(bool is_wtxid, const uint256& hash) : m_is_wtxid(is_wtxid), m_hash(hash) {}
     431                 :            : 
     432                 :            : public:
     433                 :     328825 :     static GenTxid Txid(const uint256& hash) { return GenTxid{false, hash}; }
     434                 :          0 :     static GenTxid Wtxid(const uint256& hash) { return GenTxid{true, hash}; }
     435                 :     328825 :     bool IsWtxid() const { return m_is_wtxid; }
     436                 :     328825 :     const uint256& GetHash() const LIFETIMEBOUND { return m_hash; }
     437         [ #  # ]:          0 :     friend bool operator==(const GenTxid& a, const GenTxid& b) { return a.m_is_wtxid == b.m_is_wtxid && a.m_hash == b.m_hash; }
     438                 :          0 :     friend bool operator<(const GenTxid& a, const GenTxid& b) { return std::tie(a.m_is_wtxid, a.m_hash) < std::tie(b.m_is_wtxid, b.m_hash); }
     439                 :            : };
     440                 :            : 
     441                 :            : #endif // BITCOIN_PRIMITIVES_TRANSACTION_H

Generated by: LCOV version 1.14