Bitcoin Core  22.99.0
P2P Digital Currency
policy.cpp
Go to the documentation of this file.
1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2020 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/kvB.
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/kvB.
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 {
78  if (tx.nVersion > TX_MAX_STANDARD_VERSION || tx.nVersion < 1) {
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 involving only keys is a 15-of-15 P2SH
96  // multisig with compressed keys (remember the 520 byte limit on
97  // redeemScript size). That works out to a (15*(33+1))+3=513 byte
98  // redeemScript, 513+1+15*(73+1)+3=1627 bytes of scriptSig, which
99  // we round off to 1650(MAX_STANDARD_SCRIPTSIG_SIZE) bytes for
100  // some minor future-proofing. That's also enough to spend a
101  // 20-of-20 CHECKMULTISIG scriptPubKey, though such a scriptPubKey
102  // is not considered standard.
104  reason = "scriptsig-size";
105  return false;
106  }
107  if (!txin.scriptSig.IsPushOnly()) {
108  reason = "scriptsig-not-pushonly";
109  return false;
110  }
111  }
112 
113  unsigned int nDataOut = 0;
114  TxoutType whichType;
115  for (const CTxOut& txout : tx.vout) {
116  if (!::IsStandard(txout.scriptPubKey, whichType)) {
117  reason = "scriptpubkey";
118  return false;
119  }
120 
121  if (whichType == TxoutType::NULL_DATA)
122  nDataOut++;
123  else if ((whichType == TxoutType::MULTISIG) && (!permit_bare_multisig)) {
124  reason = "bare-multisig";
125  return false;
126  } else if (IsDust(txout, dust_relay_fee)) {
127  reason = "dust";
128  return false;
129  }
130  }
131 
132  // only one OP_RETURN txout is permitted
133  if (nDataOut > 1) {
134  reason = "multi-op-return";
135  return false;
136  }
137 
138  return true;
139 }
140 
159 bool AreInputsStandard(const CTransaction& tx, const CCoinsViewCache& mapInputs, bool taproot_active)
160 {
161  if (tx.IsCoinBase())
162  return true; // Coinbases don't use vin normally
163 
164  for (unsigned int i = 0; i < tx.vin.size(); i++)
165  {
166  const CTxOut& prev = mapInputs.AccessCoin(tx.vin[i].prevout).out;
167 
168  std::vector<std::vector<unsigned char> > vSolutions;
169  TxoutType whichType = Solver(prev.scriptPubKey, vSolutions);
170  if (whichType == TxoutType::NONSTANDARD || whichType == TxoutType::WITNESS_UNKNOWN) {
171  // WITNESS_UNKNOWN failures are typically also caught with a policy
172  // flag in the script interpreter, but it can be helpful to catch
173  // this type of NONSTANDARD transaction earlier in transaction
174  // validation.
175  return false;
176  } else if (whichType == TxoutType::SCRIPTHASH) {
177  std::vector<std::vector<unsigned char> > stack;
178  // convert the scriptSig into a stack, so we can inspect the redeemScript
179  if (!EvalScript(stack, tx.vin[i].scriptSig, SCRIPT_VERIFY_NONE, BaseSignatureChecker(), SigVersion::BASE))
180  return false;
181  if (stack.empty())
182  return false;
183  CScript subscript(stack.back().begin(), stack.back().end());
184  if (subscript.GetSigOpCount(true) > MAX_P2SH_SIGOPS) {
185  return false;
186  }
187  } else if (whichType == TxoutType::WITNESS_V1_TAPROOT) {
188  // Don't allow Taproot spends unless Taproot is active.
189  if (!taproot_active) return false;
190  }
191  }
192 
193  return true;
194 }
195 
196 bool IsWitnessStandard(const CTransaction& tx, const CCoinsViewCache& mapInputs)
197 {
198  if (tx.IsCoinBase())
199  return true; // Coinbases are skipped
200 
201  for (unsigned int i = 0; i < tx.vin.size(); i++)
202  {
203  // We don't care if witness for this input is empty, since it must not be bloated.
204  // If the script is invalid without witness, it would be caught sooner or later during validation.
205  if (tx.vin[i].scriptWitness.IsNull())
206  continue;
207 
208  const CTxOut &prev = mapInputs.AccessCoin(tx.vin[i].prevout).out;
209 
210  // get the scriptPubKey corresponding to this input:
211  CScript prevScript = prev.scriptPubKey;
212 
213  bool p2sh = false;
214  if (prevScript.IsPayToScriptHash()) {
215  std::vector <std::vector<unsigned char> > stack;
216  // If the scriptPubKey is P2SH, we try to extract the redeemScript casually by converting the scriptSig
217  // into a stack. We do not check IsPushOnly nor compare the hash as these will be done later anyway.
218  // If the check fails at this stage, we know that this txid must be a bad one.
219  if (!EvalScript(stack, tx.vin[i].scriptSig, SCRIPT_VERIFY_NONE, BaseSignatureChecker(), SigVersion::BASE))
220  return false;
221  if (stack.empty())
222  return false;
223  prevScript = CScript(stack.back().begin(), stack.back().end());
224  p2sh = true;
225  }
226 
227  int witnessversion = 0;
228  std::vector<unsigned char> witnessprogram;
229 
230  // Non-witness program must not be associated with any witness
231  if (!prevScript.IsWitnessProgram(witnessversion, witnessprogram))
232  return false;
233 
234  // Check P2WSH standard limits
235  if (witnessversion == 0 && witnessprogram.size() == WITNESS_V0_SCRIPTHASH_SIZE) {
236  if (tx.vin[i].scriptWitness.stack.back().size() > MAX_STANDARD_P2WSH_SCRIPT_SIZE)
237  return false;
238  size_t sizeWitnessStack = tx.vin[i].scriptWitness.stack.size() - 1;
239  if (sizeWitnessStack > MAX_STANDARD_P2WSH_STACK_ITEMS)
240  return false;
241  for (unsigned int j = 0; j < sizeWitnessStack; j++) {
242  if (tx.vin[i].scriptWitness.stack[j].size() > MAX_STANDARD_P2WSH_STACK_ITEM_SIZE)
243  return false;
244  }
245  }
246 
247  // Check policy limits for Taproot spends:
248  // - MAX_STANDARD_TAPSCRIPT_STACK_ITEM_SIZE limit for stack item size
249  // - No annexes
250  if (witnessversion == 1 && witnessprogram.size() == WITNESS_V1_TAPROOT_SIZE && !p2sh) {
251  // Taproot spend (non-P2SH-wrapped, version 1, witness program size 32; see BIP 341)
252  auto stack = MakeSpan(tx.vin[i].scriptWitness.stack);
253  if (stack.size() >= 2 && !stack.back().empty() && stack.back()[0] == ANNEX_TAG) {
254  // Annexes are nonstandard as long as no semantics are defined for them.
255  return false;
256  }
257  if (stack.size() >= 2) {
258  // Script path spend (2 or more stack elements after removing optional annex)
259  const auto& control_block = SpanPopBack(stack);
260  SpanPopBack(stack); // Ignore script
261  if (control_block.empty()) return false; // Empty control block is invalid
262  if ((control_block[0] & TAPROOT_LEAF_MASK) == TAPROOT_LEAF_TAPSCRIPT) {
263  // Leaf version 0xc0 (aka Tapscript, see BIP 342)
264  for (const auto& item : stack) {
265  if (item.size() > MAX_STANDARD_TAPSCRIPT_STACK_ITEM_SIZE) return false;
266  }
267  }
268  } else if (stack.size() == 1) {
269  // Key path spend (1 stack element after removing optional annex)
270  // (no policy rules apply)
271  } else {
272  // 0 stack elements; this is already invalid by consensus rules
273  return false;
274  }
275  }
276  }
277  return true;
278 }
279 
280 int64_t GetVirtualTransactionSize(int64_t nWeight, int64_t nSigOpCost, unsigned int bytes_per_sigop)
281 {
282  return (std::max(nWeight, nSigOpCost * bytes_per_sigop) + WITNESS_SCALE_FACTOR - 1) / WITNESS_SCALE_FACTOR;
283 }
284 
285 int64_t GetVirtualTransactionSize(const CTransaction& tx, int64_t nSigOpCost, unsigned int bytes_per_sigop)
286 {
287  return GetVirtualTransactionSize(GetTransactionWeight(tx), nSigOpCost, bytes_per_sigop);
288 }
289 
290 int64_t GetVirtualTransactionInputSize(const CTxIn& txin, int64_t nSigOpCost, unsigned int bytes_per_sigop)
291 {
292  return GetVirtualTransactionSize(GetTransactionInputWeight(txin), nSigOpCost, bytes_per_sigop);
293 }
GetVirtualTransactionInputSize
int64_t GetVirtualTransactionInputSize(const CTxIn &txin, int64_t nSigOpCost, unsigned int bytes_per_sigop)
Definition: policy.cpp:290
GetSerializeSize
size_t GetSerializeSize(const T &t, int nVersion=0)
Definition: serialize.h:1080
CTxIn
An input of a transaction.
Definition: transaction.h:65
policy.h
CTransaction::vin
const std::vector< CTxIn > vin
Definition: transaction.h:270
MAX_STANDARD_P2WSH_SCRIPT_SIZE
static const unsigned int MAX_STANDARD_P2WSH_SCRIPT_SIZE
The maximum size in bytes of a standard witnessScript.
Definition: policy.h:46
WITNESS_V0_SCRIPTHASH_SIZE
static constexpr size_t WITNESS_V0_SCRIPTHASH_SIZE
Signature hash sizes.
Definition: interpreter.h:214
Solver
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:144
SigVersion::BASE
@ BASE
Bare scripts and BIP16 P2SH-wrapped redeemscripts.
IsStandard
bool IsStandard(const CScript &scriptPubKey, TxoutType &whichType)
Definition: policy.cpp:53
TxoutType
TxoutType
Definition: standard.h:59
TxoutType::NONSTANDARD
@ NONSTANDARD
TxoutType::WITNESS_UNKNOWN
@ WITNESS_UNKNOWN
Only for Witness versions not already defined above.
IsWitnessStandard
bool IsWitnessStandard(const CTransaction &tx, const CCoinsViewCache &mapInputs)
Check if the transaction is over standard P2WSH resources limit: 3600bytes witnessScript size,...
Definition: policy.cpp:196
ANNEX_TAG
static constexpr unsigned int ANNEX_TAG
Definition: script.h:50
SpanPopBack
T & SpanPopBack(Span< T > &span)
Pop the last element off a span, and return a reference to that element.
Definition: span.h:230
CScript::IsWitnessProgram
bool IsWitnessProgram(int &version, std::vector< unsigned char > &program) const
Definition: script.cpp:220
validation.h
IsStandardTx
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
BaseSignatureChecker
Definition: interpreter.h:231
CCoinsViewCache::AccessCoin
const Coin & AccessCoin(const COutPoint &output) const
Return a reference to Coin in the cache, or coinEmpty if not found.
Definition: coins.cpp:137
TX_MAX_STANDARD_VERSION
static constexpr decltype(CTransaction::nVersion) TX_MAX_STANDARD_VERSION
Definition: policy.h:98
CScript::IsPayToScriptHash
bool IsPayToScriptHash() const
Definition: script.cpp:201
AreInputsStandard
bool AreInputsStandard(const CTransaction &tx, const CCoinsViewCache &mapInputs, bool taproot_active)
Check transaction inputs to mitigate two potential denial-of-service attacks:
Definition: policy.cpp:159
CFeeRate
Fee rate in satoshis per kilobyte: CAmount / kB.
Definition: feerate.h:29
TxoutType::WITNESS_V1_TAPROOT
@ WITNESS_V1_TAPROOT
CTransaction
The basic transaction that is broadcasted on the network and contained in blocks.
Definition: transaction.h:259
Coin::out
CTxOut out
unspent transaction output
Definition: coins.h:34
CTxOut::nValue
CAmount nValue
Definition: transaction.h:131
CScript::IsPushOnly
bool IsPushOnly(const_iterator pc) const
Called by IsStandardTx and P2SH/BIP62 VerifyScript (which makes it consensus-critical).
Definition: script.cpp:236
CTransaction::IsCoinBase
bool IsCoinBase() const
Definition: transaction.h:315
MAX_STANDARD_TAPSCRIPT_STACK_ITEM_SIZE
static const 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:44
MAX_P2SH_SIGOPS
static const unsigned int MAX_P2SH_SIGOPS
Maximum number of signature check operations in an IsStandard() P2SH script.
Definition: policy.h:28
CTxOut
An output of a transaction.
Definition: transaction.h:128
MAX_STANDARD_SCRIPTSIG_SIZE
static const unsigned int MAX_STANDARD_SCRIPTSIG_SIZE
The maximum size of a standard ScriptSig.
Definition: policy.h:48
CTransaction::vout
const std::vector< CTxOut > vout
Definition: transaction.h:271
CTxOut::scriptPubKey
CScript scriptPubKey
Definition: transaction.h:132
MAX_STANDARD_P2WSH_STACK_ITEM_SIZE
static const 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:42
span.h
TAPROOT_LEAF_MASK
static constexpr uint8_t TAPROOT_LEAF_MASK
Definition: interpreter.h:218
CAmount
int64_t CAmount
Amount in satoshis (Can be negative)
Definition: amount.h:12
MAX_STANDARD_P2WSH_STACK_ITEMS
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
TxoutType::SCRIPTHASH
@ SCRIPTHASH
nMaxDatacarrierBytes
unsigned nMaxDatacarrierBytes
Maximum size of TxoutType::NULL_DATA scripts that this node considers standard.
Definition: standard.cpp:20
CScript
Serialized script, used inside transaction inputs and outputs.
Definition: script.h:404
coins.h
TxoutType::NULL_DATA
@ NULL_DATA
unspendable OP_RETURN script that carries data
SCRIPT_VERIFY_NONE
@ SCRIPT_VERIFY_NONE
Definition: interpreter.h:43
MAX_STANDARD_TX_WEIGHT
static const unsigned int MAX_STANDARD_TX_WEIGHT
The maximum weight for transactions we're willing to relay/mine.
Definition: policy.h:24
GetTransactionWeight
static int64_t GetTransactionWeight(const CTransaction &tx)
Definition: validation.h:146
CCoinsViewCache
CCoinsView that adds a memory cache for transactions to another CCoinsView.
Definition: coins.h:213
EvalScript
bool EvalScript(std::vector< std::vector< unsigned char > > &stack, const CScript &script, unsigned int flags, const BaseSignatureChecker &checker, SigVersion sigversion, ScriptExecutionData &execdata, ScriptError *serror)
Definition: interpreter.cpp:431
CScript::GetSigOpCount
unsigned int GetSigOpCount(bool fAccurate) const
Pre-version-0.6, Bitcoin always counted CHECKMULTISIGs as 20 sigops.
Definition: script.cpp:153
prevector::size
size_type size() const
Definition: prevector.h:282
CTxIn::scriptSig
CScript scriptSig
Definition: transaction.h:69
TxoutType::MULTISIG
@ MULTISIG
GetTransactionInputWeight
static int64_t GetTransactionInputWeight(const CTxIn &txin)
Definition: validation.h:154
TAPROOT_LEAF_TAPSCRIPT
static constexpr uint8_t TAPROOT_LEAF_TAPSCRIPT
Definition: interpreter.h:219
IsDust
bool IsDust(const CTxOut &txout, const CFeeRate &dustRelayFeeIn)
Definition: policy.cpp:48
WITNESS_V1_TAPROOT_SIZE
static constexpr size_t WITNESS_V1_TAPROOT_SIZE
Definition: interpreter.h:216
CTransaction::nVersion
const int32_t nVersion
Definition: transaction.h:272
CScript::IsUnspendable
bool IsUnspendable() const
Returns whether the script is guaranteed to fail at execution, regardless of the initial stack.
Definition: script.h:543
CFeeRate::GetFee
CAmount GetFee(uint32_t num_bytes) const
Return the fee in satoshis for the given size in bytes.
Definition: feerate.cpp:21
fAcceptDatacarrier
bool fAcceptDatacarrier
A data carrying output is an unspendable output containing data.
Definition: standard.cpp:19
MakeSpan
constexpr Span< A > MakeSpan(A(&a)[N])
MakeSpan for arrays:
Definition: span.h:222
GetDustThreshold
CAmount GetDustThreshold(const CTxOut &txout, const CFeeRate &dustRelayFeeIn)
Definition: policy.cpp:14
GetVirtualTransactionSize
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:280
WITNESS_SCALE_FACTOR
static const int WITNESS_SCALE_FACTOR
Definition: consensus.h:21