Bitcoin Core 31.99.0
P2P Digital Currency
tx_verify.cpp
Go to the documentation of this file.
1// Copyright (c) 2017-present The Bitcoin Core 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 <chain.h>
8#include <coins.h>
9#include <consensus/amount.h>
10#include <consensus/consensus.h>
13#include <script/interpreter.h>
14#include <script/script.h>
15#include <tinyformat.h>
16#include <util/check.h>
17#include <util/moneystr.h>
18
19#include <algorithm>
20#include <cstddef>
21#include <string>
22
23bool IsFinalTx(const CTransaction &tx, int nBlockHeight, int64_t nBlockTime)
24{
25 if (tx.nLockTime == 0)
26 return true;
27 if ((int64_t)tx.nLockTime < ((int64_t)tx.nLockTime < LOCKTIME_THRESHOLD ? (int64_t)nBlockHeight : nBlockTime))
28 return true;
29
30 // Even if tx.nLockTime isn't satisfied by nBlockHeight/nBlockTime, a
31 // transaction is still considered final if all inputs' nSequence ==
32 // SEQUENCE_FINAL (0xffffffff), in which case nLockTime is ignored.
33 //
34 // Because of this behavior OP_CHECKLOCKTIMEVERIFY/CheckLockTime() will
35 // also check that the spending input's nSequence != SEQUENCE_FINAL,
36 // ensuring that an unsatisfied nLockTime value will actually cause
37 // IsFinalTx() to return false here:
38 for (const auto& txin : tx.vin) {
39 if (!(txin.nSequence == CTxIn::SEQUENCE_FINAL))
40 return false;
41 }
42 return true;
43}
44
45std::pair<int, int64_t> CalculateSequenceLocks(const CTransaction &tx, int flags, std::vector<int>& prevHeights, const CBlockIndex& block)
46{
47 assert(prevHeights.size() == tx.vin.size());
48
49 // Will be set to the equivalent height- and time-based nLockTime
50 // values that would be necessary to satisfy all relative lock-
51 // time constraints given our view of block chain history.
52 // The semantics of nLockTime are the last invalid height/time, so
53 // use -1 to have the effect of any height or time being valid.
54 int nMinHeight = -1;
55 int64_t nMinTime = -1;
56
57 bool fEnforceBIP68 = tx.version >= 2 && flags & LOCKTIME_VERIFY_SEQUENCE;
58
59 // Do not enforce sequence numbers as a relative lock time
60 // unless we have been instructed to
61 if (!fEnforceBIP68) {
62 return std::make_pair(nMinHeight, nMinTime);
63 }
64
65 for (size_t txinIndex = 0; txinIndex < tx.vin.size(); txinIndex++) {
66 const CTxIn& txin = tx.vin[txinIndex];
67
68 // Sequence numbers with the most significant bit set are not
69 // treated as relative lock-times, nor are they given any
70 // consensus-enforced meaning at this point.
72 // The height of this input is not relevant for sequence locks
73 prevHeights[txinIndex] = 0;
74 continue;
75 }
76
77 int nCoinHeight = prevHeights[txinIndex];
78
80 const int64_t nCoinTime{Assert(block.GetAncestor(std::max(nCoinHeight - 1, 0)))->GetMedianTimePast()};
81 // NOTE: Subtract 1 to maintain nLockTime semantics
82 // BIP 68 relative lock times have the semantics of calculating
83 // the first block or time at which the transaction would be
84 // valid. When calculating the effective block time or height
85 // for the entire transaction, we switch to using the
86 // semantics of nLockTime which is the last invalid block
87 // time or height. Thus we subtract 1 from the calculated
88 // time or height.
89
90 // Time-based relative lock-times are measured from the
91 // smallest allowed timestamp of the block containing the
92 // txout being spent, which is the median time past of the
93 // block prior.
94 nMinTime = std::max(nMinTime, nCoinTime + (int64_t)((txin.nSequence & CTxIn::SEQUENCE_LOCKTIME_MASK) << CTxIn::SEQUENCE_LOCKTIME_GRANULARITY) - 1);
95 } else {
96 nMinHeight = std::max(nMinHeight, nCoinHeight + (int)(txin.nSequence & CTxIn::SEQUENCE_LOCKTIME_MASK) - 1);
97 }
98 }
99
100 return std::make_pair(nMinHeight, nMinTime);
101}
102
103bool EvaluateSequenceLocks(const CBlockIndex& block, std::pair<int, int64_t> lockPair)
104{
105 assert(block.pprev);
106 int64_t nBlockTime = block.pprev->GetMedianTimePast();
107 if (lockPair.first >= block.nHeight || lockPair.second >= nBlockTime)
108 return false;
109
110 return true;
111}
112
113bool SequenceLocks(const CTransaction &tx, int flags, std::vector<int>& prevHeights, const CBlockIndex& block)
114{
115 return EvaluateSequenceLocks(block, CalculateSequenceLocks(tx, flags, prevHeights, block));
116}
117
118unsigned int GetLegacySigOpCount(const CTransaction& tx)
119{
120 unsigned int nSigOps = 0;
121 for (const auto& txin : tx.vin)
122 {
123 nSigOps += txin.scriptSig.GetSigOpCount(false);
124 }
125 for (const auto& txout : tx.vout)
126 {
127 nSigOps += txout.scriptPubKey.GetSigOpCount(false);
128 }
129 return nSigOps;
130}
131
132unsigned int GetP2SHSigOpCount(const CTransaction& tx, const CCoinsViewCache& inputs)
133{
134 if (tx.IsCoinBase())
135 return 0;
136
137 unsigned int nSigOps = 0;
138 for (unsigned int i = 0; i < tx.vin.size(); i++)
139 {
140 const Coin& coin = inputs.AccessCoin(tx.vin[i].prevout);
141 assert(!coin.IsSpent());
142 const CTxOut &prevout = coin.out;
143 if (prevout.scriptPubKey.IsPayToScriptHash())
144 nSigOps += prevout.scriptPubKey.GetSigOpCount(tx.vin[i].scriptSig);
145 }
146 return nSigOps;
147}
148
150{
151 int64_t nSigOps = GetLegacySigOpCount(tx) * WITNESS_SCALE_FACTOR;
152
153 if (tx.IsCoinBase())
154 return nSigOps;
155
157 nSigOps += GetP2SHSigOpCount(tx, inputs) * WITNESS_SCALE_FACTOR;
158 }
159
160 for (unsigned int i = 0; i < tx.vin.size(); i++)
161 {
162 const Coin& coin = inputs.AccessCoin(tx.vin[i].prevout);
163 assert(!coin.IsSpent());
164 const CTxOut &prevout = coin.out;
165 nSigOps += CountWitnessSigOps(tx.vin[i].scriptSig, prevout.scriptPubKey, tx.vin[i].scriptWitness, flags);
166 }
167 return nSigOps;
168}
169
170bool Consensus::CheckTxInputs(const CTransaction& tx, TxValidationState& state, const CCoinsViewCache& inputs, int nSpendHeight, CAmount& txfee)
171{
172 // are the actual inputs available?
173 if (!inputs.HaveInputs(tx)) {
174 return state.Invalid(TxValidationResult::TX_MISSING_INPUTS, "bad-txns-inputs-missingorspent",
175 strprintf("%s: inputs missing/spent", __func__));
176 }
177
178 CAmount nValueIn = 0;
179 for (unsigned int i = 0; i < tx.vin.size(); ++i) {
180 const COutPoint &prevout = tx.vin[i].prevout;
181 const Coin& coin = inputs.AccessCoin(prevout);
182 assert(!coin.IsSpent());
183
184 // If prev is coinbase, check that it's matured
185 if (coin.IsCoinBase() && nSpendHeight - coin.nHeight < COINBASE_MATURITY) {
186 return state.Invalid(TxValidationResult::TX_PREMATURE_SPEND, "bad-txns-premature-spend-of-coinbase",
187 strprintf("tried to spend coinbase at depth %d", nSpendHeight - coin.nHeight));
188 }
189
190 // Check for negative or overflow input values
191 nValueIn += coin.out.nValue;
192 if (!MoneyRange(coin.out.nValue) || !MoneyRange(nValueIn)) {
193 return state.Invalid(TxValidationResult::TX_CONSENSUS, "bad-txns-inputvalues-outofrange");
194 }
195 }
196
197 // `tx.GetValueOut()` won't throw in validation paths because output-range checks run first
198 // (`bad-txns-vout-negative`, `bad-txns-vout-toolarge`, `bad-txns-txouttotal-toolarge`):
199 // * `MemPoolAccept::PreChecks`: `CheckTransaction()` is called before this method;
200 // * `Chainstate::ConnectBlock`: `CheckTransaction()` is called via `CheckBlock()` before this method.
201 const CAmount value_out = tx.GetValueOut();
202 if (nValueIn < value_out) {
203 return state.Invalid(TxValidationResult::TX_CONSENSUS, "bad-txns-in-belowout",
204 strprintf("value in (%s) < value out (%s)", FormatMoney(nValueIn), FormatMoney(value_out)));
205 }
206
207 // Tally transaction fees
208 const CAmount txfee_aux = nValueIn - value_out;
209 if (!MoneyRange(txfee_aux)) {
210 // Unreachable, given the following preconditions:
211 // * `value_out` comes from `tx.GetValueOut()`, which throws unless `MoneyRange(value_out)` and asserts `MoneyRange(nValueOut)` on return.
212 // * `MoneyRange(nValueIn)` was enforced in the input loop.
213 // * `nValueIn < value_out` was handled above, so `nValueIn >= value_out` here (and `txfee_aux >= 0`).
214 // Therefore `0 <= txfee_aux = nValueIn - value_out <= nValueIn <= MAX_MONEY`.
215 return state.Invalid(TxValidationResult::TX_CONSENSUS, "bad-txns-fee-outofrange");
216 }
217
218 txfee = txfee_aux;
219 return true;
220}
bool MoneyRange(const CAmount &nValue)
Definition: amount.h:27
int64_t CAmount
Amount in satoshis (Can be negative)
Definition: amount.h:12
int flags
Definition: bitcoin-tx.cpp:530
#define Assert(val)
Identity function.
Definition: check.h:116
The block chain is a tree shaped structure starting with the genesis block at the root,...
Definition: chain.h:94
CBlockIndex * pprev
pointer to the index of the predecessor of this block
Definition: chain.h:100
int64_t GetMedianTimePast() const
Definition: chain.h:233
CBlockIndex * GetAncestor(int height)
Efficiently find an ancestor of this block.
Definition: chain.cpp:109
int nHeight
height of the entry in the chain. The genesis block has height 0
Definition: chain.h:106
CCoinsView that adds a memory cache for transactions to another CCoinsView.
Definition: coins.h:437
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:322
const Coin & AccessCoin(const COutPoint &output) const
Return a reference to Coin in the cache, or coinEmpty if not found.
Definition: coins.cpp:170
An outpoint - a combination of a transaction hash and an index n into its vout.
Definition: transaction.h:29
bool IsPayToScriptHash() const
Definition: script.cpp:224
unsigned int GetSigOpCount(bool fAccurate) const
Pre-version-0.6, Bitcoin always counted CHECKMULTISIGs as 20 sigops.
Definition: script.cpp:159
The basic transaction that is broadcasted on the network and contained in blocks.
Definition: transaction.h:281
const uint32_t nLockTime
Definition: transaction.h:294
const std::vector< CTxOut > vout
Definition: transaction.h:292
bool IsCoinBase() const
Definition: transaction.h:341
CAmount GetValueOut() const
Definition: transaction.cpp:98
const uint32_t version
Definition: transaction.h:293
const std::vector< CTxIn > vin
Definition: transaction.h:291
An input of a transaction.
Definition: transaction.h:62
static constexpr uint32_t SEQUENCE_FINAL
Setting nSequence to this value for every input in a transaction disables nLockTime/IsFinalTx().
Definition: transaction.h:76
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:114
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:99
uint32_t nSequence
Definition: transaction.h:66
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:104
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:93
An output of a transaction.
Definition: transaction.h:140
CScript scriptPubKey
Definition: transaction.h:143
CAmount nValue
Definition: transaction.h:142
A UTXO entry.
Definition: coins.h:46
bool IsCoinBase() const
Definition: coins.h:70
CTxOut out
unspent transaction output
Definition: coins.h:49
bool IsSpent() const
Either this coin never existed (see e.g.
Definition: coins.h:94
uint32_t nHeight
at which height this containing transaction was included in the active block chain
Definition: coins.h:55
bool Invalid(Result result, const std::string &reject_reason="", const std::string &debug_message="")
Definition: validation.h:96
@ 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:28
static const int COINBASE_MATURITY
Coinbase transaction outputs can only be spent after this number of new blocks (network rule)
Definition: consensus.h:19
static const int WITNESS_SCALE_FACTOR
Definition: consensus.h:21
size_t CountWitnessSigOps(const CScript &scriptSig, const CScript &scriptPubKey, const CScriptWitness &witness, script_verify_flags flags)
std::string FormatMoney(const CAmount n)
Money parsing/formatting utilities.
Definition: moneystr.cpp:19
bool CheckTxInputs(const CTransaction &tx, TxValidationState &state, const CCoinsViewCache &inputs, int nSpendHeight, CAmount &txfee)
Check whether all inputs of this transaction are valid (no double spends and amounts) This does not m...
Definition: tx_verify.cpp:170
static const unsigned int LOCKTIME_THRESHOLD
Definition: script.h:48
#define strprintf
Format arguments and return the string or write to given std::ostream (see tinyformat::format doc for...
Definition: tinyformat.h:1172
bool EvaluateSequenceLocks(const CBlockIndex &block, std::pair< int, int64_t > lockPair)
Definition: tx_verify.cpp:103
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:45
int64_t GetTransactionSigOpCost(const CTransaction &tx, const CCoinsViewCache &inputs, script_verify_flags flags)
Compute total signature operation cost of a transaction.
Definition: tx_verify.cpp:149
unsigned int GetLegacySigOpCount(const CTransaction &tx)
Auxiliary functions for transaction validation (ideally should not be exposed)
Definition: tx_verify.cpp:118
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:113
unsigned int GetP2SHSigOpCount(const CTransaction &tx, const CCoinsViewCache &inputs)
Count ECDSA signature operations in pay-to-script-hash inputs.
Definition: tx_verify.cpp:132
bool IsFinalTx(const CTransaction &tx, int nBlockHeight, int64_t nBlockTime)
Check if transaction is final and can be included in a block with the specified height and time.
Definition: tx_verify.cpp:23
assert(!tx.IsCoinBase())