Bitcoin Core  0.20.99
P2P Digital Currency
policy.cpp
Go to the documentation of this file.
1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2019 The Bitcoin Core developers
3 // Distributed under the MIT software license, see the accompanying
4 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
5 
6 // NOTE: This file is intended to be customised by the end user, and includes only local node policy logic
7 
8 #include <policy/policy.h>
9 
10 #include <consensus/validation.h>
11 #include <coins.h>
12 #include <span.h>
13 
14 CAmount GetDustThreshold(const CTxOut& txout, const CFeeRate& dustRelayFeeIn)
15 {
16  // "Dust" is defined in terms of dustRelayFee,
17  // which has units satoshis-per-kilobyte.
18  // If you'd pay more in fees than the value of the output
19  // to spend something, then we consider it dust.
20  // A typical spendable non-segwit txout is 34 bytes big, and will
21  // need a CTxIn of at least 148 bytes to spend:
22  // so dust is a spendable txout less than
23  // 182*dustRelayFee/1000 (in satoshis).
24  // 546 satoshis at the default rate of 3000 sat/kB.
25  // A typical spendable segwit txout is 31 bytes big, and will
26  // need a CTxIn of at least 67 bytes to spend:
27  // so dust is a spendable txout less than
28  // 98*dustRelayFee/1000 (in satoshis).
29  // 294 satoshis at the default rate of 3000 sat/kB.
30  if (txout.scriptPubKey.IsUnspendable())
31  return 0;
32 
33  size_t nSize = GetSerializeSize(txout);
34  int witnessversion = 0;
35  std::vector<unsigned char> witnessprogram;
36 
37  if (txout.scriptPubKey.IsWitnessProgram(witnessversion, witnessprogram)) {
38  // sum the sizes of the parts of a transaction input
39  // with 75% segwit discount applied to the script size.
40  nSize += (32 + 4 + 1 + (107 / WITNESS_SCALE_FACTOR) + 4);
41  } else {
42  nSize += (32 + 4 + 1 + 107 + 4); // the 148 mentioned above
43  }
44 
45  return dustRelayFeeIn.GetFee(nSize);
46 }
47 
48 bool IsDust(const CTxOut& txout, const CFeeRate& dustRelayFeeIn)
49 {
50  return (txout.nValue < GetDustThreshold(txout, dustRelayFeeIn));
51 }
52 
53 bool IsStandard(const CScript& scriptPubKey, TxoutType& whichType)
54 {
55  std::vector<std::vector<unsigned char> > vSolutions;
56  whichType = Solver(scriptPubKey, vSolutions);
57 
58  if (whichType == TxoutType::NONSTANDARD) {
59  return false;
60  } else if (whichType == TxoutType::MULTISIG) {
61  unsigned char m = vSolutions.front()[0];
62  unsigned char n = vSolutions.back()[0];
63  // Support up to x-of-3 multisig txns as standard
64  if (n < 1 || n > 3)
65  return false;
66  if (m < 1 || m > n)
67  return false;
68  } else if (whichType == TxoutType::NULL_DATA &&
69  (!fAcceptDatacarrier || scriptPubKey.size() > nMaxDatacarrierBytes)) {
70  return false;
71  }
72 
73  return true;
74 }
75 
76 bool IsStandardTx(const CTransaction& tx, bool permit_bare_multisig, const CFeeRate& dust_relay_fee, std::string& reason)
77 {
79  reason = "version";
80  return false;
81  }
82 
83  // Extremely large transactions with lots of inputs can cost the network
84  // almost as much to process as they cost the sender in fees, because
85  // computing signature hashes is O(ninputs*txsize). Limiting transactions
86  // to MAX_STANDARD_TX_WEIGHT mitigates CPU exhaustion attacks.
87  unsigned int sz = GetTransactionWeight(tx);
88  if (sz > MAX_STANDARD_TX_WEIGHT) {
89  reason = "tx-size";
90  return false;
91  }
92 
93  for (const CTxIn& txin : tx.vin)
94  {
95  // Biggest 'standard' txin is a 15-of-15 P2SH multisig with compressed
96  // keys (remember the 520 byte limit on redeemScript size). That works
97  // out to a (15*(33+1))+3=513 byte redeemScript, 513+1+15*(73+1)+3=1627
98  // bytes of scriptSig, which we round off to 1650 bytes for some minor
99  // future-proofing. That's also enough to spend a 20-of-20
100  // CHECKMULTISIG scriptPubKey, though such a scriptPubKey is not
101  // considered standard.
102  if (txin.scriptSig.size() > 1650) {
103  reason = "scriptsig-size";
104  return false;
105  }
106  if (!txin.scriptSig.IsPushOnly()) {
107  reason = "scriptsig-not-pushonly";
108  return false;
109  }
110  }
111 
112  unsigned int nDataOut = 0;
113  TxoutType whichType;
114  for (const CTxOut& txout : tx.vout) {
115  if (!::IsStandard(txout.scriptPubKey, whichType)) {
116  reason = "scriptpubkey";
117  return false;
118  }
119 
120  if (whichType == TxoutType::NULL_DATA)
121  nDataOut++;
122  else if ((whichType == TxoutType::MULTISIG) && (!permit_bare_multisig)) {
123  reason = "bare-multisig";
124  return false;
125  } else if (IsDust(txout, dust_relay_fee)) {
126  reason = "dust";
127  return false;
128  }
129  }
130 
131  // only one OP_RETURN txout is permitted
132  if (nDataOut > 1) {
133  reason = "multi-op-return";
134  return false;
135  }
136 
137  return true;
138 }
139 
158 bool AreInputsStandard(const CTransaction& tx, const CCoinsViewCache& mapInputs)
159 {
160  if (tx.IsCoinBase())
161  return true; // Coinbases don't use vin normally
162 
163  for (unsigned int i = 0; i < tx.vin.size(); i++)
164  {
165  const CTxOut& prev = mapInputs.AccessCoin(tx.vin[i].prevout).out;
166 
167  std::vector<std::vector<unsigned char> > vSolutions;
168  TxoutType whichType = Solver(prev.scriptPubKey, vSolutions);
169  if (whichType == TxoutType::NONSTANDARD || whichType == TxoutType::WITNESS_UNKNOWN) {
170  // WITNESS_UNKNOWN failures are typically also caught with a policy
171  // flag in the script interpreter, but it can be helpful to catch
172  // this type of NONSTANDARD transaction earlier in transaction
173  // validation.
174  return false;
175  } else if (whichType == TxoutType::SCRIPTHASH) {
176  std::vector<std::vector<unsigned char> > stack;
177  // convert the scriptSig into a stack, so we can inspect the redeemScript
178  if (!EvalScript(stack, tx.vin[i].scriptSig, SCRIPT_VERIFY_NONE, BaseSignatureChecker(), SigVersion::BASE))
179  return false;
180  if (stack.empty())
181  return false;
182  CScript subscript(stack.back().begin(), stack.back().end());
183  if (subscript.GetSigOpCount(true) > MAX_P2SH_SIGOPS) {
184  return false;
185  }
186  }
187  }
188 
189  return true;
190 }
191 
192 bool IsWitnessStandard(const CTransaction& tx, const CCoinsViewCache& mapInputs)
193 {
194  if (tx.IsCoinBase())
195  return true; // Coinbases are skipped
196 
197  for (unsigned int i = 0; i < tx.vin.size(); i++)
198  {
199  // We don't care if witness for this input is empty, since it must not be bloated.
200  // If the script is invalid without witness, it would be caught sooner or later during validation.
201  if (tx.vin[i].scriptWitness.IsNull())
202  continue;
203 
204  const CTxOut &prev = mapInputs.AccessCoin(tx.vin[i].prevout).out;
205 
206  // get the scriptPubKey corresponding to this input:
207  CScript prevScript = prev.scriptPubKey;
208 
209  bool p2sh = false;
210  if (prevScript.IsPayToScriptHash()) {
211  std::vector <std::vector<unsigned char> > stack;
212  // If the scriptPubKey is P2SH, we try to extract the redeemScript casually by converting the scriptSig
213  // into a stack. We do not check IsPushOnly nor compare the hash as these will be done later anyway.
214  // If the check fails at this stage, we know that this txid must be a bad one.
215  if (!EvalScript(stack, tx.vin[i].scriptSig, SCRIPT_VERIFY_NONE, BaseSignatureChecker(), SigVersion::BASE))
216  return false;
217  if (stack.empty())
218  return false;
219  prevScript = CScript(stack.back().begin(), stack.back().end());
220  p2sh = true;
221  }
222 
223  int witnessversion = 0;
224  std::vector<unsigned char> witnessprogram;
225 
226  // Non-witness program must not be associated with any witness
227  if (!prevScript.IsWitnessProgram(witnessversion, witnessprogram))
228  return false;
229 
230  // Check P2WSH standard limits
231  if (witnessversion == 0 && witnessprogram.size() == WITNESS_V0_SCRIPTHASH_SIZE) {
232  if (tx.vin[i].scriptWitness.stack.back().size() > MAX_STANDARD_P2WSH_SCRIPT_SIZE)
233  return false;
234  size_t sizeWitnessStack = tx.vin[i].scriptWitness.stack.size() - 1;
235  if (sizeWitnessStack > MAX_STANDARD_P2WSH_STACK_ITEMS)
236  return false;
237  for (unsigned int j = 0; j < sizeWitnessStack; j++) {
238  if (tx.vin[i].scriptWitness.stack[j].size() > MAX_STANDARD_P2WSH_STACK_ITEM_SIZE)
239  return false;
240  }
241  }
242 
243  // Check policy limits for Taproot spends:
244  // - MAX_STANDARD_TAPSCRIPT_STACK_ITEM_SIZE limit for stack item size
245  // - No annexes
246  if (witnessversion == 1 && witnessprogram.size() == WITNESS_V1_TAPROOT_SIZE && !p2sh) {
247  // Taproot spend (non-P2SH-wrapped, version 1, witness program size 32; see BIP 341)
248  auto stack = MakeSpan(tx.vin[i].scriptWitness.stack);
249  if (stack.size() >= 2 && !stack.back().empty() && stack.back()[0] == ANNEX_TAG) {
250  // Annexes are nonstandard as long as no semantics are defined for them.
251  return false;
252  }
253  if (stack.size() >= 2) {
254  // Script path spend (2 or more stack elements after removing optional annex)
255  const auto& control_block = SpanPopBack(stack);
256  SpanPopBack(stack); // Ignore script
257  if (control_block.empty()) return false; // Empty control block is invalid
258  if ((control_block[0] & TAPROOT_LEAF_MASK) == TAPROOT_LEAF_TAPSCRIPT) {
259  // Leaf version 0xc0 (aka Tapscript, see BIP 342)
260  for (const auto& item : stack) {
261  if (item.size() > MAX_STANDARD_TAPSCRIPT_STACK_ITEM_SIZE) return false;
262  }
263  }
264  } else if (stack.size() == 1) {
265  // Key path spend (1 stack element after removing optional annex)
266  // (no policy rules apply)
267  } else {
268  // 0 stack elements; this is already invalid by consensus rules
269  return false;
270  }
271  }
272  }
273  return true;
274 }
275 
276 int64_t GetVirtualTransactionSize(int64_t nWeight, int64_t nSigOpCost, unsigned int bytes_per_sigop)
277 {
278  return (std::max(nWeight, nSigOpCost * bytes_per_sigop) + WITNESS_SCALE_FACTOR - 1) / WITNESS_SCALE_FACTOR;
279 }
280 
281 int64_t GetVirtualTransactionSize(const CTransaction& tx, int64_t nSigOpCost, unsigned int bytes_per_sigop)
282 {
283  return GetVirtualTransactionSize(GetTransactionWeight(tx), nSigOpCost, bytes_per_sigop);
284 }
285 
286 int64_t GetVirtualTransactionInputSize(const CTxIn& txin, int64_t nSigOpCost, unsigned int bytes_per_sigop)
287 {
288  return GetVirtualTransactionSize(GetTransactionInputWeight(txin), nSigOpCost, bytes_per_sigop);
289 }
static int64_t GetTransactionWeight(const CTransaction &tx)
Definition: validation.h:146
CAmount nValue
Definition: transaction.h:131
static const int32_t MAX_STANDARD_VERSION
Definition: transaction.h:269
static const int WITNESS_SCALE_FACTOR
Definition: consensus.h:21
CScript scriptPubKey
Definition: transaction.h:132
const Coin & AccessCoin(const COutPoint &output) const
Return a reference to Coin in the cache, or coinEmpty if not found.
Definition: coins.cpp:131
static constexpr size_t WITNESS_V1_TAPROOT_SIZE
Definition: interpreter.h:212
bool IsPayToScriptHash() const
Definition: script.cpp:201
FeeReason reason
Definition: fees.h:71
CTxOut out
unspent transaction output
Definition: coins.h:34
bool fAcceptDatacarrier
A data carrying output is an unspendable output containing data.
Definition: standard.cpp:16
static const unsigned int MAX_STANDARD_P2WSH_SCRIPT_SIZE
The maximum size of a standard witnessScript.
Definition: policy.h:46
static constexpr uint8_t TAPROOT_LEAF_TAPSCRIPT
Definition: interpreter.h:215
Bare scripts and BIP16 P2SH-wrapped redeemscripts.
bool IsWitnessProgram(int &version, std::vector< unsigned char > &program) const
Definition: script.cpp:220
int64_t GetVirtualTransactionSize(int64_t nWeight, int64_t nSigOpCost, unsigned int bytes_per_sigop)
Compute the virtual transaction size (weight reinterpreted as bytes).
Definition: policy.cpp:276
static const unsigned int MAX_STANDARD_TAPSCRIPT_STACK_ITEM_SIZE
The maximum size of each witness stack item in a standard BIP 342 script (Taproot, leaf version 0xc0)
Definition: policy.h:44
unspendable OP_RETURN script that carries data
bool IsCoinBase() const
Definition: transaction.h:324
const std::vector< CTxIn > vin
Definition: transaction.h:276
bool IsWitnessStandard(const CTransaction &tx, const CCoinsViewCache &mapInputs)
Check if the transaction is over standard P2WSH resources limit: 3600bytes witnessScript size...
Definition: policy.cpp:192
size_t GetSerializeSize(const T &t, int nVersion=0)
Definition: serialize.h:1116
bool IsUnspendable() const
Returns whether the script is guaranteed to fail at execution, regardless of the initial stack...
Definition: script.h:543
int64_t CAmount
Amount in satoshis (Can be negative)
Definition: amount.h:12
bool AreInputsStandard(const CTransaction &tx, const CCoinsViewCache &mapInputs)
Check transaction inputs to mitigate two potential denial-of-service attacks:
Definition: policy.cpp:158
int64_t GetVirtualTransactionInputSize(const CTxIn &txin, int64_t nSigOpCost, unsigned int bytes_per_sigop)
Definition: policy.cpp:286
static const unsigned int MAX_P2SH_SIGOPS
Maximum number of signature check operations in an IsStandard() P2SH script.
Definition: policy.h:28
An input of a transaction.
Definition: transaction.h:65
static int64_t GetTransactionInputWeight(const CTxIn &txin)
Definition: validation.h:154
bool IsPushOnly(const_iterator pc) const
Called by IsStandardTx and P2SH/BIP62 VerifyScript (which makes it consensus-critical).
Definition: script.cpp:236
TxoutType
Definition: standard.h:122
static constexpr uint8_t TAPROOT_LEAF_MASK
Definition: interpreter.h:214
const std::vector< CTxOut > vout
Definition: transaction.h:277
An output of a transaction.
Definition: transaction.h:128
static constexpr size_t WITNESS_V0_SCRIPTHASH_SIZE
Signature hash sizes.
Definition: interpreter.h:210
static const unsigned int MAX_STANDARD_P2WSH_STACK_ITEMS
The maximum number of witness stack items in a standard P2WSH script.
Definition: policy.h:40
CAmount GetDustThreshold(const CTxOut &txout, const CFeeRate &dustRelayFeeIn)
Definition: policy.cpp:14
CScript scriptSig
Definition: transaction.h:69
static const unsigned int MAX_STANDARD_P2WSH_STACK_ITEM_SIZE
The maximum size of each witness stack item in a standard P2WSH script.
Definition: policy.h:42
const int32_t nVersion
Definition: transaction.h:278
Serialized script, used inside transaction inputs and outputs.
Definition: script.h:404
static constexpr unsigned int ANNEX_TAG
Definition: script.h:50
static const unsigned int MAX_STANDARD_TX_WEIGHT
The maximum weight for transactions we&#39;re willing to relay/mine.
Definition: policy.h:24
T & SpanPopBack(Span< T > &span)
Pop the last element off a span, and return a reference to that element.
Definition: span.h:201
TxoutType Solver(const CScript &scriptPubKey, std::vector< std::vector< unsigned char >> &vSolutionsRet)
Parse a scriptPubKey and identify script type for standard scripts.
Definition: standard.cpp:110
Only for Witness versions not already defined above.
Fee rate in satoshis per kilobyte: CAmount / kB.
Definition: feerate.h:29
bool IsDust(const CTxOut &txout, const CFeeRate &dustRelayFeeIn)
Definition: policy.cpp:48
size_type size() const
Definition: prevector.h:282
The basic transaction that is broadcasted on the network and contained in blocks. ...
Definition: transaction.h:259
CCoinsView that adds a memory cache for transactions to another CCoinsView.
Definition: coins.h:236
bool IsStandardTx(const CTransaction &tx, bool permit_bare_multisig, const CFeeRate &dust_relay_fee, std::string &reason)
Check for standard transaction types.
Definition: policy.cpp:76
bool EvalScript(std::vector< std::vector< unsigned char > > &stack, const CScript &script, unsigned int flags, const BaseSignatureChecker &checker, SigVersion sigversion, ScriptExecutionData &execdata, ScriptError *serror)
bool IsStandard(const CScript &scriptPubKey, TxoutType &whichType)
Definition: policy.cpp:53
unsigned nMaxDatacarrierBytes
Maximum size of TxoutType::NULL_DATA scripts that this node considers standard.
Definition: standard.cpp:17
CAmount GetFee(size_t nBytes) const
Return the fee in satoshis for the given size in bytes.
Definition: feerate.cpp:21
Span< A > constexpr MakeSpan(A(&a)[N])
MakeSpan for arrays:
Definition: span.h:193