mirror of
https://github.com/bitcoin/bitcoin.git
synced 2026-02-05 21:21:17 +00:00
17cf9ff7efdbab07644fc2f9017fcac1b0757c38 Use cluster size limit for -maxmempool bound, and allow -maxmempool=0 in general (Suhas Daftuar) 315e43e5d86c06b1e51b907f1942cab150205d24 Sanity check `GetFeerateDiagram()` in CTxMemPool::check() (Suhas Daftuar) de2e9a24c40e1915827506250ed0bbda4009ce83 test: extend package rbf functional test to larger clusters (Suhas Daftuar) 4ef4ddb504e53cb148e8dd713695db37df0e1e4f doc: update policy/packages.md for new package acceptance logic (Suhas Daftuar) 79f73ad713a8d62a6172fbad228cbca848f9ff57 Add check that GetSortedScoreWithTopology() agrees with CompareMiningScoreWithTopology() (Suhas Daftuar) a86ac117681727b6e72ab50ed751d0d3b0cdff34 Update comments for CTxMemPool class (Suhas Daftuar) 9567eaa66da88a79c54f7a77922d817862122af2 Invoke TxGraph::DoWork() at appropriate times (Suhas Daftuar) 6c5c44f774058bf2a0dfaaadc78347dcb5815f52 test: add functional test for new cluster mempool RPCs (Suhas Daftuar) 72f60c877e001bb8cbcd3a7fb7addfdaba149693 doc: Update mempool_replacements.md to reflect feerate diagram checks (Suhas Daftuar) 21693f031a534193cc7f066a5c6e23db3937bf39 Expose cluster information via rpc (Suhas Daftuar) 72e74e0d42284c712529bf3c619b1b740c070f1b fuzz: try to add more code coverage for mempool fuzzing (Suhas Daftuar) f107417490ab5b81d3ec139de777a19db87845b6 bench: add more mempool benchmarks (Suhas Daftuar) 7976eb1ae77af2c88e1e61e85d4a61390b34b986 Avoid violating mempool policy limits in tests (Suhas Daftuar) 84de685cf7ee3baf3ca73087e5222411a0504df8 Stop tracking parents/children outside of txgraph (Suhas Daftuar) 88672e205ba1570fc92449b557fd32d836618781 Rewrite GatherClusters to use the txgraph implementation (Suhas Daftuar) 1ca4f01090cfa968c789fafde42054da3263a0e2 Fix miniminer_tests to work with cluster limits (Suhas Daftuar) 1902111e0f20fe6b5c12be019d24691d6b0b8d3e Eliminate CheckPackageLimits, which no longer does anything (Suhas Daftuar) 3a646ec4626441c8c2946598f94199a65d9646d6 Rework RBF and TRUC validation (Suhas Daftuar) 19b8479868e5c854d9268e3647b9488f9b23af0f Make getting parents/children a function of the mempool, not a mempool entry (Suhas Daftuar) 5560913e51af036b5e6907e08cd07488617b12f7 Rework truc_policy to use descendants, not children (Suhas Daftuar) a4458d6c406215dccb31fd35e0968a65a3269670 Use txgraph to calculate descendants (Suhas Daftuar) c8b6f70d6492a153b59697d6303fc0515f316f89 Use txgraph to calculate ancestors (Suhas Daftuar) 241a3e666b59abb695c9d0a13d7458a763c2c5a0 Simplify ancestor calculation functions (Suhas Daftuar) b9cec7f0a1e089cd77bb2fa1c2b54e93442e594c Make removeConflicts private (Suhas Daftuar) 0402e6c7808017bf5c04edb4b68128ede7d1c1e7 Remove unused limits from CalculateMemPoolAncestors (Suhas Daftuar) 08be765ac26a3ae721cb3574d4348602a9982e44 Remove mempool logic designed to maintain ancestor/descendant state (Suhas Daftuar) fc4e3e6bc12284d3b328c1ad19502294accfe5ad Remove unused members from CTxMemPoolEntry (Suhas Daftuar) ff3b398d124b9efa49b612dbbb715bbe5d53e727 mempool: eliminate accessors to mempool entry ancestor/descendant cached state (Suhas Daftuar) b9a2039f51226dce2c4e38ce5f26eefee171744b Eliminate use of cached ancestor data in miniminer_tests and truc_policy (Suhas Daftuar) ba09fc9774d5a0eaa58d93a2fa20bef1efc74f1e mempool: Remove unused function CalculateDescendantMaximum (Suhas Daftuar) 8e49477e86b3089ea70d1f2659b9fd3a8a1f7db4 wallet: Replace max descendant count with cluster_count (Suhas Daftuar) e031085fd464b528c186948d3cbf1c08a5a8d624 Eliminate Single-Conflict RBF Carve Out (Suhas Daftuar) cf3ab8e1d0a2f2bdf72e61e2c2dcb35987e5b9bd Stop enforcing descendant size/count limits (Suhas Daftuar) 89ae38f48965ec0d6c0600ce4269fdc797274161 test: remove rbf carveout test from mempool_limit.py (Suhas Daftuar) c0bd04d18fdf77a2f20f3c32f8eee4f1d71afd79 Calculate descendant information for mempool RPC output on-the-fly (Suhas Daftuar) bdcefb8a8b0667539744eae63e9eb5b7dc1c51da Use mempool/txgraph to determine if a tx has descendants (Suhas Daftuar) 69e1eaa6ed22f542ab48da755fa63f7694a15533 Add test case for cluster size limits to TRUC logic (Suhas Daftuar) 9cda64b86c593f0d6ff8f17e483e6566f436b200 Stop enforcing ancestor size/count limits (Suhas Daftuar) 1f93227a84a54397699ca40d889f98913e4d5868 Remove dependency on cached ancestor data in mini-miner (Suhas Daftuar) 9fbe0a4ac26c2fddaa3201cdfd8b69bf1f5ffa01 rpc: Calculate ancestor data from scratch for mempool rpc calls (Suhas Daftuar) 7961496dda2eb24a3f09d661005f06611558a20a Reimplement GetTransactionAncestry() to not rely on cached data (Suhas Daftuar) feceaa42e8eb43344ced33d94187e93268d45187 Remove CTxMemPool::GetSortedDepthAndScore (Suhas Daftuar) 21b5cea588a7bfe758a8d14efe90046b111db428 Use cluster linearization for transaction relay sort order (Suhas Daftuar) 6445aa7d97551ec5d501d91f6829071c67169122 Remove the ancestor and descendant indices from the mempool (Suhas Daftuar) 216e6937290338950215795291dbf0a533e234cf Implement new RBF logic for cluster mempool (Suhas Daftuar) ff8f115dec6eb41f739e6e6738dd60becfa168fd policy: Remove CPFP carveout rule (Suhas Daftuar) c3f1afc934e69a9849625924f72a5886a85eb833 test: rewrite PopulateMempool to not violate mempool policy (cluster size) limits (Suhas Daftuar) 47ab32fdb158069d4422e0f92078603c6df070a6 Select transactions for blocks based on chunk feerate (Suhas Daftuar) dec138d1ddc79cc3a06e53ed255f0931ce46e684 fuzz: remove comparison between mini_miner block construction and miner (Suhas Daftuar) 6c2bceb200aa7206d44b551d42ad3e70943f1425 bench: rewrite ComplexMemPool to not create oversized clusters (Suhas Daftuar) 1ad4590f63855e856d59616d41a87873315c3a2e Limit mempool size based on chunk feerate (Suhas Daftuar) b11c89cab210c87ebaf34fbd2a73d28353e8c7bd Rework miner_tests to not require large cluster limit (Suhas Daftuar) 95a8297d481e96d65ac81e4dac72b2ebecb9c765 Check cluster limits when using -walletrejectlongchains (Suhas Daftuar) 95762e6759597d201d685ed6bf6df6eedccf9a00 Do not allow mempool clusters to exceed configured limits (Suhas Daftuar) edb3e7cdf63688058ad2b90bea0d4933d9967be8 [test] rework/delete feature_rbf tests requiring large clusters (glozow) 435fd5671116b990cf3b875b99036606f921a71d test: update feature_rbf.py replacement test (Suhas Daftuar) 34e32985e811607e7566ae7a6caeacdf8bd8384f Add new (unused) limits for cluster size/count (Suhas Daftuar) 838d7e3553661cb6ba0be32dd872bafb444822d9 Add transactions to txgraph, but without cluster dependencies (Suhas Daftuar) d5ed9cb3eb52c33c5ac36421bb2da00290be6087 Add accessor for sigops-adjusted weight (Suhas Daftuar) 1bf3b513966e34b45ea359cbe7576383437f5d93 Add sigops adjusted weight calculator (Suhas Daftuar) c18c68a950d3a17e80ad0bc11ac7ee3de1a87f6c Create a txgraph inside CTxMemPool (Suhas Daftuar) 29a94d5b2f26a4a8b7464894e4db944ea67241b7 Make CTxMemPoolEntry derive from TxGraph::Ref (Suhas Daftuar) 92b0079fe3863b20b71282aa82341d4b6ee4b337 Allow moving CTxMemPoolEntry objects, disallow copying (Suhas Daftuar) 6c73e4744837a7dc138a9177df3a48f30a1ba6c1 mempool: Store iterators into mapTx in mapNextTx (Suhas Daftuar) 51430680ecb722e1d4ee4a26dac5724050f41c9e Allow moving an Epoch::Marker (Suhas Daftuar) Pull request description: [Reopening #28676 here as a new PR, because GitHub is slow to load the page making it hard to scroll through and see comments. Also, that PR was originally opened with a prototype implementation which has changed significantly with the introduction of `TxGraph`.] This is an implementation of the [cluster mempool proposal](https://delvingbitcoin.org/t/an-overview-of-the-cluster-mempool-proposal/393). This branch implements the following observable behavior changes: - Maintains a partitioning of the mempool into connected clusters (via the `txgraph` class), which are limited in vsize to 101 kvB by default, and limited in count to 64 by default. - Each cluster is sorted ("linearized") to try to optimize for selecting highest-feerate-subsets of a cluster first - Transaction selection for mining is updated to use the cluster linearizations, selecting highest feerate "chunks" first for inclusion in a block template. - Mempool eviction is updated to use the cluster linearizations, selecting lowest feerate "chunks" first for removal. - The RBF rules are updated to: (a) drop the requirement that no new inputs are introduced; (b) change the feerate requirement to instead check that the feerate diagram of the mempool will strictly improve; (c) replace the direct conflicts limit with a directly-conflicting-clusters limit. - The CPFP carveout rule is eliminated (it doesn't make sense in a cluster-limited mempool) - The ancestor and descendant limits are no longer enforced. - New cluster count/cluster vsize limits are now enforced instead. - Transaction relay now uses chunk feerate comparisons to determine the order that newly received transactions are announced to peers. Additionally, the cached ancestor and descendant data are dropped from the mempool, along with the multi_index indices that were maintained to sort the mempool by ancestor and descendant feerates. For compatibility (eg with wallet behavior or RPCs exposing this), this information is now calculated dynamically instead. ACKs for top commit: instagibbs: reACK 17cf9ff7efdbab07644fc2f9017fcac1b0757c38 glozow: reACK 17cf9ff7efdbab07644fc2f9017fcac1b0757c38 sipa: ACK 17cf9ff7efdbab07644fc2f9017fcac1b0757c38 Tree-SHA512: bbde46d913d56f8d9c0426cb0a6c4fa80b01b0a4c2299500769921f886082fb4f51f1694e0ee1bc318c52e1976d7ebed8134a64eda0b8044f3a708c04938eee7
395 lines
16 KiB
C++
395 lines
16 KiB
C++
// Copyright (c) 2009-2010 Satoshi Nakamoto
|
|
// Copyright (c) 2009-present The Bitcoin Core developers
|
|
// Distributed under the MIT software license, see the accompanying
|
|
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
|
|
|
|
// NOTE: This file is intended to be customised by the end user, and includes only local node policy logic
|
|
|
|
#include <policy/policy.h>
|
|
|
|
#include <coins.h>
|
|
#include <consensus/amount.h>
|
|
#include <consensus/consensus.h>
|
|
#include <consensus/validation.h>
|
|
#include <policy/feerate.h>
|
|
#include <primitives/transaction.h>
|
|
#include <script/interpreter.h>
|
|
#include <script/script.h>
|
|
#include <script/solver.h>
|
|
#include <serialize.h>
|
|
#include <span.h>
|
|
|
|
#include <algorithm>
|
|
#include <cstddef>
|
|
#include <vector>
|
|
|
|
CAmount GetDustThreshold(const CTxOut& txout, const CFeeRate& dustRelayFeeIn)
|
|
{
|
|
// "Dust" is defined in terms of dustRelayFee,
|
|
// which has units satoshis-per-kilobyte.
|
|
// If you'd pay more in fees than the value of the output
|
|
// to spend something, then we consider it dust.
|
|
// A typical spendable non-segwit txout is 34 bytes big, and will
|
|
// need a CTxIn of at least 148 bytes to spend:
|
|
// so dust is a spendable txout less than
|
|
// 182*dustRelayFee/1000 (in satoshis).
|
|
// 546 satoshis at the default rate of 3000 sat/kvB.
|
|
// A typical spendable segwit P2WPKH txout is 31 bytes big, and will
|
|
// need a CTxIn of at least 67 bytes to spend:
|
|
// so dust is a spendable txout less than
|
|
// 98*dustRelayFee/1000 (in satoshis).
|
|
// 294 satoshis at the default rate of 3000 sat/kvB.
|
|
if (txout.scriptPubKey.IsUnspendable())
|
|
return 0;
|
|
|
|
uint64_t nSize{GetSerializeSize(txout)};
|
|
int witnessversion = 0;
|
|
std::vector<unsigned char> witnessprogram;
|
|
|
|
// Note this computation is for spending a Segwit v0 P2WPKH output (a 33 bytes
|
|
// public key + an ECDSA signature). For Segwit v1 Taproot outputs the minimum
|
|
// satisfaction is lower (a single BIP340 signature) but this computation was
|
|
// kept to not further reduce the dust level.
|
|
// See discussion in https://github.com/bitcoin/bitcoin/pull/22779 for details.
|
|
if (txout.scriptPubKey.IsWitnessProgram(witnessversion, witnessprogram)) {
|
|
// sum the sizes of the parts of a transaction input
|
|
// with 75% segwit discount applied to the script size.
|
|
nSize += (32 + 4 + 1 + (107 / WITNESS_SCALE_FACTOR) + 4);
|
|
} else {
|
|
nSize += (32 + 4 + 1 + 107 + 4); // the 148 mentioned above
|
|
}
|
|
|
|
return dustRelayFeeIn.GetFee(nSize);
|
|
}
|
|
|
|
bool IsDust(const CTxOut& txout, const CFeeRate& dustRelayFeeIn)
|
|
{
|
|
return (txout.nValue < GetDustThreshold(txout, dustRelayFeeIn));
|
|
}
|
|
|
|
std::vector<uint32_t> GetDust(const CTransaction& tx, CFeeRate dust_relay_rate)
|
|
{
|
|
std::vector<uint32_t> dust_outputs;
|
|
for (uint32_t i{0}; i < tx.vout.size(); ++i) {
|
|
if (IsDust(tx.vout[i], dust_relay_rate)) dust_outputs.push_back(i);
|
|
}
|
|
return dust_outputs;
|
|
}
|
|
|
|
bool IsStandard(const CScript& scriptPubKey, TxoutType& whichType)
|
|
{
|
|
std::vector<std::vector<unsigned char> > vSolutions;
|
|
whichType = Solver(scriptPubKey, vSolutions);
|
|
|
|
if (whichType == TxoutType::NONSTANDARD) {
|
|
return false;
|
|
} else if (whichType == TxoutType::MULTISIG) {
|
|
unsigned char m = vSolutions.front()[0];
|
|
unsigned char n = vSolutions.back()[0];
|
|
// Support up to x-of-3 multisig txns as standard
|
|
if (n < 1 || n > 3)
|
|
return false;
|
|
if (m < 1 || m > n)
|
|
return false;
|
|
}
|
|
|
|
return true;
|
|
}
|
|
|
|
bool IsStandardTx(const CTransaction& tx, const std::optional<unsigned>& max_datacarrier_bytes, bool permit_bare_multisig, const CFeeRate& dust_relay_fee, std::string& reason)
|
|
{
|
|
if (tx.version > TX_MAX_STANDARD_VERSION || tx.version < TX_MIN_STANDARD_VERSION) {
|
|
reason = "version";
|
|
return false;
|
|
}
|
|
|
|
// Extremely large transactions with lots of inputs can cost the network
|
|
// almost as much to process as they cost the sender in fees, because
|
|
// computing signature hashes is O(ninputs*txsize). Limiting transactions
|
|
// to MAX_STANDARD_TX_WEIGHT mitigates CPU exhaustion attacks.
|
|
unsigned int sz = GetTransactionWeight(tx);
|
|
if (sz > MAX_STANDARD_TX_WEIGHT) {
|
|
reason = "tx-size";
|
|
return false;
|
|
}
|
|
|
|
for (const CTxIn& txin : tx.vin)
|
|
{
|
|
// Biggest 'standard' txin involving only keys is a 15-of-15 P2SH
|
|
// multisig with compressed keys (remember the MAX_SCRIPT_ELEMENT_SIZE byte limit on
|
|
// redeemScript size). That works out to a (15*(33+1))+3=513 byte
|
|
// redeemScript, 513+1+15*(73+1)+3=1627 bytes of scriptSig, which
|
|
// we round off to 1650(MAX_STANDARD_SCRIPTSIG_SIZE) bytes for
|
|
// some minor future-proofing. That's also enough to spend a
|
|
// 20-of-20 CHECKMULTISIG scriptPubKey, though such a scriptPubKey
|
|
// is not considered standard.
|
|
if (txin.scriptSig.size() > MAX_STANDARD_SCRIPTSIG_SIZE) {
|
|
reason = "scriptsig-size";
|
|
return false;
|
|
}
|
|
if (!txin.scriptSig.IsPushOnly()) {
|
|
reason = "scriptsig-not-pushonly";
|
|
return false;
|
|
}
|
|
}
|
|
|
|
unsigned int datacarrier_bytes_left = max_datacarrier_bytes.value_or(0);
|
|
TxoutType whichType;
|
|
for (const CTxOut& txout : tx.vout) {
|
|
if (!::IsStandard(txout.scriptPubKey, whichType)) {
|
|
reason = "scriptpubkey";
|
|
return false;
|
|
}
|
|
|
|
if (whichType == TxoutType::NULL_DATA) {
|
|
unsigned int size = txout.scriptPubKey.size();
|
|
if (size > datacarrier_bytes_left) {
|
|
reason = "datacarrier";
|
|
return false;
|
|
}
|
|
datacarrier_bytes_left -= size;
|
|
} else if ((whichType == TxoutType::MULTISIG) && (!permit_bare_multisig)) {
|
|
reason = "bare-multisig";
|
|
return false;
|
|
}
|
|
}
|
|
|
|
// Only MAX_DUST_OUTPUTS_PER_TX dust is permitted(on otherwise valid ephemeral dust)
|
|
if (GetDust(tx, dust_relay_fee).size() > MAX_DUST_OUTPUTS_PER_TX) {
|
|
reason = "dust";
|
|
return false;
|
|
}
|
|
|
|
return true;
|
|
}
|
|
|
|
/**
|
|
* Check the total number of non-witness sigops across the whole transaction, as per BIP54.
|
|
*/
|
|
static bool CheckSigopsBIP54(const CTransaction& tx, const CCoinsViewCache& inputs)
|
|
{
|
|
Assert(!tx.IsCoinBase());
|
|
|
|
unsigned int sigops{0};
|
|
for (const auto& txin: tx.vin) {
|
|
const auto& prev_txo{inputs.AccessCoin(txin.prevout).out};
|
|
|
|
// Unlike the existing block wide sigop limit which counts sigops present in the block
|
|
// itself (including the scriptPubKey which is not executed until spending later), BIP54
|
|
// counts sigops in the block where they are potentially executed (only).
|
|
// This means sigops in the spent scriptPubKey count toward the limit.
|
|
// `fAccurate` means correctly accounting sigops for CHECKMULTISIGs(VERIFY) with 16 pubkeys
|
|
// or fewer. This method of accounting was introduced by BIP16, and BIP54 reuses it.
|
|
// The GetSigOpCount call on the previous scriptPubKey counts both bare and P2SH sigops.
|
|
sigops += txin.scriptSig.GetSigOpCount(/*fAccurate=*/true);
|
|
sigops += prev_txo.scriptPubKey.GetSigOpCount(txin.scriptSig);
|
|
|
|
if (sigops > MAX_TX_LEGACY_SIGOPS) {
|
|
return false;
|
|
}
|
|
}
|
|
|
|
return true;
|
|
}
|
|
|
|
/**
|
|
* Check transaction inputs.
|
|
*
|
|
* This does three things:
|
|
* * Prevents mempool acceptance of spends of future
|
|
* segwit versions we don't know how to validate
|
|
* * Mitigates a potential denial-of-service attack with
|
|
* P2SH scripts with a crazy number of expensive
|
|
* CHECKSIG/CHECKMULTISIG operations.
|
|
* * Prevents spends of unknown/irregular scriptPubKeys,
|
|
* which mitigates potential denial-of-service attacks
|
|
* involving expensive scripts and helps reserve them
|
|
* as potential new upgrade hooks.
|
|
*
|
|
* Note that only the non-witness portion of the transaction is checked here.
|
|
*
|
|
* We also check the total number of non-witness sigops across the whole transaction, as per BIP54.
|
|
*/
|
|
bool AreInputsStandard(const CTransaction& tx, const CCoinsViewCache& mapInputs)
|
|
{
|
|
if (tx.IsCoinBase()) {
|
|
return true; // Coinbases don't use vin normally
|
|
}
|
|
|
|
if (!CheckSigopsBIP54(tx, mapInputs)) {
|
|
return false;
|
|
}
|
|
|
|
for (unsigned int i = 0; i < tx.vin.size(); i++) {
|
|
const CTxOut& prev = mapInputs.AccessCoin(tx.vin[i].prevout).out;
|
|
|
|
std::vector<std::vector<unsigned char> > vSolutions;
|
|
TxoutType whichType = Solver(prev.scriptPubKey, vSolutions);
|
|
if (whichType == TxoutType::NONSTANDARD || whichType == TxoutType::WITNESS_UNKNOWN) {
|
|
// WITNESS_UNKNOWN failures are typically also caught with a policy
|
|
// flag in the script interpreter, but it can be helpful to catch
|
|
// this type of NONSTANDARD transaction earlier in transaction
|
|
// validation.
|
|
return false;
|
|
} else if (whichType == TxoutType::SCRIPTHASH) {
|
|
std::vector<std::vector<unsigned char> > stack;
|
|
// convert the scriptSig into a stack, so we can inspect the redeemScript
|
|
if (!EvalScript(stack, tx.vin[i].scriptSig, SCRIPT_VERIFY_NONE, BaseSignatureChecker(), SigVersion::BASE))
|
|
return false;
|
|
if (stack.empty())
|
|
return false;
|
|
CScript subscript(stack.back().begin(), stack.back().end());
|
|
if (subscript.GetSigOpCount(true) > MAX_P2SH_SIGOPS) {
|
|
return false;
|
|
}
|
|
}
|
|
}
|
|
|
|
return true;
|
|
}
|
|
|
|
bool IsWitnessStandard(const CTransaction& tx, const CCoinsViewCache& mapInputs)
|
|
{
|
|
if (tx.IsCoinBase())
|
|
return true; // Coinbases are skipped
|
|
|
|
for (unsigned int i = 0; i < tx.vin.size(); i++)
|
|
{
|
|
// We don't care if witness for this input is empty, since it must not be bloated.
|
|
// If the script is invalid without witness, it would be caught sooner or later during validation.
|
|
if (tx.vin[i].scriptWitness.IsNull())
|
|
continue;
|
|
|
|
const CTxOut &prev = mapInputs.AccessCoin(tx.vin[i].prevout).out;
|
|
|
|
// get the scriptPubKey corresponding to this input:
|
|
CScript prevScript = prev.scriptPubKey;
|
|
|
|
// witness stuffing detected
|
|
if (prevScript.IsPayToAnchor()) {
|
|
return false;
|
|
}
|
|
|
|
bool p2sh = false;
|
|
if (prevScript.IsPayToScriptHash()) {
|
|
std::vector <std::vector<unsigned char> > stack;
|
|
// If the scriptPubKey is P2SH, we try to extract the redeemScript casually by converting the scriptSig
|
|
// into a stack. We do not check IsPushOnly nor compare the hash as these will be done later anyway.
|
|
// If the check fails at this stage, we know that this txid must be a bad one.
|
|
if (!EvalScript(stack, tx.vin[i].scriptSig, SCRIPT_VERIFY_NONE, BaseSignatureChecker(), SigVersion::BASE))
|
|
return false;
|
|
if (stack.empty())
|
|
return false;
|
|
prevScript = CScript(stack.back().begin(), stack.back().end());
|
|
p2sh = true;
|
|
}
|
|
|
|
int witnessversion = 0;
|
|
std::vector<unsigned char> witnessprogram;
|
|
|
|
// Non-witness program must not be associated with any witness
|
|
if (!prevScript.IsWitnessProgram(witnessversion, witnessprogram))
|
|
return false;
|
|
|
|
// Check P2WSH standard limits
|
|
if (witnessversion == 0 && witnessprogram.size() == WITNESS_V0_SCRIPTHASH_SIZE) {
|
|
if (tx.vin[i].scriptWitness.stack.back().size() > MAX_STANDARD_P2WSH_SCRIPT_SIZE)
|
|
return false;
|
|
size_t sizeWitnessStack = tx.vin[i].scriptWitness.stack.size() - 1;
|
|
if (sizeWitnessStack > MAX_STANDARD_P2WSH_STACK_ITEMS)
|
|
return false;
|
|
for (unsigned int j = 0; j < sizeWitnessStack; j++) {
|
|
if (tx.vin[i].scriptWitness.stack[j].size() > MAX_STANDARD_P2WSH_STACK_ITEM_SIZE)
|
|
return false;
|
|
}
|
|
}
|
|
|
|
// Check policy limits for Taproot spends:
|
|
// - MAX_STANDARD_TAPSCRIPT_STACK_ITEM_SIZE limit for stack item size
|
|
// - No annexes
|
|
if (witnessversion == 1 && witnessprogram.size() == WITNESS_V1_TAPROOT_SIZE && !p2sh) {
|
|
// Taproot spend (non-P2SH-wrapped, version 1, witness program size 32; see BIP 341)
|
|
std::span stack{tx.vin[i].scriptWitness.stack};
|
|
if (stack.size() >= 2 && !stack.back().empty() && stack.back()[0] == ANNEX_TAG) {
|
|
// Annexes are nonstandard as long as no semantics are defined for them.
|
|
return false;
|
|
}
|
|
if (stack.size() >= 2) {
|
|
// Script path spend (2 or more stack elements after removing optional annex)
|
|
const auto& control_block = SpanPopBack(stack);
|
|
SpanPopBack(stack); // Ignore script
|
|
if (control_block.empty()) return false; // Empty control block is invalid
|
|
if ((control_block[0] & TAPROOT_LEAF_MASK) == TAPROOT_LEAF_TAPSCRIPT) {
|
|
// Leaf version 0xc0 (aka Tapscript, see BIP 342)
|
|
for (const auto& item : stack) {
|
|
if (item.size() > MAX_STANDARD_TAPSCRIPT_STACK_ITEM_SIZE) return false;
|
|
}
|
|
}
|
|
} else if (stack.size() == 1) {
|
|
// Key path spend (1 stack element after removing optional annex)
|
|
// (no policy rules apply)
|
|
} else {
|
|
// 0 stack elements; this is already invalid by consensus rules
|
|
return false;
|
|
}
|
|
}
|
|
}
|
|
return true;
|
|
}
|
|
|
|
bool SpendsNonAnchorWitnessProg(const CTransaction& tx, const CCoinsViewCache& prevouts)
|
|
{
|
|
if (tx.IsCoinBase()) {
|
|
return false;
|
|
}
|
|
|
|
int version;
|
|
std::vector<uint8_t> program;
|
|
for (const auto& txin: tx.vin) {
|
|
const auto& prev_spk{prevouts.AccessCoin(txin.prevout).out.scriptPubKey};
|
|
|
|
// Note this includes not-yet-defined witness programs.
|
|
if (prev_spk.IsWitnessProgram(version, program) && !prev_spk.IsPayToAnchor(version, program)) {
|
|
return true;
|
|
}
|
|
|
|
// For P2SH extract the redeem script and check if it spends a non-Taproot witness program. Note
|
|
// this is fine to call EvalScript (as done in AreInputsStandard/IsWitnessStandard) because this
|
|
// function is only ever called after IsStandardTx, which checks the scriptsig is pushonly.
|
|
if (prev_spk.IsPayToScriptHash()) {
|
|
// If EvalScript fails or results in an empty stack, the transaction is invalid by consensus.
|
|
std::vector <std::vector<uint8_t>> stack;
|
|
if (!EvalScript(stack, txin.scriptSig, SCRIPT_VERIFY_NONE, BaseSignatureChecker{}, SigVersion::BASE)
|
|
|| stack.empty()) {
|
|
continue;
|
|
}
|
|
const CScript redeem_script{stack.back().begin(), stack.back().end()};
|
|
if (redeem_script.IsWitnessProgram(version, program)) {
|
|
return true;
|
|
}
|
|
}
|
|
}
|
|
|
|
return false;
|
|
}
|
|
|
|
int64_t GetSigOpsAdjustedWeight(int64_t weight, int64_t sigop_cost, unsigned int bytes_per_sigop)
|
|
{
|
|
return std::max(weight, sigop_cost * bytes_per_sigop);
|
|
}
|
|
|
|
int64_t GetVirtualTransactionSize(int64_t nWeight, int64_t nSigOpCost, unsigned int bytes_per_sigop)
|
|
{
|
|
return (GetSigOpsAdjustedWeight(nWeight, nSigOpCost, bytes_per_sigop) + WITNESS_SCALE_FACTOR - 1) / WITNESS_SCALE_FACTOR;
|
|
}
|
|
|
|
int64_t GetVirtualTransactionSize(const CTransaction& tx, int64_t nSigOpCost, unsigned int bytes_per_sigop)
|
|
{
|
|
return GetVirtualTransactionSize(GetTransactionWeight(tx), nSigOpCost, bytes_per_sigop);
|
|
}
|
|
|
|
int64_t GetVirtualTransactionInputSize(const CTxIn& txin, int64_t nSigOpCost, unsigned int bytes_per_sigop)
|
|
{
|
|
return GetVirtualTransactionSize(GetTransactionInputWeight(txin), nSigOpCost, bytes_per_sigop);
|
|
}
|