Inside Bitcoin
Opening the selected file…
Opening the selected file…
The code behind the network, with room to understand it.
Release published 2026-10-28 · Snapshot fetched 2026-11-01. Latest stable release at fetch time; development branches and Git history are excluded. Only the selected code window and visible folders load here.
1// Copyright (c) 2009-2010 Satoshi Nakamoto2// Copyright (c) 2009-present The Bitcoin Core developers3// Distributed under the MIT software license, see the accompanying4// file COPYING or http://www.opensource.org/licenses/mit-license.php.6// NOTE: This file is intended to be customised by the end user, and includes only local node policy logic8#include <policy/policy.h>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#include <tinyformat.h>23#include <algorithm>24#include <cstddef>25#include <vector>27CAmount GetDustThreshold(const CTxOut& txout, const CFeeRate& dustRelayFeeIn)28{29// "Dust" is defined in terms of dustRelayFee,30// which has units satoshis-per-kilobyte.31// If you'd pay more in fees than the value of the output32// to spend something, then we consider it dust.33// A typical spendable non-segwit txout is 34 bytes big, and will34// need a CTxIn of at least 148 bytes to spend:35// so dust is a spendable txout less than36// 182*dustRelayFee/1000 (in satoshis).37// 546 satoshis at the default rate of 3000 sat/kvB.38// A typical spendable segwit P2WPKH txout is 31 bytes big, and will39// need a CTxIn of at least 67 bytes to spend:40// so dust is a spendable txout less than41// 98*dustRelayFee/1000 (in satoshis).42// 294 satoshis at the default rate of 3000 sat/kvB.43if (txout.scriptPubKey.IsUnspendable())44return 0;46uint64_t nSize{GetSerializeSize(txout)};47int witnessversion = 0;48std::vector<unsigned char> witnessprogram;50// Note this computation is for spending a Segwit v0 P2WPKH output (a 33 bytes51// public key + an ECDSA signature). For Segwit v1 Taproot outputs the minimum52// satisfaction is lower (a single BIP340 signature) but this computation was53// kept to not further reduce the dust level.54// See discussion in https://github.com/bitcoin/bitcoin/pull/22779 for details.55if (txout.scriptPubKey.IsWitnessProgram(witnessversion, witnessprogram)) {56// sum the sizes of the parts of a transaction input57// with 75% segwit discount applied to the script size.58nSize += (32 + 4 + 1 + (107 / WITNESS_SCALE_FACTOR) + 4);59} else {60nSize += (32 + 4 + 1 + 107 + 4); // the 148 mentioned above61}63return dustRelayFeeIn.GetFee(nSize);64}66bool IsDust(const CTxOut& txout, const CFeeRate& dustRelayFeeIn)67{68return (txout.nValue < GetDustThreshold(txout, dustRelayFeeIn));69}71std::vector<uint32_t> GetDust(const CTransaction& tx, CFeeRate dust_relay_rate)72{73std::vector<uint32_t> dust_outputs;74for (uint32_t i{0}; i < tx.vout.size(); ++i) {75if (IsDust(tx.vout[i], dust_relay_rate)) dust_outputs.push_back(i);76}77return dust_outputs;78}80bool IsStandard(const CScript& scriptPubKey, TxoutType& whichType)81{82std::vector<std::vector<unsigned char> > vSolutions;83whichType = Solver(scriptPubKey, vSolutions);85if (whichType == TxoutType::NONSTANDARD) {86return false;87} else if (whichType == TxoutType::MULTISIG) {88unsigned char m = vSolutions.front()[0];89unsigned char n = vSolutions.back()[0];90// Support up to x-of-3 multisig txns as standard91if (n < 1 || n > 3)92return false;93if (m < 1 || m > n)94return false;95}97return true;98}100bool IsStandardTx(const CTransaction& tx, const std::optional<unsigned>& max_datacarrier_bytes, bool permit_bare_multisig, const CFeeRate& dust_relay_fee, std::string& reason)101{102if (tx.version > TX_MAX_STANDARD_VERSION || tx.version < TX_MIN_STANDARD_VERSION) {103reason = "version";104return false;105}107// Extremely large transactions with lots of inputs can cost the network108// almost as much to process as they cost the sender in fees, because109// computing signature hashes is O(ninputs*txsize). Limiting transactions110// to MAX_STANDARD_TX_WEIGHT mitigates CPU exhaustion attacks.111unsigned int sz = GetTransactionWeight(tx);112if (sz > MAX_STANDARD_TX_WEIGHT) {113reason = "tx-size";114return false;115}117for (const CTxIn& txin : tx.vin)118{119// Biggest 'standard' txin involving only keys is a 15-of-15 P2SH120// multisig with compressed keys (remember the MAX_SCRIPT_ELEMENT_SIZE byte limit on121// redeemScript size). That works out to a (15*(33+1))+3=513 byte122// redeemScript, 513+1+15*(73+1)+3=1627 bytes of scriptSig, which123// we round off to 1650(MAX_STANDARD_SCRIPTSIG_SIZE) bytes for124// some minor future-proofing. That's also enough to spend a125// 20-of-20 CHECKMULTISIG scriptPubKey, though such a scriptPubKey126// is not considered standard.127if (txin.scriptSig.size() > MAX_STANDARD_SCRIPTSIG_SIZE) {128reason = "scriptsig-size";129return false;130}131if (!txin.scriptSig.IsPushOnly()) {132reason = "scriptsig-not-pushonly";133return false;134}135}137unsigned int datacarrier_bytes_left = max_datacarrier_bytes.value_or(0);138TxoutType whichType;139for (const CTxOut& txout : tx.vout) {140if (!::IsStandard(txout.scriptPubKey, whichType)) {141reason = "scriptpubkey";142return false;143}145if (whichType == TxoutType::NULL_DATA) {146unsigned int size = txout.scriptPubKey.size();147if (size > datacarrier_bytes_left) {148reason = "datacarrier";149return false;150}151datacarrier_bytes_left -= size;152} else if ((whichType == TxoutType::MULTISIG) && (!permit_bare_multisig)) {153reason = "bare-multisig";154return false;155}156}158// Only MAX_DUST_OUTPUTS_PER_TX dust is permitted(on otherwise valid ephemeral dust)159if (GetDust(tx, dust_relay_fee).size() > MAX_DUST_OUTPUTS_PER_TX) {160reason = "dust";161return false;162}164return true;165}167/**168* Check the total number of non-witness sigops across the whole transaction, as per BIP54.169*/170static bool CheckSigopsBIP54(const CTransaction& tx, const CCoinsViewCache& inputs)171{172Assert(!tx.IsCoinBase());174unsigned int sigops{0};175for (const auto& txin: tx.vin) {176const auto& prev_txo{inputs.AccessCoin(txin.prevout).out};178// Unlike the existing block wide sigop limit which counts sigops present in the block179// itself (including the scriptPubKey which is not executed until spending later), BIP54180// counts sigops in the block where they are potentially executed (only).181// This means sigops in the spent scriptPubKey count toward the limit.182// `fAccurate` means correctly accounting sigops for CHECKMULTISIGs(VERIFY) with 16 pubkeys183// or fewer. This method of accounting was introduced by BIP16, and BIP54 reuses it.184// The GetSigOpCount call on the previous scriptPubKey counts both bare and P2SH sigops.185sigops += txin.scriptSig.GetSigOpCount(/*fAccurate=*/true);186sigops += prev_txo.scriptPubKey.GetSigOpCount(txin.scriptSig);188if (sigops > MAX_TX_LEGACY_SIGOPS) {189return false;190}191}193return true;194}196/**197* Check transaction inputs.198*199* This does three things:200* * Prevents mempool acceptance of spends of future201* segwit versions we don't know how to validate202* * Mitigates a potential denial-of-service attack with203* P2SH scripts with a crazy number of expensive204* CHECKSIG/CHECKMULTISIG operations.205* * Prevents spends of unknown/irregular scriptPubKeys,206* which mitigates potential denial-of-service attacks207* involving expensive scripts and helps reserve them208* as potential new upgrade hooks.209*210* Note that only the non-witness portion of the transaction is checked here.211*212* We also check the total number of non-witness sigops across the whole transaction, as per BIP54.213*/214TxValidationState ValidateInputsStandardness(const CTransaction& tx, const CCoinsViewCache& mapInputs)215{216TxValidationState state;217if (tx.IsCoinBase()) {218return state; // Coinbases don't use vin normally219}221if (!CheckSigopsBIP54(tx, mapInputs)) {222state.Invalid(TxValidationResult::TX_INPUTS_NOT_STANDARD, "bad-txns-nonstandard-inputs", "non-witness sigops exceed bip54 limit");223return state;224}226for (unsigned int i = 0; i < tx.vin.size(); i++) {227const CTxOut& prev = mapInputs.AccessCoin(tx.vin[i].prevout).out;229std::vector<std::vector<unsigned char> > vSolutions;230TxoutType whichType = Solver(prev.scriptPubKey, vSolutions);231if (whichType == TxoutType::NONSTANDARD) {232state.Invalid(TxValidationResult::TX_INPUTS_NOT_STANDARD, "bad-txns-nonstandard-inputs", strprintf("input %u script unknown", i));233return state;234} else if (whichType == TxoutType::WITNESS_UNKNOWN) {235// WITNESS_UNKNOWN failures are typically also caught with a policy236// flag in the script interpreter, but it can be helpful to catch237// this type of NONSTANDARD transaction earlier in transaction238// validation.239state.Invalid(TxValidationResult::TX_INPUTS_NOT_STANDARD, "bad-txns-nonstandard-inputs", strprintf("input %u witness program is undefined", i));240return state;241} else if (whichType == TxoutType::SCRIPTHASH) {242std::vector<std::vector<unsigned char> > stack;243ScriptError serror;244// convert the scriptSig into a stack, so we can inspect the redeemScript245if (!EvalScript(stack, tx.vin[i].scriptSig, SCRIPT_VERIFY_NONE, BaseSignatureChecker(), SigVersion::BASE, &serror)) {246state.Invalid(TxValidationResult::TX_INPUTS_NOT_STANDARD, "bad-txns-nonstandard-inputs", strprintf("p2sh scriptsig malformed (input %u: %s)", i, ScriptErrorString(serror)));247return state;248}249if (stack.empty()) {250state.Invalid(TxValidationResult::TX_INPUTS_NOT_STANDARD, "bad-txns-nonstandard-inputs", strprintf("input %u P2SH redeemscript missing", i));