Bitcoin ABC 0.33.12
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 bool fEnforceBIP68 = tx.nVersion >= 2 && flags & LOCKTIME_VERIFY_SEQUENCE;
119
120 // Do not enforce sequence numbers as a relative lock time
121 // unless we have been instructed to
122 if (!fEnforceBIP68) {
123 return std::make_pair(nMinHeight, nMinTime);
124 }
125
126 for (size_t txinIndex = 0; txinIndex < tx.vin.size(); txinIndex++) {
127 const CTxIn &txin = tx.vin[txinIndex];
128
129 // Sequence numbers with the most significant bit set are not
130 // treated as relative lock-times, nor are they given any
131 // consensus-enforced meaning at this point.
132 if (txin.nSequence & CTxIn::SEQUENCE_LOCKTIME_DISABLE_FLAG) {
133 // The height of this input is not relevant for sequence locks
134 prevHeights[txinIndex] = 0;
135 continue;
136 }
137
138 int nCoinHeight = prevHeights[txinIndex];
139
140 if (txin.nSequence & CTxIn::SEQUENCE_LOCKTIME_TYPE_FLAG) {
141 const int64_t nCoinTime{
142 Assert(block.GetAncestor(std::max(nCoinHeight - 1, 0)))
143 ->GetMedianTimePast()};
144 // NOTE: Subtract 1 to maintain nLockTime semantics.
145 // BIP 68 relative lock times have the semantics of calculating the
146 // first block or time at which the transaction would be valid. When
147 // calculating the effective block time or height for the entire
148 // transaction, we switch to using the semantics of nLockTime which
149 // is the last invalid block time or height. Thus we subtract 1 from
150 // the calculated time or height.
151
152 // Time-based relative lock-times are measured from the smallest
153 // allowed timestamp of the block containing the txout being spent,
154 // which is the median time past of the block prior.
155 nMinTime = std::max(
156 nMinTime,
157 nCoinTime +
158 int64_t((txin.nSequence & CTxIn::SEQUENCE_LOCKTIME_MASK)
160 1);
161 } else {
162 nMinHeight = std::max(
163 nMinHeight,
164 nCoinHeight +
165 int(txin.nSequence & CTxIn::SEQUENCE_LOCKTIME_MASK) - 1);
166 }
167 }
168
169 return std::make_pair(nMinHeight, nMinTime);
170}
171
173 std::pair<int, int64_t> lockPair) {
174 assert(block.pprev);
175 int64_t nBlockTime = block.pprev->GetMedianTimePast();
176 if (lockPair.first >= block.nHeight || lockPair.second >= nBlockTime) {
177 return false;
178 }
179
180 return true;
181}
182
183bool SequenceLocks(const CTransaction &tx, int flags,
184 std::vector<int> &prevHeights, const CBlockIndex &block) {
186 block, CalculateSequenceLocks(tx, flags, prevHeights, block));
187}
188
189namespace Consensus {
190bool CheckTxInputs(const CTransaction &tx, TxValidationState &state,
191 const CCoinsViewCache &inputs, int nSpendHeight,
192 Amount &txfee) {
193 // are the actual inputs available?
194 if (!inputs.HaveInputs(tx)) {
196 "bad-txns-inputs-missingorspent",
197 strprintf("%s: inputs missing/spent", __func__));
198 }
199
200 Amount nValueIn = Amount::zero();
201 for (const auto &in : tx.vin) {
202 const COutPoint &prevout = in.prevout;
203 const Coin &coin = inputs.AccessCoin(prevout);
204 assert(!coin.IsSpent());
205
206 // If prev is coinbase, check that it's matured
207 if (coin.IsCoinBase() &&
208 nSpendHeight - coin.GetHeight() < COINBASE_MATURITY) {
209 return state.Invalid(
211 "bad-txns-premature-spend-of-coinbase",
212 strprintf("tried to spend coinbase at depth %d",
213 nSpendHeight - coin.GetHeight()));
214 }
215
216 // Check for negative or overflow input values
217 nValueIn += coin.GetTxOut().nValue;
218 if (!MoneyRange(coin.GetTxOut().nValue) || !MoneyRange(nValueIn)) {
220 "bad-txns-inputvalues-outofrange");
221 }
222 }
223
224 const Amount value_out = tx.GetValueOut();
225 if (nValueIn < value_out) {
226 return state.Invalid(
227 TxValidationResult::TX_CONSENSUS, "bad-txns-in-belowout",
228 strprintf("value in (%s) < value out (%s)", FormatMoney(nValueIn),
229 FormatMoney(value_out)));
230 }
231
232 // Tally transaction fees
233 const Amount txfee_aux = nValueIn - value_out;
234 if (!MoneyRange(txfee_aux)) {
236 "bad-txns-fee-outofrange");
237 }
238
239 txfee = txfee_aux;
240 return true;
241}
242} // 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:177
int flags
Definition: bitcoin-tx.cpp:546
#define Assert(val)
Identity function.
Definition: check.h:87
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:171
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:358
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:353
const Coin & AccessCoin(const COutPoint &output) const
Return a reference to Coin in the cache, or coinEmpty if not found.
Definition: coins.cpp:199
static constexpr uint32_t MIN_VERSION
Definition: transaction.h:199
static constexpr uint32_t MAX_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:31
uint32_t GetHeight() const
Definition: coins.h:48
bool IsCoinBase() const
Definition: coins.h:49
CTxOut & GetTxOut()
Definition: coins.h:52
bool IsSpent() const
Definition: coins.h:50
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:190
static const unsigned int LOCKTIME_THRESHOLD
Definition: script.h:44
size_t GetSerializeSize(const T &t)
Definition: serialize.h:1264
Definition: amount.h:23
static constexpr Amount zero() noexcept
Definition: amount.h:36
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:1203
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:172
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:183
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())