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
11#include <coins.h>
12#include <span.h>
13
14CAmount 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 P2WPKH 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 // Note this computation is for spending a Segwit v0 P2WPKH output (a 33 bytes
38 // public key + an ECDSA signature). For Segwit v1 Taproot outputs the minimum
39 // satisfaction is lower (a single BIP340 signature) but this computation was
40 // kept to not further reduce the dust level.
41 // See discussion in https://github.com/bitcoin/bitcoin/pull/22779 for details.
42 if (txout.scriptPubKey.IsWitnessProgram(witnessversion, witnessprogram)) {
43 // sum the sizes of the parts of a transaction input
44 // with 75% segwit discount applied to the script size.
45 nSize += (32 + 4 + 1 + (107 / WITNESS_SCALE_FACTOR) + 4);
46 } else {
47 nSize += (32 + 4 + 1 + 107 + 4); // the 148 mentioned above
48 }
49
50 return dustRelayFeeIn.GetFee(nSize);
51}
52
53bool IsDust(const CTxOut& txout, const CFeeRate& dustRelayFeeIn)
54{
55 return (txout.nValue < GetDustThreshold(txout, dustRelayFeeIn));
56}
57
58bool IsStandard(const CScript& scriptPubKey, TxoutType& whichType)
59{
60 std::vector<std::vector<unsigned char> > vSolutions;
61 whichType = Solver(scriptPubKey, vSolutions);
62
63 if (whichType == TxoutType::NONSTANDARD) {
64 return false;
65 } else if (whichType == TxoutType::MULTISIG) {
66 unsigned char m = vSolutions.front()[0];
67 unsigned char n = vSolutions.back()[0];
68 // Support up to x-of-3 multisig txns as standard
69 if (n < 1 || n > 3)
70 return false;
71 if (m < 1 || m > n)
72 return false;
73 } else if (whichType == TxoutType::NULL_DATA &&
74 (!fAcceptDatacarrier || scriptPubKey.size() > nMaxDatacarrierBytes)) {
75 return false;
76 }
77
78 return true;
79}
80
81bool IsStandardTx(const CTransaction& tx, bool permit_bare_multisig, const CFeeRate& dust_relay_fee, std::string& reason)
82{
83 if (tx.nVersion > TX_MAX_STANDARD_VERSION || tx.nVersion < 1) {
84 reason = "version";
85 return false;
86 }
87
88 // Extremely large transactions with lots of inputs can cost the network
89 // almost as much to process as they cost the sender in fees, because
90 // computing signature hashes is O(ninputs*txsize). Limiting transactions
91 // to MAX_STANDARD_TX_WEIGHT mitigates CPU exhaustion attacks.
92 unsigned int sz = GetTransactionWeight(tx);
93 if (sz > MAX_STANDARD_TX_WEIGHT) {
94 reason = "tx-size";
95 return false;
96 }
97
98 for (const CTxIn& txin : tx.vin)
99 {
100 // Biggest 'standard' txin involving only keys is a 15-of-15 P2SH
101 // multisig with compressed keys (remember the 520 byte limit on
102 // redeemScript size). That works out to a (15*(33+1))+3=513 byte
103 // redeemScript, 513+1+15*(73+1)+3=1627 bytes of scriptSig, which
104 // we round off to 1650(MAX_STANDARD_SCRIPTSIG_SIZE) bytes for
105 // some minor future-proofing. That's also enough to spend a
106 // 20-of-20 CHECKMULTISIG scriptPubKey, though such a scriptPubKey
107 // is not considered standard.
109 reason = "scriptsig-size";
110 return false;
111 }
112 if (!txin.scriptSig.IsPushOnly()) {
113 reason = "scriptsig-not-pushonly";
114 return false;
115 }
116 }
117
118 unsigned int nDataOut = 0;
119 TxoutType whichType;
120 for (const CTxOut& txout : tx.vout) {
121 if (!::IsStandard(txout.scriptPubKey, whichType)) {
122 reason = "scriptpubkey";
123 return false;
124 }
125
126 if (whichType == TxoutType::NULL_DATA)
127 nDataOut++;
128 else if ((whichType == TxoutType::MULTISIG) && (!permit_bare_multisig)) {
129 reason = "bare-multisig";
130 return false;
131 } else if (IsDust(txout, dust_relay_fee)) {
132 reason = "dust";
133 return false;
134 }
135 }
136
137 // only one OP_RETURN txout is permitted
138 if (nDataOut > 1) {
139 reason = "multi-op-return";
140 return false;
141 }
142
143 return true;
144}
145
164bool AreInputsStandard(const CTransaction& tx, const CCoinsViewCache& mapInputs, bool taproot_active)
165{
166 if (tx.IsCoinBase())
167 return true; // Coinbases don't use vin normally
168
169 for (unsigned int i = 0; i < tx.vin.size(); i++)
170 {
171 const CTxOut& prev = mapInputs.AccessCoin(tx.vin[i].prevout).out;
172
173 std::vector<std::vector<unsigned char> > vSolutions;
174 TxoutType whichType = Solver(prev.scriptPubKey, vSolutions);
175 if (whichType == TxoutType::NONSTANDARD || whichType == TxoutType::WITNESS_UNKNOWN) {
176 // WITNESS_UNKNOWN failures are typically also caught with a policy
177 // flag in the script interpreter, but it can be helpful to catch
178 // this type of NONSTANDARD transaction earlier in transaction
179 // validation.
180 return false;
181 } else if (whichType == TxoutType::SCRIPTHASH) {
182 std::vector<std::vector<unsigned char> > stack;
183 // convert the scriptSig into a stack, so we can inspect the redeemScript
185 return false;
186 if (stack.empty())
187 return false;
188 CScript subscript(stack.back().begin(), stack.back().end());
189 if (subscript.GetSigOpCount(true) > MAX_P2SH_SIGOPS) {
190 return false;
191 }
192 } else if (whichType == TxoutType::WITNESS_V1_TAPROOT) {
193 // Don't allow Taproot spends unless Taproot is active.
194 if (!taproot_active) return false;
195 }
196 }
197
198 return true;
199}
200
201bool IsWitnessStandard(const CTransaction& tx, const CCoinsViewCache& mapInputs)
202{
203 if (tx.IsCoinBase())
204 return true; // Coinbases are skipped
205
206 for (unsigned int i = 0; i < tx.vin.size(); i++)
207 {
208 // We don't care if witness for this input is empty, since it must not be bloated.
209 // If the script is invalid without witness, it would be caught sooner or later during validation.
210 if (tx.vin[i].scriptWitness.IsNull())
211 continue;
212
213 const CTxOut &prev = mapInputs.AccessCoin(tx.vin[i].prevout).out;
214
215 // get the scriptPubKey corresponding to this input:
216 CScript prevScript = prev.scriptPubKey;
217
218 bool p2sh = false;
219 if (prevScript.IsPayToScriptHash()) {
220 std::vector <std::vector<unsigned char> > stack;
221 // If the scriptPubKey is P2SH, we try to extract the redeemScript casually by converting the scriptSig
222 // into a stack. We do not check IsPushOnly nor compare the hash as these will be done later anyway.
223 // If the check fails at this stage, we know that this txid must be a bad one.
225 return false;
226 if (stack.empty())
227 return false;
228 prevScript = CScript(stack.back().begin(), stack.back().end());
229 p2sh = true;
230 }
231
232 int witnessversion = 0;
233 std::vector<unsigned char> witnessprogram;
234
235 // Non-witness program must not be associated with any witness
236 if (!prevScript.IsWitnessProgram(witnessversion, witnessprogram))
237 return false;
238
239 // Check P2WSH standard limits
240 if (witnessversion == 0 && witnessprogram.size() == WITNESS_V0_SCRIPTHASH_SIZE) {
241 if (tx.vin[i].scriptWitness.stack.back().size() > MAX_STANDARD_P2WSH_SCRIPT_SIZE)
242 return false;
243 size_t sizeWitnessStack = tx.vin[i].scriptWitness.stack.size() - 1;
244 if (sizeWitnessStack > MAX_STANDARD_P2WSH_STACK_ITEMS)
245 return false;
246 for (unsigned int j = 0; j < sizeWitnessStack; j++) {
247 if (tx.vin[i].scriptWitness.stack[j].size() > MAX_STANDARD_P2WSH_STACK_ITEM_SIZE)
248 return false;
249 }
250 }
251
252 // Check policy limits for Taproot spends:
253 // - MAX_STANDARD_TAPSCRIPT_STACK_ITEM_SIZE limit for stack item size
254 // - No annexes
255 if (witnessversion == 1 && witnessprogram.size() == WITNESS_V1_TAPROOT_SIZE && !p2sh) {
256 // Taproot spend (non-P2SH-wrapped, version 1, witness program size 32; see BIP 341)
257 auto stack = MakeSpan(tx.vin[i].scriptWitness.stack);
258 if (stack.size() >= 2 && !stack.back().empty() && stack.back()[0] == ANNEX_TAG) {
259 // Annexes are nonstandard as long as no semantics are defined for them.
260 return false;
261 }
262 if (stack.size() >= 2) {
263 // Script path spend (2 or more stack elements after removing optional annex)
264 const auto& control_block = SpanPopBack(stack);
265 SpanPopBack(stack); // Ignore script
266 if (control_block.empty()) return false; // Empty control block is invalid
267 if ((control_block[0] & TAPROOT_LEAF_MASK) == TAPROOT_LEAF_TAPSCRIPT) {
268 // Leaf version 0xc0 (aka Tapscript, see BIP 342)
269 for (const auto& item : stack) {
270 if (item.size() > MAX_STANDARD_TAPSCRIPT_STACK_ITEM_SIZE) return false;
271 }
272 }
273 } else if (stack.size() == 1) {
274 // Key path spend (1 stack element after removing optional annex)
275 // (no policy rules apply)
276 } else {
277 // 0 stack elements; this is already invalid by consensus rules
278 return false;
279 }
280 }
281 }
282 return true;
283}
284
285int64_t GetVirtualTransactionSize(int64_t nWeight, int64_t nSigOpCost, unsigned int bytes_per_sigop)
286{
287 return (std::max(nWeight, nSigOpCost * bytes_per_sigop) + WITNESS_SCALE_FACTOR - 1) / WITNESS_SCALE_FACTOR;
288}
289
290int64_t GetVirtualTransactionSize(const CTransaction& tx, int64_t nSigOpCost, unsigned int bytes_per_sigop)
291{
292 return GetVirtualTransactionSize(GetTransactionWeight(tx), nSigOpCost, bytes_per_sigop);
293}
294
295int64_t GetVirtualTransactionInputSize(const CTxIn& txin, int64_t nSigOpCost, unsigned int bytes_per_sigop)
296{
297 return GetVirtualTransactionSize(GetTransactionInputWeight(txin), nSigOpCost, bytes_per_sigop);
298}
int64_t CAmount
Amount in satoshis (Can be negative)
Definition: amount.h:12
CCoinsView that adds a memory cache for transactions to another CCoinsView.
Definition: coins.h:214
const Coin & AccessCoin(const COutPoint &output) const
Return a reference to Coin in the cache, or coinEmpty if not found.
Definition: coins.cpp:137
Fee rate in satoshis per kilobyte: CAmount / kB.
Definition: feerate.h:30
CAmount GetFee(uint32_t num_bytes) const
Return the fee in satoshis for the given size in bytes.
Definition: feerate.cpp:23
Serialized script, used inside transaction inputs and outputs.
Definition: script.h:406
bool IsPushOnly(const_iterator pc) const
Called by IsStandardTx and P2SH/BIP62 VerifyScript (which makes it consensus-critical).
Definition: script.cpp:236
bool IsPayToScriptHash() const
Definition: script.cpp:201
bool IsUnspendable() const
Returns whether the script is guaranteed to fail at execution, regardless of the initial stack.
Definition: script.h:544
unsigned int GetSigOpCount(bool fAccurate) const
Pre-version-0.6, Bitcoin always counted CHECKMULTISIGs as 20 sigops.
Definition: script.cpp:153
bool IsWitnessProgram(int &version, std::vector< unsigned char > &program) const
Definition: script.cpp:220
The basic transaction that is broadcasted on the network and contained in blocks.
Definition: transaction.h:260
const std::vector< CTxOut > vout
Definition: transaction.h:271
bool IsCoinBase() const
Definition: transaction.h:315
const int32_t nVersion
Definition: transaction.h:272
const std::vector< CTxIn > vin
Definition: transaction.h:270
An input of a transaction.
Definition: transaction.h:66
CScript scriptSig
Definition: transaction.h:69
An output of a transaction.
Definition: transaction.h:129
CScript scriptPubKey
Definition: transaction.h:132
CAmount nValue
Definition: transaction.h:131
CTxOut out
unspent transaction output
Definition: coins.h:34
size_type size() const
Definition: prevector.h:282
static int64_t GetTransactionInputWeight(const CTxIn &txin)
Definition: validation.h:154
static int64_t GetTransactionWeight(const CTransaction &tx)
Definition: validation.h:146
static const int WITNESS_SCALE_FACTOR
Definition: consensus.h:21
bool EvalScript(std::vector< std::vector< unsigned char > > &stack, const CScript &script, unsigned int flags, const BaseSignatureChecker &checker, SigVersion sigversion, ScriptExecutionData &execdata, ScriptError *serror)
@ BASE
Bare scripts and BIP16 P2SH-wrapped redeemscripts.
@ SCRIPT_VERIFY_NONE
Definition: interpreter.h:43
static constexpr uint8_t TAPROOT_LEAF_MASK
Definition: interpreter.h:225
static constexpr uint8_t TAPROOT_LEAF_TAPSCRIPT
Definition: interpreter.h:226
static constexpr size_t WITNESS_V0_SCRIPTHASH_SIZE
Signature hash sizes.
Definition: interpreter.h:221
static constexpr size_t WITNESS_V1_TAPROOT_SIZE
Definition: interpreter.h:223
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:164
CAmount GetDustThreshold(const CTxOut &txout, const CFeeRate &dustRelayFeeIn)
Definition: policy.cpp:14
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:285
int64_t GetVirtualTransactionInputSize(const CTxIn &txin, int64_t nSigOpCost, unsigned int bytes_per_sigop)
Definition: policy.cpp:295
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:81
bool IsWitnessStandard(const CTransaction &tx, const CCoinsViewCache &mapInputs)
Check if the transaction is over standard P2WSH resources limit: 3600bytes witnessScript size,...
Definition: policy.cpp:201
bool IsStandard(const CScript &scriptPubKey, TxoutType &whichType)
Definition: policy.cpp:58
bool IsDust(const CTxOut &txout, const CFeeRate &dustRelayFeeIn)
Definition: policy.cpp:53
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
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
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
static const unsigned int MAX_STANDARD_TX_WEIGHT
The maximum weight for transactions we're willing to relay/mine.
Definition: policy.h:24
static const unsigned int MAX_P2SH_SIGOPS
Maximum number of signature check operations in an IsStandard() P2SH script.
Definition: policy.h:28
static constexpr decltype(CTransaction::nVersion) TX_MAX_STANDARD_VERSION
Definition: policy.h:98
static const unsigned int MAX_STANDARD_SCRIPTSIG_SIZE
The maximum size of a standard ScriptSig.
Definition: policy.h:48
static const unsigned int MAX_STANDARD_P2WSH_SCRIPT_SIZE
The maximum size in bytes of a standard witnessScript.
Definition: policy.h:46
static constexpr unsigned int ANNEX_TAG
Definition: script.h:51
size_t GetSerializeSize(const T &t, int nVersion=0)
Definition: serialize.h:1080
T & SpanPopBack(Span< T > &span)
Pop the last element off a span, and return a reference to that element.
Definition: span.h:230
constexpr Span< A > MakeSpan(A(&a)[N])
MakeSpan for arrays:
Definition: span.h:222
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
bool fAcceptDatacarrier
A data carrying output is an unspendable output containing data.
Definition: standard.cpp:19
unsigned nMaxDatacarrierBytes
Maximum size of TxoutType::NULL_DATA scripts that this node considers standard.
Definition: standard.cpp:20
TxoutType
Definition: standard.h:59
@ WITNESS_V1_TAPROOT
@ WITNESS_UNKNOWN
Only for Witness versions not already defined above.
@ NULL_DATA
unspendable OP_RETURN script that carries data