Bitcoin Core  29.1.0
P2P Digital Currency
policy.cpp
Go to the documentation of this file.
1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2022 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 <coins.h>
11 #include <consensus/amount.h>
12 #include <consensus/consensus.h>
13 #include <consensus/validation.h>
14 #include <policy/feerate.h>
15 #include <primitives/transaction.h>
16 #include <script/interpreter.h>
17 #include <script/script.h>
18 #include <script/solver.h>
19 #include <serialize.h>
20 #include <span.h>
21 
22 #include <algorithm>
23 #include <cstddef>
24 #include <vector>
25 
26 CAmount GetDustThreshold(const CTxOut& txout, const CFeeRate& dustRelayFeeIn)
27 {
28  // "Dust" is defined in terms of dustRelayFee,
29  // which has units satoshis-per-kilobyte.
30  // If you'd pay more in fees than the value of the output
31  // to spend something, then we consider it dust.
32  // A typical spendable non-segwit txout is 34 bytes big, and will
33  // need a CTxIn of at least 148 bytes to spend:
34  // so dust is a spendable txout less than
35  // 182*dustRelayFee/1000 (in satoshis).
36  // 546 satoshis at the default rate of 3000 sat/kvB.
37  // A typical spendable segwit P2WPKH txout is 31 bytes big, and will
38  // need a CTxIn of at least 67 bytes to spend:
39  // so dust is a spendable txout less than
40  // 98*dustRelayFee/1000 (in satoshis).
41  // 294 satoshis at the default rate of 3000 sat/kvB.
42  if (txout.scriptPubKey.IsUnspendable())
43  return 0;
44 
45  size_t nSize = GetSerializeSize(txout);
46  int witnessversion = 0;
47  std::vector<unsigned char> witnessprogram;
48 
49  // Note this computation is for spending a Segwit v0 P2WPKH output (a 33 bytes
50  // public key + an ECDSA signature). For Segwit v1 Taproot outputs the minimum
51  // satisfaction is lower (a single BIP340 signature) but this computation was
52  // kept to not further reduce the dust level.
53  // See discussion in https://github.com/bitcoin/bitcoin/pull/22779 for details.
54  if (txout.scriptPubKey.IsWitnessProgram(witnessversion, witnessprogram)) {
55  // sum the sizes of the parts of a transaction input
56  // with 75% segwit discount applied to the script size.
57  nSize += (32 + 4 + 1 + (107 / WITNESS_SCALE_FACTOR) + 4);
58  } else {
59  nSize += (32 + 4 + 1 + 107 + 4); // the 148 mentioned above
60  }
61 
62  return dustRelayFeeIn.GetFee(nSize);
63 }
64 
65 bool IsDust(const CTxOut& txout, const CFeeRate& dustRelayFeeIn)
66 {
67  return (txout.nValue < GetDustThreshold(txout, dustRelayFeeIn));
68 }
69 
70 std::vector<uint32_t> GetDust(const CTransaction& tx, CFeeRate dust_relay_rate)
71 {
72  std::vector<uint32_t> dust_outputs;
73  for (uint32_t i{0}; i < tx.vout.size(); ++i) {
74  if (IsDust(tx.vout[i], dust_relay_rate)) dust_outputs.push_back(i);
75  }
76  return dust_outputs;
77 }
78 
79 bool IsStandard(const CScript& scriptPubKey, const std::optional<unsigned>& max_datacarrier_bytes, TxoutType& whichType)
80 {
81  std::vector<std::vector<unsigned char> > vSolutions;
82  whichType = Solver(scriptPubKey, vSolutions);
83 
84  if (whichType == TxoutType::NONSTANDARD) {
85  return false;
86  } else if (whichType == TxoutType::MULTISIG) {
87  unsigned char m = vSolutions.front()[0];
88  unsigned char n = vSolutions.back()[0];
89  // Support up to x-of-3 multisig txns as standard
90  if (n < 1 || n > 3)
91  return false;
92  if (m < 1 || m > n)
93  return false;
94  } else if (whichType == TxoutType::NULL_DATA) {
95  if (!max_datacarrier_bytes || scriptPubKey.size() > *max_datacarrier_bytes) {
96  return false;
97  }
98  }
99 
100  return true;
101 }
102 
103 bool IsStandardTx(const CTransaction& tx, const std::optional<unsigned>& max_datacarrier_bytes, bool permit_bare_multisig, const CFeeRate& dust_relay_fee, std::string& reason)
104 {
105  if (tx.version > TX_MAX_STANDARD_VERSION || tx.version < 1) {
106  reason = "version";
107  return false;
108  }
109 
110  // Extremely large transactions with lots of inputs can cost the network
111  // almost as much to process as they cost the sender in fees, because
112  // computing signature hashes is O(ninputs*txsize). Limiting transactions
113  // to MAX_STANDARD_TX_WEIGHT mitigates CPU exhaustion attacks.
114  unsigned int sz = GetTransactionWeight(tx);
115  if (sz > MAX_STANDARD_TX_WEIGHT) {
116  reason = "tx-size";
117  return false;
118  }
119 
120  for (const CTxIn& txin : tx.vin)
121  {
122  // Biggest 'standard' txin involving only keys is a 15-of-15 P2SH
123  // multisig with compressed keys (remember the MAX_SCRIPT_ELEMENT_SIZE byte limit on
124  // redeemScript size). That works out to a (15*(33+1))+3=513 byte
125  // redeemScript, 513+1+15*(73+1)+3=1627 bytes of scriptSig, which
126  // we round off to 1650(MAX_STANDARD_SCRIPTSIG_SIZE) bytes for
127  // some minor future-proofing. That's also enough to spend a
128  // 20-of-20 CHECKMULTISIG scriptPubKey, though such a scriptPubKey
129  // is not considered standard.
131  reason = "scriptsig-size";
132  return false;
133  }
134  if (!txin.scriptSig.IsPushOnly()) {
135  reason = "scriptsig-not-pushonly";
136  return false;
137  }
138  }
139 
140  unsigned int nDataOut = 0;
141  TxoutType whichType;
142  for (const CTxOut& txout : tx.vout) {
143  if (!::IsStandard(txout.scriptPubKey, max_datacarrier_bytes, whichType)) {
144  reason = "scriptpubkey";
145  return false;
146  }
147 
148  if (whichType == TxoutType::NULL_DATA)
149  nDataOut++;
150  else if ((whichType == TxoutType::MULTISIG) && (!permit_bare_multisig)) {
151  reason = "bare-multisig";
152  return false;
153  }
154  }
155 
156  // Only MAX_DUST_OUTPUTS_PER_TX dust is permitted(on otherwise valid ephemeral dust)
157  if (GetDust(tx, dust_relay_fee).size() > MAX_DUST_OUTPUTS_PER_TX) {
158  reason = "dust";
159  return false;
160  }
161 
162  // only one OP_RETURN txout is permitted
163  if (nDataOut > 1) {
164  reason = "multi-op-return";
165  return false;
166  }
167 
168  return true;
169 }
170 
174 static bool CheckSigopsBIP54(const CTransaction& tx, const CCoinsViewCache& inputs)
175 {
176  Assert(!tx.IsCoinBase());
177 
178  unsigned int sigops{0};
179  for (const auto& txin: tx.vin) {
180  const auto& prev_txo{inputs.AccessCoin(txin.prevout).out};
181 
182  // Unlike the existing block wide sigop limit which counts sigops present in the block
183  // itself (including the scriptPubKey which is not executed until spending later), BIP54
184  // counts sigops in the block where they are potentially executed (only).
185  // This means sigops in the spent scriptPubKey count toward the limit.
186  // `fAccurate` means correctly accounting sigops for CHECKMULTISIGs(VERIFY) with 16 pubkeys
187  // or fewer. This method of accounting was introduced by BIP16, and BIP54 reuses it.
188  // The GetSigOpCount call on the previous scriptPubKey counts both bare and P2SH sigops.
189  sigops += txin.scriptSig.GetSigOpCount(/*fAccurate=*/true);
190  sigops += prev_txo.scriptPubKey.GetSigOpCount(txin.scriptSig);
191 
192  if (sigops > MAX_TX_LEGACY_SIGOPS) {
193  return false;
194  }
195  }
196 
197  return true;
198 }
199 
220 bool AreInputsStandard(const CTransaction& tx, const CCoinsViewCache& mapInputs)
221 {
222  if (tx.IsCoinBase()) {
223  return true; // Coinbases don't use vin normally
224  }
225 
226  if (!CheckSigopsBIP54(tx, mapInputs)) {
227  return false;
228  }
229 
230  for (unsigned int i = 0; i < tx.vin.size(); i++) {
231  const CTxOut& prev = mapInputs.AccessCoin(tx.vin[i].prevout).out;
232 
233  std::vector<std::vector<unsigned char> > vSolutions;
234  TxoutType whichType = Solver(prev.scriptPubKey, vSolutions);
235  if (whichType == TxoutType::NONSTANDARD || whichType == TxoutType::WITNESS_UNKNOWN) {
236  // WITNESS_UNKNOWN failures are typically also caught with a policy
237  // flag in the script interpreter, but it can be helpful to catch
238  // this type of NONSTANDARD transaction earlier in transaction
239  // validation.
240  return false;
241  } else if (whichType == TxoutType::SCRIPTHASH) {
242  std::vector<std::vector<unsigned char> > stack;
243  // convert the scriptSig into a stack, so we can inspect the redeemScript
244  if (!EvalScript(stack, tx.vin[i].scriptSig, SCRIPT_VERIFY_NONE, BaseSignatureChecker(), SigVersion::BASE))
245  return false;
246  if (stack.empty())
247  return false;
248  CScript subscript(stack.back().begin(), stack.back().end());
249  if (subscript.GetSigOpCount(true) > MAX_P2SH_SIGOPS) {
250  return false;
251  }
252  }
253  }
254 
255  return true;
256 }
257 
258 bool IsWitnessStandard(const CTransaction& tx, const CCoinsViewCache& mapInputs)
259 {
260  if (tx.IsCoinBase())
261  return true; // Coinbases are skipped
262 
263  for (unsigned int i = 0; i < tx.vin.size(); i++)
264  {
265  // We don't care if witness for this input is empty, since it must not be bloated.
266  // If the script is invalid without witness, it would be caught sooner or later during validation.
267  if (tx.vin[i].scriptWitness.IsNull())
268  continue;
269 
270  const CTxOut &prev = mapInputs.AccessCoin(tx.vin[i].prevout).out;
271 
272  // get the scriptPubKey corresponding to this input:
273  CScript prevScript = prev.scriptPubKey;
274 
275  // witness stuffing detected
276  if (prevScript.IsPayToAnchor()) {
277  return false;
278  }
279 
280  bool p2sh = false;
281  if (prevScript.IsPayToScriptHash()) {
282  std::vector <std::vector<unsigned char> > stack;
283  // If the scriptPubKey is P2SH, we try to extract the redeemScript casually by converting the scriptSig
284  // into a stack. We do not check IsPushOnly nor compare the hash as these will be done later anyway.
285  // If the check fails at this stage, we know that this txid must be a bad one.
286  if (!EvalScript(stack, tx.vin[i].scriptSig, SCRIPT_VERIFY_NONE, BaseSignatureChecker(), SigVersion::BASE))
287  return false;
288  if (stack.empty())
289  return false;
290  prevScript = CScript(stack.back().begin(), stack.back().end());
291  p2sh = true;
292  }
293 
294  int witnessversion = 0;
295  std::vector<unsigned char> witnessprogram;
296 
297  // Non-witness program must not be associated with any witness
298  if (!prevScript.IsWitnessProgram(witnessversion, witnessprogram))
299  return false;
300 
301  // Check P2WSH standard limits
302  if (witnessversion == 0 && witnessprogram.size() == WITNESS_V0_SCRIPTHASH_SIZE) {
303  if (tx.vin[i].scriptWitness.stack.back().size() > MAX_STANDARD_P2WSH_SCRIPT_SIZE)
304  return false;
305  size_t sizeWitnessStack = tx.vin[i].scriptWitness.stack.size() - 1;
306  if (sizeWitnessStack > MAX_STANDARD_P2WSH_STACK_ITEMS)
307  return false;
308  for (unsigned int j = 0; j < sizeWitnessStack; j++) {
309  if (tx.vin[i].scriptWitness.stack[j].size() > MAX_STANDARD_P2WSH_STACK_ITEM_SIZE)
310  return false;
311  }
312  }
313 
314  // Check policy limits for Taproot spends:
315  // - MAX_STANDARD_TAPSCRIPT_STACK_ITEM_SIZE limit for stack item size
316  // - No annexes
317  if (witnessversion == 1 && witnessprogram.size() == WITNESS_V1_TAPROOT_SIZE && !p2sh) {
318  // Taproot spend (non-P2SH-wrapped, version 1, witness program size 32; see BIP 341)
319  Span stack{tx.vin[i].scriptWitness.stack};
320  if (stack.size() >= 2 && !stack.back().empty() && stack.back()[0] == ANNEX_TAG) {
321  // Annexes are nonstandard as long as no semantics are defined for them.
322  return false;
323  }
324  if (stack.size() >= 2) {
325  // Script path spend (2 or more stack elements after removing optional annex)
326  const auto& control_block = SpanPopBack(stack);
327  SpanPopBack(stack); // Ignore script
328  if (control_block.empty()) return false; // Empty control block is invalid
329  if ((control_block[0] & TAPROOT_LEAF_MASK) == TAPROOT_LEAF_TAPSCRIPT) {
330  // Leaf version 0xc0 (aka Tapscript, see BIP 342)
331  for (const auto& item : stack) {
332  if (item.size() > MAX_STANDARD_TAPSCRIPT_STACK_ITEM_SIZE) return false;
333  }
334  }
335  } else if (stack.size() == 1) {
336  // Key path spend (1 stack element after removing optional annex)
337  // (no policy rules apply)
338  } else {
339  // 0 stack elements; this is already invalid by consensus rules
340  return false;
341  }
342  }
343  }
344  return true;
345 }
346 
347 int64_t GetVirtualTransactionSize(int64_t nWeight, int64_t nSigOpCost, unsigned int bytes_per_sigop)
348 {
349  return (std::max(nWeight, nSigOpCost * bytes_per_sigop) + WITNESS_SCALE_FACTOR - 1) / WITNESS_SCALE_FACTOR;
350 }
351 
352 int64_t GetVirtualTransactionSize(const CTransaction& tx, int64_t nSigOpCost, unsigned int bytes_per_sigop)
353 {
354  return GetVirtualTransactionSize(GetTransactionWeight(tx), nSigOpCost, bytes_per_sigop);
355 }
356 
357 int64_t GetVirtualTransactionInputSize(const CTxIn& txin, int64_t nSigOpCost, unsigned int bytes_per_sigop)
358 {
359  return GetVirtualTransactionSize(GetTransactionInputWeight(txin), nSigOpCost, bytes_per_sigop);
360 }
unsigned int GetSigOpCount(bool fAccurate) const
Pre-version-0.6, Bitcoin always counted CHECKMULTISIGs as 20 sigops.
Definition: script.cpp:159
CAmount nValue
Definition: transaction.h:152
bool IsStandardTx(const CTransaction &tx, const std::optional< unsigned > &max_datacarrier_bytes, bool permit_bare_multisig, const CFeeRate &dust_relay_fee, std::string &reason)
Check for standard transaction types.
Definition: policy.cpp:103
static const int WITNESS_SCALE_FACTOR
Definition: consensus.h:21
CScript scriptPubKey
Definition: transaction.h:153
const Coin & AccessCoin(const COutPoint &output) const
Return a reference to Coin in the cache, or coinEmpty if not found.
Definition: coins.cpp:154
static constexpr size_t WITNESS_V1_TAPROOT_SIZE
Definition: interpreter.h:229
bool IsPayToScriptHash() const
Definition: script.cpp:224
static constexpr unsigned int MAX_STANDARD_TAPSCRIPT_STACK_ITEM_SIZE
The maximum size in bytes of each witness stack item in a standard BIP 342 script (Taproot...
Definition: policy.h:54
TxoutType Solver(const CScript &scriptPubKey, std::vector< std::vector< unsigned char >> &vSolutionsRet)
Parse a scriptPubKey and identify script type for standard scripts.
Definition: solver.cpp:141
size_t GetSerializeSize(const T &t)
Definition: serialize.h:1103
CTxOut out
unspent transaction output
Definition: coins.h:36
static constexpr uint8_t TAPROOT_LEAF_TAPSCRIPT
Definition: interpreter.h:232
Bare scripts and BIP16 P2SH-wrapped redeemscripts.
bool IsWitnessProgram(int &version, std::vector< unsigned char > &program) const
Definition: script.cpp:243
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:347
bool IsStandard(const CScript &scriptPubKey, const std::optional< unsigned > &max_datacarrier_bytes, TxoutType &whichType)
Definition: policy.cpp:79
static int32_t GetTransactionWeight(const CTransaction &tx)
Definition: validation.h:133
bool IsCoinBase() const
Definition: transaction.h:356
const std::vector< CTxIn > vin
Definition: transaction.h:306
bool IsWitnessStandard(const CTransaction &tx, const CCoinsViewCache &mapInputs)
Check if the transaction is over standard P2WSH resources limit: 3600bytes witnessScript size...
Definition: policy.cpp:258
static constexpr unsigned int MAX_DUST_OUTPUTS_PER_TX
Maximum number of ephemeral dust outputs allowed.
Definition: policy.h:92
bool IsUnspendable() const
Returns whether the script is guaranteed to fail at execution, regardless of the initial stack...
Definition: script.h:571
int64_t CAmount
Amount in satoshis (Can be negative)
Definition: amount.h:12
static decltype(CTransaction::version) constexpr TX_MAX_STANDARD_VERSION
Definition: policy.h:149
bool AreInputsStandard(const CTransaction &tx, const CCoinsViewCache &mapInputs)
Check transaction inputs to mitigate two potential denial-of-service attacks:
Definition: policy.cpp:220
int64_t GetVirtualTransactionInputSize(const CTxIn &txin, int64_t nSigOpCost, unsigned int bytes_per_sigop)
Definition: policy.cpp:357
An input of a transaction.
Definition: transaction.h:66
static int64_t GetTransactionInputWeight(const CTxIn &txin)
Definition: validation.h:141
bool IsPushOnly(const_iterator pc) const
Called by IsStandardTx and P2SH/BIP62 VerifyScript (which makes it consensus-critical).
Definition: script.cpp:259
static constexpr unsigned int MAX_STANDARD_SCRIPTSIG_SIZE
The maximum size of a standard ScriptSig.
Definition: policy.h:58
static constexpr unsigned int MAX_STANDARD_P2WSH_SCRIPT_SIZE
The maximum size in bytes of a standard witnessScript.
Definition: policy.h:56
static constexpr uint8_t TAPROOT_LEAF_MASK
Definition: interpreter.h:231
const std::vector< CTxOut > vout
Definition: transaction.h:307
static constexpr unsigned int MAX_P2SH_SIGOPS
Maximum number of signature check operations in an IsStandard() P2SH script.
Definition: policy.h:38
An output of a transaction.
Definition: transaction.h:149
static constexpr size_t WITNESS_V0_SCRIPTHASH_SIZE
Signature hash sizes.
Definition: interpreter.h:227
CAmount GetDustThreshold(const CTxOut &txout, const CFeeRate &dustRelayFeeIn)
Definition: policy.cpp:26
static constexpr unsigned int MAX_TX_LEGACY_SIGOPS
The maximum number of potentially executed legacy signature operations in a single standard tx...
Definition: policy.h:42
bool IsPayToAnchor() const
Definition: script.cpp:207
std::vector< uint32_t > GetDust(const CTransaction &tx, CFeeRate dust_relay_rate)
Get the vout index numbers of all dust outputs.
Definition: policy.cpp:70
CScript scriptSig
Definition: transaction.h:70
static constexpr int32_t MAX_STANDARD_TX_WEIGHT
The maximum weight for transactions we&#39;re willing to relay/mine.
Definition: policy.h:34
TxoutType
Definition: solver.h:22
static constexpr unsigned int ANNEX_TAG
Definition: script.h:58
static constexpr unsigned int MAX_STANDARD_P2WSH_STACK_ITEM_SIZE
The maximum size in bytes of each witness stack item in a standard P2WSH script.
Definition: policy.h:52
Serialized script, used inside transaction inputs and outputs.
Definition: script.h:414
static bool CheckSigopsBIP54(const CTransaction &tx, const CCoinsViewCache &inputs)
Check the total number of non-witness sigops across the whole transaction, as per BIP54...
Definition: policy.cpp:174
T & SpanPopBack(Span< T > &span)
Pop the last element off a span, and return a reference to that element.
Definition: span.h:248
static constexpr unsigned int MAX_STANDARD_P2WSH_STACK_ITEMS
The maximum number of witness stack items in a standard P2WSH script.
Definition: policy.h:50
Fee rate in satoshis per kilovirtualbyte: CAmount / kvB.
Definition: feerate.h:32
CAmount GetFee(uint32_t num_bytes) const
Return the fee in satoshis for the given vsize in vbytes.
Definition: feerate.cpp:23
bool IsDust(const CTxOut &txout, const CFeeRate &dustRelayFeeIn)
Definition: policy.cpp:65
size_type size() const
Definition: prevector.h:294
A Span is an object that can refer to a contiguous sequence of objects.
Definition: span.h:97
The basic transaction that is broadcasted on the network and contained in blocks. ...
Definition: transaction.h:295
CCoinsView that adds a memory cache for transactions to another CCoinsView.
Definition: coins.h:362
bool EvalScript(std::vector< std::vector< unsigned char > > &stack, const CScript &script, unsigned int flags, const BaseSignatureChecker &checker, SigVersion sigversion, ScriptExecutionData &execdata, ScriptError *serror)
Only for Witness versions not already defined above.
#define Assert(val)
Identity function.
Definition: check.h:85
const uint32_t version
Definition: transaction.h:308
unspendable OP_RETURN script that carries data