Line data Source code
1 : // Copyright (c) 2009-2010 Satoshi Nakamoto
2 : // Copyright (c) 2009-2019 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 <stdint.h>
10 : #include <amount.h>
11 : #include <script/script.h>
12 : #include <serialize.h>
13 : #include <uint256.h>
14 :
15 : #include <tuple>
16 :
17 : static const int SERIALIZE_TRANSACTION_NO_WITNESS = 0x40000000;
18 :
19 : /** An outpoint - a combination of a transaction hash and an index n into its vout */
20 : class COutPoint
21 : {
22 : public:
23 : uint256 hash;
24 : uint32_t n;
25 :
26 : static constexpr uint32_t NULL_INDEX = std::numeric_limits<uint32_t>::max();
27 :
28 12484904 : COutPoint(): n(NULL_INDEX) { }
29 39736914 : COutPoint(const uint256& hashIn, uint32_t nIn): hash(hashIn), n(nIn) { }
30 :
31 84925084 : SERIALIZE_METHODS(COutPoint, obj) { READWRITE(obj.hash, obj.n); }
32 :
33 22535 : void SetNull() { hash.SetNull(); n = NULL_INDEX; }
34 16741691 : bool IsNull() const { return (hash.IsNull() && n == NULL_INDEX); }
35 :
36 242470190 : friend bool operator<(const COutPoint& a, const COutPoint& b)
37 : {
38 242470190 : int cmp = a.hash.Compare(b.hash);
39 242470190 : return cmp < 0 || (cmp == 0 && a.n < b.n);
40 : }
41 :
42 48067595 : friend bool operator==(const COutPoint& a, const COutPoint& b)
43 : {
44 48067595 : return (a.hash == b.hash && a.n == b.n);
45 : }
46 :
47 13 : friend bool operator!=(const COutPoint& a, const COutPoint& b)
48 : {
49 13 : return !(a == b);
50 : }
51 :
52 : std::string ToString() const;
53 : };
54 :
55 : /** An input of a transaction. It contains the location of the previous
56 : * transaction's output that it claims and a signature that matches the
57 : * output's public key.
58 : */
59 14834899 : class CTxIn
60 : {
61 : public:
62 : COutPoint prevout;
63 : CScript scriptSig;
64 : uint32_t nSequence;
65 : CScriptWitness scriptWitness; //!< Only serialized through CTransaction
66 :
67 : /* Setting nSequence to this value for every input in a transaction
68 : * disables nLockTime. */
69 : static const uint32_t SEQUENCE_FINAL = 0xffffffff;
70 :
71 : /* Below flags apply in the context of BIP 68*/
72 : /* If this flag set, CTxIn::nSequence is NOT interpreted as a
73 : * relative lock-time. */
74 : static const uint32_t SEQUENCE_LOCKTIME_DISABLE_FLAG = (1U << 31);
75 :
76 : /* If CTxIn::nSequence encodes a relative lock-time and this flag
77 : * is set, the relative lock-time has units of 512 seconds,
78 : * otherwise it specifies blocks with a granularity of 1. */
79 : static const uint32_t SEQUENCE_LOCKTIME_TYPE_FLAG = (1 << 22);
80 :
81 : /* If CTxIn::nSequence encodes a relative lock-time, this mask is
82 : * applied to extract that lock-time from the sequence field. */
83 : static const uint32_t SEQUENCE_LOCKTIME_MASK = 0x0000ffff;
84 :
85 : /* In order to use the same number of bits to encode roughly the
86 : * same wall-clock duration, and because blocks are naturally
87 : * limited to occur every 600s on average, the minimum granularity
88 : * for time-based relative lock-time is fixed at 512 seconds.
89 : * Converting from CTxIn::nSequence to seconds is performed by
90 : * multiplying by 512 = 2^9, or equivalently shifting up by
91 : * 9 bits. */
92 : static const int SEQUENCE_LOCKTIME_GRANULARITY = 9;
93 :
94 8523809 : CTxIn()
95 4261902 : {
96 4261906 : nSequence = SEQUENCE_FINAL;
97 8523808 : }
98 :
99 : explicit CTxIn(COutPoint prevoutIn, CScript scriptSigIn=CScript(), uint32_t nSequenceIn=SEQUENCE_FINAL);
100 : CTxIn(uint256 hashPrevTx, uint32_t nOut, CScript scriptSigIn=CScript(), uint32_t nSequenceIn=SEQUENCE_FINAL);
101 :
102 16861890 : SERIALIZE_METHODS(CTxIn, obj) { READWRITE(obj.prevout, obj.scriptSig, obj.nSequence); }
103 :
104 98 : friend bool operator==(const CTxIn& a, const CTxIn& b)
105 : {
106 148 : return (a.prevout == b.prevout &&
107 50 : a.scriptSig == b.scriptSig &&
108 50 : a.nSequence == b.nSequence);
109 : }
110 :
111 : friend bool operator!=(const CTxIn& a, const CTxIn& b)
112 : {
113 : return !(a == b);
114 : }
115 :
116 : std::string ToString() const;
117 : };
118 :
119 : /** An output of a transaction. It contains the public key that the next input
120 : * must be able to sign with to claim it.
121 : */
122 270589791 : class CTxOut
123 : {
124 : public:
125 : CAmount nValue;
126 : CScript scriptPubKey;
127 :
128 124676715 : CTxOut()
129 62338351 : {
130 62338364 : SetNull();
131 124676658 : }
132 :
133 : CTxOut(const CAmount& nValueIn, CScript scriptPubKeyIn);
134 :
135 78212751 : SERIALIZE_METHODS(CTxOut, obj) { READWRITE(obj.nValue, obj.scriptPubKey); }
136 :
137 69277133 : void SetNull()
138 : {
139 69277133 : nValue = -1;
140 69277133 : scriptPubKey.clear();
141 69277133 : }
142 :
143 74273322 : bool IsNull() const
144 : {
145 74273322 : return (nValue == -1);
146 : }
147 :
148 413579 : friend bool operator==(const CTxOut& a, const CTxOut& b)
149 : {
150 827158 : return (a.nValue == b.nValue &&
151 413579 : a.scriptPubKey == b.scriptPubKey);
152 : }
153 :
154 19471 : friend bool operator!=(const CTxOut& a, const CTxOut& b)
155 : {
156 19471 : return !(a == b);
157 : }
158 :
159 : std::string ToString() const;
160 : };
161 :
162 : struct CMutableTransaction;
163 :
164 : /**
165 : * Basic transaction serialization format:
166 : * - int32_t nVersion
167 : * - std::vector<CTxIn> vin
168 : * - std::vector<CTxOut> vout
169 : * - uint32_t nLockTime
170 : *
171 : * Extended transaction serialization format:
172 : * - int32_t nVersion
173 : * - unsigned char dummy = 0x00
174 : * - unsigned char flags (!= 0)
175 : * - std::vector<CTxIn> vin
176 : * - std::vector<CTxOut> vout
177 : * - if (flags & 1):
178 : * - CTxWitness wit;
179 : * - uint32_t nLockTime
180 : */
181 : template<typename Stream, typename TxType>
182 251985 : inline void UnserializeTransaction(TxType& tx, Stream& s) {
183 251985 : const bool fAllowWitness = !(s.GetVersion() & SERIALIZE_TRANSACTION_NO_WITNESS);
184 :
185 251985 : s >> tx.nVersion;
186 251985 : unsigned char flags = 0;
187 251985 : tx.vin.clear();
188 251985 : tx.vout.clear();
189 : /* Try to read the vin. In case the dummy is there, this will be read as an empty vector. */
190 251985 : s >> tx.vin;
191 251985 : if (tx.vin.size() == 0 && fAllowWitness) {
192 : /* We read a dummy or an empty vin. */
193 127978 : s >> flags;
194 127978 : if (flags != 0) {
195 127973 : s >> tx.vin;
196 127973 : s >> tx.vout;
197 127973 : }
198 : } else {
199 : /* We read a non-empty vin. Assume a normal vout follows. */
200 124001 : s >> tx.vout;
201 : }
202 251969 : if ((flags & 1) && fAllowWitness) {
203 : /* The witness flag is present, and we support witnesses. */
204 127973 : flags ^= 1;
205 320170 : for (size_t i = 0; i < tx.vin.size(); i++) {
206 192199 : s >> tx.vin[i].scriptWitness.stack;
207 : }
208 127972 : if (!tx.HasWitness()) {
209 : /* It's illegal to encode witnesses when all witness stacks are empty. */
210 2 : throw std::ios_base::failure("Superfluous witness record");
211 : }
212 : }
213 251967 : if (flags) {
214 : /* Unknown flag in the serialization */
215 2 : throw std::ios_base::failure("Unknown transaction optional data");
216 : }
217 251965 : s >> tx.nLockTime;
218 251969 : }
219 :
220 : template<typename Stream, typename TxType>
221 2741884 : inline void SerializeTransaction(const TxType& tx, Stream& s) {
222 2741884 : const bool fAllowWitness = !(s.GetVersion() & SERIALIZE_TRANSACTION_NO_WITNESS);
223 :
224 2741884 : s << tx.nVersion;
225 2741884 : unsigned char flags = 0;
226 : // Consistency check
227 2741884 : if (fAllowWitness) {
228 : /* Check whether witnesses need to be serialized. */
229 993382 : if (tx.HasWitness()) {
230 476435 : flags |= 1;
231 476435 : }
232 : }
233 2741884 : if (flags) {
234 : /* Use extended format in case witnesses are to be serialized. */
235 476435 : std::vector<CTxIn> vinDummy;
236 476435 : s << vinDummy;
237 476435 : s << flags;
238 476434 : }
239 2741884 : s << tx.vin;
240 2741884 : s << tx.vout;
241 2741884 : if (flags & 1) {
242 1357264 : for (size_t i = 0; i < tx.vin.size(); i++) {
243 880829 : s << tx.vin[i].scriptWitness.stack;
244 : }
245 476435 : }
246 2741884 : s << tx.nLockTime;
247 2741884 : }
248 :
249 :
250 : /** The basic transaction that is broadcasted on the network and contained in
251 : * blocks. A transaction can contain multiple inputs and outputs.
252 : */
253 1940562 : class CTransaction
254 : {
255 : public:
256 : // Default transaction version.
257 : static const int32_t CURRENT_VERSION=2;
258 :
259 : // Changing the default transaction version requires a two step process: first
260 : // adapting relay policy by bumping MAX_STANDARD_VERSION, and then later date
261 : // bumping the default CURRENT_VERSION at which point both CURRENT_VERSION and
262 : // MAX_STANDARD_VERSION will be equal.
263 : static const int32_t MAX_STANDARD_VERSION=2;
264 :
265 : // The local variables are made const to prevent unintended modification
266 : // without updating the cached hash value. However, CTransaction is not
267 : // actually immutable; deserialization and assignment are implemented,
268 : // and bypass the constness. This is safe, as they update the entire
269 : // structure, including the hash.
270 : const std::vector<CTxIn> vin;
271 : const std::vector<CTxOut> vout;
272 : const int32_t nVersion;
273 : const uint32_t nLockTime;
274 :
275 : private:
276 : /** Memory only. */
277 : const uint256 hash;
278 : const uint256 m_witness_hash;
279 :
280 : uint256 ComputeHash() const;
281 : uint256 ComputeWitnessHash() const;
282 :
283 : public:
284 : /** Construct a CTransaction that qualifies as IsNull() */
285 : CTransaction();
286 :
287 : /** Convert a CMutableTransaction into a CTransaction. */
288 : explicit CTransaction(const CMutableTransaction &tx);
289 : CTransaction(CMutableTransaction &&tx);
290 :
291 : template <typename Stream>
292 2621668 : inline void Serialize(Stream& s) const {
293 2621668 : SerializeTransaction(*this, s);
294 2621668 : }
295 :
296 : /** This deserializing constructor is provided instead of an Unserialize method.
297 : * Unserialize is not possible, since it would require overwriting const fields. */
298 : template <typename Stream>
299 241275 : CTransaction(deserialize_type, Stream& s) : CTransaction(CMutableTransaction(deserialize, s)) {}
300 :
301 10127 : bool IsNull() const {
302 10127 : return vin.empty() && vout.empty();
303 : }
304 :
305 2565196946 : const uint256& GetHash() const { return hash; }
306 8606774 : const uint256& GetWitnessHash() const { return m_witness_hash; };
307 :
308 : // Return sum of txouts.
309 : CAmount GetValueOut() const;
310 :
311 : /**
312 : * Get the total transaction size in bytes, including witness data.
313 : * "Total Size" defined in BIP141 and BIP144.
314 : * @return Total transaction size in bytes
315 : */
316 : unsigned int GetTotalSize() const;
317 :
318 23430916 : bool IsCoinBase() const
319 : {
320 23430916 : return (vin.size() == 1 && vin[0].prevout.IsNull());
321 : }
322 :
323 2581 : friend bool operator==(const CTransaction& a, const CTransaction& b)
324 : {
325 2581 : return a.hash == b.hash;
326 : }
327 :
328 48 : friend bool operator!=(const CTransaction& a, const CTransaction& b)
329 : {
330 48 : return a.hash != b.hash;
331 : }
332 :
333 : std::string ToString() const;
334 :
335 2030817 : bool HasWitness() const
336 : {
337 3652124 : for (size_t i = 0; i < vin.size(); i++) {
338 2320663 : if (!vin[i].scriptWitness.IsNull()) {
339 699372 : return true;
340 : }
341 : }
342 1331466 : return false;
343 2030838 : }
344 : };
345 :
346 : /** A mutable version of CTransaction. */
347 2396383 : struct CMutableTransaction
348 : {
349 : std::vector<CTxIn> vin;
350 : std::vector<CTxOut> vout;
351 : int32_t nVersion;
352 : uint32_t nLockTime;
353 :
354 : CMutableTransaction();
355 : explicit CMutableTransaction(const CTransaction& tx);
356 :
357 : template <typename Stream>
358 120215 : inline void Serialize(Stream& s) const {
359 120215 : SerializeTransaction(*this, s);
360 120215 : }
361 :
362 :
363 : template <typename Stream>
364 251985 : inline void Unserialize(Stream& s) {
365 251985 : UnserializeTransaction(*this, s);
366 251985 : }
367 :
368 : template <typename Stream>
369 482550 : CMutableTransaction(deserialize_type, Stream& s) {
370 241275 : Unserialize(s);
371 482550 : }
372 :
373 : /** Compute the hash of this CMutableTransaction. This is computed on the
374 : * fly, as opposed to GetHash() in CTransaction, which uses a cached result.
375 : */
376 : uint256 GetHash() const;
377 :
378 129392 : bool HasWitness() const
379 : {
380 131479 : for (size_t i = 0; i < vin.size(); i++) {
381 130242 : if (!vin[i].scriptWitness.IsNull()) {
382 128154 : return true;
383 : }
384 : }
385 1238 : return false;
386 129392 : }
387 : };
388 :
389 : typedef std::shared_ptr<const CTransaction> CTransactionRef;
390 91 : static inline CTransactionRef MakeTransactionRef() { return std::make_shared<const CTransaction>(); }
391 456284 : template <typename Tx> static inline CTransactionRef MakeTransactionRef(Tx&& txIn) { return std::make_shared<const CTransaction>(std::forward<Tx>(txIn)); }
392 :
393 : /** A generic txid reference (txid or wtxid). */
394 : class GenTxid
395 : {
396 : const bool m_is_wtxid;
397 : const uint256 m_hash;
398 : public:
399 4554838 : GenTxid(bool is_wtxid, const uint256& hash) : m_is_wtxid(is_wtxid), m_hash(hash) {}
400 2337699 : bool IsWtxid() const { return m_is_wtxid; }
401 2442799 : const uint256& GetHash() const { return m_hash; }
402 : friend bool operator==(const GenTxid& a, const GenTxid& b) { return a.m_is_wtxid == b.m_is_wtxid && a.m_hash == b.m_hash; }
403 : 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); }
404 : };
405 :
406 : #endif // BITCOIN_PRIMITIVES_TRANSACTION_H
|