1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2016 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.
6 #ifndef BITCOIN_PRIMITIVES_TRANSACTION_H
7 #define BITCOIN_PRIMITIVES_TRANSACTION_H
10 #include "script/script.h"
11 #include "serialize.h"
14 static const int SERIALIZE_TRANSACTION_NO_WITNESS
= 0x40000000;
16 static const int WITNESS_SCALE_FACTOR
= 4;
18 /** An outpoint - a combination of a transaction hash and an index n into its vout */
25 COutPoint() { SetNull(); }
26 COutPoint(uint256 hashIn
, uint32_t nIn
) { hash
= hashIn
; n
= nIn
; }
28 ADD_SERIALIZE_METHODS
;
30 template <typename Stream
, typename Operation
>
31 inline void SerializationOp(Stream
& s
, Operation ser_action
) {
36 void SetNull() { hash
.SetNull(); n
= (uint32_t) -1; }
37 bool IsNull() const { return (hash
.IsNull() && n
== (uint32_t) -1); }
39 friend bool operator<(const COutPoint
& a
, const COutPoint
& b
)
41 int cmp
= a
.hash
.Compare(b
.hash
);
42 return cmp
< 0 || (cmp
== 0 && a
.n
< b
.n
);
45 friend bool operator==(const COutPoint
& a
, const COutPoint
& b
)
47 return (a
.hash
== b
.hash
&& a
.n
== b
.n
);
50 friend bool operator!=(const COutPoint
& a
, const COutPoint
& b
)
55 std::string
ToString() const;
58 /** An input of a transaction. It contains the location of the previous
59 * transaction's output that it claims and a signature that matches the
60 * output's public key.
68 CScriptWitness scriptWitness
; //! Only serialized through CTransaction
70 /* Setting nSequence to this value for every input in a transaction
71 * disables nLockTime. */
72 static const uint32_t SEQUENCE_FINAL
= 0xffffffff;
74 /* Below flags apply in the context of BIP 68*/
75 /* If this flag set, CTxIn::nSequence is NOT interpreted as a
76 * relative lock-time. */
77 static const uint32_t SEQUENCE_LOCKTIME_DISABLE_FLAG
= (1 << 31);
79 /* If CTxIn::nSequence encodes a relative lock-time and this flag
80 * is set, the relative lock-time has units of 512 seconds,
81 * otherwise it specifies blocks with a granularity of 1. */
82 static const uint32_t SEQUENCE_LOCKTIME_TYPE_FLAG
= (1 << 22);
84 /* If CTxIn::nSequence encodes a relative lock-time, this mask is
85 * applied to extract that lock-time from the sequence field. */
86 static const uint32_t SEQUENCE_LOCKTIME_MASK
= 0x0000ffff;
88 /* In order to use the same number of bits to encode roughly the
89 * same wall-clock duration, and because blocks are naturally
90 * limited to occur every 600s on average, the minimum granularity
91 * for time-based relative lock-time is fixed at 512 seconds.
92 * Converting from CTxIn::nSequence to seconds is performed by
93 * multiplying by 512 = 2^9, or equivalently shifting up by
95 static const int SEQUENCE_LOCKTIME_GRANULARITY
= 9;
99 nSequence
= SEQUENCE_FINAL
;
102 explicit CTxIn(COutPoint prevoutIn
, CScript scriptSigIn
=CScript(), uint32_t nSequenceIn
=SEQUENCE_FINAL
);
103 CTxIn(uint256 hashPrevTx
, uint32_t nOut
, CScript scriptSigIn
=CScript(), uint32_t nSequenceIn
=SEQUENCE_FINAL
);
105 ADD_SERIALIZE_METHODS
;
107 template <typename Stream
, typename Operation
>
108 inline void SerializationOp(Stream
& s
, Operation ser_action
) {
110 READWRITE(*(CScriptBase
*)(&scriptSig
));
111 READWRITE(nSequence
);
114 friend bool operator==(const CTxIn
& a
, const CTxIn
& b
)
116 return (a
.prevout
== b
.prevout
&&
117 a
.scriptSig
== b
.scriptSig
&&
118 a
.nSequence
== b
.nSequence
);
121 friend bool operator!=(const CTxIn
& a
, const CTxIn
& b
)
126 std::string
ToString() const;
129 /** An output of a transaction. It contains the public key that the next input
130 * must be able to sign with to claim it.
136 CScript scriptPubKey
;
143 CTxOut(const CAmount
& nValueIn
, CScript scriptPubKeyIn
);
145 ADD_SERIALIZE_METHODS
;
147 template <typename Stream
, typename Operation
>
148 inline void SerializationOp(Stream
& s
, Operation ser_action
) {
150 READWRITE(*(CScriptBase
*)(&scriptPubKey
));
156 scriptPubKey
.clear();
161 return (nValue
== -1);
164 CAmount
GetDustThreshold(const CFeeRate
&minRelayTxFee
) const
166 // "Dust" is defined in terms of CTransaction::minRelayTxFee,
167 // which has units satoshis-per-kilobyte.
168 // If you'd pay more than 1/3 in fees
169 // to spend something, then we consider it dust.
170 // A typical spendable non-segwit txout is 34 bytes big, and will
171 // need a CTxIn of at least 148 bytes to spend:
172 // so dust is a spendable txout less than
173 // 546*minRelayTxFee/1000 (in satoshis).
174 // A typical spendable segwit txout is 31 bytes big, and will
175 // need a CTxIn of at least 67 bytes to spend:
176 // so dust is a spendable txout less than
177 // 294*minRelayTxFee/1000 (in satoshis).
178 if (scriptPubKey
.IsUnspendable())
181 size_t nSize
= GetSerializeSize(*this, SER_DISK
, 0);
182 int witnessversion
= 0;
183 std::vector
<unsigned char> witnessprogram
;
185 if (scriptPubKey
.IsWitnessProgram(witnessversion
, witnessprogram
)) {
186 // sum the sizes of the parts of a transaction input
187 // with 75% segwit discount applied to the script size.
188 nSize
+= (32 + 4 + 1 + (107 / WITNESS_SCALE_FACTOR
) + 4);
190 nSize
+= (32 + 4 + 1 + 107 + 4); // the 148 mentioned above
193 return 3 * minRelayTxFee
.GetFee(nSize
);
196 bool IsDust(const CFeeRate
&minRelayTxFee
) const
198 return (nValue
< GetDustThreshold(minRelayTxFee
));
201 friend bool operator==(const CTxOut
& a
, const CTxOut
& b
)
203 return (a
.nValue
== b
.nValue
&&
204 a
.scriptPubKey
== b
.scriptPubKey
);
207 friend bool operator!=(const CTxOut
& a
, const CTxOut
& b
)
212 std::string
ToString() const;
215 struct CMutableTransaction
;
218 * Basic transaction serialization format:
220 * - std::vector<CTxIn> vin
221 * - std::vector<CTxOut> vout
222 * - uint32_t nLockTime
224 * Extended transaction serialization format:
226 * - unsigned char dummy = 0x00
227 * - unsigned char flags (!= 0)
228 * - std::vector<CTxIn> vin
229 * - std::vector<CTxOut> vout
232 * - uint32_t nLockTime
234 template<typename Stream
, typename TxType
>
235 inline void UnserializeTransaction(TxType
& tx
, Stream
& s
) {
236 const bool fAllowWitness
= !(s
.GetVersion() & SERIALIZE_TRANSACTION_NO_WITNESS
);
239 unsigned char flags
= 0;
242 /* Try to read the vin. In case the dummy is there, this will be read as an empty vector. */
244 if (tx
.vin
.size() == 0 && fAllowWitness
) {
245 /* We read a dummy or an empty vin. */
252 /* We read a non-empty vin. Assume a normal vout follows. */
255 if ((flags
& 1) && fAllowWitness
) {
256 /* The witness flag is present, and we support witnesses. */
258 for (size_t i
= 0; i
< tx
.vin
.size(); i
++) {
259 s
>> tx
.vin
[i
].scriptWitness
.stack
;
263 /* Unknown flag in the serialization */
264 throw std::ios_base::failure("Unknown transaction optional data");
269 template<typename Stream
, typename TxType
>
270 inline void SerializeTransaction(const TxType
& tx
, Stream
& s
) {
271 const bool fAllowWitness
= !(s
.GetVersion() & SERIALIZE_TRANSACTION_NO_WITNESS
);
274 unsigned char flags
= 0;
277 /* Check whether witnesses need to be serialized. */
278 if (tx
.HasWitness()) {
283 /* Use extended format in case witnesses are to be serialized. */
284 std::vector
<CTxIn
> vinDummy
;
291 for (size_t i
= 0; i
< tx
.vin
.size(); i
++) {
292 s
<< tx
.vin
[i
].scriptWitness
.stack
;
299 /** The basic transaction that is broadcasted on the network and contained in
300 * blocks. A transaction can contain multiple inputs and outputs.
305 // Default transaction version.
306 static const int32_t CURRENT_VERSION
=2;
308 // Changing the default transaction version requires a two step process: first
309 // adapting relay policy by bumping MAX_STANDARD_VERSION, and then later date
310 // bumping the default CURRENT_VERSION at which point both CURRENT_VERSION and
311 // MAX_STANDARD_VERSION will be equal.
312 static const int32_t MAX_STANDARD_VERSION
=2;
314 // The local variables are made const to prevent unintended modification
315 // without updating the cached hash value. However, CTransaction is not
316 // actually immutable; deserialization and assignment are implemented,
317 // and bypass the constness. This is safe, as they update the entire
318 // structure, including the hash.
319 const int32_t nVersion
;
320 const std::vector
<CTxIn
> vin
;
321 const std::vector
<CTxOut
> vout
;
322 const uint32_t nLockTime
;
328 uint256
ComputeHash() const;
331 /** Construct a CTransaction that qualifies as IsNull() */
334 /** Convert a CMutableTransaction into a CTransaction. */
335 CTransaction(const CMutableTransaction
&tx
);
336 CTransaction(CMutableTransaction
&&tx
);
338 template <typename Stream
>
339 inline void Serialize(Stream
& s
) const {
340 SerializeTransaction(*this, s
);
343 /** This deserializing constructor is provided instead of an Unserialize method.
344 * Unserialize is not possible, since it would require overwriting const fields. */
345 template <typename Stream
>
346 CTransaction(deserialize_type
, Stream
& s
) : CTransaction(CMutableTransaction(deserialize
, s
)) {}
348 bool IsNull() const {
349 return vin
.empty() && vout
.empty();
352 const uint256
& GetHash() const {
356 // Compute a hash that includes both transaction and witness data
357 uint256
GetWitnessHash() const;
359 // Return sum of txouts.
360 CAmount
GetValueOut() const;
361 // GetValueIn() is a method on CCoinsViewCache, because
362 // inputs must be known to compute value in.
365 * Get the total transaction size in bytes, including witness data.
366 * "Total Size" defined in BIP141 and BIP144.
367 * @return Total transaction size in bytes
369 unsigned int GetTotalSize() const;
371 bool IsCoinBase() const
373 return (vin
.size() == 1 && vin
[0].prevout
.IsNull());
376 friend bool operator==(const CTransaction
& a
, const CTransaction
& b
)
378 return a
.hash
== b
.hash
;
381 friend bool operator!=(const CTransaction
& a
, const CTransaction
& b
)
383 return a
.hash
!= b
.hash
;
386 std::string
ToString() const;
388 bool HasWitness() const
390 for (size_t i
= 0; i
< vin
.size(); i
++) {
391 if (!vin
[i
].scriptWitness
.IsNull()) {
399 /** A mutable version of CTransaction. */
400 struct CMutableTransaction
403 std::vector
<CTxIn
> vin
;
404 std::vector
<CTxOut
> vout
;
407 CMutableTransaction();
408 CMutableTransaction(const CTransaction
& tx
);
410 template <typename Stream
>
411 inline void Serialize(Stream
& s
) const {
412 SerializeTransaction(*this, s
);
416 template <typename Stream
>
417 inline void Unserialize(Stream
& s
) {
418 UnserializeTransaction(*this, s
);
421 template <typename Stream
>
422 CMutableTransaction(deserialize_type
, Stream
& s
) {
426 /** Compute the hash of this CMutableTransaction. This is computed on the
427 * fly, as opposed to GetHash() in CTransaction, which uses a cached result.
429 uint256
GetHash() const;
431 friend bool operator==(const CMutableTransaction
& a
, const CMutableTransaction
& b
)
433 return a
.GetHash() == b
.GetHash();
436 bool HasWitness() const
438 for (size_t i
= 0; i
< vin
.size(); i
++) {
439 if (!vin
[i
].scriptWitness
.IsNull()) {
447 typedef std::shared_ptr
<const CTransaction
> CTransactionRef
;
448 static inline CTransactionRef
MakeTransactionRef() { return std::make_shared
<const CTransaction
>(); }
449 template <typename Tx
> static inline CTransactionRef
MakeTransactionRef(Tx
&& txIn
) { return std::make_shared
<const CTransaction
>(std::forward
<Tx
>(txIn
)); }
451 /** Compute the weight of a transaction, as defined by BIP 141 */
452 int64_t GetTransactionWeight(const CTransaction
&tx
);
454 #endif // BITCOIN_PRIMITIVES_TRANSACTION_H