Fabcoin Core  0.16.2
P2P Digital Currency
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 <script/standard.h>
11 #include <consensus/validation.h>
12 #include <chainparams.h>
13 
14 // TODO remove the following dependencies
15 #include <chain.h>
16 #include <coins.h>
17 #include <utilmoneystr.h>
18 
19 bool IsFinalTx(const CTransaction &tx, int nBlockHeight, int64_t nBlockTime)
20 {
21  if (tx.nLockTime == 0)
22  return true;
23  if ((int64_t)tx.nLockTime < ((int64_t)tx.nLockTime < LOCKTIME_THRESHOLD ? (int64_t)nBlockHeight : nBlockTime))
24  return true;
25  for (const auto& txin : tx.vin) {
26  if (!(txin.nSequence == CTxIn::SEQUENCE_FINAL))
27  return false;
28  }
29  return true;
30 }
31 
32 std::pair<int, int64_t> CalculateSequenceLocks(const CTransaction &tx, int flags, std::vector<int>* prevHeights, const CBlockIndex& block)
33 {
34  assert(prevHeights->size() == tx.vin.size());
35 
36  // Will be set to the equivalent height- and time-based nLockTime
37  // values that would be necessary to satisfy all relative lock-
38  // time constraints given our view of block chain history.
39  // The semantics of nLockTime are the last invalid height/time, so
40  // use -1 to have the effect of any height or time being valid.
41  int nMinHeight = -1;
42  int64_t nMinTime = -1;
43 
44  // tx.nVersion is signed integer so requires cast to unsigned otherwise
45  // we would be doing a signed comparison and half the range of nVersion
46  // wouldn't support BIP 68.
47  bool fEnforceBIP68 = static_cast<uint32_t>(tx.nVersion) >= 2
48  && flags & LOCKTIME_VERIFY_SEQUENCE;
49 
50  // Do not enforce sequence numbers as a relative lock time
51  // unless we have been instructed to
52  if (!fEnforceBIP68) {
53  return std::make_pair(nMinHeight, nMinTime);
54  }
55 
56  for (size_t txinIndex = 0; txinIndex < tx.vin.size(); txinIndex++) {
57  const CTxIn& txin = tx.vin[txinIndex];
58 
59  // Sequence numbers with the most significant bit set are not
60  // treated as relative lock-times, nor are they given any
61  // consensus-enforced meaning at this point.
63  // The height of this input is not relevant for sequence locks
64  (*prevHeights)[txinIndex] = 0;
65  continue;
66  }
67 
68  int nCoinHeight = (*prevHeights)[txinIndex];
69 
71  int64_t nCoinTime = block.GetAncestor(std::max(nCoinHeight-1, 0))->GetMedianTimePast();
72  // NOTE: Subtract 1 to maintain nLockTime semantics
73  // BIP 68 relative lock times have the semantics of calculating
74  // the first block or time at which the transaction would be
75  // valid. When calculating the effective block time or height
76  // for the entire transaction, we switch to using the
77  // semantics of nLockTime which is the last invalid block
78  // time or height. Thus we subtract 1 from the calculated
79  // time or height.
80 
81  // Time-based relative lock-times are measured from the
82  // smallest allowed timestamp of the block containing the
83  // txout being spent, which is the median time past of the
84  // block prior.
85  nMinTime = std::max(nMinTime, nCoinTime + (int64_t)((txin.nSequence & CTxIn::SEQUENCE_LOCKTIME_MASK) << CTxIn::SEQUENCE_LOCKTIME_GRANULARITY) - 1);
86  } else {
87  nMinHeight = std::max(nMinHeight, nCoinHeight + (int)(txin.nSequence & CTxIn::SEQUENCE_LOCKTIME_MASK) - 1);
88  }
89  }
90 
91  return std::make_pair(nMinHeight, nMinTime);
92 }
93 
94 bool EvaluateSequenceLocks(const CBlockIndex& block, std::pair<int, int64_t> lockPair)
95 {
96  assert(block.pprev);
97  int64_t nBlockTime = block.pprev->GetMedianTimePast();
98  if (lockPair.first >= block.nHeight || lockPair.second >= nBlockTime)
99  return false;
100 
101  return true;
102 }
103 
104 bool SequenceLocks(const CTransaction &tx, int flags, std::vector<int>* prevHeights, const CBlockIndex& block)
105 {
106  return EvaluateSequenceLocks(block, CalculateSequenceLocks(tx, flags, prevHeights, block));
107 }
108 
109 unsigned int GetLegacySigOpCount(const CTransaction& tx)
110 {
111  unsigned int nSigOps = 0;
112  for (const auto& txin : tx.vin)
113  {
114  nSigOps += txin.scriptSig.GetSigOpCount(false);
115  }
116  for (const auto& txout : tx.vout)
117  {
118  nSigOps += txout.scriptPubKey.GetSigOpCount(false);
119  }
120  return nSigOps;
121 }
122 
123 unsigned int GetP2SHSigOpCount(const CTransaction& tx, const CCoinsViewCache& inputs)
124 {
125  if (tx.IsCoinBase())
126  return 0;
127 
128  unsigned int nSigOps = 0;
129  for (unsigned int i = 0; i < tx.vin.size(); i++)
130  {
131  const Coin& coin = inputs.AccessCoin(tx.vin[i].prevout);
132  assert(!coin.IsSpent());
133  const CTxOut &prevout = coin.out;
134  if (prevout.scriptPubKey.IsPayToScriptHash())
135  nSigOps += prevout.scriptPubKey.GetSigOpCount(tx.vin[i].scriptSig);
136  }
137  return nSigOps;
138 }
139 
140 int64_t GetTransactionSigOpCost(const CTransaction& tx, const CCoinsViewCache& inputs, int flags)
141 {
142  int64_t nSigOps = GetLegacySigOpCount(tx) * WITNESS_SCALE_FACTOR;
143 
144  if (tx.IsCoinBase())
145  return nSigOps;
146 
147  if (flags & SCRIPT_VERIFY_P2SH) {
148  nSigOps += GetP2SHSigOpCount(tx, inputs) * WITNESS_SCALE_FACTOR;
149  }
150 
151  for (unsigned int i = 0; i < tx.vin.size(); i++)
152  {
153  const Coin& coin = inputs.AccessCoin(tx.vin[i].prevout);
154  assert(!coin.IsSpent());
155  const CTxOut &prevout = coin.out;
156  nSigOps += CountWitnessSigOps(tx.vin[i].scriptSig, prevout.scriptPubKey, &tx.vin[i].scriptWitness, flags);
157  }
158  return nSigOps;
159 }
160 
161 bool CheckTransaction(const CTransaction& tx, CValidationState &state, bool fCheckDuplicateInputs)
162 {
163  // Basic checks that don't depend on any context
164  if (tx.vin.empty())
165  return state.DoS(10, false, REJECT_INVALID, "bad-txns-vin-empty");
166  if (tx.vout.empty())
167  return state.DoS(10, false, REJECT_INVALID, "bad-txns-vout-empty");
168  // Size limits (this doesn't take the witness into account, as that hasn't been checked for malleability)
170  if (::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION | SERIALIZE_TRANSACTION_NO_WITNESS) > MAX_TRANSACTION_BASE_SIZE ||
171  ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION | SERIALIZE_TRANSACTION_NO_WITNESS) * WITNESS_SCALE_FACTOR > dgpMaxBlockWeight)
172  return state.DoS(100, false, REJECT_INVALID, "bad-txns-oversize");
173 
174  // Check for negative or overflow output values
175  CAmount nValueOut = 0;
176  for (const auto& txout : tx.vout)
177  {
178  if (txout.IsEmpty() && !tx.IsCoinBase() )
179  return state.DoS(100, false, REJECT_INVALID, "bad-txns-vout-empty");
180  if (txout.nValue < 0)
181  return state.DoS(100, false, REJECT_INVALID, "bad-txns-vout-negative");
182  if (txout.nValue > MAX_MONEY)
183  return state.DoS(100, false, REJECT_INVALID, "bad-txns-vout-toolarge");
184  nValueOut += txout.nValue;
185  if (!MoneyRange(nValueOut))
186  return state.DoS(100, false, REJECT_INVALID, "bad-txns-txouttotal-toolarge");
187 
189  if (txout.scriptPubKey.HasOpCall() || txout.scriptPubKey.HasOpCreate()) {
190  std::vector<valtype> vSolutions;
191  txnouttype whichType;
192  if (!Solver(txout.scriptPubKey, whichType, vSolutions, true)) {
193  return state.DoS(100, false, REJECT_INVALID, "bad-txns-contract-nonstandard");
194  }
195  }
197  }
198 
199  // Check for duplicate inputs - note that this check is slow so we skip it in CheckBlock
200  if (fCheckDuplicateInputs) {
201  std::set<COutPoint> vInOutPoints;
202  for (const auto& txin : tx.vin)
203  {
204  if (!vInOutPoints.insert(txin.prevout).second)
205  return state.DoS(100, false, REJECT_INVALID, "bad-txns-inputs-duplicate");
206  }
207  }
208 
209  if (tx.IsCoinBase())
210  {
211  if (tx.vin[0].scriptSig.size() < 2 || tx.vin[0].scriptSig.size() > 100)
212  return state.DoS(100, false, REJECT_INVALID, "bad-cb-length");
213  }
214  else
215  {
216  for (const auto& txin : tx.vin)
217  if (txin.prevout.IsNull())
218  return state.DoS(10, false, REJECT_INVALID, "bad-txns-prevout-null");
219  }
220 
221  return true;
222 }
223 
224 bool Consensus::CheckTxInputs(const CTransaction& tx, CValidationState& state, const CCoinsViewCache& inputs, int nSpendHeight)
225 {
226  // This doesn't trigger the DoS code on purpose; if it did, it would make it easier
227  // for an attacker to attempt to split the network.
228  if (!inputs.HaveInputs(tx))
229  return state.Invalid(false, 0, "", "Inputs unavailable");
230 
231  CAmount nValueIn = 0;
232  CAmount nFees = 0;
233  for (unsigned int i = 0; i < tx.vin.size(); i++)
234  {
235  const COutPoint &prevout = tx.vin[i].prevout;
236  const Coin& coin = inputs.AccessCoin(prevout);
237  assert(!coin.IsSpent());
238 
239  // If prev is coinbase, check that it's matured
240  if (coin.IsCoinBase()) {
241  const Consensus::Params& consensus = ::GetParams().GetConsensus();
242  if (nSpendHeight - coin.nHeight < COINBASE_MATURITY)
243  return state.Invalid(false,
244  REJECT_INVALID, "bad-txns-premature-spend-of-coinbase",
245  strprintf("tried to spend coinbase at depth %d", nSpendHeight - coin.nHeight));
246 
247  if( coin.nHeight < consensus.CoinbaseLock && coin.nHeight != 2 )
248  {
249  if (nSpendHeight - coin.nHeight < consensus.CoinbaseLock)
250  return state.Invalid(false,
251  REJECT_INVALID, "bad-txns-premature-spend-of-coinbase",
252  strprintf("tried to spend coinbase on height %d at depth %d", coin.nHeight, nSpendHeight - coin.nHeight));
253  }
254  }
255 
256  // Check for negative or overflow input values
257  nValueIn += coin.out.nValue;
258  if (!MoneyRange(coin.out.nValue) || !MoneyRange(nValueIn))
259  return state.DoS(100, false, REJECT_INVALID, "bad-txns-inputvalues-outofrange");
260 
261  }
262 
263  if (nValueIn < tx.GetValueOut())
264  return state.DoS(100, false, REJECT_INVALID, "bad-txns-in-belowout", false,
265  strprintf("value in (%s) < value out (%s)", FormatMoney(nValueIn), FormatMoney(tx.GetValueOut())));
266 
267  // Tally transaction fees
268  CAmount nTxFee = nValueIn - tx.GetValueOut();
269  if (nTxFee < 0)
270  return state.DoS(100, false, REJECT_INVALID, "bad-txns-fee-negative");
271  nFees += nTxFee;
272  if (!MoneyRange(nFees))
273  return state.DoS(100, false, REJECT_INVALID, "bad-txns-fee-outofrange");
274  return true;
275 }
CAmount nValue
Definition: transaction.h:134
bool Solver(const CScript &scriptPubKey, txnouttype &typeRet, std::vector< std::vector< unsigned char > > &vSolutionsRet, bool contractConsensus)
Return public keys or hashes from scriptPubKey, for &#39;standard&#39; transaction types. ...
Definition: standard.cpp:46
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:32
bool CheckTxInputs(const CTransaction &tx, CValidationState &state, const CCoinsViewCache &inputs, int nSpendHeight)
Check whether all inputs of this transaction are valid (no double spends and amounts) This does not m...
Definition: tx_verify.cpp:224
CScript scriptPubKey
Definition: transaction.h:135
CBlockIndex * pprev
pointer to the index of the predecessor of this block
Definition: chain.h:184
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:104
A UTXO entry.
Definition: coins.h:29
#define strprintf
Definition: tinyformat.h:1054
size_t CountWitnessSigOps(const CScript &scriptSig, const CScript &scriptPubKey, const CScriptWitness *witness, unsigned int flags)
size_t GetSerializeSize(const T &t, int nType, int nVersion=0)
Definition: serialize.h:989
static const uint32_t SEQUENCE_FINAL
Only serialized through CTransaction.
Definition: transaction.h:71
bool MoneyRange(const CAmount &nValue)
Definition: amount.h:24
static const uint32_t SEQUENCE_LOCKTIME_DISABLE_FLAG
Definition: transaction.h:76
const Consensus::Params & GetConsensus() const
Definition: chainparams.h:60
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:236
CTxOut out
unspent transaction output
Definition: coins.h:33
bool IsSpent() const
Definition: coins.h:75
static const int SEQUENCE_LOCKTIME_GRANULARITY
Definition: transaction.h:94
assert(len-trim+(2 *lenIndices)<=WIDTH)
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:41
bool IsCoinBase() const
Definition: coins.h:54
const std::vector< CTxIn > vin
Definition: transaction.h:292
int64_t CAmount
Amount in lius (Can be negative)
Definition: amount.h:15
uint32_t nHeight
at which height this containing transaction was included in the active block chain ...
Definition: coins.h:39
const CChainParams & GetParams()
An input of a transaction.
Definition: transaction.h:61
unsigned int GetSigOpCount(bool fAccurate) const
Pre-version-0.6, Fabcoin always counted CHECKMULTISIGs as 20 sigops.
Definition: script.cpp:159
int CoinbaseLock
Block height before which the coinbase subsidy will be locked for the same period.
Definition: params.h:62
CAmount GetValueOut() const
Definition: transaction.cpp:84
const std::vector< CTxOut > vout
Definition: transaction.h:293
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:119
bool EvaluateSequenceLocks(const CBlockIndex &block, std::pair< int, int64_t > lockPair)
Definition: tx_verify.cpp:94
An output of a transaction.
Definition: transaction.h:131
static const uint32_t SEQUENCE_LOCKTIME_TYPE_FLAG
Definition: transaction.h:81
Parameters that influence chain consensus.
Definition: params.h:39
An outpoint - a combination of a transaction hash and an index n into its vout.
Definition: transaction.h:18
std::string FormatMoney(const CAmount &n)
Money parsing/formatting utilities.
txnouttype
Definition: standard.h:51
Capture information about block/transaction validation.
Definition: validation.h:27
const int32_t nVersion
Definition: transaction.h:294
static const uint32_t SEQUENCE_LOCKTIME_MASK
Definition: transaction.h:85
unsigned int GetLegacySigOpCount(const CTransaction &tx)
Auxiliary functions for transaction validation (ideally should not be exposed)
Definition: tx_verify.cpp:109
The block chain is a tree shaped structure starting with the genesis block at the root...
Definition: chain.h:177
uint32_t nSequence
Definition: transaction.h:66
unsigned int GetP2SHSigOpCount(const CTransaction &tx, const CCoinsViewCache &inputs)
Count ECDSA signature operations in pay-to-script-hash inputs.
Definition: tx_verify.cpp:123
bool CheckTransaction(const CTransaction &tx, CValidationState &state, bool fCheckDuplicateInputs)
Transaction validation functions.
Definition: tx_verify.cpp:161
bool IsCoinBase() const
Definition: transaction.h:349
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:19
dev::WithExisting max(dev::WithExisting _a, dev::WithExisting _b)
Definition: Common.h:326
The basic transaction that is broadcasted on the network and contained in blocks. ...
Definition: transaction.h:275
int nHeight
height of the entry in the chain. The genesis block has height 0
Definition: chain.h:193
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:85
bool Invalid(bool ret=false, unsigned int _chRejectCode=0, const std::string &_strRejectReason="", const std::string &_strDebugMessage="")
Definition: validation.h:55
int64_t GetMedianTimePast() const
Definition: chain.h:341
int64_t GetTransactionSigOpCost(const CTransaction &tx, const CCoinsViewCache &inputs, int flags)
Compute total signature operation cost of a transaction.
Definition: tx_verify.cpp:140
const uint32_t nLockTime
Definition: transaction.h:295
unsigned int dgpMaxBlockWeight
The maximum allowed weight for a block, see BIP 141 (network rule)
Definition: consensus.cpp:8