1 // Copyright (c) 2017-2019 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>
8 #include <primitives/transaction.h>
9 #include <script/interpreter.h>
10 #include <consensus/validation.h>
11 #include <chainparams.h>
12 
13 // TODO remove the following dependencies
14 #include <chain.h>
15 #include <coins.h>
16 #include <util/moneystr.h>
17 
IsFinalTx(const CTransaction & tx,int nBlockHeight,int64_t nBlockTime)18 bool IsFinalTx(const CTransaction &tx, int nBlockHeight, int64_t nBlockTime)
19 {
20     if (tx.nLockTime == 0)
21         return true;
22     if ((int64_t)tx.nLockTime < ((int64_t)tx.nLockTime < LOCKTIME_THRESHOLD ? (int64_t)nBlockHeight : nBlockTime))
23         return true;
24     for (const auto& txin : tx.vin) {
25         if (!(txin.nSequence == CTxIn::SEQUENCE_FINAL))
26             return false;
27     }
28     return true;
29 }
30 
CalculateSequenceLocks(const CTransaction & tx,int flags,std::vector<int> * prevHeights,const CBlockIndex & block)31 std::pair<int, int64_t> CalculateSequenceLocks(const CTransaction &tx, int flags, std::vector<int>* prevHeights, const CBlockIndex& block)
32 {
33     assert(prevHeights->size() == tx.vin.size());
34 
35     // Will be set to the equivalent height- and time-based nLockTime
36     // values that would be necessary to satisfy all relative lock-
37     // time constraints given our view of block chain history.
38     // The semantics of nLockTime are the last invalid height/time, so
39     // use -1 to have the effect of any height or time being valid.
40     int nMinHeight = -1;
41     int64_t nMinTime = -1;
42 
43     // tx.nVersion is signed integer so requires cast to unsigned otherwise
44     // we would be doing a signed comparison and half the range of nVersion
45     // wouldn't support BIP 68.
46     bool fEnforceBIP68 = static_cast<uint32_t>(tx.nVersion) >= 2
47                       && flags & LOCKTIME_VERIFY_SEQUENCE;
48 
49     // Do not enforce sequence numbers as a relative lock time
50     // unless we have been instructed to
51     if (!fEnforceBIP68) {
52         return std::make_pair(nMinHeight, nMinTime);
53     }
54 
55     for (size_t txinIndex = 0; txinIndex < tx.vin.size(); txinIndex++) {
56         const CTxIn& txin = tx.vin[txinIndex];
57 
58         // Sequence numbers with the most significant bit set are not
59         // treated as relative lock-times, nor are they given any
60         // consensus-enforced meaning at this point.
61         if (txin.nSequence & CTxIn::SEQUENCE_LOCKTIME_DISABLE_FLAG) {
62             // The height of this input is not relevant for sequence locks
63             (*prevHeights)[txinIndex] = 0;
64             continue;
65         }
66 
67         int nCoinHeight = (*prevHeights)[txinIndex];
68 
69         if (txin.nSequence & CTxIn::SEQUENCE_LOCKTIME_TYPE_FLAG) {
70             int64_t nCoinTime = block.GetAncestor(std::max(nCoinHeight-1, 0))->GetMedianTimePast();
71             // NOTE: Subtract 1 to maintain nLockTime semantics
72             // BIP 68 relative lock times have the semantics of calculating
73             // the first block or time at which the transaction would be
74             // valid. When calculating the effective block time or height
75             // for the entire transaction, we switch to using the
76             // semantics of nLockTime which is the last invalid block
77             // time or height.  Thus we subtract 1 from the calculated
78             // time or height.
79 
80             // Time-based relative lock-times are measured from the
81             // smallest allowed timestamp of the block containing the
82             // txout being spent, which is the median time past of the
83             // block prior.
84             nMinTime = std::max(nMinTime, nCoinTime + (int64_t)((txin.nSequence & CTxIn::SEQUENCE_LOCKTIME_MASK) << CTxIn::SEQUENCE_LOCKTIME_GRANULARITY) - 1);
85         } else {
86             nMinHeight = std::max(nMinHeight, nCoinHeight + (int)(txin.nSequence & CTxIn::SEQUENCE_LOCKTIME_MASK) - 1);
87         }
88     }
89 
90     return std::make_pair(nMinHeight, nMinTime);
91 }
92 
EvaluateSequenceLocks(const CBlockIndex & block,std::pair<int,int64_t> lockPair)93 bool EvaluateSequenceLocks(const CBlockIndex& block, std::pair<int, int64_t> lockPair)
94 {
95     assert(block.pprev);
96     int64_t nBlockTime = block.pprev->GetMedianTimePast();
97     if (lockPair.first >= block.nHeight || lockPair.second >= nBlockTime)
98         return false;
99 
100     return true;
101 }
102 
SequenceLocks(const CTransaction & tx,int flags,std::vector<int> * prevHeights,const CBlockIndex & block)103 bool SequenceLocks(const CTransaction &tx, int flags, std::vector<int>* prevHeights, const CBlockIndex& block)
104 {
105     return EvaluateSequenceLocks(block, CalculateSequenceLocks(tx, flags, prevHeights, block));
106 }
107 
GetLegacySigOpCount(const CTransaction & tx)108 unsigned int GetLegacySigOpCount(const CTransaction& tx)
109 {
110     unsigned int nSigOps = 0;
111     for (const auto& txin : tx.vin)
112     {
113         nSigOps += txin.scriptSig.GetSigOpCount(false);
114     }
115     for (const auto& txout : tx.vout)
116     {
117         nSigOps += txout.scriptPubKey.GetSigOpCount(false);
118     }
119     return nSigOps;
120 }
121 
GetP2SHSigOpCount(const CTransaction & tx,const CCoinsViewCache & inputs)122 unsigned int GetP2SHSigOpCount(const CTransaction& tx, const CCoinsViewCache& inputs)
123 {
124     if (tx.IsCoinBase())
125         return 0;
126 
127     unsigned int nSigOps = 0;
128     for (unsigned int i = 0; i < tx.vin.size(); i++)
129     {
130         const Coin& coin = inputs.AccessCoin(tx.vin[i].prevout);
131         assert(!coin.IsSpent());
132         const CTxOut &prevout = coin.out;
133         if (prevout.scriptPubKey.IsPayToScriptHash())
134             nSigOps += prevout.scriptPubKey.GetSigOpCount(tx.vin[i].scriptSig);
135     }
136     return nSigOps;
137 }
138 
GetTransactionSigOpCost(const CTransaction & tx,const CCoinsViewCache & inputs,int flags)139 int64_t GetTransactionSigOpCost(const CTransaction& tx, const CCoinsViewCache& inputs, int flags)
140 {
141     int64_t nSigOps = GetLegacySigOpCount(tx) * WITNESS_SCALE_FACTOR;
142 
143     if (tx.IsCoinBase())
144         return nSigOps;
145 
146     if (flags & SCRIPT_VERIFY_P2SH) {
147         nSigOps += GetP2SHSigOpCount(tx, inputs) * WITNESS_SCALE_FACTOR;
148     }
149 
150     for (unsigned int i = 0; i < tx.vin.size(); i++)
151     {
152         const Coin& coin = inputs.AccessCoin(tx.vin[i].prevout);
153         assert(!coin.IsSpent());
154         const CTxOut &prevout = coin.out;
155         nSigOps += CountWitnessSigOps(tx.vin[i].scriptSig, prevout.scriptPubKey, &tx.vin[i].scriptWitness, flags);
156     }
157     return nSigOps;
158 }
159 
CheckTxInputs(const CTransaction & tx,TxValidationState & state,const CCoinsViewCache & inputs,int nSpendHeight,CAmount & txfee)160 bool Consensus::CheckTxInputs(const CTransaction& tx, TxValidationState& state, const CCoinsViewCache& inputs, int nSpendHeight, CAmount& txfee)
161 {
162     // are the actual inputs available?
163     if (!inputs.HaveInputs(tx)) {
164         return state.Invalid(TxValidationResult::TX_MISSING_INPUTS, "bad-txns-inputs-missingorspent",
165                          strprintf("%s: inputs missing/spent", __func__));
166     }
167 
168     CAmount nValueIn = 0;
169     for (unsigned int i = 0; i < tx.vin.size(); ++i) {
170         const COutPoint &prevout = tx.vin[i].prevout;
171         const Coin& coin = inputs.AccessCoin(prevout);
172         assert(!coin.IsSpent());
173 
174         // If prev is coinbase, check that it's matured
175         if ((coin.IsCoinBase() || coin.IsCoinStake()) && nSpendHeight - coin.nHeight < ::Params().GetConsensus().CoinbaseMaturity(nSpendHeight)) {
176             return state.Invalid(TxValidationResult::TX_PREMATURE_SPEND, "bad-txns-premature-spend-of-coinbase",
177                 strprintf("tried to spend coinbase at depth %d", nSpendHeight - coin.nHeight));
178         }
179 
180         // Check for negative or overflow input values
181         nValueIn += coin.out.nValue;
182         if (!MoneyRange(coin.out.nValue) || !MoneyRange(nValueIn)) {
183             return state.Invalid(TxValidationResult::TX_CONSENSUS, "bad-txns-inputvalues-outofrange");
184         }
185     }
186 
187     if (!tx.IsCoinStake())
188     {
189         const CAmount value_out = tx.GetValueOut();
190         if (nValueIn < value_out) {
191             return state.Invalid(TxValidationResult::TX_CONSENSUS, "bad-txns-in-belowout",
192                 strprintf("value in (%s) < value out (%s)", FormatMoney(nValueIn), FormatMoney(value_out)));
193         }
194 
195         // Tally transaction fees
196         const CAmount txfee_aux = nValueIn - value_out;
197         if (!MoneyRange(txfee_aux)) {
198             return state.Invalid(TxValidationResult::TX_CONSENSUS, "bad-txns-fee-outofrange");
199         }
200 
201         txfee = txfee_aux;
202     }
203 
204     return true;
205 }
206