policy.cpp raw
1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2022 The Limenka 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/ct.h>
14 #include <consensus/validation.h>
15 #include <kernel/mempool_options.h>
16 #include <policy/feerate.h>
17 #include <policy/settings.h>
18 #include <primitives/transaction.h>
19 #include <script/interpreter.h>
20 #include <script/script.h>
21 #include <script/solver.h>
22 #include <serialize.h>
23 #include <span.h>
24
25 #include <algorithm>
26 #include <cstddef>
27 #include <limits>
28 #include <utility>
29 #include <vector>
30
31 unsigned int g_script_size_policy_limit{DEFAULT_SCRIPT_SIZE_POLICY_LIMIT};
32
33 CAmount GetDustThreshold(const CTxOut& txout, const CFeeRate& dustRelayFeeIn)
34 {
35 // "Dust" is defined in terms of dustRelayFee,
36 // which has units satoshis-per-kilobyte.
37 // If you'd pay more in fees than the value of the output
38 // to spend something, then we consider it dust.
39 // A typical spendable non-segwit txout is 34 bytes big, and will
40 // need a CTxIn of at least 148 bytes to spend:
41 // so dust is a spendable txout less than
42 // 182*dustRelayFee/1000 (in satoshis).
43 // 546 satoshis at the default rate of 3000 sat/kvB.
44 // A typical spendable segwit P2WPKH txout is 31 bytes big, and will
45 // need a CTxIn of at least 67 bytes to spend:
46 // so dust is a spendable txout less than
47 // 98*dustRelayFee/1000 (in satoshis).
48 // 294 satoshis at the default rate of 3000 sat/kvB.
49 if (txout.scriptPubKey.IsUnspendable())
50 return 0;
51
52 size_t nSize = GetSerializeSize(txout);
53 int witnessversion = 0;
54 std::vector<unsigned char> witnessprogram;
55
56 // Note this computation is for spending a Segwit v0 P2WPKH output (a 33 bytes
57 // public key + an ECDSA signature). For Segwit v1 Taproot outputs the minimum
58 // satisfaction is lower (a single BIP340 signature) but this computation was
59 // kept to not further reduce the dust level.
60 // See discussion in https://github.com/limenka/limenka/pull/22779 for details.
61 if (txout.scriptPubKey.IsWitnessProgram(witnessversion, witnessprogram)) {
62 // sum the sizes of the parts of a transaction input
63 // with 75% segwit discount applied to the script size.
64 nSize += (32 + 4 + 1 + (107 / WITNESS_SCALE_FACTOR) + 4);
65 } else {
66 nSize += (32 + 4 + 1 + 107 + 4); // the 148 mentioned above
67 }
68
69 return dustRelayFeeIn.GetFee(nSize);
70 }
71
72 bool IsDust(const CTxOut& txout, const CFeeRate& dustRelayFeeIn)
73 {
74 return (txout.nValue < GetDustThreshold(txout, dustRelayFeeIn));
75 }
76
77 std::vector<uint32_t> GetDust(const CTransaction& tx, CFeeRate dust_relay_rate)
78 {
79 std::vector<uint32_t> dust_outputs;
80 for (uint32_t i{0}; i < tx.vout.size(); ++i) {
81 if (IsDust(tx.vout[i], dust_relay_rate) &&
82 tx.vout[i].scriptPubKey.size() != 0) {
83 // Confidential outputs (witness v4/33) carry their value in a
84 // commitment; the transparent nValue is always zero and the
85 // dust notion does not apply.
86 int witver;
87 std::vector<uint8_t> witprog;
88 const bool is_ct = tx.vout[i].scriptPubKey.IsWitnessProgram(witver, witprog) &&
89 witver == 4 && witprog.size() == WITNESS_V4_BPCT_SIZE;
90 if (!is_ct) dust_outputs.push_back(i);
91 }
92 }
93 return dust_outputs;
94 }
95
96 /**
97 * Note this must assign whichType even if returning false, in case
98 * IsStandardTx ignores the "scriptpubkey" rejection.
99 */
100 bool IsStandard(const CScript& scriptPubKey, const std::optional<unsigned>& max_datacarrier_bytes, TxoutType& whichType)
101 {
102 std::vector<std::vector<unsigned char> > vSolutions;
103 whichType = Solver(scriptPubKey, vSolutions);
104
105 if (whichType == TxoutType::NONSTANDARD) {
106 return false;
107 } else if (whichType == TxoutType::MULTISIG) {
108 unsigned char m = vSolutions.front()[0];
109 unsigned char n = vSolutions.back()[0];
110 // Support up to x-of-3 multisig txns as standard
111 if (n < 1 || n > 3)
112 return false;
113 if (m < 1 || m > n)
114 return false;
115 } else if (whichType == TxoutType::NULL_DATA) {
116 if (!max_datacarrier_bytes || scriptPubKey.size() > *max_datacarrier_bytes) {
117 return false;
118 }
119 }
120
121 return true;
122 }
123
124 static inline bool MaybeReject_(std::string& out_reason, const std::string& reason, const std::string& reason_prefix, const ignore_rejects_type& ignore_rejects) {
125 if (ignore_rejects.count(reason_prefix + reason)) {
126 return false;
127 }
128
129 out_reason = reason_prefix + reason;
130 return true;
131 }
132
133 #define MaybeReject(reason) do { \
134 if (MaybeReject_(out_reason, reason, reason_prefix, ignore_rejects)) { \
135 return false; \
136 } \
137 } while(0)
138
139 bool IsStandardTx(const CTransaction& tx, const kernel::MemPoolOptions& opts, std::string& out_reason, const ignore_rejects_type& ignore_rejects)
140 {
141 const std::string reason_prefix;
142
143 if (tx.version > TX_MAX_STANDARD_VERSION || tx.version < 1) {
144 MaybeReject("version");
145 }
146
147 // Extremely large transactions with lots of inputs can cost the network
148 // almost as much to process as they cost the sender in fees, because
149 // computing signature hashes is O(ninputs*txsize). Limiting transactions
150 // to MAX_STANDARD_TX_WEIGHT mitigates CPU exhaustion attacks.
151 unsigned int sz = GetTransactionWeight(tx);
152 if (sz > MAX_STANDARD_TX_WEIGHT) {
153 MaybeReject("tx-size");
154 }
155
156 if (tx.nLockTime == 21 && opts.reject_parasites) {
157 MaybeReject("parasite-cat21");
158 }
159
160 for (const CTxIn& txin : tx.vin)
161 {
162 // Biggest 'standard' txin involving only keys is a 15-of-15 P2SH
163 // multisig with compressed keys (remember the MAX_SCRIPT_ELEMENT_SIZE byte limit on
164 // redeemScript size). That works out to a (15*(33+1))+3=513 byte
165 // redeemScript, 513+1+15*(73+1)+3=1627 bytes of scriptSig, which
166 // we round off to 1650(MAX_STANDARD_SCRIPTSIG_SIZE) bytes for
167 // some minor future-proofing. That's also enough to spend a
168 // 20-of-20 CHECKMULTISIG scriptPubKey, though such a scriptPubKey
169 // is not considered standard.
170 if (txin.scriptSig.size() > std::min(MAX_STANDARD_SCRIPTSIG_SIZE, g_script_size_policy_limit)) {
171 MaybeReject("scriptsig-size");
172 }
173 if (!txin.scriptSig.IsPushOnly()) {
174 MaybeReject("scriptsig-not-pushonly");
175 }
176 }
177
178 unsigned int nDataOut = 0;
179 unsigned int n_dust{0};
180 unsigned int n_monetary{0};
181 TxoutType whichType;
182 for (size_t i{tx.vout.size()}; i; ) {
183 const CTxOut& txout = tx.vout[--i];
184
185 if (txout.scriptPubKey.size() > g_script_size_policy_limit) {
186 MaybeReject("scriptpubkey-size");
187 }
188
189 // CT kernel outputs are OP_RETURN carriers above the standard
190 // datacarrier size; they are required for confidential transactions.
191 const bool is_ct_kernel = IsCTKernelScript(txout.scriptPubKey);
192 if (!is_ct_kernel && !::IsStandard(txout.scriptPubKey, opts.max_datacarrier_bytes, whichType)) {
193 MaybeReject("scriptpubkey");
194 }
195
196 if (whichType == TxoutType::WITNESS_UNKNOWN && !opts.acceptunknownwitness) {
197 MaybeReject("scriptpubkey-unknown-witnessversion");
198 }
199
200 if (whichType == TxoutType::ANCHOR && !opts.permitephemeral_anchor) {
201 MaybeReject("anchor");
202 }
203
204 if (whichType != TxoutType::WITNESS_V4_BPCT && IsDust(txout, opts.dust_relay_feerate)) {
205 if (whichType != TxoutType::ANCHOR && !opts.permitephemeral_send) {
206 MaybeReject("dust-nonanchor");
207 }
208 if (txout.nValue && !opts.permitephemeral_dust) {
209 MaybeReject("dust-nonzero");
210 }
211 ++n_dust;
212 } else if (whichType != TxoutType::NULL_DATA && whichType != TxoutType::WITNESS_V4_BPCT) {
213 ++n_monetary;
214 }
215
216 if (whichType == TxoutType::NULL_DATA) {
217 if (txout.scriptPubKey.size() > 2 && txout.scriptPubKey[1] == OP_13 && opts.reject_tokens) {
218 MaybeReject("tokens-runes");
219 }
220 nDataOut++;
221 continue;
222 }
223 else if ((whichType == TxoutType::PUBKEY) && (!opts.permit_bare_pubkey)) {
224 MaybeReject("bare-pubkey");
225 }
226 else if ((whichType == TxoutType::MULTISIG) && (!opts.permit_bare_multisig)) {
227 MaybeReject("bare-multisig");
228 }
229 else if (whichType == TxoutType::WITNESS_V0_SCRIPTHASH && opts.reject_tokens && txout.scriptPubKey.IsOLGA(tx.vout.size() - i)) {
230 MaybeReject("tokens-olga");
231 }
232 else if (whichType == TxoutType::WITNESS_V1_TAPROOT && opts.reject_taproot) {
233 MaybeReject("taproot-rejected");
234 }
235 }
236
237 // Only MAX_DUST_OUTPUTS_PER_TX dust is permitted(on otherwise valid ephemeral dust)
238 if (n_dust > MAX_DUST_OUTPUTS_PER_TX) {
239 MaybeReject("dust");
240 }
241
242 // only one OP_RETURN txout is permitted
243 if (nDataOut > opts.max_op_return_outputs) {
244 MaybeReject("multi-op-return");
245 }
246
247 if (!n_monetary) {
248 if (nDataOut && !opts.permitbaredatacarrier) {
249 MaybeReject("bare-datacarrier");
250 }
251 if ((!nDataOut) && !opts.permitbareanchor) {
252 MaybeReject("bare-anchor");
253 }
254 }
255
256 return true;
257 }
258
259 /**
260 * Check the total number of non-witness sigops across the whole transaction, as per BIP54.
261 */
262 static bool CheckSigopsBIP54(const CTransaction& tx, const CCoinsViewCache& inputs, const kernel::MemPoolOptions& opts)
263 {
264 Assert(!tx.IsCoinBase());
265
266 unsigned int sigops{0};
267 for (const auto& txin: tx.vin) {
268 const auto& prev_txo{inputs.AccessCoin(txin.prevout).out};
269
270 // Unlike the existing block wide sigop limit which counts sigops present in the block
271 // itself (including the scriptPubKey which is not executed until spending later), BIP54
272 // counts sigops in the block where they are potentially executed (only).
273 // This means sigops in the spent scriptPubKey count toward the limit.
274 // `fAccurate` means correctly accounting sigops for CHECKMULTISIGs(VERIFY) with 16 pubkeys
275 // or fewer. This method of accounting was introduced by BIP16, and BIP54 reuses it.
276 // The GetSigOpCount call on the previous scriptPubKey counts both bare and P2SH sigops.
277 sigops += txin.scriptSig.GetSigOpCount(/*fAccurate=*/true);
278 sigops += prev_txo.scriptPubKey.GetSigOpCount(txin.scriptSig);
279
280 if (sigops > opts.maxtxlegacysigops) {
281 return false;
282 }
283 }
284
285 return true;
286 }
287
288 /**
289 * Check transaction inputs to mitigate two
290 * potential denial-of-service attacks:
291 *
292 * 1. scriptSigs with extra data stuffed into them,
293 * not consumed by scriptPubKey (or P2SH script)
294 * 2. P2SH scripts with a crazy number of expensive
295 * CHECKSIG/CHECKMULTISIG operations
296 *
297 * Why bother? To avoid denial-of-service attacks; an attacker
298 * can submit a standard HASH... OP_EQUAL transaction,
299 * which will get accepted into blocks. The redemption
300 * script can be anything; an attacker could use a very
301 * expensive-to-check-upon-redemption script like:
302 * DUP CHECKSIG DROP ... repeated 100 times... OP_1
303 *
304 * Note that only the non-witness portion of the transaction is checked here.
305 *
306 * We also check the total number of non-witness sigops across the whole transaction, as per BIP54.
307 */
308 bool AreInputsStandard(const CTransaction& tx, const CCoinsViewCache& mapInputs, const kernel::MemPoolOptions& opts, const std::string& reason_prefix, std::string& out_reason, const ignore_rejects_type& ignore_rejects)
309 {
310 if (tx.IsCoinBase()) {
311 return true; // Coinbases don't use vin normally
312 }
313
314 if (!CheckSigopsBIP54(tx, mapInputs, opts)) {
315 MaybeReject("sigops-toomany-overall");
316 }
317
318 for (unsigned int i = 0; i < tx.vin.size(); i++) {
319 const CTxOut& prev = mapInputs.AccessCoin(tx.vin[i].prevout).out;
320
321 if (prev.scriptPubKey.size() > g_script_size_policy_limit) {
322 MaybeReject("script-size");
323 }
324
325 std::vector<std::vector<unsigned char> > vSolutions;
326 TxoutType whichType = Solver(prev.scriptPubKey, vSolutions);
327 if (whichType == TxoutType::NONSTANDARD) {
328 MaybeReject("script-unknown");
329 } else if (whichType == TxoutType::WITNESS_UNKNOWN) {
330 // WITNESS_UNKNOWN failures are typically also caught with a policy
331 // flag in the script interpreter, but it can be helpful to catch
332 // this type of NONSTANDARD transaction earlier in transaction
333 // validation.
334 MaybeReject("witness-unknown");
335 } else if (whichType == TxoutType::SCRIPTHASH) {
336 if (!tx.vin[i].scriptSig.IsPushOnly()) {
337 // The only way we got this far, is if the user ignored scriptsig-not-pushonly.
338 // However, this case is invalid, and will be caught later on.
339 // But for now, we don't want to run the [possibly expensive] script here.
340 continue;
341 }
342 std::vector<std::vector<unsigned char> > stack;
343 // convert the scriptSig into a stack, so we can inspect the redeemScript
344 if (!EvalScript(stack, tx.vin[i].scriptSig, SCRIPT_VERIFY_NONE, BaseSignatureChecker(), SigVersion::BASE))
345 {
346 // This case is also invalid or a bug
347 out_reason = reason_prefix + "scriptsig-failure";
348 return false;
349 }
350 if (stack.empty())
351 {
352 // Also invalid
353 out_reason = reason_prefix + "scriptcheck-missing";
354 return false;
355 }
356 CScript subscript(stack.back().begin(), stack.back().end());
357 if (subscript.size() > g_script_size_policy_limit) {
358 MaybeReject("scriptcheck-size");
359 }
360 if (subscript.GetSigOpCount(true) > MAX_P2SH_SIGOPS) {
361 MaybeReject("scriptcheck-sigops");
362 }
363 }
364 }
365
366 return true;
367 }
368
369 bool IsWitnessStandard(const CTransaction& tx, const CCoinsViewCache& mapInputs, const std::string& reason_prefix, std::string& out_reason, const ignore_rejects_type& ignore_rejects, bool reject_p2sh_taproot)
370 {
371 if (tx.IsCoinBase())
372 return true; // Coinbases are skipped
373
374 for (unsigned int i = 0; i < tx.vin.size(); i++)
375 {
376 // We don't care if witness for this input is empty, since it must not be bloated.
377 // If the script is invalid without witness, it would be caught sooner or later during validation.
378 if (tx.vin[i].scriptWitness.IsNull())
379 continue;
380
381 const CTxOut &prev = mapInputs.AccessCoin(tx.vin[i].prevout).out;
382
383 // get the scriptPubKey corresponding to this input:
384 CScript prevScript = prev.scriptPubKey;
385
386 // witness stuffing detected
387 if (prevScript.IsPayToAnchor()) {
388 MaybeReject("anchor-not-empty");
389 }
390
391 bool p2sh = false;
392 if (prevScript.IsPayToScriptHash()) {
393 std::vector <std::vector<unsigned char> > stack;
394 // If the scriptPubKey is P2SH, we try to extract the redeemScript casually by converting the scriptSig
395 // into a stack. We do not check IsPushOnly nor compare the hash as these will be done later anyway.
396 // If the check fails at this stage, we know that this txid must be a bad one.
397 if (!EvalScript(stack, tx.vin[i].scriptSig, SCRIPT_VERIFY_NONE, BaseSignatureChecker(), SigVersion::BASE))
398 {
399 out_reason = reason_prefix + "scriptsig-failure";
400 return false;
401 }
402 if (stack.empty())
403 {
404 out_reason = reason_prefix + "scriptcheck-missing";
405 return false;
406 }
407 prevScript = CScript(stack.back().begin(), stack.back().end());
408 p2sh = true;
409 }
410
411 int witnessversion = 0;
412 std::vector<unsigned char> witnessprogram;
413
414 // Non-witness program must not be associated with any witness
415 if (!prevScript.IsWitnessProgram(witnessversion, witnessprogram))
416 {
417 out_reason = reason_prefix + "nonwitness-input";
418 return false;
419 }
420
421 // P2SH-wrapped taproot bypasses the fork's witness-v1 creation ban
422 // (the redeemScript is hidden inside the scriptSig at creation
423 // time), so reject the spend side as non-standard when the flag
424 // day is active.
425 if (p2sh && witnessversion == 1 && witnessprogram.size() == WITNESS_V1_TAPROOT_SIZE && reject_p2sh_taproot) {
426 out_reason = reason_prefix + "p2sh-taproot-rejected";
427 return false;
428 }
429
430 if (GetSerializeSize(tx.vin[i].scriptWitness.stack) > g_script_size_policy_limit) {
431 MaybeReject("witness-size");
432 }
433
434 // Check P2WSH standard limits
435 if (witnessversion == 0 && witnessprogram.size() == WITNESS_V0_SCRIPTHASH_SIZE) {
436 if (tx.vin[i].scriptWitness.stack.back().size() > MAX_STANDARD_P2WSH_SCRIPT_SIZE)
437 MaybeReject("script-size");
438 size_t sizeWitnessStack = tx.vin[i].scriptWitness.stack.size() - 1;
439 if (sizeWitnessStack > MAX_STANDARD_P2WSH_STACK_ITEMS)
440 MaybeReject("stackitem-count");
441 for (unsigned int j = 0; j < sizeWitnessStack; j++) {
442 if (tx.vin[i].scriptWitness.stack[j].size() > MAX_STANDARD_P2WSH_STACK_ITEM_SIZE)
443 MaybeReject("stackitem-size");
444 }
445 }
446
447 // Check policy limits for Taproot spends:
448 // - MAX_STANDARD_TAPSCRIPT_STACK_ITEM_SIZE limit for stack item size
449 // - No annexes
450 if (witnessversion == 1 && witnessprogram.size() == WITNESS_V1_TAPROOT_SIZE && !p2sh) {
451 // Taproot spend (non-P2SH-wrapped, version 1, witness program size 32; see BIP 341)
452 Span stack{tx.vin[i].scriptWitness.stack};
453 if (stack.size() >= 2 && !stack.back().empty() && stack.back()[0] == ANNEX_TAG) {
454 // Annexes are nonstandard as long as no semantics are defined for them.
455 MaybeReject("taproot-annex");
456 // If reject reason is ignored, continue as if the annex wasn't there.
457 SpanPopBack(stack);
458 }
459 if (stack.size() >= 2) {
460 // Script path spend (2 or more stack elements after removing optional annex)
461 const auto& control_block = SpanPopBack(stack);
462 SpanPopBack(stack); // Ignore script
463 if (control_block.empty()) {
464 // Empty control block is invalid
465 out_reason = reason_prefix + "taproot-control-missing";
466 return false;
467 }
468 if ((control_block[0] & TAPROOT_LEAF_MASK) == TAPROOT_LEAF_TAPSCRIPT) {
469 // Leaf version 0xc0 (aka Tapscript, see BIP 342)
470 if (!ignore_rejects.count(reason_prefix + "taproot-stackitem-size")) {
471 for (const auto& item : stack) {
472 if (item.size() > MAX_STANDARD_TAPSCRIPT_STACK_ITEM_SIZE) {
473 out_reason = reason_prefix + "taproot-stackitem-size";
474 return false;
475 }
476 }
477
478 }
479 } else if (stack.size() == 1) {
480 // Key path spend (1 stack element after removing optional annex)
481 // (no policy rules apply)
482 } else {
483 // 0 stack elements; this is already invalid by consensus rules
484 out_reason = reason_prefix + "taproot-witness-missing";
485 return false;
486 }
487 }
488 }
489
490 // Check P2SPKH standard limits
491 if (witnessversion == 3 && witnessprogram.size() == WITNESS_V3_SPKHASH_SIZE && !p2sh) {
492 if (tx.vin[i].scriptWitness.stack.size() != 2) {
493 MaybeReject("p2spkh-stack-size");
494 } else {
495 if (tx.vin[i].scriptWitness.stack[0].size() != 64 && tx.vin[i].scriptWitness.stack[0].size() != 65)
496 MaybeReject("p2spkh-sig-size");
497 if (tx.vin[i].scriptWitness.stack[1].size() != 32)
498 MaybeReject("p2spkh-pubkey-size");
499 }
500 }
501 }
502 return true;
503 }
504
505 bool SpendsNonAnchorWitnessProg(const CTransaction& tx, const CCoinsViewCache& prevouts)
506 {
507 if (tx.IsCoinBase()) {
508 return false;
509 }
510
511 int version;
512 std::vector<uint8_t> program;
513 for (const auto& txin: tx.vin) {
514 const auto& prev_spk{prevouts.AccessCoin(txin.prevout).out.scriptPubKey};
515
516 // Note this includes not-yet-defined witness programs.
517 if (prev_spk.IsWitnessProgram(version, program) && !prev_spk.IsPayToAnchor(version, program)) {
518 return true;
519 }
520
521 // For P2SH extract the redeem script and check if it spends a non-Taproot witness program. Note
522 // this is fine to call EvalScript (as done in AreInputsStandard/IsWitnessStandard) because this
523 // function is only ever called after IsStandardTx, which checks the scriptsig is pushonly.
524 if (prev_spk.IsPayToScriptHash()) {
525 // If EvalScript fails or results in an empty stack, the transaction is invalid by consensus.
526 std::vector <std::vector<uint8_t>> stack;
527 if (!EvalScript(stack, txin.scriptSig, SCRIPT_VERIFY_NONE, BaseSignatureChecker{}, SigVersion::BASE)
528 || stack.empty()) {
529 continue;
530 }
531 const CScript redeem_script{stack.back().begin(), stack.back().end()};
532 if (redeem_script.IsWitnessProgram(version, program)) {
533 return true;
534 }
535 }
536 }
537
538 return false;
539 }
540
541 int64_t GetVirtualTransactionSize(int64_t nWeight, int64_t nSigOpCost, unsigned int bytes_per_sigop)
542 {
543 return (std::max(nWeight, nSigOpCost * bytes_per_sigop) + WITNESS_SCALE_FACTOR - 1) / WITNESS_SCALE_FACTOR;
544 }
545
546 int64_t GetVirtualTransactionSize(const CTransaction& tx, int64_t nSigOpCost, unsigned int bytes_per_sigop)
547 {
548 return GetVirtualTransactionSize(GetTransactionWeight(tx), nSigOpCost, bytes_per_sigop);
549 }
550
551 int64_t GetVirtualTransactionInputSize(const CTxIn& txin, int64_t nSigOpCost, unsigned int bytes_per_sigop)
552 {
553 return GetVirtualTransactionSize(GetTransactionInputWeight(txin), nSigOpCost, bytes_per_sigop);
554 }
555
556 std::pair<CScript, unsigned int> GetScriptForTransactionInput(CScript prevScript, const CTxIn& txin)
557 {
558 bool p2sh = false;
559 if (prevScript.IsPayToScriptHash()) {
560 std::vector <std::vector<unsigned char> > stack;
561 if (!EvalScript(stack, txin.scriptSig, SCRIPT_VERIFY_NONE, BaseSignatureChecker(), SigVersion::BASE)) {
562 return std::make_pair(CScript(), 0);
563 }
564 if (stack.empty()) {
565 return std::make_pair(CScript(), 0);
566 }
567 prevScript = CScript(stack.back().begin(), stack.back().end());
568 p2sh = true;
569 }
570
571 int witnessversion = 0;
572 std::vector<unsigned char> witnessprogram;
573
574 if (!prevScript.IsWitnessProgram(witnessversion, witnessprogram)) {
575 // For P2SH, scriptSig is always push-only, so the actual script is only the last stack item
576 // For non-P2SH, prevScript is likely the real script, but not part of this transaction, and scriptSig could very well be executable, so return the latter instead
577 return std::make_pair(p2sh ? prevScript : txin.scriptSig, WITNESS_SCALE_FACTOR);
578 }
579
580 Span stack{txin.scriptWitness.stack};
581
582 if (witnessversion == 0 && witnessprogram.size() == WITNESS_V0_SCRIPTHASH_SIZE) {
583 if (stack.empty()) return std::make_pair(CScript(), 0); // invalid
584 auto& script_data = stack.back();
585 prevScript = CScript(script_data.begin(), script_data.end());
586 return std::make_pair(prevScript, 1);
587 }
588
589 if (witnessversion == 1 && witnessprogram.size() == WITNESS_V1_TAPROOT_SIZE && !p2sh) {
590 if (stack.size() >= 2 && !stack.back().empty() && stack.back()[0] == ANNEX_TAG) {
591 SpanPopBack(stack);
592 }
593 if (stack.size() >= 2) {
594 SpanPopBack(stack); // Ignore control block
595 prevScript = CScript(stack.back().begin(), stack.back().end());
596 return std::make_pair(prevScript, 1);
597 }
598 }
599
600 return std::make_pair(CScript(), 0);
601 }
602
603 std::pair<size_t, size_t> DatacarrierBytes(const CTransaction& tx, const CCoinsViewCache& view)
604 {
605 std::pair<size_t, size_t> ret{0, 0};
606
607 for (const CTxIn& txin : tx.vin) {
608 const CTxOut &utxo = view.AccessCoin(txin.prevout).out;
609 auto[script, consensus_weight_per_byte] = GetScriptForTransactionInput(utxo.scriptPubKey, txin);
610 const auto dcb = script.DatacarrierBytes(0, &txin.scriptWitness);
611 ret.first += dcb.first;
612 ret.second += dcb.second;
613 }
614 for (size_t i{tx.vout.size()}; i; ) {
615 const CTxOut& txout = tx.vout[--i];
616 const auto dcb = txout.scriptPubKey.DatacarrierBytes(tx.vout.size() - i);
617 ret.first += dcb.first;
618 ret.second += dcb.second;
619 }
620
621 return ret;
622 }
623
624 int32_t CalculateExtraTxWeight(const CTransaction& tx, const CCoinsViewCache& view, const unsigned int weight_per_data_byte)
625 {
626 int64_t mod_weight{0};
627
628 // Add in any extra weight for data bytes
629 if (weight_per_data_byte > 1) {
630 for (const CTxIn& txin : tx.vin) {
631 const CTxOut &utxo = view.AccessCoin(txin.prevout).out;
632 auto[script, consensus_weight_per_byte] = GetScriptForTransactionInput(utxo.scriptPubKey, txin);
633 if (weight_per_data_byte > consensus_weight_per_byte) {
634 const auto dcb = script.DatacarrierBytes(0, &txin.scriptWitness);
635 mod_weight += int64_t(dcb.first + dcb.second) * (weight_per_data_byte - consensus_weight_per_byte);
636 }
637 }
638 if (weight_per_data_byte > WITNESS_SCALE_FACTOR) {
639 for (size_t i{tx.vout.size()}; i; ) {
640 const CTxOut& txout = tx.vout[--i];
641 const auto dcb = txout.scriptPubKey.DatacarrierBytes(tx.vout.size() - i);
642 mod_weight += int64_t(dcb.first + dcb.second) * (weight_per_data_byte - WITNESS_SCALE_FACTOR);
643 }
644 }
645 }
646
647 return int32_t(std::min(mod_weight, int64_t{std::numeric_limits<int32_t>::max()}));
648 }
649