Dash Core Source Documentation (0.16.0.1)

Find detailed information regarding the Dash Core source code.

tx_verify.cpp
Go to the documentation of this file.
1 // Copyright (c) 2017-2017 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 <consensus/consensus.h>
9 #include <script/interpreter.h>
10 #include <consensus/validation.h>
11 
12 // TODO remove the following dependencies
13 #include <chain.h>
14 #include <coins.h>
15 #include <utilmoneystr.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  for (const auto& txin : tx.vin) {
24  if (!(txin.nSequence == CTxIn::SEQUENCE_FINAL))
25  return false;
26  }
27  return true;
28 }
29 
30 std::pair<int, int64_t> CalculateSequenceLocks(const CTransaction &tx, int flags, std::vector<int>* prevHeights, const CBlockIndex& block)
31 {
32  assert(prevHeights->size() == tx.vin.size());
33 
34  // Will be set to the equivalent height- and time-based nLockTime
35  // values that would be necessary to satisfy all relative lock-
36  // time constraints given our view of block chain history.
37  // The semantics of nLockTime are the last invalid height/time, so
38  // use -1 to have the effect of any height or time being valid.
39  int nMinHeight = -1;
40  int64_t nMinTime = -1;
41 
42  // tx.nVersion is signed integer so requires cast to unsigned otherwise
43  // we would be doing a signed comparison and half the range of nVersion
44  // wouldn't support BIP 68.
45  bool fEnforceBIP68 = static_cast<uint32_t>(tx.nVersion) >= 2
47 
48  // Do not enforce sequence numbers as a relative lock time
49  // unless we have been instructed to
50  if (!fEnforceBIP68) {
51  return std::make_pair(nMinHeight, nMinTime);
52  }
53 
54  for (size_t txinIndex = 0; txinIndex < tx.vin.size(); txinIndex++) {
55  const CTxIn& txin = tx.vin[txinIndex];
56 
57  // Sequence numbers with the most significant bit set are not
58  // treated as relative lock-times, nor are they given any
59  // consensus-enforced meaning at this point.
61  // The height of this input is not relevant for sequence locks
62  (*prevHeights)[txinIndex] = 0;
63  continue;
64  }
65 
66  int nCoinHeight = (*prevHeights)[txinIndex];
67 
69  int64_t nCoinTime = block.GetAncestor(std::max(nCoinHeight-1, 0))->GetMedianTimePast();
70  // NOTE: Subtract 1 to maintain nLockTime semantics
71  // BIP 68 relative lock times have the semantics of calculating
72  // the first block or time at which the transaction would be
73  // valid. When calculating the effective block time or height
74  // for the entire transaction, we switch to using the
75  // semantics of nLockTime which is the last invalid block
76  // time or height. Thus we subtract 1 from the calculated
77  // time or height.
78 
79  // Time-based relative lock-times are measured from the
80  // smallest allowed timestamp of the block containing the
81  // txout being spent, which is the median time past of the
82  // block prior.
83  nMinTime = std::max(nMinTime, nCoinTime + (int64_t)((txin.nSequence & CTxIn::SEQUENCE_LOCKTIME_MASK) << CTxIn::SEQUENCE_LOCKTIME_GRANULARITY) - 1);
84  } else {
85  nMinHeight = std::max(nMinHeight, nCoinHeight + (int)(txin.nSequence & CTxIn::SEQUENCE_LOCKTIME_MASK) - 1);
86  }
87  }
88 
89  return std::make_pair(nMinHeight, nMinTime);
90 }
91 
92 bool EvaluateSequenceLocks(const CBlockIndex& block, std::pair<int, int64_t> lockPair)
93 {
94  assert(block.pprev);
95  int64_t nBlockTime = block.pprev->GetMedianTimePast();
96  if (lockPair.first >= block.nHeight || lockPair.second >= nBlockTime)
97  return false;
98 
99  return true;
100 }
101 
102 bool SequenceLocks(const CTransaction &tx, int flags, std::vector<int>* prevHeights, const CBlockIndex& block)
103 {
104  return EvaluateSequenceLocks(block, CalculateSequenceLocks(tx, flags, prevHeights, block));
105 }
106 
107 unsigned int GetLegacySigOpCount(const CTransaction& tx)
108 {
109  unsigned int nSigOps = 0;
110  for (const auto& txin : tx.vin)
111  {
112  nSigOps += txin.scriptSig.GetSigOpCount(false);
113  }
114  for (const auto& txout : tx.vout)
115  {
116  nSigOps += txout.scriptPubKey.GetSigOpCount(false);
117  }
118  return nSigOps;
119 }
120 
121 unsigned int GetP2SHSigOpCount(const CTransaction& tx, const CCoinsViewCache& inputs)
122 {
123  if (tx.IsCoinBase())
124  return 0;
125 
126  unsigned int nSigOps = 0;
127  for (unsigned int i = 0; i < tx.vin.size(); i++)
128  {
129  const Coin& coin = inputs.AccessCoin(tx.vin[i].prevout);
130  assert(!coin.IsSpent());
131  const CTxOut &prevout = coin.out;
132  if (prevout.scriptPubKey.IsPayToScriptHash())
133  nSigOps += prevout.scriptPubKey.GetSigOpCount(tx.vin[i].scriptSig);
134  }
135  return nSigOps;
136 }
137 
138 unsigned int GetTransactionSigOpCount(const CTransaction& tx, const CCoinsViewCache& inputs, int flags)
139 {
140  unsigned int nSigOps = GetLegacySigOpCount(tx);
141 
142  if (tx.IsCoinBase())
143  return nSigOps;
144 
145  if (flags & SCRIPT_VERIFY_P2SH) {
146  nSigOps += GetP2SHSigOpCount(tx, inputs);
147  }
148 
149  return nSigOps;
150 }
151 
153 {
154  bool allowEmptyTxInOut = false;
156  allowEmptyTxInOut = true;
157  }
158 
159  // Basic checks that don't depend on any context
160  if (!allowEmptyTxInOut && tx.vin.empty())
161  return state.DoS(10, false, REJECT_INVALID, "bad-txns-vin-empty");
162  if (!allowEmptyTxInOut && tx.vout.empty())
163  return state.DoS(10, false, REJECT_INVALID, "bad-txns-vout-empty");
164  // Size limits
166  return state.DoS(100, false, REJECT_INVALID, "bad-txns-oversize");
167  if (tx.vExtraPayload.size() > MAX_TX_EXTRA_PAYLOAD)
168  return state.DoS(100, false, REJECT_INVALID, "bad-txns-payload-oversize");
169 
170  // Check for negative or overflow output values
171  CAmount nValueOut = 0;
172  for (const auto& txout : tx.vout)
173  {
174  if (txout.nValue < 0)
175  return state.DoS(100, false, REJECT_INVALID, "bad-txns-vout-negative");
176  if (txout.nValue > MAX_MONEY)
177  return state.DoS(100, false, REJECT_INVALID, "bad-txns-vout-toolarge");
178  nValueOut += txout.nValue;
179  if (!MoneyRange(nValueOut))
180  return state.DoS(100, false, REJECT_INVALID, "bad-txns-txouttotal-toolarge");
181  }
182 
183  // Check for duplicate inputs
184  std::set<COutPoint> vInOutPoints;
185  for (const auto& txin : tx.vin)
186  {
187  if (!vInOutPoints.insert(txin.prevout).second)
188  return state.DoS(100, false, REJECT_INVALID, "bad-txns-inputs-duplicate");
189  }
190 
191  if (tx.IsCoinBase())
192  {
193  size_t minCbSize = 2;
194  if (tx.nType == TRANSACTION_COINBASE) {
195  // With the introduction of CbTx, coinbase scripts are not required anymore to hold a valid block height
196  minCbSize = 1;
197  }
198  if (tx.vin[0].scriptSig.size() < minCbSize || tx.vin[0].scriptSig.size() > 100)
199  return state.DoS(100, false, REJECT_INVALID, "bad-cb-length");
200  }
201  else
202  {
203  for (const auto& txin : tx.vin)
204  if (txin.prevout.IsNull())
205  return state.DoS(10, false, REJECT_INVALID, "bad-txns-prevout-null");
206  }
207 
208  return true;
209 }
210 
211 bool Consensus::CheckTxInputs(const CTransaction& tx, CValidationState& state, const CCoinsViewCache& inputs, int nSpendHeight, CAmount& txfee)
212 {
213  // are the actual inputs available?
214  if (!inputs.HaveInputs(tx)) {
215  return state.DoS(100, false, REJECT_INVALID, "bad-txns-inputs-missingorspent", false,
216  strprintf("%s: inputs missing/spent", __func__));
217  }
218 
219  CAmount nValueIn = 0;
220  for (unsigned int i = 0; i < tx.vin.size(); ++i) {
221  const COutPoint &prevout = tx.vin[i].prevout;
222  const Coin& coin = inputs.AccessCoin(prevout);
223  assert(!coin.IsSpent());
224 
225  // If prev is coinbase, check that it's matured
226  if (coin.IsCoinBase() && nSpendHeight - coin.nHeight < COINBASE_MATURITY) {
227  return state.Invalid(false,
228  REJECT_INVALID, "bad-txns-premature-spend-of-coinbase",
229  strprintf("tried to spend coinbase at depth %d", nSpendHeight - coin.nHeight));
230  }
231 
232  // Check for negative or overflow input values
233  nValueIn += coin.out.nValue;
234  if (!MoneyRange(coin.out.nValue) || !MoneyRange(nValueIn)) {
235  return state.DoS(100, false, REJECT_INVALID, "bad-txns-inputvalues-outofrange");
236  }
237  }
238 
239  const CAmount value_out = tx.GetValueOut();
240  if (nValueIn < value_out) {
241  return state.DoS(100, false, REJECT_INVALID, "bad-txns-in-belowout", false,
242  strprintf("value in (%s) < value out (%s)", FormatMoney(nValueIn), FormatMoney(value_out)));
243  }
244 
245  // Tally transaction fees
246  const CAmount txfee_aux = nValueIn - value_out;
247  if (!MoneyRange(txfee_aux)) {
248  return state.DoS(100, false, REJECT_INVALID, "bad-txns-fee-outofrange");
249  }
250 
251  txfee = txfee_aux;
252  return true;
253 }
unsigned int GetSigOpCount(bool fAccurate) const
Pre-version-0.6, Bitcoin always counted CHECKMULTISIGs as 20 sigops.
Definition: script.cpp:153
CAmount nValue
Definition: transaction.h:147
bool IsSpent() const
Definition: coins.h:75
static constexpr unsigned int LOCKTIME_VERIFY_SEQUENCE
Flags for nSequence and nLockTime locks.
Definition: consensus.h:28
bool IsCoinBase() const
Definition: coins.h:54
bool CheckTransaction(const CTransaction &tx, CValidationState &state)
Transaction validation functions.
Definition: tx_verify.cpp:152
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&#39;s median time past at which the transaction will be co...
Definition: tx_verify.cpp:30
CScript scriptPubKey
Definition: transaction.h:148
CBlockIndex * pprev
pointer to the index of the predecessor of this block
Definition: chain.h:177
const Coin & AccessCoin(const COutPoint &output) const
Return a reference to Coin in the cache, or a pruned one if not found.
Definition: coins.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:102
A UTXO entry.
Definition: coins.h:29
static const CAmount MAX_MONEY
No amount larger than this (in satoshi) is valid.
Definition: amount.h:26
#define strprintf
Definition: tinyformat.h:1066
size_t GetSerializeSize(const T &t, int nType, int nVersion=0)
Definition: serialize.h:1295
static const uint32_t SEQUENCE_FINAL
Definition: transaction.h:79
bool MoneyRange(const CAmount &nValue)
Definition: amount.h:27
static const uint32_t SEQUENCE_LOCKTIME_DISABLE_FLAG
Definition: transaction.h:84
CTxOut out
unspent transaction output
Definition: coins.h:33
static const int COINBASE_MATURITY
Coinbase transaction outputs can only be spent after this number of new blocks (network rule) ...
Definition: consensus.h:24
int flags
Definition: dash-tx.cpp:462
static const int SEQUENCE_LOCKTIME_GRANULARITY
Definition: transaction.h:102
bool DoS(int level, bool ret=false, unsigned int chRejectCodeIn=0, const std::string &strRejectReasonIn="", bool corruptionIn=false, const std::string &strDebugMessageIn="")
Definition: validation.h:36
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:235
static const unsigned char REJECT_INVALID
Definition: validation.h:13
bool IsCoinBase() const
Definition: transaction.h:272
const std::vector< CTxIn > vin
Definition: transaction.h:215
CAmount GetValueOut() const
Definition: transaction.cpp:99
unsigned int GetTransactionSigOpCount(const CTransaction &tx, const CCoinsViewCache &inputs, int flags)
Count total signature operations for a transaction.
Definition: tx_verify.cpp:138
int64_t CAmount
Amount in satoshis (Can be negative)
Definition: amount.h:12
uint32_t nHeight
at which height this containing transaction was included in the active block chain ...
Definition: coins.h:39
An input of a transaction.
Definition: transaction.h:70
bool CheckTxInputs(const CTransaction &tx, CValidationState &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:211
static const unsigned int MAX_LEGACY_BLOCK_SIZE
The maximum allowed size for a serialized block, in bytes (network rule)
Definition: consensus.h:10
const std::vector< CTxOut > vout
Definition: transaction.h:216
bool EvaluateSequenceLocks(const CBlockIndex &block, std::pair< int, int64_t > lockPair)
Definition: tx_verify.cpp:92
An output of a transaction.
Definition: transaction.h:144
static const uint32_t SEQUENCE_LOCKTIME_TYPE_FLAG
Definition: transaction.h:89
An outpoint - a combination of a transaction hash and an index n into its vout.
Definition: transaction.h:26
std::string FormatMoney(const CAmount &n)
Money parsing/formatting utilities.
int64_t GetMedianTimePast() const
Definition: chain.h:309
const int16_t nVersion
Definition: transaction.h:217
Capture information about block/transaction validation.
Definition: validation.h:22
static const uint32_t SEQUENCE_LOCKTIME_MASK
Definition: transaction.h:93
unsigned int GetLegacySigOpCount(const CTransaction &tx)
Auxiliary functions for transaction validation (ideally should not be exposed)
Definition: tx_verify.cpp:107
The block chain is a tree shaped structure starting with the genesis block at the root...
Definition: chain.h:170
uint32_t nSequence
Definition: transaction.h:75
static const int PROTOCOL_VERSION
network protocol versioning
Definition: version.h:14
const std::vector< uint8_t > vExtraPayload
Definition: transaction.h:220
unsigned int GetP2SHSigOpCount(const CTransaction &tx, const CCoinsViewCache &inputs)
Count ECDSA signature operations in pay-to-script-hash inputs.
Definition: tx_verify.cpp:121
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
static const unsigned int LOCKTIME_THRESHOLD
Definition: script.h:39
The basic transaction that is broadcasted on the network and contained in blocks. ...
Definition: transaction.h:198
int nHeight
height of the entry in the chain. The genesis block has height 0
Definition: chain.h:183
CCoinsView that adds a memory cache for transactions to another CCoinsView.
Definition: coins.h:201
CBlockIndex * GetAncestor(int height)
Efficiently find an ancestor of this block.
Definition: chain.cpp:110
bool Invalid(bool ret=false, unsigned int _chRejectCode=0, const std::string &_strRejectReason="", const std::string &_strDebugMessage="")
Definition: validation.h:50
const int16_t nType
Definition: transaction.h:218
static const unsigned int MAX_TX_EXTRA_PAYLOAD
The maximum allowed size of version 3 extra payload.
Definition: consensus.h:22
const uint32_t nLockTime
Definition: transaction.h:219
Released under the MIT license