Bitcoin ABC 0.32.6
P2P Digital Currency
tx_verify.cpp
Go to the documentation of this file.
1// Copyright (c) 2018-2020 The Bitcoin developers
2// Distributed under the MIT software license, see the accompanying
3// file COPYING or http://www.opensource.org/licenses/mit-license.php.
4
6
7#include <blockindex.h>
8#include <chain.h>
9#include <coins.h>
11#include <consensus/amount.h>
12#include <consensus/consensus.h>
13#include <consensus/params.h>
16#include <script/script_flags.h>
17#include <util/check.h>
18#include <util/moneystr.h> // For FormatMoney
19
20static bool IsFinalTx(const CTransaction &tx, int nBlockHeight,
21 int64_t nBlockTime) {
22 if (tx.nLockTime == 0) {
23 return true;
24 }
25
26 int64_t lockTime = tx.nLockTime;
27 int64_t lockTimeLimit =
28 (lockTime < LOCKTIME_THRESHOLD) ? nBlockHeight : nBlockTime;
29 if (lockTime < lockTimeLimit) {
30 return true;
31 }
32
33 for (const auto &txin : tx.vin) {
34 if (txin.nSequence != CTxIn::SEQUENCE_FINAL) {
35 return false;
36 }
37 }
38 return true;
39}
40
42 const CTransaction &tx,
43 TxValidationState &state, int nHeight,
44 int64_t nMedianTimePast) {
45 if (!IsFinalTx(tx, nHeight, nMedianTimePast)) {
46 // While this is only one transaction, we use txns in the error to
47 // ensure continuity with other clients.
49 "bad-txns-nonfinal", "non-final transaction");
50 }
51
52 if (IsMagneticAnomalyEnabled(params, nHeight)) {
53 // Size limit
56 "bad-txns-undersize");
57 }
58 }
59
60 if (IsWellingtonEnabled(params, nHeight)) {
61 // Restrict version to 1 and 2
62 if (tx.nVersion > CTransaction::MAX_VERSION ||
63 tx.nVersion < CTransaction::MIN_VERSION) {
65 "bad-txns-version");
66 }
67 }
68
69 return true;
70}
71
73 const CBlockIndex &active_chain_tip, const Consensus::Params &params,
74 const CTransaction &tx, TxValidationState &state) {
76
77 // ContextualCheckTransactionForCurrentBlock() uses
78 // active_chain_tip.Height()+1 to evaluate nLockTime because when
79 // IsFinalTx() is called within AcceptBlock(), the height of the
80 // block *being* evaluated is what is used. Thus if we want to know if a
81 // transaction can be part of the *next* block, we need to call
82 // ContextualCheckTransaction() with one more than
83 // active_chain_tip.Height().
84 const int nBlockHeight = active_chain_tip.nHeight + 1;
85
86 // BIP113 will require that time-locked transactions have nLockTime set to
87 // less than the median time of the previous block they're contained in.
88 // When the next block is created its previous block will be the current
89 // chain tip, so we use that to calculate the median time passed to
90 // ContextualCheckTransaction().
91 // This time can also be used for consensus upgrades.
92 const int64_t nMedianTimePast{active_chain_tip.GetMedianTimePast()};
93
94 return ContextualCheckTransaction(params, tx, state, nBlockHeight,
95 nMedianTimePast);
96}
97
104std::pair<int, int64_t> CalculateSequenceLocks(const CTransaction &tx,
105 int flags,
106 std::vector<int> &prevHeights,
107 const CBlockIndex &block) {
108 assert(prevHeights.size() == tx.vin.size());
109
110 // Will be set to the equivalent height- and time-based nLockTime
111 // values that would be necessary to satisfy all relative lock-
112 // time constraints given our view of block chain history.
113 // The semantics of nLockTime are the last invalid height/time, so
114 // use -1 to have the effect of any height or time being valid.
115 int nMinHeight = -1;
116 int64_t nMinTime = -1;
117
118 // tx.nVersion is signed integer so requires cast to unsigned otherwise
119 // we would be doing a signed comparison and half the range of nVersion
120 // wouldn't support BIP 68.
121 bool fEnforceBIP68 = static_cast<uint32_t>(tx.nVersion) >= 2 &&
123
124 // Do not enforce sequence numbers as a relative lock time
125 // unless we have been instructed to
126 if (!fEnforceBIP68) {
127 return std::make_pair(nMinHeight, nMinTime);
128 }
129
130 for (size_t txinIndex = 0; txinIndex < tx.vin.size(); txinIndex++) {
131 const CTxIn &txin = tx.vin[txinIndex];
132
133 // Sequence numbers with the most significant bit set are not
134 // treated as relative lock-times, nor are they given any
135 // consensus-enforced meaning at this point.
136 if (txin.nSequence & CTxIn::SEQUENCE_LOCKTIME_DISABLE_FLAG) {
137 // The height of this input is not relevant for sequence locks
138 prevHeights[txinIndex] = 0;
139 continue;
140 }
141
142 int nCoinHeight = prevHeights[txinIndex];
143
144 if (txin.nSequence & CTxIn::SEQUENCE_LOCKTIME_TYPE_FLAG) {
145 const int64_t nCoinTime{
146 Assert(block.GetAncestor(std::max(nCoinHeight - 1, 0)))
147 ->GetMedianTimePast()};
148 // NOTE: Subtract 1 to maintain nLockTime semantics.
149 // BIP 68 relative lock times have the semantics of calculating the
150 // first block or time at which the transaction would be valid. When
151 // calculating the effective block time or height for the entire
152 // transaction, we switch to using the semantics of nLockTime which
153 // is the last invalid block time or height. Thus we subtract 1 from
154 // the calculated time or height.
155
156 // Time-based relative lock-times are measured from the smallest
157 // allowed timestamp of the block containing the txout being spent,
158 // which is the median time past of the block prior.
159 nMinTime = std::max(
160 nMinTime,
161 nCoinTime +
162 int64_t((txin.nSequence & CTxIn::SEQUENCE_LOCKTIME_MASK)
164 1);
165 } else {
166 nMinHeight = std::max(
167 nMinHeight,
168 nCoinHeight +
169 int(txin.nSequence & CTxIn::SEQUENCE_LOCKTIME_MASK) - 1);
170 }
171 }
172
173 return std::make_pair(nMinHeight, nMinTime);
174}
175
177 std::pair<int, int64_t> lockPair) {
178 assert(block.pprev);
179 int64_t nBlockTime = block.pprev->GetMedianTimePast();
180 if (lockPair.first >= block.nHeight || lockPair.second >= nBlockTime) {
181 return false;
182 }
183
184 return true;
185}
186
187bool SequenceLocks(const CTransaction &tx, int flags,
188 std::vector<int> &prevHeights, const CBlockIndex &block) {
190 block, CalculateSequenceLocks(tx, flags, prevHeights, block));
191}
192
193namespace Consensus {
194bool CheckTxInputs(const CTransaction &tx, TxValidationState &state,
195 const CCoinsViewCache &inputs, int nSpendHeight,
196 Amount &txfee) {
197 // are the actual inputs available?
198 if (!inputs.HaveInputs(tx)) {
200 "bad-txns-inputs-missingorspent",
201 strprintf("%s: inputs missing/spent", __func__));
202 }
203
204 Amount nValueIn = Amount::zero();
205 for (const auto &in : tx.vin) {
206 const COutPoint &prevout = in.prevout;
207 const Coin &coin = inputs.AccessCoin(prevout);
208 assert(!coin.IsSpent());
209
210 // If prev is coinbase, check that it's matured
211 if (coin.IsCoinBase() &&
212 nSpendHeight - coin.GetHeight() < COINBASE_MATURITY) {
213 return state.Invalid(
215 "bad-txns-premature-spend-of-coinbase",
216 strprintf("tried to spend coinbase at depth %d",
217 nSpendHeight - coin.GetHeight()));
218 }
219
220 // Check for negative or overflow input values
221 nValueIn += coin.GetTxOut().nValue;
222 if (!MoneyRange(coin.GetTxOut().nValue) || !MoneyRange(nValueIn)) {
224 "bad-txns-inputvalues-outofrange");
225 }
226 }
227
228 const Amount value_out = tx.GetValueOut();
229 if (nValueIn < value_out) {
230 return state.Invalid(
231 TxValidationResult::TX_CONSENSUS, "bad-txns-in-belowout",
232 strprintf("value in (%s) < value out (%s)", FormatMoney(nValueIn),
233 FormatMoney(value_out)));
234 }
235
236 // Tally transaction fees
237 const Amount txfee_aux = nValueIn - value_out;
238 if (!MoneyRange(txfee_aux)) {
240 "bad-txns-fee-outofrange");
241 }
242
243 txfee = txfee_aux;
244 return true;
245}
246} // namespace Consensus
bool IsWellingtonEnabled(const Consensus::Params &params, int32_t nHeight)
Check if May 15th, 2023 protocol upgrade has activated.
Definition: activation.cpp:91
bool IsMagneticAnomalyEnabled(const Consensus::Params &params, int32_t nHeight)
Check if Nov 15, 2018 HF has activated using block height.
Definition: activation.cpp:37
bool MoneyRange(const Amount nValue)
Definition: amount.h:171
int flags
Definition: bitcoin-tx.cpp:542
#define Assert(val)
Identity function.
Definition: check.h:84
The block chain is a tree shaped structure starting with the genesis block at the root,...
Definition: blockindex.h:25
CBlockIndex * pprev
pointer to the index of the predecessor of this block
Definition: blockindex.h:32
int64_t GetMedianTimePast() const
Definition: blockindex.h:172
CBlockIndex * GetAncestor(int height)
Efficiently find an ancestor of this block.
Definition: blockindex.cpp:62
int nHeight
height of the entry in the chain. The genesis block has height 0
Definition: blockindex.h:38
CCoinsView that adds a memory cache for transactions to another CCoinsView.
Definition: coins.h:363
bool HaveInputs(const CTransaction &tx) const
Check whether all prevouts of the transaction are present in the UTXO set represented by this view.
Definition: coins.cpp:340
const Coin & AccessCoin(const COutPoint &output) const
Return a reference to Coin in the cache, or coinEmpty if not found.
Definition: coins.cpp:195
static constexpr int32_t MAX_VERSION
Definition: transaction.h:199
static constexpr int32_t MIN_VERSION
Definition: transaction.h:199
static const uint32_t SEQUENCE_LOCKTIME_DISABLE_FLAG
If this flag set, CTxIn::nSequence is NOT interpreted as a relative lock-time.
Definition: transaction.h:76
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:89
static const uint32_t SEQUENCE_FINAL
Setting nSequence to this value for every input in a transaction disables nLockTime.
Definition: transaction.h:69
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:83
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:99
Amount nValue
Definition: transaction.h:130
A UTXO entry.
Definition: coins.h:29
uint32_t GetHeight() const
Definition: coins.h:46
bool IsCoinBase() const
Definition: coins.h:47
CTxOut & GetTxOut()
Definition: coins.h:50
bool IsSpent() const
Definition: coins.h:48
bool Invalid(Result result, const std::string &reject_reason="", const std::string &debug_message="")
Definition: validation.h:101
@ TX_MISSING_INPUTS
transaction was missing some of its inputs
@ TX_PREMATURE_SPEND
transaction spends a coinbase too early, or violates locktime/sequence locks
@ TX_CONSENSUS
invalid by consensus rules
static constexpr unsigned int LOCKTIME_VERIFY_SEQUENCE
Flags for nSequence and nLockTime locks.
Definition: consensus.h:38
static const uint64_t MIN_TX_SIZE
The minimum allowed size for a transaction, in bytes.
Definition: consensus.h:16
static const int COINBASE_MATURITY
Coinbase transaction outputs can only be spent after this number of new blocks (network rule).
Definition: consensus.h:32
RecursiveMutex cs_main
Mutex to guard access to validation specific variables, such as reading or changing the chainstate.
Definition: cs_main.cpp:7
unsigned int nHeight
std::string FormatMoney(const Amount amt)
Do not use these functions to represent or parse monetary amounts to or from JSON but use AmountFromV...
Definition: moneystr.cpp:13
bool CheckTxInputs(const CTransaction &tx, TxValidationState &state, const CCoinsViewCache &inputs, int nSpendHeight, Amount &txfee)
Check whether all inputs of this transaction are valid (no double spends and amounts).
Definition: tx_verify.cpp:194
static const unsigned int LOCKTIME_THRESHOLD
Definition: script.h:44
size_t GetSerializeSize(const T &t)
Definition: serialize.h:1262
Definition: amount.h:21
static constexpr Amount zero() noexcept
Definition: amount.h:34
Parameters that influence chain consensus.
Definition: params.h:34
#define strprintf
Format arguments and return the string or write to given std::ostream (see tinyformat::format doc for...
Definition: tinyformat.h:1202
bool ContextualCheckTransactionForCurrentBlock(const CBlockIndex &active_chain_tip, const Consensus::Params &params, const CTransaction &tx, TxValidationState &state)
Definition: tx_verify.cpp:72
static bool IsFinalTx(const CTransaction &tx, int nBlockHeight, int64_t nBlockTime)
Definition: tx_verify.cpp:20
bool EvaluateSequenceLocks(const CBlockIndex &block, std::pair< int, int64_t > lockPair)
Definition: tx_verify.cpp:176
std::pair< int, int64_t > CalculateSequenceLocks(const CTransaction &tx, int flags, std::vector< int > &prevHeights, const CBlockIndex &block)
Calculates the block height and previous block's median time past at which the transaction will be co...
Definition: tx_verify.cpp:104
bool SequenceLocks(const CTransaction &tx, int flags, std::vector< int > &prevHeights, const CBlockIndex &block)
Check if transaction is final per BIP 68 sequence numbers and can be included in a block.
Definition: tx_verify.cpp:187
bool ContextualCheckTransaction(const Consensus::Params &params, const CTransaction &tx, TxValidationState &state, int nHeight, int64_t nMedianTimePast)
Context dependent validity checks for non coinbase transactions.
Definition: tx_verify.cpp:41
AssertLockHeld(pool.cs)
assert(!tx.IsCoinBase())