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