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