Branch data Line data Source code
1 : : // Copyright (c) 2009-2010 Satoshi Nakamoto
2 : : // Copyright (c) 2009-present 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 <primitives/transaction_identifier.h> // IWYU pragma: export
12 : : #include <script/script.h>
13 : : #include <serialize.h>
14 : :
15 : : #include <algorithm>
16 : : #include <compare>
17 : : #include <cstddef>
18 : : #include <cstdint>
19 : : #include <ios>
20 : : #include <limits>
21 : : #include <memory>
22 : : #include <numeric>
23 : : #include <string>
24 : : #include <tuple>
25 : : #include <utility>
26 : : #include <vector>
27 : :
28 : : /** An outpoint - a combination of a transaction hash and an index n into its vout */
29 : : class COutPoint
30 : : {
31 : : public:
32 : : Txid hash;
33 : : uint32_t n;
34 : :
35 : : static constexpr uint32_t NULL_INDEX = std::numeric_limits<uint32_t>::max();
36 : :
37 [ + + ]: 50102454 : COutPoint(): n(NULL_INDEX) { }
[ + - + - ]
38 [ + - ][ + - ]: 47071307 : COutPoint(const Txid& hashIn, uint32_t nIn): hash(hashIn), n(nIn) { }
[ + - + - ]
[ + - + -
+ - + - +
- ]
39 : :
40 [ + - - + ]: 3912021387 : SERIALIZE_METHODS(COutPoint, obj) { READWRITE(obj.hash, obj.n); }
41 : :
42 [ + - ]: 837498 : void SetNull() { hash.SetNull(); n = NULL_INDEX; }
43 [ + + + + ]: 60277838 : bool IsNull() const { return (hash.IsNull() && n == NULL_INDEX); }
44 : :
45 : 764441090 : friend bool operator<(const COutPoint& a, const COutPoint& b)
46 : : {
47 : 764441090 : return std::tie(a.hash, a.n) < std::tie(b.hash, b.n);
48 : : }
49 : :
50 : 202805606 : friend bool operator==(const COutPoint& a, const COutPoint& b)
51 : : {
52 [ + + + + ]: 202805606 : return (a.hash == b.hash && a.n == b.n);
53 : : }
54 : :
55 : : std::string ToString() const;
56 : : };
57 : :
58 : : /** An input of a transaction. It contains the location of the previous
59 : : * transaction's output that it claims and a signature that matches the
60 : : * output's public key.
61 : : */
62 : 111564111 : class CTxIn
63 : : {
64 : : public:
65 : : COutPoint prevout;
66 : : CScript scriptSig;
67 : : uint32_t nSequence;
68 : : CScriptWitness scriptWitness; //!< Only serialized through CTransaction
69 : :
70 : : /**
71 : : * Setting nSequence to this value for every input in a transaction
72 : : * disables nLockTime/IsFinalTx().
73 : : * It fails OP_CHECKLOCKTIMEVERIFY/CheckLockTime() for any input that has
74 : : * it set (BIP 65).
75 : : * It has SEQUENCE_LOCKTIME_DISABLE_FLAG set (BIP 68/112).
76 : : */
77 : : static constexpr uint32_t SEQUENCE_FINAL{0xffffffff};
78 : : /**
79 : : * This is the maximum sequence number that enables both nLockTime and
80 : : * OP_CHECKLOCKTIMEVERIFY (BIP 65).
81 : : * It has SEQUENCE_LOCKTIME_DISABLE_FLAG set (BIP 68/112).
82 : : */
83 : : static constexpr uint32_t MAX_SEQUENCE_NONFINAL{SEQUENCE_FINAL - 1};
84 : :
85 : : // Below flags apply in the context of BIP 68. BIP 68 requires the tx
86 : : // version to be set to 2, or higher.
87 : : /**
88 : : * If this flag is set, CTxIn::nSequence is NOT interpreted as a
89 : : * relative lock-time.
90 : : * It skips SequenceLocks() for any input that has it set (BIP 68).
91 : : * It fails OP_CHECKSEQUENCEVERIFY/CheckSequence() for any input that has
92 : : * it set (BIP 112).
93 : : */
94 : : static constexpr uint32_t SEQUENCE_LOCKTIME_DISABLE_FLAG{1U << 31};
95 : :
96 : : /**
97 : : * If CTxIn::nSequence encodes a relative lock-time and this flag
98 : : * is set, the relative lock-time has units of 512 seconds,
99 : : * otherwise it specifies blocks with a granularity of 1. */
100 : : static constexpr uint32_t SEQUENCE_LOCKTIME_TYPE_FLAG{1 << 22};
101 : :
102 : : /**
103 : : * If CTxIn::nSequence encodes a relative lock-time, this mask is
104 : : * applied to extract that lock-time from the sequence field. */
105 : : static constexpr uint32_t SEQUENCE_LOCKTIME_MASK{0x0000ffff};
106 : :
107 : : /**
108 : : * In order to use the same number of bits to encode roughly the
109 : : * same wall-clock duration, and because blocks are naturally
110 : : * limited to occur every 600s on average, the minimum granularity
111 : : * for time-based relative lock-time is fixed at 512 seconds.
112 : : * Converting from CTxIn::nSequence to seconds is performed by
113 : : * multiplying by 512 = 2^9, or equivalently shifting up by
114 : : * 9 bits. */
115 : : static constexpr int SEQUENCE_LOCKTIME_GRANULARITY{9};
116 : :
117 : 28727800 : CTxIn()
118 : 28727800 : {
119 : 28727800 : nSequence = SEQUENCE_FINAL;
120 : 28727800 : }
121 : :
122 : : explicit CTxIn(COutPoint prevoutIn, CScript scriptSigIn=CScript(), uint32_t nSequenceIn=SEQUENCE_FINAL);
123 : : CTxIn(Txid hashPrevTx, uint32_t nOut, CScript scriptSigIn=CScript(), uint32_t nSequenceIn=SEQUENCE_FINAL);
124 : :
125 : 3881650307 : SERIALIZE_METHODS(CTxIn, obj) { READWRITE(obj.prevout, obj.scriptSig, obj.nSequence); }
126 : :
127 : 5438277 : friend bool operator==(const CTxIn& a, const CTxIn& b)
128 : : {
129 [ + - ]: 148430 : return (a.prevout == b.prevout &&
130 [ + + ]: 5438277 : a.scriptSig == b.scriptSig &&
131 [ - + ]: 148430 : a.nSequence == b.nSequence);
132 : : }
133 : :
134 : : std::string ToString() const;
135 : : };
136 : :
137 : : /** An output of a transaction. It contains the public key that the next input
138 : : * must be able to sign with to claim it.
139 : : */
140 [ + + ][ + - ]: 341142201 : class CTxOut
[ + + + + ]
[ + - + + ]
[ + - + - ]
[ - - + -
+ - - - +
- ]
[ + - + -
+ - + - +
- + - ]
141 : : {
142 : : public:
143 : : CAmount nValue;
144 : : CScript scriptPubKey;
145 : :
146 : 56917407 : CTxOut()
147 : 56917407 : {
148 : 113834814 : SetNull();
149 : 56917407 : }
150 : :
151 : : CTxOut(const CAmount& nValueIn, CScript scriptPubKeyIn);
152 : :
153 : 833994998 : SERIALIZE_METHODS(CTxOut, obj) { READWRITE(obj.nValue, obj.scriptPubKey); }
154 : :
155 : 57318865 : void SetNull()
156 : : {
157 : 57318865 : nValue = -1;
158 : 57318865 : scriptPubKey.clear();
159 : : }
160 : :
161 : 59274725 : bool IsNull() const
162 : : {
163 [ + + ]: 59265412 : return (nValue == -1);
[ + + + + ]
[ - + - +
- + ][ - -
+ + + + -
+ ][ + - +
+ + + +
- ][ - - -
+ - + - +
- - ]
[ + + + +
+ + + + +
+ + + ]
[ - + - +
- + - + -
+ - + - +
+ + - - -
+ + + ]
[ - - + +
+ + + + +
- + + + +
+ + + + -
+ - + + +
- + + + -
- ]
164 : : }
165 : :
166 : 1040656 : friend bool operator==(const CTxOut& a, const CTxOut& b)
167 : : {
168 [ + + + + ]: 2081057 : return (a.nValue == b.nValue &&
169 : 1040401 : a.scriptPubKey == b.scriptPubKey);
170 : : }
171 : :
172 : : std::string ToString() const;
173 : : };
174 : :
175 : : struct CMutableTransaction;
176 : :
177 : : struct TransactionSerParams {
178 : : const bool allow_witness;
179 [ + + ]: 49110078 : SER_PARAMS_OPFUNC
[ + - + + ]
[ + - + -
+ - ][ + -
+ + + + +
+ ][ + - +
+ + + + +
+ + ]
[ - - - -
- - - - -
- + - +
- ]
[ - - + -
+ - + + +
+ - - + -
- - + - +
- ]
180 : : };
181 : : inline constexpr TransactionSerParams TX_WITH_WITNESS{.allow_witness = true};
182 : : inline constexpr TransactionSerParams TX_NO_WITNESS{.allow_witness = false};
183 : :
184 : : /**
185 : : * Basic transaction serialization format:
186 : : * - uint32_t version
187 : : * - std::vector<CTxIn> vin
188 : : * - std::vector<CTxOut> vout
189 : : * - uint32_t nLockTime
190 : : *
191 : : * Extended transaction serialization format:
192 : : * - uint32_t version
193 : : * - unsigned char dummy = 0x00
194 : : * - unsigned char flags (!= 0)
195 : : * - std::vector<CTxIn> vin
196 : : * - std::vector<CTxOut> vout
197 : : * - if (flags & 1):
198 : : * - CScriptWitness scriptWitness; (deserialized into CTxIn)
199 : : * - uint32_t nLockTime
200 : : */
201 : : template<typename Stream, typename TxType>
202 : 6947350 : void UnserializeTransaction(TxType& tx, Stream& s, const TransactionSerParams& params)
203 : : {
204 : 6947350 : const bool fAllowWitness = params.allow_witness;
205 : :
206 : 6947350 : s >> tx.version;
207 : 6944805 : unsigned char flags = 0;
208 : 6944805 : tx.vin.clear();
209 : 6944805 : tx.vout.clear();
210 : : /* Try to read the vin. In case the dummy is there, this will be read as an empty vector. */
211 : 6944805 : s >> tx.vin;
212 [ - + + + : 6928060 : if (tx.vin.size() == 0 && fAllowWitness) {
+ + ]
213 : : /* We read a dummy or an empty vin. */
214 : 3920603 : s >> flags;
215 [ + + ][ # # ]: 3920603 : if (flags != 0) {
216 : 280319 : s >> tx.vin;
217 : 277931 : s >> tx.vout;
218 : : }
219 : : } else {
220 : : /* We read a non-empty vin. Assume a normal vout follows. */
221 : 3007396 : s >> tx.vout;
222 : : }
223 [ + + + - ]: 6921871 : if ((flags & 1) && fAllowWitness) {
[ # # # # ]
224 : : /* The witness flag is present, and we support witnesses. */
225 : 274777 : flags ^= 1;
226 [ - + + + ]: 1410897 : for (size_t i = 0; i < tx.vin.size(); i++) {
[ # # # # ]
227 : 1137996 : s >> tx.vin[i].scriptWitness.stack;
228 : : }
229 [ + + ][ # # ]: 272901 : if (!tx.HasWitness()) {
230 : : /* It's illegal to encode witnesses when all witness stacks are empty. */
231 [ + - ][ # # ]: 3752 : throw std::ios_base::failure("Superfluous witness record");
232 : : }
233 : : }
234 [ + + ][ # # ]: 6918119 : if (flags) {
235 : : /* Unknown flag in the serialization */
236 [ + - ][ # # ]: 3158 : throw std::ios_base::failure("Unknown transaction optional data");
237 : : }
238 : 6916540 : s >> tx.nLockTime;
239 : 6916402 : }
240 : :
241 : : template<typename Stream, typename TxType>
242 : 73909919 : void SerializeTransaction(const TxType& tx, Stream& s, const TransactionSerParams& params)
243 : : {
244 : 73909919 : const bool fAllowWitness = params.allow_witness;
245 : :
246 : 73909919 : s << tx.version;
247 : 73909919 : unsigned char flags = 0;
248 : : // Consistency check
249 [ + + ][ + + ]: 73909919 : if (fAllowWitness) {
250 : : /* Check whether witnesses need to be serialized. */
251 [ + + ]: 27322076 : if (tx.HasWitness()) {
252 : : flags |= 1;
253 : : }
254 : : }
255 : : if (flags) {
256 : : /* Use extended format in case witnesses are to be serialized. */
257 [ + - ][ + - ]: 11600111 : std::vector<CTxIn> vinDummy;
258 [ + - ][ + - ]: 11600111 : s << vinDummy;
259 : 11600111 : s << flags;
260 : 11600111 : }
261 : 73909919 : s << tx.vin;
262 : 73909919 : s << tx.vout;
263 [ + + ][ + + ]: 73909919 : if (flags & 1) {
264 [ - + + + ]: 65199291 : for (size_t i = 0; i < tx.vin.size(); i++) {
[ - + + + ]
265 : 53599180 : s << tx.vin[i].scriptWitness.stack;
266 : : }
267 : : }
268 : 73909919 : s << tx.nLockTime;
269 : 73909919 : }
270 : :
271 : : template<typename TxType>
272 : 1983 : inline CAmount CalculateOutputValue(const TxType& tx)
273 : : {
274 : 13978 : return std::accumulate(tx.vout.cbegin(), tx.vout.cend(), CAmount{0}, [](CAmount sum, const auto& txout) { return sum + txout.nValue; });
275 : : }
276 : :
277 : : struct EqualsOptions {
278 : : bool include_script_sig{true};
279 : : bool include_witness_data{true};
280 : : };
281 : :
282 : :
283 : : /** The basic transaction that is broadcasted on the network and contained in
284 : : * blocks. A transaction can contain multiple inputs and outputs.
285 : : */
286 [ + + ][ + + ]: 16846087 : class CTransaction
[ + + ][ + - ]
[ + - + - ]
[ - + - - ]
287 : : {
288 : : public:
289 : : // Default transaction version.
290 : : static constexpr uint32_t CURRENT_VERSION{2};
291 : :
292 : : // The local variables are made const to prevent unintended modification
293 : : // without updating the cached hash value. However, CTransaction is not
294 : : // actually immutable; deserialization and assignment are implemented,
295 : : // and bypass the constness. This is safe, as they update the entire
296 : : // structure, including the hash.
297 : : const std::vector<CTxIn> vin;
298 : : const std::vector<CTxOut> vout;
299 : : const uint32_t version;
300 : : const uint32_t nLockTime;
301 : :
302 : : private:
303 : : /** Memory only. */
304 : : const bool m_has_witness;
305 : : const Txid hash;
306 : : const Wtxid m_witness_hash;
307 : :
308 : : Txid ComputeHash() const;
309 : : Wtxid ComputeWitnessHash() const;
310 : :
311 : : bool ComputeHasWitness() const;
312 : :
313 : : public:
314 : : /** Convert a CMutableTransaction into a CTransaction. */
315 : : explicit CTransaction(const CMutableTransaction& tx);
316 : : explicit CTransaction(CMutableTransaction&& tx);
317 : :
318 : : template <typename Stream>
319 [ + - ]: 71985949 : inline void Serialize(Stream& s) const {
320 [ + - ]: 71985949 : SerializeTransaction(*this, s, s.template GetParams<TransactionSerParams>());
321 : 2070 : }
322 : :
323 : : /** This deserializing constructor is provided instead of an Unserialize method.
324 : : * Unserialize is not possible, since it would require overwriting const fields. */
325 : : template <typename Stream>
326 [ + - ]: 2831 : CTransaction(deserialize_type, const TransactionSerParams& params, Stream& s) : CTransaction(CMutableTransaction(deserialize, params, s)) {}
327 : : template <typename Stream>
328 [ + - ]: 6486946 : CTransaction(deserialize_type, Stream& s) : CTransaction(CMutableTransaction(deserialize, s)) {}
329 : :
330 : 2333 : bool IsNull() const {
331 [ + + - + ]: 2333 : return vin.empty() && vout.empty();
332 : : }
333 : :
334 [ + + ][ + - ]: 80569386 : const Txid& GetHash() const LIFETIMEBOUND { return hash; }
[ # # # # ]
[ + - + - ]
[ + - + -
+ - ][ + -
+ - + - +
- ][ - - +
+ + + - -
+ - ][ # #
# # # # #
# # # ]
[ + - + -
+ - + - +
- + - + -
+ - ]
[ + - + -
+ - + - +
- + - + -
+ - + - +
- - - -
- ]
335 [ # # ][ + - ]: 99419569 : const Wtxid& GetWitnessHash() const LIFETIMEBOUND { return m_witness_hash; };
[ # # # # ]
[ # # # # ]
[ + - + - ]
[ + - + -
+ - + - ]
[ - - + +
+ + + - +
- - - ]
[ + - + -
+ - + - +
- - - + -
+ - ]
[ + - + -
+ - + - +
- + - + -
+ - + - +
- + - +
- ]
336 : :
337 : : // Return sum of txouts.
338 : : CAmount GetValueOut() const;
339 : :
340 : : /**
341 : : * Calculate the total transaction size in bytes, including witness data.
342 : : * "Total Size" defined in BIP141 and BIP144.
343 : : * @return Total transaction size in bytes
344 : : */
345 : : unsigned int ComputeTotalSize() const;
346 : :
347 : 20527515 : bool IsCoinBase() const
348 : : {
349 [ - + + + : 20527515 : return (vin.size() == 1 && vin[0].prevout.IsNull());
+ + ]
350 : : }
351 : :
352 : 1237 : bool Equals(const CTransaction& other, const EqualsOptions opts = {}) const
353 : : {
354 : 2315 : return nLockTime == other.nLockTime &&
355 [ + + + + ]: 2120 : version == other.version &&
356 [ + + + + ]: 3319 : vout == other.vout &&
357 : 1040 : std::ranges::equal(vin, other.vin, [&opts](const CTxIn& self, const CTxIn& other) {
358 : 8043 : return self.prevout == other.prevout &&
359 [ + - + - ]: 8042 : self.nSequence == other.nSequence &&
360 [ + + + - : 12064 : (opts.include_script_sig ? self.scriptSig == other.scriptSig : true) &&
+ + ]
361 [ + - ]: 4021 : (opts.include_witness_data ? self.scriptWitness.stack == other.scriptWitness.stack : true);
362 : 1237 : });
363 : : }
364 : :
365 : : std::string ToString() const;
366 : :
367 [ + + ]: 43230887 : bool HasWitness() const { return m_has_witness; }
[ + + + - ]
[ - - + -
+ + ][ + +
+ + + + +
+ ][ - - +
+ + + + +
+ + ]
368 : : };
369 : :
370 : : /** A mutable version of CTransaction. */
371 [ + + ][ + - ]: 14350924 : struct CMutableTransaction
[ # # # # ]
372 : : {
373 : : std::vector<CTxIn> vin;
374 : : std::vector<CTxOut> vout;
375 : : uint32_t version;
376 : : uint32_t nLockTime;
377 : :
378 : : explicit CMutableTransaction();
379 : : explicit CMutableTransaction(const CTransaction& tx);
380 : :
381 : : template <typename Stream>
382 : 1923970 : inline void Serialize(Stream& s) const {
383 : 1923970 : SerializeTransaction(*this, s, s.template GetParams<TransactionSerParams>());
384 : : }
385 : :
386 : : template <typename Stream>
387 [ + + ]: 6944519 : inline void Unserialize(Stream& s) {
388 [ + + ]: 6944519 : UnserializeTransaction(*this, s, s.template GetParams<TransactionSerParams>());
389 : 6461146 : }
390 : :
391 : : template <typename Stream>
392 [ + + ]: 2831 : CMutableTransaction(deserialize_type, const TransactionSerParams& params, Stream& s) {
393 [ + + ]: 2831 : UnserializeTransaction(*this, s, params);
394 : 2887 : }
395 : :
396 : : template <typename Stream>
397 [ + + ]: 6486946 : CMutableTransaction(deserialize_type, Stream& s) {
398 : 6461146 : Unserialize(s);
399 : 6512746 : }
400 : :
401 : : /** Compute the hash of this CMutableTransaction. This is computed on the
402 : : * fly, as opposed to GetHash() in CTransaction, which uses a cached result.
403 : : */
404 : : Txid GetHash() const;
405 : :
406 : 273762 : bool HasWitness() const
407 : : {
408 [ - + + + ]: 480445 : for (size_t i = 0; i < vin.size(); i++) {
409 [ + + ]: 477791 : if (!vin[i].scriptWitness.IsNull()) {
410 : : return true;
411 : : }
412 : : }
413 : : return false;
414 : : }
415 : : };
416 : :
417 : : typedef std::shared_ptr<const CTransaction> CTransactionRef;
418 [ + - ]: 6484381 : template <typename Tx> static inline CTransactionRef MakeTransactionRef(Tx&& txIn) { return std::make_shared<const CTransaction>(std::forward<Tx>(txIn)); }
[ + - + + ]
[ + - + - ]
[ + - + -
+ - ][ + -
+ + + - +
- ][ + - +
+ + - +
+ ][ + - +
- + - +
- ][ + - +
- + - + -
+ - ]
[ # # # #
# # # # #
# # # ]
[ + - + -
+ - + - +
- + - ]
419 : :
420 : : namespace std {
421 : : /** Disable default std::hash for CTransactionRef to prevent accidentally
422 : : * comparing by pointer. Use CTransactionRefHash or provide a custom
423 : : * hasher. */
424 : : template <>
425 : : struct hash<CTransactionRef> {
426 : : hash() = delete;
427 : : // Belt-and-suspenders, already implied by the above.
428 : : size_t operator()(const CTransactionRef&) const = delete;
429 : : };
430 : : } // namespace std
431 : :
432 : : #endif // BITCOIN_PRIMITIVES_TRANSACTION_H
|