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