Bitcoin ABC 0.32.4
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#include <version.h> // For PROTOCOL_VERSION
20
21static bool IsFinalTx(const CTransaction &tx, int nBlockHeight,
22 int64_t nBlockTime) {
23 if (tx.nLockTime == 0) {
24 return true;
25 }
26
27 int64_t lockTime = tx.nLockTime;
28 int64_t lockTimeLimit =
29 (lockTime < LOCKTIME_THRESHOLD) ? nBlockHeight : nBlockTime;
30 if (lockTime < lockTimeLimit) {
31 return true;
32 }
33
34 for (const auto &txin : tx.vin) {
35 if (txin.nSequence != CTxIn::SEQUENCE_FINAL) {
36 return false;
37 }
38 }
39 return true;
40}
41
43 const CTransaction &tx,
44 TxValidationState &state, int nHeight,
45 int64_t nMedianTimePast) {
46 if (!IsFinalTx(tx, nHeight, nMedianTimePast)) {
47 // While this is only one transaction, we use txns in the error to
48 // ensure continuity with other clients.
50 "bad-txns-nonfinal", "non-final transaction");
51 }
52
53 if (IsMagneticAnomalyEnabled(params, nHeight)) {
54 // Size limit
57 "bad-txns-undersize");
58 }
59 }
60
61 if (IsWellingtonEnabled(params, nHeight)) {
62 // Restrict version to 1 and 2
63 if (tx.nVersion > CTransaction::MAX_VERSION ||
64 tx.nVersion < CTransaction::MIN_VERSION) {
66 "bad-txns-version");
67 }
68 }
69
70 return true;
71}
72
74 const CBlockIndex &active_chain_tip, const Consensus::Params &params,
75 const CTransaction &tx, TxValidationState &state) {
77
78 // ContextualCheckTransactionForCurrentBlock() uses
79 // active_chain_tip.Height()+1 to evaluate nLockTime because when
80 // IsFinalTx() is called within AcceptBlock(), the height of the
81 // block *being* evaluated is what is used. Thus if we want to know if a
82 // transaction can be part of the *next* block, we need to call
83 // ContextualCheckTransaction() with one more than
84 // active_chain_tip.Height().
85 const int nBlockHeight = active_chain_tip.nHeight + 1;
86
87 // BIP113 will require that time-locked transactions have nLockTime set to
88 // less than the median time of the previous block they're contained in.
89 // When the next block is created its previous block will be the current
90 // chain tip, so we use that to calculate the median time passed to
91 // ContextualCheckTransaction().
92 // This time can also be used for consensus upgrades.
93 const int64_t nMedianTimePast{active_chain_tip.GetMedianTimePast()};
94
95 return ContextualCheckTransaction(params, tx, state, nBlockHeight,
96 nMedianTimePast);
97}
98
105std::pair<int, int64_t> CalculateSequenceLocks(const CTransaction &tx,
106 int flags,
107 std::vector<int> &prevHeights,
108 const CBlockIndex &block) {
109 assert(prevHeights.size() == tx.vin.size());
110
111 // Will be set to the equivalent height- and time-based nLockTime
112 // values that would be necessary to satisfy all relative lock-
113 // time constraints given our view of block chain history.
114 // The semantics of nLockTime are the last invalid height/time, so
115 // use -1 to have the effect of any height or time being valid.
116 int nMinHeight = -1;
117 int64_t nMinTime = -1;
118
119 // tx.nVersion is signed integer so requires cast to unsigned otherwise
120 // we would be doing a signed comparison and half the range of nVersion
121 // wouldn't support BIP 68.
122 bool fEnforceBIP68 = static_cast<uint32_t>(tx.nVersion) >= 2 &&
124
125 // Do not enforce sequence numbers as a relative lock time
126 // unless we have been instructed to
127 if (!fEnforceBIP68) {
128 return std::make_pair(nMinHeight, nMinTime);
129 }
130
131 for (size_t txinIndex = 0; txinIndex < tx.vin.size(); txinIndex++) {
132 const CTxIn &txin = tx.vin[txinIndex];
133
134 // Sequence numbers with the most significant bit set are not
135 // treated as relative lock-times, nor are they given any
136 // consensus-enforced meaning at this point.
137 if (txin.nSequence & CTxIn::SEQUENCE_LOCKTIME_DISABLE_FLAG) {
138 // The height of this input is not relevant for sequence locks
139 prevHeights[txinIndex] = 0;
140 continue;
141 }
142
143 int nCoinHeight = prevHeights[txinIndex];
144
145 if (txin.nSequence & CTxIn::SEQUENCE_LOCKTIME_TYPE_FLAG) {
146 const int64_t nCoinTime{
147 Assert(block.GetAncestor(std::max(nCoinHeight - 1, 0)))
148 ->GetMedianTimePast()};
149 // NOTE: Subtract 1 to maintain nLockTime semantics.
150 // BIP 68 relative lock times have the semantics of calculating the
151 // first block or time at which the transaction would be valid. When
152 // calculating the effective block time or height for the entire
153 // transaction, we switch to using the semantics of nLockTime which
154 // is the last invalid block time or height. Thus we subtract 1 from
155 // the calculated time or height.
156
157 // Time-based relative lock-times are measured from the smallest
158 // allowed timestamp of the block containing the txout being spent,
159 // which is the median time past of the block prior.
160 nMinTime = std::max(
161 nMinTime,
162 nCoinTime +
163 int64_t((txin.nSequence & CTxIn::SEQUENCE_LOCKTIME_MASK)
165 1);
166 } else {
167 nMinHeight = std::max(
168 nMinHeight,
169 nCoinHeight +
170 int(txin.nSequence & CTxIn::SEQUENCE_LOCKTIME_MASK) - 1);
171 }
172 }
173
174 return std::make_pair(nMinHeight, nMinTime);
175}
176
178 std::pair<int, int64_t> lockPair) {
179 assert(block.pprev);
180 int64_t nBlockTime = block.pprev->GetMedianTimePast();
181 if (lockPair.first >= block.nHeight || lockPair.second >= nBlockTime) {
182 return false;
183 }
184
185 return true;
186}
187
188bool SequenceLocks(const CTransaction &tx, int flags,
189 std::vector<int> &prevHeights, const CBlockIndex &block) {
191 block, CalculateSequenceLocks(tx, flags, prevHeights, block));
192}
193
194namespace Consensus {
195bool CheckTxInputs(const CTransaction &tx, TxValidationState &state,
196 const CCoinsViewCache &inputs, int nSpendHeight,
197 Amount &txfee) {
198 // are the actual inputs available?
199 if (!inputs.HaveInputs(tx)) {
201 "bad-txns-inputs-missingorspent",
202 strprintf("%s: inputs missing/spent", __func__));
203 }
204
205 Amount nValueIn = Amount::zero();
206 for (const auto &in : tx.vin) {
207 const COutPoint &prevout = in.prevout;
208 const Coin &coin = inputs.AccessCoin(prevout);
209 assert(!coin.IsSpent());
210
211 // If prev is coinbase, check that it's matured
212 if (coin.IsCoinBase() &&
213 nSpendHeight - coin.GetHeight() < COINBASE_MATURITY) {
214 return state.Invalid(
216 "bad-txns-premature-spend-of-coinbase",
217 strprintf("tried to spend coinbase at depth %d",
218 nSpendHeight - coin.GetHeight()));
219 }
220
221 // Check for negative or overflow input values
222 nValueIn += coin.GetTxOut().nValue;
223 if (!MoneyRange(coin.GetTxOut().nValue) || !MoneyRange(nValueIn)) {
225 "bad-txns-inputvalues-outofrange");
226 }
227 }
228
229 const Amount value_out = tx.GetValueOut();
230 if (nValueIn < value_out) {
231 return state.Invalid(
232 TxValidationResult::TX_CONSENSUS, "bad-txns-in-belowout",
233 strprintf("value in (%s) < value out (%s)", FormatMoney(nValueIn),
234 FormatMoney(value_out)));
235 }
236
237 // Tally transaction fees
238 const Amount txfee_aux = nValueIn - value_out;
239 if (!MoneyRange(txfee_aux)) {
241 "bad-txns-fee-outofrange");
242 }
243
244 txfee = txfee_aux;
245 return true;
246}
247} // 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:166
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:341
const Coin & AccessCoin(const COutPoint &output) const
Return a reference to Coin in the cache, or coinEmpty if not found.
Definition: coins.cpp:196
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:195
static const unsigned int LOCKTIME_THRESHOLD
Definition: script.h:44
size_t GetSerializeSize(const T &t, int nVersion=0)
Definition: serialize.h:1207
Definition: amount.h:19
static constexpr Amount zero() noexcept
Definition: amount.h:32
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:73
static bool IsFinalTx(const CTransaction &tx, int nBlockHeight, int64_t nBlockTime)
Definition: tx_verify.cpp:21
bool EvaluateSequenceLocks(const CBlockIndex &block, std::pair< int, int64_t > lockPair)
Definition: tx_verify.cpp:177
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:105
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:188
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:42
AssertLockHeld(pool.cs)
assert(!tx.IsCoinBase())
static const int PROTOCOL_VERSION
network protocol versioning
Definition: version.h:11