Bitcoin Core  31.0.0
P2P Digital Currency
transaction.h
Go to the documentation of this file.
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 <compare>
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 
28 class COutPoint
29 {
30 public:
32  uint32_t n;
33 
34  static constexpr uint32_t NULL_INDEX = std::numeric_limits<uint32_t>::max();
35 
37  COutPoint(const Txid& hashIn, uint32_t nIn): hash(hashIn), n(nIn) { }
38 
39  SERIALIZE_METHODS(COutPoint, obj) { READWRITE(obj.hash, obj.n); }
40 
41  void SetNull() { hash.SetNull(); n = NULL_INDEX; }
42  bool IsNull() const { return (hash.IsNull() && n == NULL_INDEX); }
43 
44  friend bool operator<(const COutPoint& a, const COutPoint& b)
45  {
46  return std::tie(a.hash, a.n) < std::tie(b.hash, b.n);
47  }
48 
49  friend bool operator==(const COutPoint& a, const COutPoint& b)
50  {
51  return (a.hash == b.hash && a.n == b.n);
52  }
53 
54  std::string ToString() const;
55 };
56 
61 class CTxIn
62 {
63 public:
66  uint32_t nSequence;
68 
76  static const uint32_t SEQUENCE_FINAL = 0xffffffff;
82  static const uint32_t MAX_SEQUENCE_NONFINAL{SEQUENCE_FINAL - 1};
83 
84  // Below flags apply in the context of BIP 68. BIP 68 requires the tx
85  // version to be set to 2, or higher.
93  static const uint32_t SEQUENCE_LOCKTIME_DISABLE_FLAG = (1U << 31);
94 
99  static const uint32_t SEQUENCE_LOCKTIME_TYPE_FLAG = (1 << 22);
100 
104  static const uint32_t SEQUENCE_LOCKTIME_MASK = 0x0000ffff;
105 
114  static const int SEQUENCE_LOCKTIME_GRANULARITY = 9;
115 
117  {
119  }
120 
121  explicit CTxIn(COutPoint prevoutIn, CScript scriptSigIn=CScript(), uint32_t nSequenceIn=SEQUENCE_FINAL);
122  CTxIn(Txid hashPrevTx, uint32_t nOut, CScript scriptSigIn=CScript(), uint32_t nSequenceIn=SEQUENCE_FINAL);
123 
124  SERIALIZE_METHODS(CTxIn, obj) { READWRITE(obj.prevout, obj.scriptSig, obj.nSequence); }
125 
126  friend bool operator==(const CTxIn& a, const CTxIn& b)
127  {
128  return (a.prevout == b.prevout &&
129  a.scriptSig == b.scriptSig &&
130  a.nSequence == b.nSequence);
131  }
132 
133  std::string ToString() const;
134 };
135 
139 class CTxOut
140 {
141 public:
144 
146  {
147  SetNull();
148  }
149 
150  CTxOut(const CAmount& nValueIn, CScript scriptPubKeyIn);
151 
152  SERIALIZE_METHODS(CTxOut, obj) { READWRITE(obj.nValue, obj.scriptPubKey); }
153 
154  void SetNull()
155  {
156  nValue = -1;
158  }
159 
160  bool IsNull() const
161  {
162  return (nValue == -1);
163  }
164 
165  friend bool operator==(const CTxOut& a, const CTxOut& b)
166  {
167  return (a.nValue == b.nValue &&
168  a.scriptPubKey == b.scriptPubKey);
169  }
170 
171  std::string ToString() const;
172 };
173 
174 struct CMutableTransaction;
175 
177  const bool allow_witness;
179 };
182 
200 template<typename Stream, typename TxType>
201 void UnserializeTransaction(TxType& tx, Stream& s, const TransactionSerParams& params)
202 {
203  const bool fAllowWitness = params.allow_witness;
204 
205  s >> tx.version;
206  unsigned char flags = 0;
207  tx.vin.clear();
208  tx.vout.clear();
209  /* Try to read the vin. In case the dummy is there, this will be read as an empty vector. */
210  s >> tx.vin;
211  if (tx.vin.size() == 0 && fAllowWitness) {
212  /* We read a dummy or an empty vin. */
213  s >> flags;
214  if (flags != 0) {
215  s >> tx.vin;
216  s >> tx.vout;
217  }
218  } else {
219  /* We read a non-empty vin. Assume a normal vout follows. */
220  s >> tx.vout;
221  }
222  if ((flags & 1) && fAllowWitness) {
223  /* The witness flag is present, and we support witnesses. */
224  flags ^= 1;
225  for (size_t i = 0; i < tx.vin.size(); i++) {
226  s >> tx.vin[i].scriptWitness.stack;
227  }
228  if (!tx.HasWitness()) {
229  /* It's illegal to encode witnesses when all witness stacks are empty. */
230  throw std::ios_base::failure("Superfluous witness record");
231  }
232  }
233  if (flags) {
234  /* Unknown flag in the serialization */
235  throw std::ios_base::failure("Unknown transaction optional data");
236  }
237  s >> tx.nLockTime;
238 }
239 
240 template<typename Stream, typename TxType>
241 void SerializeTransaction(const TxType& tx, Stream& s, const TransactionSerParams& params)
242 {
243  const bool fAllowWitness = params.allow_witness;
244 
245  s << tx.version;
246  unsigned char flags = 0;
247  // Consistency check
248  if (fAllowWitness) {
249  /* Check whether witnesses need to be serialized. */
250  if (tx.HasWitness()) {
251  flags |= 1;
252  }
253  }
254  if (flags) {
255  /* Use extended format in case witnesses are to be serialized. */
256  std::vector<CTxIn> vinDummy;
257  s << vinDummy;
258  s << flags;
259  }
260  s << tx.vin;
261  s << tx.vout;
262  if (flags & 1) {
263  for (size_t i = 0; i < tx.vin.size(); i++) {
264  s << tx.vin[i].scriptWitness.stack;
265  }
266  }
267  s << tx.nLockTime;
268 }
269 
270 template<typename TxType>
271 inline CAmount CalculateOutputValue(const TxType& tx)
272 {
273  return std::accumulate(tx.vout.cbegin(), tx.vout.cend(), CAmount{0}, [](CAmount sum, const auto& txout) { return sum + txout.nValue; });
274 }
275 
276 
281 {
282 public:
283  // Default transaction version.
284  static const uint32_t CURRENT_VERSION{2};
285 
286  // The local variables are made const to prevent unintended modification
287  // without updating the cached hash value. However, CTransaction is not
288  // actually immutable; deserialization and assignment are implemented,
289  // and bypass the constness. This is safe, as they update the entire
290  // structure, including the hash.
291  const std::vector<CTxIn> vin;
292  const std::vector<CTxOut> vout;
293  const uint32_t version;
294  const uint32_t nLockTime;
295 
296 private:
298  const bool m_has_witness;
299  const Txid hash;
301 
302  Txid ComputeHash() const;
303  Wtxid ComputeWitnessHash() const;
304 
305  bool ComputeHasWitness() const;
306 
307 public:
309  explicit CTransaction(const CMutableTransaction& tx);
310  explicit CTransaction(CMutableTransaction&& tx);
311 
312  template <typename Stream>
313  inline void Serialize(Stream& s) const {
314  SerializeTransaction(*this, s, s.template GetParams<TransactionSerParams>());
315  }
316 
319  template <typename Stream>
321  template <typename Stream>
323 
324  bool IsNull() const {
325  return vin.empty() && vout.empty();
326  }
327 
328  const Txid& GetHash() const LIFETIMEBOUND { return hash; }
329  const Wtxid& GetWitnessHash() const LIFETIMEBOUND { return m_witness_hash; };
330 
331  // Return sum of txouts.
332  CAmount GetValueOut() const;
333 
339  unsigned int ComputeTotalSize() const;
340 
341  bool IsCoinBase() const
342  {
343  return (vin.size() == 1 && vin[0].prevout.IsNull());
344  }
345 
346  friend bool operator==(const CTransaction& a, const CTransaction& b)
347  {
348  return a.GetWitnessHash() == b.GetWitnessHash();
349  }
350 
351  std::string ToString() const;
352 
353  bool HasWitness() const { return m_has_witness; }
354 };
355 
358 {
359  std::vector<CTxIn> vin;
360  std::vector<CTxOut> vout;
361  uint32_t version;
362  uint32_t nLockTime;
363 
364  explicit CMutableTransaction();
365  explicit CMutableTransaction(const CTransaction& tx);
366 
367  template <typename Stream>
368  inline void Serialize(Stream& s) const {
369  SerializeTransaction(*this, s, s.template GetParams<TransactionSerParams>());
370  }
371 
372  template <typename Stream>
373  inline void Unserialize(Stream& s) {
374  UnserializeTransaction(*this, s, s.template GetParams<TransactionSerParams>());
375  }
376 
377  template <typename Stream>
379  UnserializeTransaction(*this, s, params);
380  }
381 
382  template <typename Stream>
384  Unserialize(s);
385  }
386 
390  Txid GetHash() const;
391 
392  bool HasWitness() const
393  {
394  for (size_t i = 0; i < vin.size(); i++) {
395  if (!vin[i].scriptWitness.IsNull()) {
396  return true;
397  }
398  }
399  return false;
400  }
401 };
402 
403 typedef std::shared_ptr<const CTransaction> CTransactionRef;
404 template <typename Tx> static inline CTransactionRef MakeTransactionRef(Tx&& txIn) { return std::make_shared<const CTransaction>(std::forward<Tx>(txIn)); }
405 
406 #endif // BITCOIN_PRIMITIVES_TRANSACTION_H
std::shared_ptr< const CTransaction > CTransactionRef
Definition: transaction.h:403
CAmount nValue
Definition: transaction.h:142
void SetNull()
Definition: transaction.h:154
void SerializeTransaction(const TxType &tx, Stream &s, const TransactionSerParams &params)
Definition: transaction.h:241
CScript scriptPubKey
Definition: transaction.h:143
std::vector< CTxIn > vin
Definition: transaction.h:359
CScriptWitness scriptWitness
Only serialized through CTransaction.
Definition: transaction.h:67
static const uint32_t SEQUENCE_FINAL
Setting nSequence to this value for every input in a transaction disables nLockTime/IsFinalTx().
Definition: transaction.h:76
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:93
constexpr deserialize_type deserialize
Definition: serialize.h:49
const Wtxid m_witness_hash
Definition: transaction.h:300
friend bool operator==(const CTxOut &a, const CTxOut &b)
Definition: transaction.h:165
CAmount CalculateOutputValue(const TxType &tx)
Definition: transaction.h:271
static const int SEQUENCE_LOCKTIME_GRANULARITY
In order to use the same number of bits to encode roughly the same wall-clock duration, and because blocks are naturally limited to occur every 600s on average, the minimum granularity for time-based relative lock-time is fixed at 512 seconds.
Definition: transaction.h:114
std::string ToString() const
Definition: transaction.cpp:40
std::string ToString() const
Definition: transaction.cpp:21
std::string ToString() const
Definition: transaction.cpp:61
bool IsNull() const
Definition: script.h:585
Dummy data type to identify deserializing constructors.
Definition: serialize.h:48
bool IsCoinBase() const
Definition: transaction.h:341
SERIALIZE_METHODS(CTxOut, obj)
Definition: transaction.h:152
const std::vector< CTxIn > vin
Definition: transaction.h:291
friend bool operator==(const COutPoint &a, const COutPoint &b)
Definition: transaction.h:49
CAmount GetValueOut() const
Definition: transaction.cpp:98
bool IsNull() const
Definition: transaction.h:160
volatile double sum
Definition: examples.cpp:10
int64_t CAmount
Amount in satoshis (Can be negative)
Definition: amount.h:12
bool ComputeHasWitness() const
Definition: transaction.cpp:74
static const uint32_t CURRENT_VERSION
Definition: transaction.h:284
#define LIFETIMEBOUND
Definition: attributes.h:16
An input of a transaction.
Definition: transaction.h:61
CMutableTransaction(deserialize_type, const TransactionSerParams &params, Stream &s)
Definition: transaction.h:378
bool IsNull() const
Definition: transaction.h:324
void Unserialize(Stream &s)
Definition: transaction.h:373
Txid hash
Definition: transaction.h:31
Wtxid ComputeWitnessHash() const
Definition: transaction.cpp:86
const bool allow_witness
Definition: transaction.h:177
uint32_t n
Definition: transaction.h:32
const std::vector< CTxOut > vout
Definition: transaction.h:292
#define SER_PARAMS_OPFUNC
Helper macro for SerParams structs.
Definition: serialize.h:1212
CTransaction(deserialize_type, const TransactionSerParams &params, Stream &s)
This deserializing constructor is provided instead of an Unserialize method.
Definition: transaction.h:320
An output of a transaction.
Definition: transaction.h:139
const Txid hash
Definition: transaction.h:299
Txid GetHash() const
Compute the hash of this CMutableTransaction.
Definition: transaction.cpp:69
static constexpr uint32_t NULL_INDEX
Definition: transaction.h:34
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:99
An outpoint - a combination of a transaction hash and an index n into its vout.
Definition: transaction.h:28
std::vector< CTxOut > vout
Definition: transaction.h:360
bool HasWitness() const
Definition: transaction.h:392
CTransaction(deserialize_type, Stream &s)
Definition: transaction.h:322
void SetNull()
Definition: transaction.h:41
static CTransactionRef MakeTransactionRef(Tx &&txIn)
Definition: transaction.h:404
CScript scriptSig
Definition: transaction.h:65
int flags
Definition: bitcoin-tx.cpp:529
CMutableTransaction(deserialize_type, Stream &s)
Definition: transaction.h:383
bool HasWitness() const
Definition: transaction.h:353
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:104
const bool m_has_witness
Memory only.
Definition: transaction.h:298
Serialized script, used inside transaction inputs and outputs.
Definition: script.h:404
uint32_t nSequence
Definition: transaction.h:66
SERIALIZE_METHODS(CTxIn, obj)
Definition: transaction.h:124
Txid ComputeHash() const
Definition: transaction.cpp:81
void Serialize(Stream &s) const
Definition: transaction.h:313
std::string ToString() const
SERIALIZE_METHODS(COutPoint, obj)
Definition: transaction.h:39
void Serialize(Stream &s) const
Definition: transaction.h:368
A mutable version of CTransaction.
Definition: transaction.h:357
constexpr bool IsNull() const
Wrapped uint256 methods.
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:82
COutPoint(const Txid &hashIn, uint32_t nIn)
Definition: transaction.h:37
bool IsNull() const
Definition: transaction.h:42
friend bool operator<(const COutPoint &a, const COutPoint &b)
Definition: transaction.h:44
The basic transaction that is broadcasted on the network and contained in blocks. ...
Definition: transaction.h:280
friend bool operator==(const CTxIn &a, const CTxIn &b)
Definition: transaction.h:126
#define READWRITE(...)
Definition: serialize.h:145
COutPoint prevout
Definition: transaction.h:64
void clear()
Definition: script.h:568
unsigned int ComputeTotalSize() const
Calculate the total transaction size in bytes, including witness data.
const Wtxid & GetWitnessHash() const LIFETIMEBOUND
Definition: transaction.h:329
void UnserializeTransaction(TxType &tx, Stream &s, const TransactionSerParams &params)
Basic transaction serialization format:
Definition: transaction.h:201
const Txid & GetHash() const LIFETIMEBOUND
Definition: transaction.h:328
const uint32_t nLockTime
Definition: transaction.h:294
friend bool operator==(const CTransaction &a, const CTransaction &b)
Definition: transaction.h:346
static constexpr TransactionSerParams TX_NO_WITNESS
Definition: transaction.h:181
static constexpr TransactionSerParams TX_WITH_WITNESS
Definition: transaction.h:180
CTransaction(const CMutableTransaction &tx)
Convert a CMutableTransaction into a CTransaction.
Definition: transaction.cpp:95
const uint32_t version
Definition: transaction.h:293