Bitcoin Core  25.99.0
P2P Digital Currency
transaction.h
Go to the documentation of this file.
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 
32 static const int SERIALIZE_TRANSACTION_NO_WITNESS = 0x40000000;
33 
35 class COutPoint
36 {
37 public:
39  uint32_t n;
40 
41  static constexpr uint32_t NULL_INDEX = std::numeric_limits<uint32_t>::max();
42 
44  COutPoint(const uint256& hashIn, uint32_t nIn): hash(hashIn), n(nIn) { }
45 
46  SERIALIZE_METHODS(COutPoint, obj) { READWRITE(obj.hash, obj.n); }
47 
48  void SetNull() { hash.SetNull(); n = NULL_INDEX; }
49  bool IsNull() const { return (hash.IsNull() && n == NULL_INDEX); }
50 
51  friend bool operator<(const COutPoint& a, const COutPoint& b)
52  {
53  int cmp = a.hash.Compare(b.hash);
54  return cmp < 0 || (cmp == 0 && a.n < b.n);
55  }
56 
57  friend bool operator==(const COutPoint& a, const COutPoint& b)
58  {
59  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 
74 class CTxIn
75 {
76 public:
79  uint32_t nSequence;
81 
89  static const uint32_t SEQUENCE_FINAL = 0xffffffff;
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.
106  static const uint32_t SEQUENCE_LOCKTIME_DISABLE_FLAG = (1U << 31);
107 
112  static const uint32_t SEQUENCE_LOCKTIME_TYPE_FLAG = (1 << 22);
113 
117  static const uint32_t SEQUENCE_LOCKTIME_MASK = 0x0000ffff;
118 
127  static const int SEQUENCE_LOCKTIME_GRANULARITY = 9;
128 
130  {
132  }
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  SERIALIZE_METHODS(CTxIn, obj) { READWRITE(obj.prevout, obj.scriptSig, obj.nSequence); }
138 
139  friend bool operator==(const CTxIn& a, const CTxIn& b)
140  {
141  return (a.prevout == b.prevout &&
142  a.scriptSig == b.scriptSig &&
143  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 
157 class CTxOut
158 {
159 public:
162 
164  {
165  SetNull();
166  }
167 
168  CTxOut(const CAmount& nValueIn, CScript scriptPubKeyIn);
169 
170  SERIALIZE_METHODS(CTxOut, obj) { READWRITE(obj.nValue, obj.scriptPubKey); }
171 
172  void SetNull()
173  {
174  nValue = -1;
176  }
177 
178  bool IsNull() const
179  {
180  return (nValue == -1);
181  }
182 
183  friend bool operator==(const CTxOut& a, const CTxOut& b)
184  {
185  return (a.nValue == b.nValue &&
186  a.scriptPubKey == b.scriptPubKey);
187  }
188 
189  friend bool operator!=(const CTxOut& a, const CTxOut& b)
190  {
191  return !(a == b);
192  }
193 
194  std::string ToString() const;
195 };
196 
197 struct CMutableTransaction;
198 
216 template<typename Stream, typename TxType>
217 inline void UnserializeTransaction(TxType& tx, Stream& s) {
218  const bool fAllowWitness = !(s.GetVersion() & SERIALIZE_TRANSACTION_NO_WITNESS);
219 
220  s >> tx.nVersion;
221  unsigned char flags = 0;
222  tx.vin.clear();
223  tx.vout.clear();
224  /* Try to read the vin. In case the dummy is there, this will be read as an empty vector. */
225  s >> tx.vin;
226  if (tx.vin.size() == 0 && fAllowWitness) {
227  /* We read a dummy or an empty vin. */
228  s >> flags;
229  if (flags != 0) {
230  s >> tx.vin;
231  s >> tx.vout;
232  }
233  } else {
234  /* We read a non-empty vin. Assume a normal vout follows. */
235  s >> tx.vout;
236  }
237  if ((flags & 1) && fAllowWitness) {
238  /* The witness flag is present, and we support witnesses. */
239  flags ^= 1;
240  for (size_t i = 0; i < tx.vin.size(); i++) {
241  s >> tx.vin[i].scriptWitness.stack;
242  }
243  if (!tx.HasWitness()) {
244  /* It's illegal to encode witnesses when all witness stacks are empty. */
245  throw std::ios_base::failure("Superfluous witness record");
246  }
247  }
248  if (flags) {
249  /* Unknown flag in the serialization */
250  throw std::ios_base::failure("Unknown transaction optional data");
251  }
252  s >> tx.nLockTime;
253 }
254 
255 template<typename Stream, typename TxType>
256 inline void SerializeTransaction(const TxType& tx, Stream& s) {
257  const bool fAllowWitness = !(s.GetVersion() & SERIALIZE_TRANSACTION_NO_WITNESS);
258 
259  s << tx.nVersion;
260  unsigned char flags = 0;
261  // Consistency check
262  if (fAllowWitness) {
263  /* Check whether witnesses need to be serialized. */
264  if (tx.HasWitness()) {
265  flags |= 1;
266  }
267  }
268  if (flags) {
269  /* Use extended format in case witnesses are to be serialized. */
270  std::vector<CTxIn> vinDummy;
271  s << vinDummy;
272  s << flags;
273  }
274  s << tx.vin;
275  s << tx.vout;
276  if (flags & 1) {
277  for (size_t i = 0; i < tx.vin.size(); i++) {
278  s << tx.vin[i].scriptWitness.stack;
279  }
280  }
281  s << tx.nLockTime;
282 }
283 
284 template<typename TxType>
285 inline CAmount CalculateOutputValue(const TxType& tx)
286 {
287  return std::accumulate(tx.vout.cbegin(), tx.vout.cend(), CAmount{0}, [](CAmount sum, const auto& txout) { return sum + txout.nValue; });
288 }
289 
290 
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:
312  const uint256 hash;
314 
315  uint256 ComputeHash() const;
316  uint256 ComputeWitnessHash() const;
317 
318 public:
320  explicit CTransaction(const CMutableTransaction& tx);
321  explicit CTransaction(CMutableTransaction&& tx);
322 
323  template <typename Stream>
324  inline void Serialize(Stream& s) const {
325  SerializeTransaction(*this, s);
326  }
327 
330  template <typename Stream>
332 
333  bool IsNull() const {
334  return vin.empty() && vout.empty();
335  }
336 
337  const uint256& GetHash() const { return hash; }
338  const uint256& GetWitnessHash() const { return m_witness_hash; };
339 
340  // Return sum of txouts.
341  CAmount GetValueOut() const;
342 
348  unsigned int GetTotalSize() const;
349 
350  bool IsCoinBase() const
351  {
352  return (vin.size() == 1 && vin[0].prevout.IsNull());
353  }
354 
355  friend bool operator==(const CTransaction& a, const CTransaction& b)
356  {
357  return a.hash == b.hash;
358  }
359 
360  friend bool operator!=(const CTransaction& a, const CTransaction& b)
361  {
362  return a.hash != b.hash;
363  }
364 
365  std::string ToString() const;
366 
367  bool HasWitness() const
368  {
369  for (size_t i = 0; i < vin.size(); i++) {
370  if (!vin[i].scriptWitness.IsNull()) {
371  return true;
372  }
373  }
374  return false;
375  }
376 };
377 
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  inline void Serialize(Stream& s) const {
391  SerializeTransaction(*this, s);
392  }
393 
394 
395  template <typename Stream>
396  inline void Unserialize(Stream& s) {
397  UnserializeTransaction(*this, s);
398  }
399 
400  template <typename Stream>
402  Unserialize(s);
403  }
404 
408  uint256 GetHash() const;
409 
410  bool HasWitness() const
411  {
412  for (size_t i = 0; i < vin.size(); i++) {
413  if (!vin[i].scriptWitness.IsNull()) {
414  return true;
415  }
416  }
417  return false;
418  }
419 };
420 
421 typedef std::shared_ptr<const CTransaction> CTransactionRef;
422 template <typename Tx> static inline CTransactionRef MakeTransactionRef(Tx&& txIn) { return std::make_shared<const CTransaction>(std::forward<Tx>(txIn)); }
423 
425 class GenTxid
426 {
429  GenTxid(bool is_wtxid, const uint256& hash) : m_is_wtxid(is_wtxid), m_hash(hash) {}
430 
431 public:
432  static GenTxid Txid(const uint256& hash) { return GenTxid{false, hash}; }
433  static GenTxid Wtxid(const uint256& hash) { return GenTxid{true, hash}; }
434  bool IsWtxid() const { return m_is_wtxid; }
435  const uint256& GetHash() const { return m_hash; }
436  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  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
int64_t CAmount
Amount in satoshis (Can be negative)
Definition: amount.h:12
int flags
Definition: bitcoin-tx.cpp:528
An outpoint - a combination of a transaction hash and an index n into its vout.
Definition: transaction.h:36
COutPoint(const uint256 &hashIn, uint32_t nIn)
Definition: transaction.h:44
uint32_t n
Definition: transaction.h:39
friend bool operator!=(const COutPoint &a, const COutPoint &b)
Definition: transaction.h:62
friend bool operator==(const COutPoint &a, const COutPoint &b)
Definition: transaction.h:57
SERIALIZE_METHODS(COutPoint, obj)
Definition: transaction.h:46
friend bool operator<(const COutPoint &a, const COutPoint &b)
Definition: transaction.h:51
void SetNull()
Definition: transaction.h:48
std::string ToString() const
Definition: transaction.cpp:20
bool IsNull() const
Definition: transaction.h:49
uint256 hash
Definition: transaction.h:38
static constexpr uint32_t NULL_INDEX
Definition: transaction.h:41
Serialized script, used inside transaction inputs and outputs.
Definition: script.h:411
void clear()
Definition: script.h:554
The basic transaction that is broadcasted on the network and contained in blocks.
Definition: transaction.h:295
uint256 ComputeWitnessHash() const
Definition: transaction.cpp:78
friend bool operator==(const CTransaction &a, const CTransaction &b)
Definition: transaction.h:355
bool HasWitness() const
Definition: transaction.h:367
bool IsNull() const
Definition: transaction.h:333
const uint32_t nLockTime
Definition: transaction.h:308
CTransaction(deserialize_type, Stream &s)
This deserializing constructor is provided instead of an Unserialize method.
Definition: transaction.h:331
CTransaction(const CMutableTransaction &tx)
Convert a CMutableTransaction into a CTransaction.
Definition: transaction.cpp:86
void Serialize(Stream &s) const
Definition: transaction.h:324
const std::vector< CTxOut > vout
Definition: transaction.h:306
uint256 ComputeHash() const
Definition: transaction.cpp:73
const uint256 & GetHash() const
Definition: transaction.h:337
std::string ToString() const
unsigned int GetTotalSize() const
Get the total transaction size in bytes, including witness data.
bool IsCoinBase() const
Definition: transaction.h:350
CAmount GetValueOut() const
Definition: transaction.cpp:89
friend bool operator!=(const CTransaction &a, const CTransaction &b)
Definition: transaction.h:360
const int32_t nVersion
Definition: transaction.h:307
const std::vector< CTxIn > vin
Definition: transaction.h:305
const uint256 & GetWitnessHash() const
Definition: transaction.h:338
const uint256 hash
Memory only.
Definition: transaction.h:312
const uint256 m_witness_hash
Definition: transaction.h:313
static const int32_t CURRENT_VERSION
Definition: transaction.h:298
An input of a transaction.
Definition: transaction.h:75
static const uint32_t MAX_SEQUENCE_NONFINAL
This is the maximum sequence number that enables both nLockTime and OP_CHECKLOCKTIMEVERIFY (BIP 65).
Definition: transaction.h:95
friend bool operator==(const CTxIn &a, const CTxIn &b)
Definition: transaction.h:139
static const uint32_t SEQUENCE_LOCKTIME_DISABLE_FLAG
If this flag is set, CTxIn::nSequence is NOT interpreted as a relative lock-time.
Definition: transaction.h:106
friend bool operator!=(const CTxIn &a, const CTxIn &b)
Definition: transaction.h:146
uint32_t nSequence
Definition: transaction.h:79
static const uint32_t SEQUENCE_LOCKTIME_MASK
If CTxIn::nSequence encodes a relative lock-time, this mask is applied to extract that lock-time from...
Definition: transaction.h:117
static const uint32_t SEQUENCE_FINAL
Setting nSequence to this value for every input in a transaction disables nLockTime/IsFinalTx().
Definition: transaction.h:89
std::string ToString() const
Definition: transaction.cpp:39
CScript scriptSig
Definition: transaction.h:78
static const uint32_t SEQUENCE_LOCKTIME_TYPE_FLAG
If CTxIn::nSequence encodes a relative lock-time and this flag is set, the relative lock-time has uni...
Definition: transaction.h:112
CScriptWitness scriptWitness
Only serialized through CTransaction.
Definition: transaction.h:80
COutPoint prevout
Definition: transaction.h:77
static const int SEQUENCE_LOCKTIME_GRANULARITY
In order to use the same number of bits to encode roughly the same wall-clock duration,...
Definition: transaction.h:127
SERIALIZE_METHODS(CTxIn, obj)
Definition: transaction.h:137
An output of a transaction.
Definition: transaction.h:158
CScript scriptPubKey
Definition: transaction.h:161
SERIALIZE_METHODS(CTxOut, obj)
Definition: transaction.h:170
friend bool operator==(const CTxOut &a, const CTxOut &b)
Definition: transaction.h:183
friend bool operator!=(const CTxOut &a, const CTxOut &b)
Definition: transaction.h:189
void SetNull()
Definition: transaction.h:172
CAmount nValue
Definition: transaction.h:160
bool IsNull() const
Definition: transaction.h:178
std::string ToString() const
Definition: transaction.cpp:60
A generic txid reference (txid or wtxid).
Definition: transaction.h:426
bool IsWtxid() const
Definition: transaction.h:434
bool m_is_wtxid
Definition: transaction.h:427
friend bool operator<(const GenTxid &a, const GenTxid &b)
Definition: transaction.h:437
const uint256 & GetHash() const
Definition: transaction.h:435
static GenTxid Wtxid(const uint256 &hash)
Definition: transaction.h:433
GenTxid(bool is_wtxid, const uint256 &hash)
Definition: transaction.h:429
uint256 m_hash
Definition: transaction.h:428
friend bool operator==(const GenTxid &a, const GenTxid &b)
Definition: transaction.h:436
static GenTxid Txid(const uint256 &hash)
Definition: transaction.h:432
constexpr bool IsNull() const
Definition: uint256.h:41
constexpr int Compare(const base_blob &other) const
Definition: uint256.h:53
constexpr void SetNull()
Definition: uint256.h:48
256-bit opaque blob.
Definition: uint256.h:105
volatile double sum
Definition: examples.cpp:10
static const int SERIALIZE_TRANSACTION_NO_WITNESS
A flag that is ORed into the protocol version to designate that a transaction should be (un)serialize...
Definition: transaction.h:32
void UnserializeTransaction(TxType &tx, Stream &s)
Basic transaction serialization format:
Definition: transaction.h:217
void SerializeTransaction(const TxType &tx, Stream &s)
Definition: transaction.h:256
CAmount CalculateOutputValue(const TxType &tx)
Definition: transaction.h:285
static CTransactionRef MakeTransactionRef(Tx &&txIn)
Definition: transaction.h:422
std::shared_ptr< const CTransaction > CTransactionRef
Definition: transaction.h:421
constexpr deserialize_type deserialize
Definition: serialize.h:48
#define READWRITE(...)
Definition: serialize.h:140
A mutable version of CTransaction.
Definition: transaction.h:380
bool HasWitness() const
Definition: transaction.h:410
uint256 GetHash() const
Compute the hash of this CMutableTransaction.
Definition: transaction.cpp:68
void Unserialize(Stream &s)
Definition: transaction.h:396
void Serialize(Stream &s) const
Definition: transaction.h:390
CMutableTransaction(deserialize_type, Stream &s)
Definition: transaction.h:401
std::vector< CTxOut > vout
Definition: transaction.h:382
std::vector< CTxIn > vin
Definition: transaction.h:381
bool IsNull() const
Definition: script.h:571
Dummy data type to identify deserializing constructors.
Definition: serialize.h:47