Bitcoin Core 32.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-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
30{
31public:
33 uint32_t n;
34
35 static constexpr uint32_t NULL_INDEX = std::numeric_limits<uint32_t>::max();
36
38 COutPoint(const Txid& hashIn, uint32_t nIn): hash(hashIn), n(nIn) { }
39
40 SERIALIZE_METHODS(COutPoint, obj) { READWRITE(obj.hash, obj.n); }
41
42 void SetNull() { hash.SetNull(); n = NULL_INDEX; }
43 bool IsNull() const { return (hash.IsNull() && n == NULL_INDEX); }
44
45 friend bool operator<(const COutPoint& a, const COutPoint& b)
46 {
47 return std::tie(a.hash, a.n) < std::tie(b.hash, b.n);
48 }
49
50 friend bool operator==(const COutPoint& a, const COutPoint& b)
51 {
52 return (a.hash == b.hash && a.n == b.n);
53 }
54
55 std::string ToString() const;
56};
57
62class CTxIn
63{
64public:
67 uint32_t nSequence;
69
77 static constexpr uint32_t SEQUENCE_FINAL{0xffffffff};
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.
94 static constexpr uint32_t SEQUENCE_LOCKTIME_DISABLE_FLAG{1U << 31};
95
100 static constexpr uint32_t SEQUENCE_LOCKTIME_TYPE_FLAG{1 << 22};
101
105 static constexpr uint32_t SEQUENCE_LOCKTIME_MASK{0x0000ffff};
106
115 static constexpr int SEQUENCE_LOCKTIME_GRANULARITY{9};
116
118 {
120 }
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 SERIALIZE_METHODS(CTxIn, obj) { READWRITE(obj.prevout, obj.scriptSig, obj.nSequence); }
126
127 friend bool operator==(const CTxIn& a, const CTxIn& b)
128 {
129 return (a.prevout == b.prevout &&
130 a.scriptSig == b.scriptSig &&
131 a.nSequence == b.nSequence);
132 }
133
134 std::string ToString() const;
135};
136
141{
142public:
145
147 {
148 SetNull();
149 }
150
151 CTxOut(const CAmount& nValueIn, CScript scriptPubKeyIn);
152
153 SERIALIZE_METHODS(CTxOut, obj) { READWRITE(obj.nValue, obj.scriptPubKey); }
154
155 void SetNull()
156 {
157 nValue = -1;
159 }
160
161 bool IsNull() const
162 {
163 return (nValue == -1);
164 }
165
166 friend bool operator==(const CTxOut& a, const CTxOut& b)
167 {
168 return (a.nValue == b.nValue &&
170 }
171
172 std::string ToString() const;
173};
174
176
178 const bool allow_witness;
180};
183
201template<typename Stream, typename TxType>
202void UnserializeTransaction(TxType& tx, Stream& s, const TransactionSerParams& params)
203{
204 const bool fAllowWitness = params.allow_witness;
205
206 s >> tx.version;
207 unsigned char flags = 0;
208 tx.vin.clear();
209 tx.vout.clear();
210 /* Try to read the vin. In case the dummy is there, this will be read as an empty vector. */
211 s >> tx.vin;
212 if (tx.vin.size() == 0 && fAllowWitness) {
213 /* We read a dummy or an empty vin. */
214 s >> flags;
215 if (flags != 0) {
216 s >> tx.vin;
217 s >> tx.vout;
218 }
219 } else {
220 /* We read a non-empty vin. Assume a normal vout follows. */
221 s >> tx.vout;
222 }
223 if ((flags & 1) && fAllowWitness) {
224 /* The witness flag is present, and we support witnesses. */
225 flags ^= 1;
226 for (size_t i = 0; i < tx.vin.size(); i++) {
227 s >> tx.vin[i].scriptWitness.stack;
228 }
229 if (!tx.HasWitness()) {
230 /* It's illegal to encode witnesses when all witness stacks are empty. */
231 throw std::ios_base::failure("Superfluous witness record");
232 }
233 }
234 if (flags) {
235 /* Unknown flag in the serialization */
236 throw std::ios_base::failure("Unknown transaction optional data");
237 }
238 s >> tx.nLockTime;
239}
240
241template<typename Stream, typename TxType>
242void SerializeTransaction(const TxType& tx, Stream& s, const TransactionSerParams& params)
243{
244 const bool fAllowWitness = params.allow_witness;
245
246 s << tx.version;
247 unsigned char flags = 0;
248 // Consistency check
249 if (fAllowWitness) {
250 /* Check whether witnesses need to be serialized. */
251 if (tx.HasWitness()) {
252 flags |= 1;
253 }
254 }
255 if (flags) {
256 /* Use extended format in case witnesses are to be serialized. */
257 std::vector<CTxIn> vinDummy;
258 s << vinDummy;
259 s << flags;
260 }
261 s << tx.vin;
262 s << tx.vout;
263 if (flags & 1) {
264 for (size_t i = 0; i < tx.vin.size(); i++) {
265 s << tx.vin[i].scriptWitness.stack;
266 }
267 }
268 s << tx.nLockTime;
269}
270
271template<typename TxType>
272inline CAmount CalculateOutputValue(const TxType& tx)
273{
274 return std::accumulate(tx.vout.cbegin(), tx.vout.cend(), CAmount{0}, [](CAmount sum, const auto& txout) { return sum + txout.nValue; });
275}
276
280};
281
282
287{
288public:
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
302private:
304 const bool m_has_witness;
305 const Txid hash;
307
308 Txid ComputeHash() const;
310
311 bool ComputeHasWitness() const;
312
313public:
315 explicit CTransaction(const CMutableTransaction& tx);
316 explicit CTransaction(CMutableTransaction&& tx);
317
318 template <typename Stream>
319 inline void Serialize(Stream& s) const {
320 SerializeTransaction(*this, s, s.template GetParams<TransactionSerParams>());
321 }
322
325 template <typename Stream>
327 template <typename Stream>
329
330 bool IsNull() const {
331 return vin.empty() && vout.empty();
332 }
333
334 const Txid& GetHash() const LIFETIMEBOUND { return hash; }
336
337 // Return sum of txouts.
338 CAmount GetValueOut() const;
339
345 unsigned int ComputeTotalSize() const;
346
347 bool IsCoinBase() const
348 {
349 return (vin.size() == 1 && vin[0].prevout.IsNull());
350 }
351
352 bool Equals(const CTransaction& other, const EqualsOptions opts = {}) const
353 {
354 return nLockTime == other.nLockTime &&
355 version == other.version &&
356 vout == other.vout &&
357 std::ranges::equal(vin, other.vin, [&opts](const CTxIn& self, const CTxIn& other) {
358 return self.prevout == other.prevout &&
359 self.nSequence == other.nSequence &&
360 (opts.include_script_sig ? self.scriptSig == other.scriptSig : true) &&
361 (opts.include_witness_data ? self.scriptWitness.stack == other.scriptWitness.stack : true);
362 });
363 }
364
365 std::string ToString() const;
366
367 bool HasWitness() const { return m_has_witness; }
368};
369
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 inline void Serialize(Stream& s) const {
383 SerializeTransaction(*this, s, s.template GetParams<TransactionSerParams>());
384 }
385
386 template <typename Stream>
387 inline void Unserialize(Stream& s) {
388 UnserializeTransaction(*this, s, s.template GetParams<TransactionSerParams>());
389 }
390
391 template <typename Stream>
393 UnserializeTransaction(*this, s, params);
394 }
395
396 template <typename Stream>
398 Unserialize(s);
399 }
400
404 Txid GetHash() const;
405
406 bool HasWitness() const
407 {
408 for (size_t i = 0; i < vin.size(); i++) {
409 if (!vin[i].scriptWitness.IsNull()) {
410 return true;
411 }
412 }
413 return false;
414 }
415};
416
417typedef std::shared_ptr<const CTransaction> CTransactionRef;
418template <typename Tx> static inline CTransactionRef MakeTransactionRef(Tx&& txIn) { return std::make_shared<const CTransaction>(std::forward<Tx>(txIn)); }
419
420namespace std {
424template <>
425struct 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
int64_t CAmount
Amount in satoshis (Can be negative)
Definition: amount.h:12
#define LIFETIMEBOUND
Definition: attributes.h:16
int flags
Definition: bitcoin-tx.cpp:531
An outpoint - a combination of a transaction hash and an index n into its vout.
Definition: transaction.h:30
uint32_t n
Definition: transaction.h:33
friend bool operator==(const COutPoint &a, const COutPoint &b)
Definition: transaction.h:50
Txid hash
Definition: transaction.h:32
SERIALIZE_METHODS(COutPoint, obj)
Definition: transaction.h:40
COutPoint(const Txid &hashIn, uint32_t nIn)
Definition: transaction.h:38
friend bool operator<(const COutPoint &a, const COutPoint &b)
Definition: transaction.h:45
void SetNull()
Definition: transaction.h:42
std::string ToString() const
Definition: transaction.cpp:21
bool IsNull() const
Definition: transaction.h:43
static constexpr uint32_t NULL_INDEX
Definition: transaction.h:35
Serialized script, used inside transaction inputs and outputs.
Definition: script.h:406
void clear()
Definition: script.h:569
The basic transaction that is broadcasted on the network and contained in blocks.
Definition: transaction.h:287
Txid ComputeHash() const
Definition: transaction.cpp:81
CTransaction(deserialize_type, const TransactionSerParams &params, Stream &s)
This deserializing constructor is provided instead of an Unserialize method.
Definition: transaction.h:326
bool HasWitness() const
Definition: transaction.h:367
static constexpr uint32_t CURRENT_VERSION
Definition: transaction.h:290
bool IsNull() const
Definition: transaction.h:330
const uint32_t nLockTime
Definition: transaction.h:300
CTransaction(deserialize_type, Stream &s)
Definition: transaction.h:328
bool Equals(const CTransaction &other, const EqualsOptions opts={}) const
Definition: transaction.h:352
unsigned int ComputeTotalSize() const
Calculate the total transaction size in bytes, including witness data.
bool ComputeHasWitness() const
Definition: transaction.cpp:74
CTransaction(const CMutableTransaction &tx)
Convert a CMutableTransaction into a CTransaction.
Definition: transaction.cpp:95
const Wtxid m_witness_hash
Definition: transaction.h:306
void Serialize(Stream &s) const
Definition: transaction.h:319
const std::vector< CTxOut > vout
Definition: transaction.h:298
std::string ToString() const
const bool m_has_witness
Memory only.
Definition: transaction.h:304
const Wtxid & GetWitnessHash() const LIFETIMEBOUND
Definition: transaction.h:335
Wtxid ComputeWitnessHash() const
Definition: transaction.cpp:86
bool IsCoinBase() const
Definition: transaction.h:347
CAmount GetValueOut() const
Definition: transaction.cpp:98
const Txid & GetHash() const LIFETIMEBOUND
Definition: transaction.h:334
const uint32_t version
Definition: transaction.h:299
const std::vector< CTxIn > vin
Definition: transaction.h:297
const Txid hash
Definition: transaction.h:305
An input of a transaction.
Definition: transaction.h:63
static constexpr uint32_t SEQUENCE_FINAL
Setting nSequence to this value for every input in a transaction disables nLockTime/IsFinalTx().
Definition: transaction.h:77
friend bool operator==(const CTxIn &a, const CTxIn &b)
Definition: transaction.h:127
static constexpr int SEQUENCE_LOCKTIME_GRANULARITY
In order to use the same number of bits to encode roughly the same wall-clock duration,...
Definition: transaction.h:115
static constexpr 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:100
uint32_t nSequence
Definition: transaction.h:67
static constexpr 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:105
static constexpr uint32_t SEQUENCE_LOCKTIME_DISABLE_FLAG
If this flag is set, CTxIn::nSequence is NOT interpreted as a relative lock-time.
Definition: transaction.h:94
std::string ToString() const
Definition: transaction.cpp:40
CScript scriptSig
Definition: transaction.h:66
CScriptWitness scriptWitness
Only serialized through CTransaction.
Definition: transaction.h:68
static constexpr uint32_t MAX_SEQUENCE_NONFINAL
This is the maximum sequence number that enables both nLockTime and OP_CHECKLOCKTIMEVERIFY (BIP 65).
Definition: transaction.h:83
COutPoint prevout
Definition: transaction.h:65
SERIALIZE_METHODS(CTxIn, obj)
Definition: transaction.h:125
An output of a transaction.
Definition: transaction.h:141
CScript scriptPubKey
Definition: transaction.h:144
SERIALIZE_METHODS(CTxOut, obj)
Definition: transaction.h:153
friend bool operator==(const CTxOut &a, const CTxOut &b)
Definition: transaction.h:166
void SetNull()
Definition: transaction.h:155
CAmount nValue
Definition: transaction.h:143
bool IsNull() const
Definition: transaction.h:161
std::string ToString() const
Definition: transaction.cpp:61
constexpr bool IsNull() const
Wrapped uint256 methods.
volatile double sum
Definition: examples.cpp:10
SocketId Stream
Definition: util.h:30
constexpr TransactionSerParams TX_NO_WITNESS
Definition: transaction.h:182
void UnserializeTransaction(TxType &tx, Stream &s, const TransactionSerParams &params)
Basic transaction serialization format:
Definition: transaction.h:202
constexpr TransactionSerParams TX_WITH_WITNESS
Definition: transaction.h:181
void SerializeTransaction(const TxType &tx, Stream &s, const TransactionSerParams &params)
Definition: transaction.h:242
CAmount CalculateOutputValue(const TxType &tx)
Definition: transaction.h:272
static CTransactionRef MakeTransactionRef(Tx &&txIn)
Definition: transaction.h:418
std::shared_ptr< const CTransaction > CTransactionRef
Definition: transaction.h:417
constexpr deserialize_type deserialize
Definition: serialize.h:52
#define SER_PARAMS_OPFUNC
Helper macro for SerParams structs.
Definition: serialize.h:1274
#define READWRITE(...)
Definition: serialize.h:148
A mutable version of CTransaction.
Definition: transaction.h:372
CMutableTransaction(deserialize_type, const TransactionSerParams &params, Stream &s)
Definition: transaction.h:392
bool HasWitness() const
Definition: transaction.h:406
void Unserialize(Stream &s)
Definition: transaction.h:387
void Serialize(Stream &s) const
Definition: transaction.h:382
CMutableTransaction(deserialize_type, Stream &s)
Definition: transaction.h:397
std::vector< CTxOut > vout
Definition: transaction.h:374
Txid GetHash() const
Compute the hash of this CMutableTransaction.
Definition: transaction.cpp:69
std::vector< CTxIn > vin
Definition: transaction.h:373
bool IsNull() const
Definition: script.h:586
bool include_witness_data
Definition: transaction.h:279
bool include_script_sig
Definition: transaction.h:278
const bool allow_witness
Definition: transaction.h:178
Dummy data type to identify deserializing constructors.
Definition: serialize.h:51
size_t operator()(const CTransactionRef &) const =delete