Merge bitcoin/bitcoin#36895: Keep witness stacks in serialized form in CScriptWitness
What changed, and why it matters
This change is a defensive memory-optimization refactor for how Bitcoin Core stores transaction witness data. It replaces a structure that used many small memory allocations with a single compact serialized buffer. The primary security benefit is reducing the worst-case memory an attacker could force a node to use by sending transactions with large witness stacks, which helps mitigate denial-of-service via memory exhaustion. The change also adds a new fuzz test to verify the new witness representation behaves identically to the old one.
Review the new CScriptWitness implementation for iterator/span lifetime safety, ensure the O(n) indexed access is not used in hot validation loops, and monitor follow-up PR #36918 for performance improvements. The change should be included in release notes as a memory-usage improvement and potential DoS hardening.
Security signals we found
Memory-usage reduction for attacker-controlled transaction witnesses
Mitigation of resource-exhaustion DoS via large witness stacks
Immutable witness representation prevents in-place modification bugs
New fuzz target added for witness serialization equivalence
Extensive test updates to preserve consensus and policy behavior
Acknowledged performance trade-offs in deserialization and indexed access
Evidence from the diff
PR #36895 changes CScriptWitness from a std::vector
Changed components
src/script/script.hsrc/script/script.cppsrc/primitives/transaction.hsrc/primitives/transaction.cppsrc/script/interpreter.cppsrc/policy/policy.cppsrc/kernel/bitcoinkernel.cppsrc/psbt.cppsrc/psbt.hsrc/test/fuzz/script_witness.cppInspect captured patch +784 / −248
### doc/release-notes-36895.md
@@ -0,0 +1,6 @@
+Mempool
+-------
+
+- Transactions retained in the mempool use less memory, especially when their
+ witnesses contain many elements. The mempool can therefore retain more
+ transactions within the same `-maxmempool` memory limit. (#36895)
### src/bench/bip352.cpp
@@ -52,12 +52,12 @@ static void GetPubKeyBench(benchmark::Bench& bench, InputType input_type)
const CScript redeem_script{GetScriptForDestination(WitnessV0KeyHash{pubkey})};
spk = GetScriptForDestination(ScriptHash{redeem_script});
txin.scriptSig = CScript() << ToByteVector(redeem_script);
- txin.scriptWitness.stack = {DUMMY_ECDSA_SIG, ToByteVector(pubkey)};
+ txin.scriptWitness = CScriptWitness{{DUMMY_ECDSA_SIG, ToByteVector(pubkey)}};
break;
}
case InputType::P2WPKH:
spk = GetScriptForDestination(WitnessV0KeyHash{pubkey});
- txin.scriptWitness.stack = {DUMMY_ECDSA_SIG, ToByteVector(pubkey)};
+ txin.scriptWitness = CScriptWitness{{DUMMY_ECDSA_SIG, ToByteVector(pubkey)}};
break;
case InputType::P2TR: {
// Script-path spend, as it runs all of the key-path extraction logic plus the control
@@ -67,7 +67,7 @@ static void GetPubKeyBench(benchmark::Bench& bench, InputType input_type)
std::vector<unsigned char> control_block{TAPROOT_LEAF_TAPSCRIPT};
const XOnlyPubKey internal_key{GenerateRandomKey().GetPubKey()};
control_block.insert(control_block.end(), internal_key.begin(), internal_key.end());
- txin.scriptWitness.stack = {DUMMY_SCHNORR_SIG, ToByteVector(DUMMY_LEAF_SCRIPT), control_block};
+ txin.scriptWitness = CScriptWitness{{DUMMY_SCHNORR_SIG, ToByteVector(DUMMY_LEAF_SCRIPT), control_block}};
expected_pubkey = XOnlyPubKey{pubkey};
break;
}
### src/bench/block_assemble.cpp
@@ -26,8 +26,7 @@ static void AssembleBlock(benchmark::Bench& bench)
{
const auto test_setup = MakeNoLogFileContext<const TestingSetup>();
- CScriptWitness witness;
- witness.stack.push_back(WITNESS_STACK_ELEM_OP_TRUE);
+ const CScriptWitness witness{{WITNESS_STACK_ELEM_OP_TRUE}};
BlockCreateOptions options{
.coinbase_output_script = P2WSH_OP_TRUE,
};
### src/bench/blockencodings.cpp
@@ -87,7 +87,7 @@ static void BlockEncodingBench(benchmark::Bench& bench, size_t n_pool, size_t n_
CMutableTransaction tx = CMutableTransaction();
tx.vin.resize(1);
tx.vin[0].scriptSig = CScript() << sigspam;
- tx.vin[0].scriptWitness.stack.push_back({1});
+ tx.vin[0].scriptWitness = CScriptWitness{{{1}}};
tx.vout = {CTxOut{CAmount(i), CScript() << OP_1 << OP_EQUAL}};
refs.push_back(MakeTransactionRef(tx));
}
### src/bench/mempool_eviction.cpp
@@ -42,15 +42,15 @@ static void MempoolEviction(benchmark::Bench& bench)
CMutableTransaction tx1 = CMutableTransaction();
tx1.vin.resize(1);
tx1.vin[0].scriptSig = CScript() << OP_1;
- tx1.vin[0].scriptWitness.stack.push_back({1});
+ tx1.vin[0].scriptWitness = CScriptWitness{{{1}}};
tx1.vout.resize(1);
tx1.vout[0].scriptPubKey = CScript() << OP_1 << OP_EQUAL;
tx1.vout[0].nValue = 10 * COIN;
CMutableTransaction tx2 = CMutableTransaction();
tx2.vin.resize(1);
tx2.vin[0].scriptSig = CScript() << OP_2;
- tx2.vin[0].scriptWitness.stack.push_back({2});
+ tx2.vin[0].scriptWitness = CScriptWitness{{{2}}};
tx2.vout.resize(1);
tx2.vout[0].scriptPubKey = CScript() << OP_2 << OP_EQUAL;
tx2.vout[0].nValue = 10 * COIN;
@@ -59,7 +59,7 @@ static void MempoolEviction(benchmark::Bench& bench)
tx3.vin.resize(1);
tx3.vin[0].prevout = COutPoint(tx2.GetHash(), 0);
tx3.vin[0].scriptSig = CScript() << OP_2;
- tx3.vin[0].scriptWitness.stack.push_back({3});
+ tx3.vin[0].scriptWitness = CScriptWitness{{{3}}};
tx3.vout.resize(1);
tx3.vout[0].scriptPubKey = CScript() << OP_3 << OP_EQUAL;
tx3.vout[0].nValue = 10 * COIN;
@@ -68,10 +68,10 @@ static void MempoolEviction(benchmark::Bench& bench)
tx4.vin.resize(2);
tx4.vin[0].prevout.SetNull();
tx4.vin[0].scriptSig = CScript() << OP_4;
- tx4.vin[0].scriptWitness.stack.push_back({4});
+ tx4.vin[0].scriptWitness = CScriptWitness{{{4}}};
tx4.vin[1].prevout.SetNull();
tx4.vin[1].scriptSig = CScript() << OP_4;
- tx4.vin[1].scriptWitness.stack.push_back({4});
+ tx4.vin[1].scriptWitness = CScriptWitness{{{4}}};
tx4.vout.resize(2);
tx4.vout[0].scriptPubKey = CScript() << OP_4 << OP_EQUAL;
tx4.vout[0].nValue = 10 * COIN;
@@ -82,10 +82,10 @@ static void MempoolEviction(benchmark::Bench& bench)
tx5.vin.resize(2);
tx5.vin[0].prevout = COutPoint(tx4.GetHash(), 0);
tx5.vin[0].scriptSig = CScript() << OP_4;
- tx5.vin[0].scriptWitness.stack.push_back({4});
+ tx5.vin[0].scriptWitness = CScriptWitness{{{4}}};
tx5.vin[1].prevout.SetNull();
tx5.vin[1].scriptSig = CScript() << OP_5;
- tx5.vin[1].scriptWitness.stack.push_back({5});
+ tx5.vin[1].scriptWitness = CScriptWitness{{{5}}};
tx5.vout.resize(2);
tx5.vout[0].scriptPubKey = CScript() << OP_5 << OP_EQUAL;
tx5.vout[0].nValue = 10 * COIN;
@@ -96,10 +96,10 @@ static void MempoolEviction(benchmark::Bench& bench)
tx6.vin.resize(2);
tx6.vin[0].prevout = COutPoint(tx4.GetHash(), 1);
tx6.vin[0].scriptSig = CScript() << OP_4;
- tx6.vin[0].scriptWitness.stack.push_back({4});
+ tx6.vin[0].scriptWitness = CScriptWitness{{{4}}};
tx6.vin[1].prevout.SetNull();
tx6.vin[1].scriptSig = CScript() << OP_6;
- tx6.vin[1].scriptWitness.stack.push_back({6});
+ tx6.vin[1].scriptWitness = CScriptWitness{{{6}}};
tx6.vout.resize(2);
tx6.vout[0].scriptPubKey = CScript() << OP_6 << OP_EQUAL;
tx6.vout[0].nValue = 10 * COIN;
@@ -110,10 +110,10 @@ static void MempoolEviction(benchmark::Bench& bench)
tx7.vin.resize(2);
tx7.vin[0].prevout = COutPoint(tx5.GetHash(), 0);
tx7.vin[0].scriptSig = CScript() << OP_5;
- tx7.vin[0].scriptWitness.stack.push_back({5});
+ tx7.vin[0].scriptWitness = CScriptWitness{{{5}}};
tx7.vin[1].prevout = COutPoint(tx6.GetHash(), 0);
tx7.vin[1].scriptSig = CScript() << OP_6;
- tx7.vin[1].scriptWitness.stack.push_back({6});
+ tx7.vin[1].scriptWitness = CScriptWitness{{{6}}};
tx7.vout.resize(2);
tx7.vout[0].scriptPubKey = CScript() << OP_7 << OP_EQUAL;
tx7.vout[0].nValue = 10 * COIN;
### src/bench/mempool_stress.cpp
@@ -51,7 +51,7 @@ static std::vector<CTransactionRef> CreateCoinCluster(FastRandomContext& det_ran
tx.vin.resize(1);
tx.vin[0].prevout = COutPoint(Txid::FromUint256(GetRandHash()), 1);
tx.vin[0].scriptSig = CScript() << CScriptNum(tx_counter);
- tx.vin[0].scriptWitness.stack.push_back(CScriptNum(x).getvch());
+ tx.vin[0].scriptWitness = CScriptWitness{{CScriptNum(x).getvch()}};
tx.vout.resize(det_rand.randrange(10)+2);
for (auto& out : tx.vout) {
out.scriptPubKey = CScript() << CScriptNum(tx_counter) << OP_EQUAL;
@@ -75,7 +75,7 @@ static std::vector<CTransactionRef> CreateCoinCluster(FastRandomContext& det_ran
tx.vin.emplace_back();
tx.vin.back().prevout = COutPoint(hash, coin.vin_left++);
tx.vin.back().scriptSig = CScript() << coin.tx_count;
- tx.vin.back().scriptWitness.stack.push_back(CScriptNum(coin.tx_count).getvch());
+ tx.vin.back().scriptWitness = CScriptWitness{{CScriptNum(coin.tx_count).getvch()}};
}
if (coin.vin_left == coin.ref->vin.size()) {
coin = available_coins.back();
### src/bench/rpc_mempool.cpp
@@ -35,7 +35,7 @@ static void RpcMempool(benchmark::Bench& bench)
CMutableTransaction tx = CMutableTransaction();
tx.vin.resize(1);
tx.vin[0].scriptSig = CScript() << OP_1;
- tx.vin[0].scriptWitness.stack.push_back({1});
+ tx.vin[0].scriptWitness = CScriptWitness{{{1}}};
tx.vout.resize(1);
tx.vout[0].scriptPubKey = CScript() << OP_1 << OP_EQUAL;
tx.vout[0].nValue = i;
### src/bench/verify_script.cpp
@@ -86,7 +86,7 @@ static void VerifyScriptBench(benchmark::Bench& bench, ScriptType script_type)
bool complete = SignTransaction(txSpend, &keystore, coins, {.sighash_type = SIGHASH_ALL}, input_errors);
assert(complete);
// Weak sanity check on witness data to ensure we produced the intended spending type
- assert(txSpend.vin[0].scriptWitness.stack.size() == ExpectedWitnessStackSize(script_type));
+ assert(txSpend.vin[0].scriptWitness.size() == ExpectedWitnessStackSize(script_type));
txdata.Init(txSpend, /*spent_outputs=*/{txCredit.vout[0]});
}
### src/bitcoin-tx.cpp
@@ -686,7 +686,7 @@ static void MutateTxSign(CMutableTransaction& tx, const std::string& flagStr)
if (!fHashSingle || (i < mergedTx.vout.size()))
ProduceSignature(keystore, MutableTransactionSignatureCreator(mergedTx, i, amount, {.sighash_type = nHashType}), prevPubKey, sigdata);
- if (amount == MAX_MONEY && !sigdata.scriptWitness.IsNull()) {
+ if (amount == MAX_MONEY && !sigdata.scriptWitness.empty()) {
throw std::runtime_error(strprintf("Missing amount for CTxOut with scriptPubKey=%s", HexStr(prevPubKey)));
}
### src/common/bip352.cpp
@@ -147,9 +147,10 @@ std::optional<PubKey> GetPubKeyFromInput(const CTxIn& txin, const CScript& spk)
const TxoutType type = Solver(spk, solutions);
if (type == TxoutType::WITNESS_V1_TAPROOT) {
- const auto& stack = txin.scriptWitness.stack;
+ const auto& stack = txin.scriptWitness;
if (stack.empty()) return std::nullopt;
- const bool has_annex = !stack.back().empty() && stack.back()[0] == ANNEX_TAG;
+ const auto last = stack.back();
+ const bool has_annex = !last.empty() && last[0] == ANNEX_TAG;
const size_t effective_size = stack.size() - (has_annex ? 1 : 0);
if (effective_size > 1) {
@@ -172,7 +173,7 @@ std::optional<PubKey> GetPubKeyFromInput(const CTxIn& txin, const CScript& spk)
}
if (type == TxoutType::WITNESS_V0_KEYHASH) {
- const auto& stack = txin.scriptWitness.stack;
+ const auto& stack = txin.scriptWitness;
if (stack.empty()) return std::nullopt;
CPubKey key{stack.back()};
if (!key.IsCompressed() || !key.IsFullyValid()) return std::nullopt;
@@ -217,8 +218,8 @@ std::optional<PubKey> GetPubKeyFromInput(const CTxIn& txin, const CScript& spk)
if (stack.empty()) return std::nullopt;
CScript redeem{stack.back().begin(), stack.back().end()};
if (Solver(redeem, solutions) != TxoutType::WITNESS_V0_KEYHASH) return std::nullopt;
- if (txin.scriptWitness.stack.empty()) return std::nullopt;
- CPubKey key{txin.scriptWitness.stack.back()};
+ if (txin.scriptWitness.empty()) return std::nullopt;
+ CPubKey key{txin.scriptWitness.back()};
if (!key.IsCompressed() || !key.IsFullyValid()) return std::nullopt;
return PubKey{key};
}
### src/consensus/validation.h
@@ -147,7 +147,7 @@ static inline int64_t GetBlockWeight(const CBlock& block)
static inline int64_t GetTransactionInputWeight(const CTxIn& txin)
{
// scriptWitness size is added here because witnesses and txins are split up in segwit serialization.
- return ::GetSerializeSize(TX_NO_WITNESS(txin)) * (WITNESS_SCALE_FACTOR - 1) + ::GetSerializeSize(TX_WITH_WITNESS(txin)) + ::GetSerializeSize(txin.scriptWitness.stack);
+ return ::GetSerializeSize(TX_NO_WITNESS(txin)) * (WITNESS_SCALE_FACTOR - 1) + ::GetSerializeSize(TX_WITH_WITNESS(txin)) + ::GetSerializeSize(txin.scriptWitness);
}
/** Compute at which vout of the block's coinbase transaction the witness commitment occurs, or -1 if not found */
### src/core_io.cpp
@@ -463,10 +463,10 @@ void TxToUniv(const CTransaction& tx, const uint256& block_hash, UniValue& entry
o.pushKV("hex", HexStr(txin.scriptSig));
in.pushKV("scriptSig", std::move(o));
}
- if (!tx.vin[i].scriptWitness.IsNull()) {
+ if (!tx.vin[i].scriptWitness.empty()) {
UniValue txinwitness(UniValue::VARR);
- txinwitness.reserve(tx.vin[i].scriptWitness.stack.size());
- for (const auto& item : tx.vin[i].scriptWitness.stack) {
+ txinwitness.reserve(tx.vin[i].scriptWitness.size());
+ for (const auto item : tx.vin[i].scriptWitness) {
txinwitness.push_back(HexStr(item));
}
in.pushKV("txinwitness", std::move(txinwitness));
### src/core_memusage.h
@@ -18,11 +18,8 @@ static inline size_t RecursiveDynamicUsage(const COutPoint& out) {
}
static inline size_t RecursiveDynamicUsage(const CTxIn& in) {
- size_t mem = RecursiveDynamicUsage(in.scriptSig) + RecursiveDynamicUsage(in.prevout) + memusage::DynamicUsage(in.scriptWitness.stack);
- for (std::vector<std::vector<unsigned char> >::const_iterator it = in.scriptWitness.stack.begin(); it != in.scriptWitness.stack.end(); it++) {
- mem += memusage::DynamicUsage(*it);
- }
- return mem;
+ // The witness accounts for the memory of all its elements.
+ return RecursiveDynamicUsage(in.scriptSig) + RecursiveDynamicUsage(in.prevout) + in.scriptWitness.DynamicMemoryUsage();
}
static inline size_t RecursiveDynamicUsage(const CTxOut& out) {
### src/kernel/bitcoinkernel.cpp
@@ -864,14 +864,16 @@ void btck_transaction_input_destroy(btck_TransactionInput* input)
size_t btck_witness_stack_count_items(const btck_WitnessStack* witness_stack)
{
- return btck_WitnessStack::get(witness_stack).stack.size();
+ return btck_WitnessStack::get(witness_stack).size();
}
int btck_witness_stack_get_item_at(const btck_WitnessStack* witness_stack, size_t index, btck_WriteBytes writer, void* user_data)
{
- const auto& stack{btck_WitnessStack::get(witness_stack).stack};
+ const auto& stack{btck_WitnessStack::get(witness_stack)};
assert(index < stack.size());
- return writer(stack[index].data(), stack[index].size(), user_data);
+ // Look up the element once.
+ const auto element = stack[index];
+ return writer(element.data(), element.size(), user_data);
}
btck_WitnessStack* btck_witness_stack_copy(const btck_WitnessStack* witness_stack)
### src/node/miner.cpp
@@ -209,7 +209,7 @@ util::NotNullUniquePtr<CBlockTemplate> BlockAssembler::CreateNewBlock()
const CTransactionRef& final_coinbase{pblock->vtx[0]};
if (final_coinbase->HasWitness()) {
- const auto& witness_stack{final_coinbase->vin[0].scriptWitness.stack};
+ const auto& witness_stack{final_coinbase->vin[0].scriptWitness};
// Consensus requires the coinbase witness stack to have exactly one
// element of 32 bytes.
Assert(witness_stack.size() == 1 && witness_stack[0].size() == 32);
### src/policy/policy.cpp
@@ -17,11 +17,11 @@
#include <script/script.h>
#include <script/solver.h>
#include <serialize.h>
-#include <span.h>
#include <tinyformat.h>
#include <algorithm>
#include <cstddef>
+#include <ranges>
#include <vector>
CAmount GetDustThreshold(const CTxOut& txout, const CFeeRate& dustRelayFeeIn)
@@ -271,7 +271,7 @@ bool IsWitnessStandard(const CTransaction& tx, const CCoinsViewCache& mapInputs)
{
// 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())
+ if (tx.vin[i].scriptWitness.empty())
continue;
const CTxOut &prev = mapInputs.AccessCoin(tx.vin[i].prevout).out;
@@ -307,13 +307,13 @@ bool IsWitnessStandard(const CTransaction& tx, const CCoinsViewCache& mapInputs)
// 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;
+ size_t sizeWitnessStack = tx.vin[i].scriptWitness.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)
+ if (tx.vin[i].scriptWitness.back().size() > MAX_STANDARD_P2WSH_SCRIPT_SIZE)
+ return false;
+ for (const auto item : tx.vin[i].scriptWitness | std::views::take(sizeWitnessStack)) {
+ if (item.size() > MAX_STANDARD_P2WSH_STACK_ITEM_SIZE)
return false;
}
}
@@ -323,19 +323,21 @@ bool IsWitnessStandard(const CTransaction& tx, const CCoinsViewCache& mapInputs)
// - 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) {
+ const auto& stack = tx.vin[i].scriptWitness;
+ // The last element (the stack is not empty), which is looked up only once.
+ const auto last = stack.back();
+ if (stack.size() >= 2 && !last.empty() && last[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
+ const auto control_block = last; // There is no annex, so this is the last element.
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) {
+ // Ignore the script and control block.
+ for (const auto item : stack | std::views::take(stack.size() - 2)) {
if (item.size() > MAX_STANDARD_TAPSCRIPT_STACK_ITEM_SIZE) return false;
}
}
### src/primitives/transaction.cpp
@@ -74,7 +74,7 @@ Txid CMutableTransaction::GetHash() const
bool CTransaction::ComputeHasWitness() const
{
return std::any_of(vin.begin(), vin.end(), [](const auto& input) {
- return !input.scriptWitness.IsNull();
+ return !input.scriptWitness.empty();
});
}
### src/primitives/transaction.h
@@ -224,7 +224,7 @@ void UnserializeTransaction(TxType& tx, Stream& s, const TransactionSerParams& p
/* The witness flag is present, and we support witnesses. */
flags ^= 1;
for (size_t i = 0; i < tx.vin.size(); i++) {
- s >> tx.vin[i].scriptWitness.stack;
+ s >> tx.vin[i].scriptWitness;
}
if (!tx.HasWitness()) {
/* It's illegal to encode witnesses when all witness stacks are empty. */
@@ -262,7 +262,7 @@ void SerializeTransaction(const TxType& tx, Stream& s, const TransactionSerParam
s << tx.vout;
if (flags & 1) {
for (size_t i = 0; i < tx.vin.size(); i++) {
- s << tx.vin[i].scriptWitness.stack;
+ s << tx.vin[i].scriptWitness;
}
}
s << tx.nLockTime;
@@ -358,7 +358,7 @@ class CTransaction
return self.prevout == other.prevout &&
self.nSequence == other.nSequence &&
(opts.include_script_sig ? self.scriptSig == other.scriptSig : true) &&
- (opts.include_witness_data ? self.scriptWitness.stack == other.scriptWitness.stack : true);
+ (opts.include_witness_data ? self.scriptWitness == other.scriptWitness : true);
});
}
@@ -406,7 +406,7 @@ struct CMutableTransaction
bool HasWitness() const
{
for (size_t i = 0; i < vin.size(); i++) {
- if (!vin[i].scriptWitness.IsNull()) {
+ if (!vin[i].scriptWitness.empty()) {
return true;
}
}
### src/psbt.cpp
@@ -179,7 +179,7 @@ bool PartiallySignedTransaction::AddInput(const PSBTInput& psbtin)
inputs.push_back(psbtin);
inputs.back().partial_sigs.clear();
inputs.back().final_script_sig.clear();
- inputs.back().final_script_witness.SetNull();
+ inputs.back().final_script_witness = {};
return true;
}
@@ -293,7 +293,7 @@ void PSBTInput::FillSignatureData(SignatureData& sigdata) const
sigdata.scriptSig = final_script_sig;
sigdata.complete = true;
}
- if (!final_script_witness.IsNull()) {
+ if (!final_script_witness.empty()) {
sigdata.scriptWitness = final_script_witness;
sigdata.complete = true;
}
@@ -362,7 +362,7 @@ void PSBTInput::FromSignatureData(const SignatureData& sigdata)
if (!sigdata.scriptSig.empty()) {
final_script_sig = sigdata.scriptSig;
}
- if (!sigdata.scriptWitness.IsNull()) {
+ if (!sigdata.scriptWitness.empty()) {
final_script_witness = sigdata.scriptWitness;
}
return;
@@ -449,7 +449,7 @@ void PSBTInput::Merge(const PSBTInput& input)
if (redeem_script.empty() && !input.redeem_script.empty()) redeem_script = input.redeem_script;
if (witness_script.empty() && !input.witness_script.empty()) witness_script = input.witness_script;
if (final_script_sig.empty() && !input.final_script_sig.empty()) final_script_sig = input.final_script_sig;
- if (final_script_witness.IsNull() && !input.final_script_witness.IsNull()) final_script_witness = input.final_script_witness;
+ if (final_script_witness.empty() && !input.final_script_witness.empty()) final_script_witness = input.final_script_witness;
if (m_tap_key_sig.empty() && !input.m_tap_key_sig.empty()) m_tap_key_sig = input.m_tap_key_sig;
if (m_tap_internal_key.IsNull() && !input.m_tap_internal_key.IsNull()) m_tap_internal_key = input.m_tap_internal_key;
if (m_tap_merkle_root.IsNull() && !input.m_tap_merkle_root.IsNull()) m_tap_merkle_root = input.m_tap_merkle_root;
@@ -469,7 +469,7 @@ void PSBTInput::Merge(const PSBTInput& input)
bool PSBTInput::HasSignatures() const
{
return !final_script_sig.empty()
- || !final_script_witness.IsNull()
+ || !final_script_witness.empty()
|| !partial_sigs.empty()
|| !m_tap_key_sig.empty()
|| !m_tap_script_sigs.empty()
@@ -546,7 +546,7 @@ void PSBTOutput::Merge(const PSBTOutput& output)
bool PSBTInputSigned(const PSBTInput& input)
{
- return !input.final_script_sig.empty() || !input.final_script_witness.IsNull();
+ return !input.final_script_sig.empty() || !input.final_script_witness.empty();
}
bool PSBTInputSignedAndVerified(const PartiallySignedTransaction& psbt, unsigned int input_index, const PrecomputedTransactionData* txdata)
### src/psbt.h
@@ -368,7 +368,7 @@ class PSBTInput
SerializeToVector(s, witness_utxo);
}
- if (final_script_sig.empty() && final_script_witness.IsNull()) {
+ if (final_script_sig.empty() && final_script_witness.empty()) {
// Write any partial signatures
for (const auto& sig_pair : partial_sigs) {
SerializeToVector(s, CompactSizeWriter(PSBT_IN_PARTIAL_SIG), std::span{sig_pair.second.first});
@@ -511,9 +511,9 @@ class PSBTInput
s << final_script_sig;
}
// write script witness
- if (!final_script_witness.IsNull()) {
+ if (!final_script_witness.empty()) {
SerializeToVector(s, CompactSizeWriter(PSBT_IN_SCRIPTWITNESS));
- SerializeToVector(s, final_script_witness.stack);
+ SerializeToVector(s, final_script_witness);
}
// Write PSBTv2 fields
@@ -659,7 +659,7 @@ class PSBTInput
case PSBT_IN_SCRIPTWITNESS:
{
ExpectedKeySize("Input Final scriptWitness", key, 1);
- UnserializeFromVector(s, final_script_witness.stack);
+ UnserializeFromVector(s, final_script_witness);
break;
}
case PSBT_IN_RIPEMD160:
@@ -1399,7 +1399,7 @@ class PartiallySignedTransaction
UnserializeFromVector(s, TX_NO_WITNESS(*tx));
// Make sure that all scriptSigs and scriptWitnesses are empty
for (const CTxIn& txin : tx->vin) {
- if (!txin.scriptSig.empty() || !txin.scriptWitness.IsNull()) {
+ if (!txin.scriptSig.empty() || !txin.scriptWitness.empty()) {
throw std::ios_base::failure("Unsigned tx does not have empty scriptSigs and scriptWitnesses.");
}
}
### src/rpc/blockchain.cpp
@@ -233,7 +233,7 @@ UniValue coinbaseTxToJSON(const CTransaction& coinbase_tx)
coinbase_tx_obj.pushKV("locktime", coinbase_tx.nLockTime);
coinbase_tx_obj.pushKV("sequence", vin_0.nSequence);
coinbase_tx_obj.pushKV("coinbase", HexStr(vin_0.scriptSig));
- const auto& witness_stack{vin_0.scriptWitness.stack};
+ const auto& witness_stack{vin_0.scriptWitness};
if (!witness_stack.empty()) {
CHECK_NONFATAL(witness_stack.size() == 1);
coinbase_tx_obj.pushKV("witness", HexStr(witness_stack[0]));
### src/rpc/rawtransaction.cpp
@@ -648,7 +648,7 @@ static RPCMethod combinerawtransaction()
// Remove all scriptSigs and scriptWitnesses from inputs
for (CTxIn& input : tx_variants_copy[k].vin) {
input.scriptSig.clear();
- input.scriptWitness.SetNull();
+ input.scriptWitness = {};
}
if (k == 0) {
first_txid = tx_variants_copy[k].GetHash();
@@ -1281,9 +1281,9 @@ static RPCMethod decodepsbt()
scriptsig.pushKV("hex", HexStr(input.final_script_sig));
in.pushKV("final_scriptSig", std::move(scriptsig));
}
- if (!input.final_script_witness.IsNull()) {
+ if (!input.final_script_witness.empty()) {
UniValue txinwitness(UniValue::VARR);
- for (const auto& item : input.final_script_witness.stack) {
+ for (const auto item : input.final_script_witness) {
txinwitness.push_back(HexStr(item));
}
in.pushKV("final_scriptwitness", std::move(txinwitness));
@@ -1805,11 +1805,11 @@ static RPCMethod converttopsbt()
// Remove all scriptSigs and scriptWitnesses from inputs
for (CTxIn& input : tx.vin) {
- if ((!input.scriptSig.empty() || !input.scriptWitness.IsNull()) && !permitsigdata) {
+ if ((!input.scriptSig.empty() || !input.scriptWitness.empty()) && !permitsigdata) {
throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "Inputs must not have scriptSigs and scriptWitnesses");
}
input.scriptSig.clear();
- input.scriptWitness.SetNull();
+ input.scriptWitness = {};
}
// Make a blank psbt
### src/rpc/rawtransaction_util.cpp
@@ -192,8 +192,8 @@ static void TxInErrorToJSON(const CTxIn& txin, UniValue& vErrorsRet, const std::
entry.pushKV("txid", txin.prevout.hash.ToString());
entry.pushKV("vout", txin.prevout.n);
UniValue witness(UniValue::VARR);
- for (unsigned int i = 0; i < txin.scriptWitness.stack.size(); i++) {
- witness.push_back(HexStr(txin.scriptWitness.stack[i]));
+ for (const auto element : txin.scriptWitness) {
+ witness.push_back(HexStr(element));
}
entry.pushKV("witness", std::move(witness));
entry.pushKV("scriptSig", HexStr(txin.scriptSig));
### src/script/interpreter.cpp
@@ -1420,7 +1420,7 @@ void PrecomputedTransactionData::Init(const T& txTo, std::vector<CTxOut>&& spent
bool uses_bip143_segwit = force;
bool uses_bip341_taproot = force;
for (size_t inpos = 0; inpos < txTo.vin.size() && !(uses_bip143_segwit && uses_bip341_taproot); ++inpos) {
- if (!txTo.vin[inpos].scriptWitness.IsNull()) {
+ if (!txTo.vin[inpos].scriptWitness.empty()) {
if (m_spent_outputs_ready && m_spent_outputs[inpos].scriptPubKey.size() == 2 + WITNESS_V1_TAPROOT_SIZE &&
m_spent_outputs[inpos].scriptPubKey[0] == OP_1) {
// Treat every witness-bearing spend with 34-byte scriptPubKey that starts with OP_1 as a Taproot
@@ -1835,10 +1835,10 @@ bool GenericTransactionSignatureChecker<T>::CheckSequence(const CScriptNum& nSeq
template class GenericTransactionSignatureChecker<CTransaction>;
template class GenericTransactionSignatureChecker<CMutableTransaction>;
-static bool ExecuteWitnessScript(const std::span<const valtype>& stack_span, const CScript& exec_script, script_verify_flags flags, SigVersion sigversion, const BaseSignatureChecker& checker, ScriptExecutionData& execdata, ScriptError* serror)
+/** Execute the script of a witness program spend (exec_script), with the remaining witness elements
+ * (stack) as its initial stack. */
+static bool ExecuteWitnessScript(std::vector<valtype> stack, const CScript& exec_script, script_verify_flags flags, SigVersion sigversion, const BaseSignatureChecker& checker, ScriptExecutionData& execdata, ScriptError* serror)
{
- std::vector<valtype> stack{stack_span.begin(), stack_span.end()};
-
if (sigversion == SigVersion::TAPSCRIPT) {
// OP_SUCCESSx processing overrides everything, including stack element size limits
CScript::const_iterator pc = exec_script.begin();
@@ -1923,7 +1923,16 @@ static bool VerifyTaprootCommitment(const std::vector<unsigned char>& control, c
static bool VerifyWitnessProgram(const CScriptWitness& witness, int witversion, const std::vector<unsigned char>& program, script_verify_flags flags, const BaseSignatureChecker& checker, ScriptError* serror, bool is_p2sh)
{
CScript exec_script; //!< Actually executed script (last stack item in P2WSH; implied P2PKH script in P2WPKH; leaf script in P2TR)
- std::span stack{witness.stack};
+ // The witness stack. Elements with other roles (the witness script, the annex, the control block,
+ // and the leaf script) are popped from it, and the remaining elements are moved into the initial
+ // execution stack.
+ auto stack = witness.ToVectors();
+ // Remove the top element from the stack, and return it.
+ const auto pop{[&] {
+ auto ret{std::move(stack.back())};
+ stack.pop_back();
+ return ret;
+ }};
ScriptExecutionData execdata;
if (witversion == 0) {
@@ -1932,21 +1941,21 @@ static bool VerifyWitnessProgram(const CScriptWitness& witness, int witversion,
if (stack.size() == 0) {
return set_error(serror, SCRIPT_ERR_WITNESS_PROGRAM_WITNESS_EMPTY);
}
- const valtype& script_bytes = SpanPopBack(stack);
+ const valtype script_bytes = pop();
exec_script = CScript(script_bytes.begin(), script_bytes.end());
uint256 hash_exec_script;
CSHA256().Write(exec_script.data(), exec_script.size()).Finalize(hash_exec_script.begin());
if (memcmp(hash_exec_script.begin(), program.data(), 32)) {
return set_error(serror, SCRIPT_ERR_WITNESS_PROGRAM_MISMATCH);
}
- return ExecuteWitnessScript(stack, exec_script, flags, SigVersion::WITNESS_V0, checker, execdata, serror);
+ return ExecuteWitnessScript(std::move(stack), exec_script, flags, SigVersion::WITNESS_V0, checker, execdata, serror);
} else if (program.size() == WITNESS_V0_KEYHASH_SIZE) {
// BIP141 P2WPKH: 20-byte witness v0 program (which encodes Hash160(pubkey))
if (stack.size() != 2) {
return set_error(serror, SCRIPT_ERR_WITNESS_PROGRAM_MISMATCH); // 2 items in witness
}
exec_script << OP_DUP << OP_HASH160 << program << OP_EQUALVERIFY << OP_CHECKSIG;
- return ExecuteWitnessScript(stack, exec_script, flags, SigVersion::WITNESS_V0, checker, execdata, serror);
+ return ExecuteWitnessScript(std::move(stack), exec_script, flags, SigVersion::WITNESS_V0, checker, execdata, serror);
} else {
return set_error(serror, SCRIPT_ERR_WITNESS_PROGRAM_WRONG_LENGTH);
}
@@ -1956,7 +1965,7 @@ static bool VerifyWitnessProgram(const CScriptWitness& witness, int witversion,
if (stack.size() == 0) return set_error(serror, SCRIPT_ERR_WITNESS_PROGRAM_WITNESS_EMPTY);
if (stack.size() >= 2 && !stack.back().empty() && stack.back()[0] == ANNEX_TAG) {
// Drop annex (this is non-standard; see IsWitnessStandard)
- const valtype& annex = SpanPopBack(stack);
+ const valtype annex = pop();
execdata.m_annex_hash = (HashWriter{} << annex).GetSHA256();
execdata.m_annex_present = true;
} else {
@@ -1971,8 +1980,8 @@ static bool VerifyWitnessProgram(const CScriptWitness& witness, int witversion,
return set_success(serror);
} else {
// Script path spending (stack size is >1 after removing optional annex)
- const valtype& control = SpanPopBack(stack);
- const valtype& script = SpanPopBack(stack);
+ const valtype control = pop();
+ const valtype script = pop();
if (control.size() < TAPROOT_CONTROL_BASE_SIZE || control.size() > TAPROOT_CONTROL_MAX_SIZE || ((control.size() - TAPROOT_CONTROL_BASE_SIZE) % TAPROOT_CONTROL_NODE_SIZE) != 0) {
return set_error(serror, SCRIPT_ERR_TAPROOT_WRONG_CONTROL_SIZE);
}
@@ -1984,9 +1993,9 @@ static bool VerifyWitnessProgram(const CScriptWitness& witness, int witversion,
if ((control[0] & TAPROOT_LEAF_MASK) == TAPROOT_LEAF_TAPSCRIPT) {
// Tapscript (leaf version 0xc0)
exec_script = CScript(script.begin(), script.end());
- execdata.m_validation_weight_left = ::GetSerializeSize(witness.stack) + VALIDATION_WEIGHT_OFFSET;
+ execdata.m_validation_weight_left = ::GetSerializeSize(witness) + VALIDATION_WEIGHT_OFFSET;
execdata.m_validation_weight_left_init = true;
- return ExecuteWitnessScript(stack, exec_script, flags, SigVersion::TAPSCRIPT, checker, execdata, serror);
+ return ExecuteWitnessScript(std::move(stack), exec_script, flags, SigVersion::TAPSCRIPT, checker, execdata, serror);
}
if (flags & SCRIPT_VERIFY_DISCOURAGE_UPGRADABLE_TAPROOT_VERSION) {
return set_error(serror, SCRIPT_ERR_DISCOURAGE_UPGRADABLE_TAPROOT_VERSION);
@@ -2118,7 +2127,7 @@ bool VerifyScript(const CScript& scriptSig, const CScript& scriptPubKey, const C
// that WITNESS implies P2SH. Otherwise, going from WITNESS->P2SH+WITNESS would be
// possible, which is not a softfork.
assert((flags & SCRIPT_VERIFY_P2SH) != 0);
- if (!hadWitness && !witness->IsNull()) {
+ if (!hadWitness && !witness->empty()) {
return set_error(serror, SCRIPT_ERR_WITNESS_UNEXPECTED);
}
}
@@ -2132,8 +2141,9 @@ size_t static WitnessSigOps(int witversion, const std::vector<unsigned char>& wi
if (witprogram.size() == WITNESS_V0_KEYHASH_SIZE)
return 1;
- if (witprogram.size() == WITNESS_V0_SCRIPTHASH_SIZE && witness.stack.size() > 0) {
- CScript subscript(witness.stack.back().begin(), witness.stack.back().end());
+ if (witprogram.size() == WITNESS_V0_SCRIPTHASH_SIZE && witness.size() > 0) {
+ const auto script = witness.back();
+ CScript subscript(script.begin(), script.end());
return subscript.GetSigOpCount(true);
}
}
### src/script/script.cpp
@@ -8,11 +8,21 @@
#include <crypto/common.h>
#include <crypto/hex_base.h>
#include <hash.h>
+#include <memusage.h>
+#include <streams.h>
#include <uint256.h>
+#include <util/check.h>
#include <util/hash_type.h>
+#include <util/string.h>
+#include <cassert>
#include <compare>
+#include <limits>
+#include <memory>
+#include <span>
+#include <stdexcept>
#include <string>
+#include <vector>
CScriptID::CScriptID(const CScript& in) : BaseHash(Hash160(in)) {}
@@ -287,14 +297,52 @@ bool CScript::IsPushOnly() const
std::string CScriptWitness::ToString() const
{
- std::string ret = "CScriptWitness(";
- for (unsigned int i = 0; i < stack.size(); i++) {
- if (i) {
- ret += ", ";
- }
- ret += HexStr(stack[i]);
- }
- return ret + ")";
+ return "CScriptWitness(" + util::Join(*this, ", ", [](auto element) { return HexStr(element); }) + ")";
+}
+
+CScriptWitness::CScriptWitness(const std::vector<std::vector<unsigned char>>& stack)
+{
+ if (stack.empty()) return;
+ SpanWriter{Allocate(::GetSerializeSize(stack)), stack};
+}
+
+std::span<std::byte> CScriptWitness::Allocate(uint64_t size)
+{
+ // The header stores the size of the serialization in 32 bits. Together with the header, it must also fit in a
+ // size_t, which may be 32 bits too.
+ if (size > std::numeric_limits<uint32_t>::max() - HEADER_SIZE) throw std::length_error("CScriptWitness too large");
+ m_data = std::make_unique_for_overwrite<std::byte[]>(HEADER_SIZE + size);
+ WriteLE32(m_data.get(), size);
+ return {m_data.get() + HEADER_SIZE, static_cast<size_t>(size)};
+}
+
+CScriptWitness::CScriptWitness(const CScriptWitness& other)
+{
+ if (other.empty()) return;
+ const auto total = HEADER_SIZE + other.Data().size();
+ m_data = std::make_unique_for_overwrite<std::byte[]>(total);
+ std::copy_n(other.m_data.get(), total, m_data.get());
+}
+
+std::span<const unsigned char> CScriptWitness::operator[](size_t index) const noexcept
+{
+ Assume(index < size());
+ auto it = begin();
+ for (size_t i = 0; i < index; ++i) ++it;
+ return *it;
+}
+
+std::vector<std::vector<unsigned char>> CScriptWitness::ToVectors() const
+{
+ std::vector<std::vector<unsigned char>> ret;
+ ret.reserve(size());
+ for (const auto element : *this) ret.emplace_back(element.begin(), element.end());
+ return ret;
+}
+
+size_t CScriptWitness::DynamicMemoryUsage() const noexcept
+{
+ return m_data ? memusage::MallocUsage(HEADER_SIZE + Data().size()) : 0;
}
bool CScript::HasValidOps() const
### src/script/script.h
@@ -10,14 +10,19 @@
#include <crypto/common.h>
#include <prevector.h>
#include <serialize.h>
+#include <span.h>
+#include <streams.h>
#include <uint256.h>
#include <util/hash_type.h>
+#include <algorithm>
#include <cassert>
#include <cstddef>
#include <cstdint>
-#include <iterator>
+#include <ios>
#include <limits>
+#include <memory>
+#include <ranges>
#include <span>
#include <stdexcept>
#include <string>
@@ -574,24 +579,172 @@ class CScript : public CScriptBase
}
};
-struct CScriptWitness
+/** A witness stack. Elements are accessed as spans, by forward iteration or by index. A witness
+ * can only be constructed as a whole (from a vector of its elements), not modified.
+ *
+ * The stack is stored as its serialization (the CompactSize-encoded number of elements, followed
+ * by each element as a CompactSize-prefixed byte string), in a single allocation. Access by index
+ * is O(n) in the position from the bottom of the stack.
+ */
+class CScriptWitness
{
- // Note that this encodes the data elements being pushed, rather than
- // encoding them as a CScript that pushes them.
- std::vector<std::vector<unsigned char> > stack;
+ /** Null pointer for an empty stack. Otherwise, it points to a header followed by the stack's
+ * serialization. For example, the stack {{0xaa}, {}, {0xbb, 0xcc}} is stored as (bytes in
+ * hex):
+ *
+ * |<- header -->|<--------- serialization ---------->|
+ * 0 1 3 4 (offsets within the serialization)
+ * +-------------+------+---------+------+------------+
+ * | 07 00 00 00 | 03 | 01 aa | 00 | 02 bb cc |
+ * +-------------+------+---------+------+------------+
+ * | | | | |
+ * | | | | element 2
+ * | | | element 1 (empty)
+ * | | element 0: its size (CompactSize), then its bytes
+ * | number of elements (CompactSize)
+ * size of the serialization (4 bytes, little endian)
+ */
+ std::unique_ptr<std::byte[]> m_data;
+ static constexpr size_t HEADER_SIZE{4};
+
+ /** The serialization of the stack. For an empty stack that is a single zero byte, stored outside
+ * m_data. As it was produced by this class, ReadCompactSize cannot fail on it, so the accessors
+ * below are noexcept. They read it without range check, as a stack constructed from vectors may
+ * have more than MAX_SIZE elements, or elements larger than that.
+ */
+ std::span<const std::byte> Data() const noexcept LIFETIMEBOUND
+ {
+ static constexpr std::byte EMPTY_SERIALIZATION[1]{};
+ if (!m_data) return EMPTY_SERIALIZATION;
+ return {m_data.get() + HEADER_SIZE, ReadLE32(m_data.get())};
+ }
+ /** Allocate m_data for a non-empty stack whose serialization has the given size, and write the
+ * header. Returns where the serialization goes, which the caller must fill. */
+ std::span<std::byte> Allocate(uint64_t size) LIFETIMEBOUND;
+
+public:
+ /** Forward iterator over the elements of the stack, exposing them as spans. */
+ class Iterator
+ {
+ std::span<const std::byte> m_rest; //!< The serialization of the remaining elements.
+
+ friend CScriptWitness;
+ explicit Iterator(std::span<const std::byte> rest LIFETIMEBOUND) noexcept : m_rest{rest} {}
+
+ public:
+ using iterator_category = std::forward_iterator_tag;
+ using value_type = std::span<const unsigned char>;
+ using difference_type = std::ptrdiff_t;
+ using pointer = void;
+ using reference = value_type;
+
+ Iterator() noexcept = default;
+ value_type operator*() const noexcept
+ {
+ SpanReader reader{m_rest};
+ const auto len = ReadCompactSize(reader, /*range_check=*/false);
+ // What the reader has left starts with the element. The serialization is std::byte, but elements are
+ // returned as unsigned char, like other script data.
+ return UCharSpanCast(m_rest.last(reader.size()).first(len));
+ }
+ Iterator& operator++() noexcept LIFETIMEBOUND
+ {
+ SpanReader reader{m_rest};
+ const auto len = ReadCompactSize(reader, /*range_check=*/false);
+ // Skip the element, which is at the start of what the reader has left.
+ m_rest = m_rest.last(reader.size() - len);
+ return *this;
+ }
+ Iterator operator++(int) noexcept { auto ret{*this}; ++*this; return ret; }
+ /** Iterators over the same stack are equal if they point to the same remaining elements. */
+ friend bool operator==(const Iterator& a, const Iterator& b) noexcept { return SameSpan(a.m_rest, b.m_rest); }
+ };
+ using iterator = Iterator;
+ using const_iterator = Iterator;
- // Some compilers complain without a default constructor
CScriptWitness() = default;
+ explicit CScriptWitness(const std::vector<std::vector<unsigned char>>& stack);
+ CScriptWitness(const CScriptWitness& other);
+ CScriptWitness& operator=(const CScriptWitness& other)
+ {
+ if (this != &other) *this = CScriptWitness{other};
+ return *this;
+ }
+ /** Moving leaves the source empty. */
+ CScriptWitness(CScriptWitness&&) noexcept = default;
+ CScriptWitness& operator=(CScriptWitness&&) noexcept = default;
- bool IsNull() const { return stack.empty(); }
+ bool empty() const noexcept { return !m_data; }
- void SetNull() { stack.clear(); stack.shrink_to_fit(); }
+ /** Number of elements. */
+ size_t size() const noexcept
+ {
+ if (!m_data) return 0;
+ SpanReader reader{Data()};
+ return ReadCompactSize(reader, /*range_check=*/false);
+ }
+ Iterator begin() const noexcept LIFETIMEBOUND
+ {
+ if (!m_data) return end();
+ const auto data = Data();
+ SpanReader reader{data};
+ ReadCompactSize(reader, /*range_check=*/false);
+ // The elements are what follows the number of elements.
+ return Iterator{data.last(reader.size())};
+ }
+ Iterator end() const noexcept LIFETIMEBOUND
+ {
+ return Iterator{Data().last(0)};
+ }
+ /** The first (bottom) element. The stack must not be empty. */
+ std::span<const unsigned char> front() const noexcept LIFETIMEBOUND { return *begin(); }
+ /** The last (top) element. This is O(n). The stack must not be empty. */
+ std::span<const unsigned char> back() const noexcept LIFETIMEBOUND { return (*this)[size() - 1]; }
+ /** The element at a given index (from the bottom), which must exist. This is O(index), so avoid it in loops over
+ * the elements; iterate instead. */
+ std::span<const unsigned char> operator[](size_t index) const noexcept LIFETIMEBOUND;
+
+ /** The elements, bottom to top, as vectors. For code that needs to modify or take ownership of them (e.g. to
+ * execute a script with them as its initial stack). */
+ std::vector<std::vector<unsigned char>> ToVectors() const;
+
+ /** The dynamic memory usage of the stack, including that of its elements. */
+ size_t DynamicMemoryUsage() const noexcept;
+
+ template <typename Stream>
+ void Serialize(Stream& s) const
+ {
+ s.write(Data());
+ }
+
+ /** Deserialize a witness stack, with the same semantics (and failures) as deserializing a
+ * std::vector<std::vector<unsigned char>>. */
+ template <typename Stream>
+ void Unserialize(Stream& s)
+ {
+ try {
+ std::vector<std::vector<unsigned char>> stack;
+ s >> stack;
+ *this = CScriptWitness{stack};
+ } catch (const std::length_error&) {
+ // A stack that is too large to store is reported like other deserialization failures.
+ throw std::ios_base::failure("Witness stack too large");
+ }
+ }
std::string ToString() const;
- bool operator==(const CScriptWitness&) const = default;
+ /** Witnesses are equal exactly when their stacks are, as a stack has only one serialization. */
+ friend bool operator==(const CScriptWitness& a, const CScriptWitness& b) noexcept
+ {
+ // Compared as unsigned chars, for which std::ranges::equal uses memcmp (unlike for std::byte).
+ return std::ranges::equal(UCharSpanCast(a.Data()), UCharSpanCast(b.Data()));
+ }
};
+// A CScriptWitness is a multi-pass range over its elements.
+static_assert(std::ranges::forward_range<const CScriptWitness>);
+
/** A reference to a CScript: the Hash160 of its serialization */
class CScriptID : public BaseHash<uint160>
{
### src/script/sign.cpp
@@ -774,7 +774,7 @@ bool ProduceSignature(const SigningProvider& provider, const BaseSignatureCreato
witnessscript << OP_DUP << OP_HASH160 << ToByteVector(result[0]) << OP_EQUALVERIFY << OP_CHECKSIG;
TxoutType subType;
solved = solved && SignStep(provider, creator, witnessscript, result, subType, SigVersion::WITNESS_V0, sigdata);
- sigdata.scriptWitness.stack = result;
+ sigdata.scriptWitness = CScriptWitness{result};
sigdata.witness = true;
result.clear();
}
@@ -797,20 +797,20 @@ bool ProduceSignature(const SigningProvider& provider, const BaseSignatureCreato
}
result.emplace_back(witnessscript.begin(), witnessscript.end());
- sigdata.scriptWitness.stack = result;
+ sigdata.scriptWitness = CScriptWitness{result};
sigdata.witness = true;
result.clear();
} else if (whichType == TxoutType::WITNESS_V1_TAPROOT && !P2SH) {
sigdata.witness = true;
if (solved) {
- sigdata.scriptWitness.stack = std::move(result);
+ sigdata.scriptWitness = CScriptWitness{result};
}
result.clear();
} else if (solved && whichType == TxoutType::WITNESS_UNKNOWN) {
sigdata.witness = true;
}
- if (!sigdata.witness) sigdata.scriptWitness.stack.clear();
+ if (!sigdata.witness) sigdata.scriptWitness = {};
if (P2SH) {
result.emplace_back(subscript.begin(), subscript.end());
}
@@ -848,7 +848,7 @@ struct Stacks
Stacks() = delete;
Stacks(const Stacks&) = delete;
- explicit Stacks(const SignatureData& data) : witness(data.scriptWitness.stack) {
+ explicit Stacks(const SignatureData& data) : witness(data.scriptWitness.ToVectors()) {
EvalScript(script, data.scriptSig, SCRIPT_VERIFY_STRICTENC, BaseSignatureChecker(), SigVersion::BASE);
}
};
@@ -1066,7 +1066,7 @@ bool SignTransaction(CMutableTransaction& mtx, const SigningProvider* keystore,
UpdateInput(txin, sigdata);
// amount must be specified for valid segwit signature
- if (amount == MAX_MONEY && !txin.scriptWitness.IsNull()) {
+ if (amount == MAX_MONEY && !txin.scriptWitness.empty()) {
input_errors[i] = _("Missing amount");
continue;
}
### src/signet.cpp
@@ -101,7 +101,7 @@ std::optional<SignetTxs> SignetTxs::Create(const CBlock& block, const CScript& c
try {
SpanReader v{signet_solution};
v >> tx_spending.vin[0].scriptSig;
- v >> tx_spending.vin[0].scriptWitness.stack;
+ v >> tx_spending.vin[0].scriptWitness;
if (!v.empty()) return std::nullopt; // extraneous data encountered
} catch (const std::exception&) {
return std::nullopt; // parsing error
### src/span.h
@@ -80,6 +80,14 @@ T& SpanPopBack(std::span<T>& span)
return back;
}
+/** Whether two spans refer to the same range of memory: the same start and the same number of
+ * elements. Spans with equal contents in different places are not the same. */
+template <typename T>
+constexpr bool SameSpan(std::span<T> a, std::span<T> b) noexcept
+{
+ return a.data() == b.data() && a.size() == b.size();
+}
+
template <typename V>
auto MakeByteSpan(const V& v) noexcept
{
### src/test/bip352_tests.cpp
@@ -58,10 +58,10 @@ BOOST_AUTO_TEST_CASE(bip352_send_and_receive_test_vectors)
const auto& script_sig_bytes = ParseHex(input["scriptSig"].get_str());
CScript script_sig = CScript(script_sig_bytes.begin(), script_sig_bytes.end());
CTxIn txin{outpoint, script_sig};
- // read the field txWitness as a stream and write txWitness >> witness.stack;
+ // Deserialize the txinwitness field into txin.scriptWitness.
const auto witness_str = ParseHex(input["txinwitness"].get_str());
if (!witness_str.empty()) {
- SpanReader(witness_str) >> txin.scriptWitness.stack;
+ SpanReader(witness_str) >> txin.scriptWitness;
}
// check if this is a silent payments input by trying to extract the public key
@@ -135,10 +135,10 @@ BOOST_AUTO_TEST_CASE(bip352_send_and_receive_test_vectors)
const auto& script_sig_bytes = ParseHex(input["scriptSig"].get_str());
CScript script_sig = CScript(script_sig_bytes.begin(), script_sig_bytes.end());
CTxIn txin{outpoint, script_sig};
- // read the field txWitness as a stream and write txWitness >> witness.stack;
+ // Deserialize the txinwitness field into txin.scriptWitness.
const auto witness_str = ParseHex(input["txinwitness"].get_str());
if (!witness_str.empty()) {
- SpanReader(witness_str) >> txin.scriptWitness.stack;
+ SpanReader(witness_str) >> txin.scriptWitness;
}
vin.push_back(txin);
coins[outpoint] = Coin{CTxOut{{}, spk}, 0, false};
@@ -233,8 +233,7 @@ BOOST_AUTO_TEST_CASE(bip352_skips_transactions_spending_unknown_segwit_versions)
COutPoint unknown_segwit_outpoint{Txid::FromHex("0000000000000000000000000000000000000000000000000000000000000002").value(), 0};
CTxIn eligible_input{eligible_outpoint};
- eligible_input.scriptWitness.stack.emplace_back(64, 0);
- eligible_input.scriptWitness.stack.emplace_back(pubkey.begin(), pubkey.end());
+ eligible_input.scriptWitness = CScriptWitness{{std::vector<unsigned char>(64, 0), ToByteVector(pubkey)}};
std::map<COutPoint, Coin> coins;
coins[eligible_outpoint] = Coin{CTxOut{{}, GetScriptForDestination(WitnessV0KeyHash{pubkey})}, 0, false};
@@ -259,8 +258,7 @@ BOOST_AUTO_TEST_CASE(bip352_scan_skips_invalid_taproot_outputs)
CTxIn txin{outpoint};
const CPubKey sender_pubkey{sender_key.GetPubKey()};
- txin.scriptWitness.stack.emplace_back();
- txin.scriptWitness.stack.emplace_back(sender_pubkey.begin(), sender_pubkey.end());
+ txin.scriptWitness = CScriptWitness{{{}, ToByteVector(sender_pubkey)}};
std::map<COutPoint, Coin> coins;
coins[outpoint] = Coin{CTxOut{{}, GetScriptForDestination(WitnessV0KeyHash{sender_pubkey})}, 0, false};
### src/test/fuzz/CMakeLists.txt
@@ -115,6 +115,7 @@ add_executable(fuzz
script_parsing.cpp
script_sigcache.cpp
script_sign.cpp
+ script_witness.cpp
scriptnum_ops.cpp
secp256k1_ec_seckey_import_export_der.cpp
secp256k1_ecdsa_signature_parse_der_lax.cpp
### src/test/fuzz/cmpctblock.cpp
@@ -206,7 +206,7 @@ FUZZ_TARGET(cmpctblock, .init = initialize_cmpctblock)
in.prevout = outpoint;
in.nSequence = sequence;
in.scriptSig = script_sig;
- in.scriptWitness.stack = script_wit_stack;
+ in.scriptWitness = CScriptWitness{script_wit_stack};
tx_mut.vin.push_back(in);
const CAmount amount_out = amount_in - AMOUNT_FEE;
### src/test/fuzz/connect_block.cpp
@@ -81,14 +81,14 @@ static CTxIn GetSpendingScript(const CTransaction& tx, uint32_t vout_index)
CTxIn res{COutPoint(tx.GetHash(), vout_index)};
if (output.scriptPubKey == P2WSH_OP_TRUE) {
res.scriptSig = CScript();
- res.scriptWitness.stack.push_back(WITNESS_STACK_ELEM_OP_TRUE);
+ res.scriptWitness = CScriptWitness{{WITNESS_STACK_ELEM_OP_TRUE}};
} else if (output.scriptPubKey == P2SH_OP_TRUE) {
res.scriptSig = P2SH_OP_TRUE_UNLOCK;
} else if (output.scriptPubKey == CScript()) {
res.scriptSig = CScript() << OP_TRUE;
} else if (output.scriptPubKey == TAPROOT_OP_TRUE) {
res.scriptSig = CScript();
- res.scriptWitness.stack = TAPROOT_OP_TRUE_WITNESS;
+ res.scriptWitness = CScriptWitness{TAPROOT_OP_TRUE_WITNESS};
}
return res;
@@ -326,10 +326,11 @@ CTransactionRef ConsumeTransaction(FuzzedDataProvider& fuzzed_data_provider,
txin.scriptSig = ConsumeScript(fuzzed_data_provider);
}
if (fuzzed_data_provider.ConsumeBool()) {
- txin.scriptWitness.stack.clear();
+ std::vector<std::vector<unsigned char>> stack;
LIMITED_WHILE(fuzzed_data_provider.ConsumeBool(), 10) {
- txin.scriptWitness.stack.push_back(ConsumeRandomLengthByteVector<unsigned char>(fuzzed_data_provider, 100));
+ stack.push_back(ConsumeRandomLengthByteVector<unsigned char>(fuzzed_data_provider, 100));
}
+ txin.scriptWitness = CScriptWitness{stack};
}
}
}
### src/test/fuzz/miniscript.cpp
@@ -1015,12 +1015,12 @@ CScript ScriptPubKey(MsCtx ctx, const CScript& script, TaprootBuilder& builder)
}
//! Fill the witness with the data additional to the script satisfaction.
-void SatisfactionToWitness(MsCtx ctx, CScriptWitness& witness, const CScript& script, TaprootBuilder& builder) {
+void SatisfactionToWitness(MsCtx ctx, std::vector<std::vector<unsigned char>>& stack, const CScript& script, TaprootBuilder& builder) {
// For P2WSH, it's only the witness script.
- witness.stack.emplace_back(script.begin(), script.end());
+ stack.emplace_back(script.begin(), script.end());
if (!miniscript::IsTapscript(ctx)) return;
// For Tapscript we also need the control block.
- witness.stack.push_back(*builder.GetSpendData().scripts.begin()->second.begin());
+ stack.push_back(*builder.GetSpendData().scripts.begin()->second.begin());
}
/** Perform various applicable tests on a miniscript Node. */
@@ -1061,7 +1061,7 @@ void TestNode(const MsCtx script_ctx, const std::optional<Node>& node, FuzzedDat
// Optionally pad the script or the witness in order to increase the sensitivity of the tests of
// the resources limits logic.
- CScriptWitness witness_mal, witness_nonmal;
+ std::vector<std::vector<unsigned char>> witness_mal, witness_nonmal;
if (provider.ConsumeBool()) {
// Under P2WSH, optionally pad the script with OP_NOPs to max op the ops limit of the constructed script.
// This makes the script obviously not actually miniscript-compatible anymore, but the
@@ -1086,8 +1086,8 @@ void TestNode(const MsCtx script_ctx, const std::optional<Node>& node, FuzzedDat
const auto node_exec_ss{node->GetExecStackSize()};
if (miniscript::IsTapscript(script_ctx) && node_exec_ss && *node_exec_ss < MAX_STACK_SIZE) {
unsigned add{(unsigned)MAX_STACK_SIZE - *node_exec_ss};
- witness_mal.stack.resize(add);
- witness_nonmal.stack.resize(add);
+ witness_mal.resize(add);
+ witness_nonmal.resize(add);
script.reserve(add);
for (unsigned i = 0; i < add; ++i) script.push_back(OP_NIP);
}
@@ -1121,10 +1121,11 @@ void TestNode(const MsCtx script_ctx, const std::optional<Node>& node, FuzzedDat
assert(wit_size <= *node->GetWitnessSize());
// Test non-malleable satisfaction.
- witness_nonmal.stack.insert(witness_nonmal.stack.end(), std::make_move_iterator(stack_nonmal.begin()), std::make_move_iterator(stack_nonmal.end()));
+ witness_nonmal.insert(witness_nonmal.end(), std::make_move_iterator(stack_nonmal.begin()), std::make_move_iterator(stack_nonmal.end()));
SatisfactionToWitness(script_ctx, witness_nonmal, script, builder);
ScriptError serror;
- bool res = VerifyScript(DUMMY_SCRIPTSIG, script_pubkey, &witness_nonmal, STANDARD_SCRIPT_VERIFY_FLAGS, CHECKER_CTX, &serror);
+ const CScriptWitness witness{witness_nonmal};
+ bool res = VerifyScript(DUMMY_SCRIPTSIG, script_pubkey, &witness, STANDARD_SCRIPT_VERIFY_FLAGS, CHECKER_CTX, &serror);
// Non-malleable satisfactions are guaranteed to be valid if ValidSatisfactions().
if (node->ValidSatisfactions()) assert(res);
// More detailed: non-malleable satisfactions must be valid, or could fail with ops count error (if CheckOpsLimit failed),
@@ -1134,12 +1135,13 @@ void TestNode(const MsCtx script_ctx, const std::optional<Node>& node, FuzzedDat
(!node->CheckStackSize() && serror == ScriptError::SCRIPT_ERR_STACK_SIZE));
}
- if (mal_success && (!nonmal_success || witness_mal.stack != witness_nonmal.stack)) {
+ if (mal_success && (!nonmal_success || witness_mal != witness_nonmal)) {
// Test malleable satisfaction only if it's different from the non-malleable one.
- witness_mal.stack.insert(witness_mal.stack.end(), std::make_move_iterator(stack_mal.begin()), std::make_move_iterator(stack_mal.end()));
+ witness_mal.insert(witness_mal.end(), std::make_move_iterator(stack_mal.begin()), std::make_move_iterator(stack_mal.end()));
SatisfactionToWitness(script_ctx, witness_mal, script, builder);
ScriptError serror;
- bool res = VerifyScript(DUMMY_SCRIPTSIG, script_pubkey, &witness_mal, STANDARD_SCRIPT_VERIFY_FLAGS, CHECKER_CTX, &serror);
+ const CScriptWitness witness{witness_mal};
+ bool res = VerifyScript(DUMMY_SCRIPTSIG, script_pubkey, &witness, STANDARD_SCRIPT_VERIFY_FLAGS, CHECKER_CTX, &serror);
// Malleable satisfactions are not guaranteed to be valid under any conditions, but they can only
// fail due to stack or ops limits.
assert(res || serror == ScriptError::SCRIPT_ERR_OP_COUNT || serror == ScriptError::SCRIPT_ERR_STACK_SIZE);
### src/test/fuzz/package_eval.cpp
@@ -305,7 +305,7 @@ FUZZ_TARGET(ephemeral_package_eval, .init = initialize_ephemeral_package_eval)
// Create input
CTxIn in;
in.prevout = outpoint;
- in.scriptWitness.stack = P2WSH_EMPTY_TRUE_STACK;
+ in.scriptWitness = CScriptWitness{P2WSH_EMPTY_TRUE_STACK};
tx_mut.vin.push_back(in);
}
@@ -457,7 +457,7 @@ FUZZ_TARGET(tx_package_eval, .init = initialize_tx_package_eval)
in.prevout = outpoint;
in.nSequence = sequence;
in.scriptSig = script_sig;
- in.scriptWitness.stack = script_wit_stack;
+ in.scriptWitness = CScriptWitness{script_wit_stack};
tx_mut.vin.push_back(in);
}
### src/test/fuzz/script.cpp
@@ -115,12 +115,13 @@ FUZZ_TARGET(script, .init = initialize_script)
const auto flags_rand{fuzzed_data_provider.ConsumeIntegral<script_verify_flags::value_type>()};
const auto flags = script_verify_flags::from_int(flags_rand) | SCRIPT_VERIFY_P2SH;
{
- CScriptWitness wit;
+ std::vector<std::vector<unsigned char>> stack;
+ stack.reserve(random_string_vector.size());
for (const auto& s : random_string_vector) {
- wit.stack.emplace_back(s.begin(), s.end());
+ stack.emplace_back(s.begin(), s.end());
}
+ CScriptWitness wit{stack};
(void)CountWitnessSigOps(script, *other_script, wit, flags);
- wit.SetNull();
}
}
### src/test/fuzz/script_assets_test_minimizer.cpp
@@ -82,12 +82,12 @@ std::vector<CTxOut> TxOutsFromJSON(const UniValue& univalue)
CScriptWitness ScriptWitnessFromJSON(const UniValue& univalue)
{
if (!univalue.isArray()) throw std::runtime_error("Script witness is not array");
- CScriptWitness scriptwitness;
+ std::vector<std::vector<unsigned char>> stack;
for (size_t i = 0; i < univalue.size(); ++i) {
auto bytes = CheckedParseHex(univalue[i].get_str());
- scriptwitness.stack.push_back(std::move(bytes));
+ stack.push_back(std::move(bytes));
}
- return scriptwitness;
+ return CScriptWitness{stack};
}
const std::map<std::string, script_verify_flag_name> FLAG_NAMES = {
### src/test/fuzz/script_witness.cpp
@@ -0,0 +1,100 @@
+// Copyright (c) The Bitcoin Core developers
+// Distributed under the MIT software license, see the accompanying
+// file COPYING or http://www.opensource.org/licenses/mit-license.php.
+
+#include <script/script.h>
+#include <serialize.h>
+#include <streams.h>
+#include <test/fuzz/FuzzedDataProvider.h>
+#include <test/fuzz/fuzz.h>
+
+#include <algorithm>
+#include <cassert>
+#include <cstddef>
+#include <ios>
+#include <optional>
+#include <span>
+#include <utility>
+#include <vector>
+
+/** Deserialization of a CScriptWitness behaves exactly like that of a
+ * std::vector<std::vector<unsigned char>>, and its accessors and serialization agree with that
+ * vector. */
+FUZZ_TARGET(script_witness_deserialize)
+{
+ // Deserialize the input as a vector of vector of unsigned chars.
+ size_t stack_left{0};
+ std::optional<std::vector<std::vector<unsigned char>>> stack;
+ try {
+ SpanReader reader{buffer};
+ std::vector<std::vector<unsigned char>> tmp;
+ reader >> tmp;
+ stack = std::move(tmp);
+ stack_left = reader.size();
+ } catch (const std::ios_base::failure&) {
+ }
+
+ // Start over, and deserialize as a CScriptWitness.
+ std::optional<CScriptWitness> witness;
+ size_t witness_left{0};
+ try {
+ SpanReader reader{buffer};
+ CScriptWitness tmp;
+ reader >> tmp;
+ witness = std::move(tmp);
+ witness_left = reader.size();
+ } catch (const std::ios_base::failure&) {
+ }
+
+ // Check whether deserialization success matches between them.
+ assert(stack.has_value() == witness.has_value());
+
+ // If deserialization succeeded (in both), compare equivalence in behavior.
+ if (!stack) return;
+ // Make sure the number of consumed bytes matches.
+ assert(stack_left == witness_left);
+ // Check equivalence after converting CScriptWitness to vector of vectors.
+ assert(witness->ToVectors() == *stack);
+ // Check size/empty.
+ assert(witness->size() == stack->size());
+ assert(witness->empty() == stack->empty());
+ // Check equivalence after converting vector of vectors to CScriptWitness.
+ assert(CScriptWitness{*stack} == *witness);
+ if (!stack->empty()) {
+ // Compare first and last element.
+ assert(std::ranges::equal(witness->front(), stack->front()));
+ assert(std::ranges::equal(witness->back(), stack->back()));
+ // A copy has the same last element.
+ assert(std::ranges::equal(CScriptWitness{*witness}.back(), stack->back()));
+ // Compare elements accessed by index. As indexing may take time linear in the index, at most MAX_INDEXED_READS
+ // of them: all if there are that few, and otherwise those at positions read from the rest of the input, after
+ // the serialized witness.
+ constexpr size_t MAX_INDEXED_READS{64};
+ if (stack->size() <= MAX_INDEXED_READS) {
+ for (size_t i = 0; i < stack->size(); ++i) {
+ assert(std::ranges::equal((*witness)[i], (*stack)[i]));
+ }
+ } else {
+ FuzzedDataProvider provider{buffer.last(witness_left).data(), witness_left};
+ LIMITED_WHILE(provider.remaining_bytes() > 0, MAX_INDEXED_READS) {
+ const auto i = provider.ConsumeIntegralInRange<size_t>(0, stack->size() - 1);
+ assert(std::ranges::equal((*witness)[i], (*stack)[i]));
+ }
+ }
+ }
+
+ // Check reserialization.
+ std::vector<unsigned char> ser_stack, ser_witness;
+ VectorWriter{ser_stack, 0, *stack};
+ VectorWriter{ser_witness, 0, *witness};
+ assert(ser_stack == ser_witness);
+ // Deserialization only accepts canonically encoded sizes, so what was read is the stack's only serialization.
+ assert(std::ranges::equal(ser_witness, buffer.first(buffer.size() - witness_left)));
+ assert(::GetSerializeSize(*witness) == ser_stack.size());
+ // Sanity check memory usage.
+ if (stack->empty()) {
+ assert(witness->DynamicMemoryUsage() == 0);
+ } else {
+ assert(witness->DynamicMemoryUsage() >= ser_stack.size());
+ }
+}
### src/test/fuzz/tx_pool.cpp
@@ -368,7 +368,7 @@ FUZZ_TARGET(tx_pool_standard, .init = initialize_tx_pool_standard)
in.prevout = outpoint;
in.nSequence = sequence;
in.scriptSig = script_sig;
- in.scriptWitness.stack = script_wit_stack;
+ in.scriptWitness = CScriptWitness{script_wit_stack};
tx_mut.vin.push_back(in);
}
### src/test/fuzz/txdownloadman.cpp
@@ -66,7 +66,7 @@ static CTransactionRef MakeTransactionSpending(const std::vector<COutPoint>& out
tx.vin.emplace_back(outpoint);
}
if (add_witness) {
- tx.vin[0].scriptWitness.stack.push_back({1});
+ tx.vin[0].scriptWitness = CScriptWitness{{{1}}};
}
for (size_t o = 0; o < num_outputs; ++o) tx.vout.emplace_back(CENT, P2WSH_OP_TRUE);
return MakeTransactionRef(tx);
### src/test/fuzz/txorphan.cpp
@@ -455,10 +455,9 @@ FUZZ_TARGET(txorphanage_sim)
while (wtxids.contains(CTransaction(tx).GetWitnessHash()) || rng.randrange(4) == 0) {
auto& input = tx.vin[rng.randrange(tx.vin.size())];
if (rng.randbool()) {
- input.scriptWitness.stack.resize(1);
- input.scriptWitness.stack[0].resize(rng.randrange(100));
+ input.scriptWitness = CScriptWitness{{std::vector<unsigned char>(rng.randrange(100))}};
} else {
- input.scriptWitness.stack.resize(0);
+ input.scriptWitness = {};
}
}
// Convert to CTransactionRef.
### src/test/fuzz/util.cpp
@@ -58,7 +58,7 @@ CMutableTransaction ConsumeTransaction(FuzzedDataProvider& fuzzed_data_provider,
const auto script_sig = p2wsh_op_true ? CScript{} : ConsumeScript(fuzzed_data_provider);
CScriptWitness script_wit;
if (p2wsh_op_true) {
- script_wit.stack = std::vector<std::vector<uint8_t>>{WITNESS_STACK_ELEM_OP_TRUE};
+ script_wit = CScriptWitness{{WITNESS_STACK_ELEM_OP_TRUE}};
} else {
script_wit = ConsumeScriptWitness(fuzzed_data_provider);
}
@@ -82,12 +82,13 @@ CMutableTransaction ConsumeTransaction(FuzzedDataProvider& fuzzed_data_provider,
CScriptWitness ConsumeScriptWitness(FuzzedDataProvider& fuzzed_data_provider, const size_t max_stack_elem_size) noexcept
{
- CScriptWitness ret;
+ std::vector<std::vector<unsigned char>> stack;
const auto n_elements = fuzzed_data_provider.ConsumeIntegralInRange<size_t>(0, max_stack_elem_size);
+ stack.reserve(n_elements);
for (size_t i = 0; i < n_elements; ++i) {
- ret.stack.push_back(ConsumeRandomLengthByteVector(fuzzed_data_provider));
+ stack.push_back(ConsumeRandomLengthByteVector(fuzzed_data_provider));
}
- return ret;
+ return CScriptWitness{stack};
}
CScript ConsumeScript(FuzzedDataProvider& fuzzed_data_provider, const bool maybe_p2wsh) noexcept
### src/test/miniscript_tests.cpp
@@ -334,12 +334,12 @@ CScript ScriptPubKey(miniscript::MiniscriptContext ctx, const CScript& script, T
}
//! Fill the witness with the data additional to the script satisfaction.
-void SatisfactionToWitness(miniscript::MiniscriptContext ctx, CScriptWitness& witness, const CScript& script, TaprootBuilder& builder) {
+void SatisfactionToWitness(miniscript::MiniscriptContext ctx, std::vector<std::vector<unsigned char>>& stack, const CScript& script, TaprootBuilder& builder) {
// For P2WSH, it's only the witness script.
- witness.stack.emplace_back(script.begin(), script.end());
+ stack.emplace_back(script.begin(), script.end());
if (!miniscript::IsTapscript(ctx)) return;
// For Tapscript we also need the control block.
- witness.stack.push_back(*builder.GetSpendData().scripts.begin()->second.begin());
+ stack.push_back(*builder.GetSpendData().scripts.begin()->second.begin());
}
struct MiniScriptTest : BasicTestingSetup {
@@ -363,26 +363,28 @@ void TestSatisfy(const KeyConverter& converter, const Node& node)
const CScript script_pubkey{ScriptPubKey(converter.MsContext(), script, builder)};
// Run malleable satisfaction algorithm.
- CScriptWitness witness_mal;
- const bool mal_success = node.Satisfy(satisfier, witness_mal.stack, false) == miniscript::Availability::YES;
- SatisfactionToWitness(converter.MsContext(), witness_mal, script, builder);
+ std::vector<std::vector<unsigned char>> stack_mal;
+ const bool mal_success = node.Satisfy(satisfier, stack_mal, false) == miniscript::Availability::YES;
+ SatisfactionToWitness(converter.MsContext(), stack_mal, script, builder);
+ const CScriptWitness witness_mal{stack_mal};
// Run non-malleable satisfaction algorithm.
- CScriptWitness witness_nonmal;
- const bool nonmal_success = node.Satisfy(satisfier, witness_nonmal.stack, true) == miniscript::Availability::YES;
+ std::vector<std::vector<unsigned char>> stack_nonmal;
+ const bool nonmal_success = node.Satisfy(satisfier, stack_nonmal, true) == miniscript::Availability::YES;
// Compute witness size (excluding script push, control block, and witness count encoding).
- const uint64_t wit_size{GetSerializeSize(witness_nonmal.stack) - GetSizeOfCompactSize(witness_nonmal.stack.size())};
- SatisfactionToWitness(converter.MsContext(), witness_nonmal, script, builder);
+ const uint64_t wit_size{GetSerializeSize(stack_nonmal) - GetSizeOfCompactSize(stack_nonmal.size())};
+ SatisfactionToWitness(converter.MsContext(), stack_nonmal, script, builder);
+ const CScriptWitness witness_nonmal{stack_nonmal};
if (nonmal_success) {
// Non-malleable satisfactions are bounded by the satisfaction size plus:
// - For P2WSH spends, the witness script
// - For Tapscript spends, both the witness script and the control block
const size_t max_stack_size{*node.GetStackSize() + 1 + miniscript::IsTapscript(converter.MsContext())};
- BOOST_CHECK(witness_nonmal.stack.size() <= max_stack_size);
+ BOOST_CHECK(witness_nonmal.size() <= max_stack_size);
// If a non-malleable satisfaction exists, the malleable one must also exist, and be identical to it.
BOOST_CHECK(mal_success);
- BOOST_CHECK(witness_nonmal.stack == witness_mal.stack);
+ BOOST_CHECK(witness_nonmal == witness_mal);
assert(wit_size <= *node.GetWitnessSize());
// Test non-malleable satisfaction.
@@ -397,7 +399,7 @@ void TestSatisfy(const KeyConverter& converter, const Node& node)
(!node.CheckStackSize() && serror == ScriptError::SCRIPT_ERR_STACK_SIZE));
}
- if (mal_success && (!nonmal_success || witness_mal.stack != witness_nonmal.stack)) {
+ if (mal_success && (!nonmal_success || witness_mal != witness_nonmal)) {
// Test malleable satisfaction only if it's different from the non-malleable one.
ScriptError serror;
bool res = VerifyScript(CScript(), script_pubkey, &witness_mal, STANDARD_SCRIPT_VERIFY_FLAGS, checker, &serror);
### src/test/orphanage_tests.cpp
@@ -46,7 +46,7 @@ static CTransactionRef MakeTransactionSpending(const std::vector<COutPoint>& out
}
}
// Ensure txid != wtxid
- tx.vin[0].scriptWitness.stack.push_back({1});
+ tx.vin[0].scriptWitness = CScriptWitness{{{1}}};
tx.vout.resize(2);
tx.vout[0].nValue = CENT;
tx.vout[0].scriptPubKey = GetScriptForDestination(PKHash(key.GetPubKey()));
@@ -59,7 +59,9 @@ static CTransactionRef MakeTransactionSpending(const std::vector<COutPoint>& out
static CTransactionRef MakeMutation(const CTransactionRef& ptx)
{
CMutableTransaction tx(*ptx);
- tx.vin[0].scriptWitness.stack.push_back({5});
+ auto stack = tx.vin[0].scriptWitness.ToVectors();
+ stack.push_back({5});
+ tx.vin[0].scriptWitness = CScriptWitness{stack};
auto mutated_tx = MakeTransactionRef(tx);
assert(ptx->GetHash() == mutated_tx->GetHash());
return mutated_tx;
### src/test/private_broadcast_tests.cpp
@@ -32,8 +32,7 @@ static CTransactionRef MakeDummyTx(uint32_t id, size_t num_witness)
mtx.vin.resize(1);
mtx.vin[0].nSequence = id;
if (num_witness > 0) {
- mtx.vin[0].scriptWitness = CScriptWitness{};
- mtx.vin[0].scriptWitness.stack.resize(num_witness);
+ mtx.vin[0].scriptWitness = CScriptWitness{std::vector<std::vector<unsigned char>>(num_witness)};
}
return MakeTransactionRef(mtx);
}
### src/test/psbt_tests.cpp
@@ -141,10 +141,10 @@ BOOST_AUTO_TEST_CASE(psbt2_addinput)
// Same thing, but with other things that have signatures
psbtin7.final_script_sig.clear();
- psbtin7.final_script_witness.stack.emplace_back();
+ psbtin7.final_script_witness = CScriptWitness{std::vector<std::vector<unsigned char>>(1)};
BOOST_CHECK(!psbt.AddInput(psbtin7));
BOOST_CHECK_EQUAL(psbt.inputs.size(), 5);
- psbtin7.final_script_witness.SetNull();
+ psbtin7.final_script_witness = {};
psbtin7.partial_sigs.emplace();
BOOST_CHECK(!psbt.AddInput(psbtin7));
BOOST_CHECK_EQUAL(psbt.inputs.size(), 5);
### src/test/rbf_tests.cpp
@@ -27,9 +27,7 @@ static inline CTransactionRef make_tx(const std::vector<CTransactionRef>& inputs
tx.vin[i].prevout.hash = inputs[i]->GetHash();
tx.vin[i].prevout.n = 0;
// Add a witness so wtxid != txid
- CScriptWitness witness;
- witness.stack.emplace_back(i + 10);
- tx.vin[i].scriptWitness = witness;
+ tx.vin[i].scriptWitness = CScriptWitness{{std::vector<unsigned char>(i + 10)}};
}
for (size_t i = 0; i < output_values.size(); ++i) {
tx.vout[i].scriptPubKey = CScript() << OP_11 << OP_EQUAL;
### src/test/script_assets_tests.cpp
@@ -63,12 +63,12 @@ static std::vector<CTxOut> TxOutsFromJSON(const UniValue& univalue)
static CScriptWitness ScriptWitnessFromJSON(const UniValue& univalue)
{
assert(univalue.isArray());
- CScriptWitness scriptwitness;
+ std::vector<std::vector<unsigned char>> stack;
for (size_t i = 0; i < univalue.size(); ++i) {
auto bytes = ParseHex(univalue[i].get_str());
- scriptwitness.stack.push_back(std::move(bytes));
+ stack.push_back(std::move(bytes));
}
- return scriptwitness;
+ return CScriptWitness{stack};
}
static std::vector<script_verify_flags> AllConsensusFlags()
### src/test/script_tests.cpp
@@ -15,6 +15,7 @@
#include <script/signingprovider.h>
#include <script/solver.h>
#include <secp256k1.h>
+#include <serialize.h>
#include <streams.h>
#include <test/data/bip341_wallet_vectors.json.h>
#include <test/data/script_tests.json.h>
@@ -31,7 +32,11 @@
#include <boost/test/unit_test.hpp>
+#include <algorithm>
+#include <cstddef>
#include <cstdint>
+#include <ios>
+#include <iterator>
#include <string>
#include <vector>
@@ -383,7 +388,9 @@ class TestBuilder
TestBuilder& AsWit()
{
assert(havePush);
- scriptWitness.stack.push_back(push);
+ auto stack = scriptWitness.ToVectors();
+ stack.push_back(push);
+ scriptWitness = CScriptWitness{stack};
havePush = false;
return *this;
}
@@ -392,10 +399,10 @@ class TestBuilder
{
DoPush();
UniValue array(UniValue::VARR);
- if (!scriptWitness.stack.empty()) {
+ if (!scriptWitness.empty()) {
UniValue wit(UniValue::VARR);
- for (unsigned i = 0; i < scriptWitness.stack.size(); i++) {
- wit.push_back(HexStr(scriptWitness.stack[i]));
+ for (const auto element : scriptWitness) {
+ wit.push_back(HexStr(element));
}
wit.push_back(ValueFromAmount(nValue));
array.push_back(std::move(wit));
@@ -921,7 +928,7 @@ BOOST_AUTO_TEST_CASE(script_json_test)
for (unsigned int idx = 0; idx < tests.size(); idx++) {
const UniValue& test = tests[idx];
std::string strTest = test.write();
- CScriptWitness witness;
+ std::vector<std::vector<unsigned char>> witness_stack;
TaprootBuilder taprootBuilder;
CAmount nValue = 0;
unsigned int pos = 0;
@@ -934,20 +941,20 @@ BOOST_AUTO_TEST_CASE(script_json_test)
static const std::string SCRIPT_FLAG{"#SCRIPT#"};
if (element.starts_with(SCRIPT_FLAG)) {
CScript script = ParseScript(element.substr(SCRIPT_FLAG.size()));
- witness.stack.push_back(ToByteVector(script));
+ witness_stack.push_back(ToByteVector(script));
} else if (element == "#CONTROLBLOCK#") {
// Taproot script control block - second from the last element in witness stack
// If #CONTROLBLOCK# we auto-generate the control block
- taprootBuilder.Add(/*depth=*/0, witness.stack.back(), TAPROOT_LEAF_TAPSCRIPT, /*track=*/true);
+ taprootBuilder.Add(/*depth=*/0, witness_stack.back(), TAPROOT_LEAF_TAPSCRIPT, /*track=*/true);
taprootBuilder.Finalize(XOnlyPubKey(keys.key0.GetPubKey()));
- auto controlblocks = taprootBuilder.GetSpendData().scripts[{witness.stack.back(), TAPROOT_LEAF_TAPSCRIPT}];
- witness.stack.push_back(*(controlblocks.begin()));
+ auto controlblocks = taprootBuilder.GetSpendData().scripts[{witness_stack.back(), TAPROOT_LEAF_TAPSCRIPT}];
+ witness_stack.push_back(*(controlblocks.begin()));
} else {
const auto witness_value{TryParseHex<unsigned char>(element)};
if (!witness_value.has_value()) {
BOOST_ERROR("Bad witness in test: " << strTest << " witness is not hex: " << element);
}
- witness.stack.push_back(witness_value.value());
+ witness_stack.push_back(witness_value.value());
}
}
nValue = AmountFromValue(test[pos][i]);
@@ -974,7 +981,7 @@ BOOST_AUTO_TEST_CASE(script_json_test)
script_verify_flags scriptflags = ParseScriptFlags(test[pos++].get_str());
int scriptError = ParseScriptError(test[pos++].get_str());
- DoTest(scriptPubKey, scriptSig, witness, scriptflags, strTest, scriptError, nValue);
+ DoTest(scriptPubKey, scriptSig, CScriptWitness{witness_stack}, scriptflags, strTest, scriptError, nValue);
}
}
@@ -1733,4 +1740,201 @@ BOOST_AUTO_TEST_CASE(formatscriptflags)
BOOST_CHECK_EQUAL(FormatScriptFlags(script_verify_flags::from_int(1u<<26)), "0x04000000");
}
+BOOST_AUTO_TEST_CASE(script_witness_representation)
+{
+ // Witnesses with different stacks are not equal, also when those stacks serialize to the same size.
+ BOOST_CHECK(CScriptWitness{{{0x01}}} != CScriptWitness{{{0x02}}});
+ BOOST_CHECK(CScriptWitness{} != CScriptWitness{{{}}});
+
+ // Element counts and sizes around CompactSize encoding boundaries.
+ static constexpr size_t COUNTS[]{0, 1, 2, 3, 252, 253, 254};
+ static constexpr size_t SIZES[]{0, 1, 32, 252, 253, 65535, 65536};
+ // Every size as the first and as the last element.
+ for (const size_t size : SIZES) {
+ const std::vector<unsigned char> first(size, 0x01);
+ const std::vector<unsigned char> last(size, 0x02);
+ const CScriptWitness witness{{first, {0xff}, last}};
+ BOOST_CHECK(std::ranges::equal(witness.front(), first));
+ BOOST_CHECK(std::ranges::equal(witness.back(), last));
+ }
+ for (const size_t count : COUNTS) {
+ for (int iter = 0; iter < 3; ++iter) {
+ std::vector<std::vector<unsigned char>> stack(count);
+ for (auto& element : stack) {
+ // Mostly small elements, as large ones make big stacks slow.
+ const auto size = m_rng.randrange(8) == 0 ? SIZES[m_rng.randrange(std::size(SIZES))] : m_rng.randrange(40);
+ element = m_rng.randbytes(size);
+ }
+ const CScriptWitness witness{stack};
+
+ BOOST_CHECK(witness.ToVectors() == stack);
+ BOOST_CHECK(CScriptWitness{witness.ToVectors()} == witness);
+ BOOST_CHECK_EQUAL(witness.size(), stack.size());
+ BOOST_CHECK_EQUAL(witness.empty(), stack.empty());
+ BOOST_CHECK_EQUAL(std::distance(witness.begin(), witness.end()), (std::ptrdiff_t)stack.size());
+ if (!stack.empty()) {
+ BOOST_CHECK(std::ranges::equal(witness.front(), stack.front()));
+ BOOST_CHECK(std::ranges::equal(witness.back(), stack.back()));
+ // Postfix increment advances the iterator, and returns where it was.
+ auto it = witness.begin();
+ BOOST_CHECK(std::ranges::equal(*it++, stack.front()));
+ BOOST_CHECK_EQUAL(std::distance(it, witness.end()), (std::ptrdiff_t)stack.size() - 1);
+ for (size_t i = 0; i < stack.size(); ++i) BOOST_CHECK(std::ranges::equal(witness[i], stack[i]));
+ }
+ // Iterating over the witness yields its elements, in order.
+ BOOST_CHECK(std::ranges::equal(witness, stack, [](auto a, const auto& b) { return std::ranges::equal(a, b); }));
+
+ // Serialization matches that of the vector of vectors, in both directions.
+ std::vector<unsigned char> ser_vec, ser_wit;
+ VectorWriter{ser_vec, 0, stack};
+ VectorWriter{ser_wit, 0, witness};
+ BOOST_CHECK(ser_vec == ser_wit);
+ BOOST_CHECK_EQUAL(::GetSerializeSize(witness), ser_vec.size());
+ // Deserialize into a non-empty witness, to check that the stack that was there is replaced.
+ CScriptWitness deser{{{0xff}}};
+ SpanReader{ser_vec} >> deser;
+ BOOST_CHECK(deser == witness);
+ if (!stack.empty()) BOOST_CHECK(std::ranges::equal(deser.back(), stack.back()));
+
+ // Moving leaves the source empty.
+ CScriptWitness moved{std::move(deser)};
+ BOOST_CHECK(moved == witness);
+ BOOST_CHECK(deser.empty() && deser.size() == 0 && deser.begin() == deser.end()); // NOLINT(bugprone-use-after-move)
+
+ // Self-assignment (through a reference, as compilers warn about a literal one) changes nothing.
+ CScriptWitness copy{witness};
+ const auto& alias = copy;
+ copy = alias;
+ BOOST_CHECK(copy == witness);
+
+ // Copy and move assignment replace the stack that was there.
+ CScriptWitness assigned{{{0xff}}};
+ assigned = copy;
+ copy = {};
+ BOOST_CHECK(copy.empty());
+ BOOST_CHECK(copy.begin() == copy.end());
+ BOOST_CHECK(assigned == witness);
+
+ CScriptWitness move_assigned{{{0xff}}};
+ move_assigned = std::move(assigned);
+ BOOST_CHECK(move_assigned == witness);
+ BOOST_CHECK(assigned.empty() && assigned.begin() == assigned.end()); // NOLINT(bugprone-use-after-move)
+ if (!stack.empty()) BOOST_CHECK(std::ranges::equal(move_assigned.back(), stack.back()));
+ }
+ }
+}
+
+BOOST_AUTO_TEST_CASE(script_witness_large_count)
+{
+ // Element counts on both sides of the boundary between the 3-byte and 5-byte CompactSize encodings. Elements are
+ // small, and only a few are accessed by index, as indexing may take time linear in the index.
+ for (const size_t count : {size_t{0xffff}, size_t{0x10000}}) {
+ std::vector<std::vector<unsigned char>> stack(count);
+ for (auto& element : stack) element = m_rng.randbytes(m_rng.randrange(3));
+ const CScriptWitness witness{stack};
+
+ BOOST_CHECK_EQUAL(witness.size(), count);
+ BOOST_CHECK_EQUAL(std::distance(witness.begin(), witness.end()), (std::ptrdiff_t)count);
+ BOOST_CHECK(witness.ToVectors() == stack);
+ BOOST_CHECK(std::ranges::equal(witness.front(), stack.front()));
+ BOOST_CHECK(std::ranges::equal(witness.back(), stack.back()));
+ for (const size_t i : {size_t{1}, count / 2, count - 2}) BOOST_CHECK(std::ranges::equal(witness[i], stack[i]));
+
+ std::vector<unsigned char> ser_vec, ser_wit;
+ VectorWriter{ser_vec, 0, stack};
+ VectorWriter{ser_wit, 0, witness};
+ BOOST_CHECK(ser_vec == ser_wit);
+ // The count is encoded as 0xfd followed by 2 bytes, or 0xfe followed by 4.
+ BOOST_CHECK_EQUAL(int{ser_wit.at(0)}, count <= 0xffff ? 0xfd : 0xfe);
+ CScriptWitness deser;
+ SpanReader{ser_vec} >> deser;
+ BOOST_CHECK(deser == witness);
+ BOOST_CHECK_EQUAL(deser.size(), count);
+ BOOST_CHECK(std::ranges::equal(deser.back(), stack.back()));
+ }
+}
+
+BOOST_AUTO_TEST_CASE(script_witness_empty)
+{
+ // Every way of producing a witness without elements gives the same witness. A transaction is serialized with
+ // witness data exactly when one of its inputs has a non-empty witness, so this determines its wtxid and whether its
+ // serialization round-trips.
+ using Stack = std::vector<std::vector<unsigned char>>;
+ const std::vector<unsigned char> ser_empty{0x00};
+ const CScriptWitness from_default;
+ const CScriptWitness from_vector{Stack{}};
+ CScriptWitness from_deser{{{0x01}}};
+ SpanReader{ser_empty} >> from_deser;
+ CScriptWitness moved_from{{{0x01}}};
+ const CScriptWitness moved_to{std::move(moved_from)};
+ BOOST_CHECK_EQUAL(moved_to.size(), 1U);
+ CScriptWitness reset{{{0x01}}};
+ reset = {};
+ const CScriptWitness copied{from_default}; // NOLINT(performance-unnecessary-copy-initialization)
+ CScriptWitness copy_assigned{{{0x01}}};
+ copy_assigned = from_default;
+
+ const std::vector<const CScriptWitness*> empties{&from_default, &from_vector, &from_deser, &moved_from, &reset, &copied, ©_assigned}; // NOLINT(bugprone-use-after-move)
+ for (const CScriptWitness* witness : empties) {
+ BOOST_CHECK(witness->empty());
+ BOOST_CHECK_EQUAL(witness->size(), 0U);
+ BOOST_CHECK(witness->begin() == witness->end());
+ BOOST_CHECK(witness->ToVectors().empty());
+ BOOST_CHECK(*witness == from_default);
+ std::vector<unsigned char> ser;
+ VectorWriter{ser, 0, *witness};
+ BOOST_CHECK(ser == ser_empty);
+ CMutableTransaction tx;
+ tx.vin.resize(1);
+ tx.vin[0].scriptWitness = *witness;
+ BOOST_CHECK(!tx.HasWitness());
+ }
+
+ // A single empty element is a different stack.
+ const CScriptWitness one_empty{Stack(1)};
+ BOOST_CHECK(!one_empty.empty());
+ BOOST_CHECK_EQUAL(one_empty.size(), 1U);
+ BOOST_CHECK(one_empty.back().empty());
+ BOOST_CHECK(one_empty != from_default);
+ std::vector<unsigned char> ser;
+ VectorWriter{ser, 0, one_empty};
+ BOOST_CHECK(ser == (std::vector<unsigned char>{0x01, 0x00}));
+ CScriptWitness deser;
+ SpanReader{ser} >> deser;
+ BOOST_CHECK(deser == one_empty);
+ CMutableTransaction tx;
+ tx.vin.resize(1);
+ tx.vin[0].scriptWitness = one_empty;
+ BOOST_CHECK(tx.HasWitness());
+}
+
+BOOST_AUTO_TEST_CASE(script_witness_to_string)
+{
+ // Elements are shown in hex, separated by commas, with nothing for an empty element.
+ BOOST_CHECK_EQUAL(CScriptWitness{}.ToString(), "CScriptWitness()");
+ BOOST_CHECK_EQUAL(CScriptWitness{{{0xaa}}}.ToString(), "CScriptWitness(aa)");
+ const CScriptWitness with_empty{{{}, {0xbb, 0xcc}, {}}};
+ BOOST_CHECK_EQUAL(with_empty.ToString(), "CScriptWitness(, bbcc, )");
+}
+
+BOOST_AUTO_TEST_CASE(script_witness_large_element)
+{
+ // A stack constructed from vectors can have an element larger than MAX_SIZE, and its accessors work.
+ std::vector<std::vector<unsigned char>> stack(2);
+ stack[0].resize(MAX_SIZE + 1);
+ stack[1] = {0x01};
+ const CScriptWitness witness{stack};
+ BOOST_CHECK_EQUAL(witness.size(), 2U);
+ BOOST_CHECK(std::ranges::equal(witness.front(), stack.front()));
+ BOOST_CHECK(std::ranges::equal(witness.back(), stack.back()));
+ BOOST_CHECK_EQUAL(std::distance(witness.begin(), witness.end()), 2);
+
+ // Deserialization does not accept such an element. It fails on the size, so the element itself is left out here.
+ DataStream stream;
+ WriteCompactSize(stream, 1);
+ WriteCompactSize(stream, MAX_SIZE + 1);
+ CScriptWitness deser;
+ BOOST_CHECK_EXCEPTION(stream >> deser, std::ios_base::failure, HasReason{"ReadCompactSize(): size too large"});
+}
+
BOOST_AUTO_TEST_SUITE_END()
### src/test/sigopcount_tests.cpp
@@ -158,9 +158,7 @@ BOOST_AUTO_TEST_CASE(GetTxSigOpCost)
{
CScript scriptPubKey = GetScriptForDestination(WitnessV0KeyHash(pubkey));
CScript scriptSig = CScript();
- CScriptWitness scriptWitness;
- scriptWitness.stack.emplace_back(0);
- scriptWitness.stack.emplace_back(0);
+ CScriptWitness scriptWitness{{{}, {}}};
BuildTxs(spendingTx, coins, creationTx, scriptPubKey, scriptSig, scriptWitness);
@@ -187,9 +185,7 @@ BOOST_AUTO_TEST_CASE(GetTxSigOpCost)
CScript scriptSig = GetScriptForDestination(WitnessV0KeyHash(pubkey));
CScript scriptPubKey = GetScriptForDestination(ScriptHash(scriptSig));
scriptSig = CScript() << ToByteVector(scriptSig);
- CScriptWitness scriptWitness;
- scriptWitness.stack.emplace_back(0);
- scriptWitness.stack.emplace_back(0);
+ CScriptWitness scriptWitness{{{}, {}}};
BuildTxs(spendingTx, coins, creationTx, scriptPubKey, scriptSig, scriptWitness);
assert(GetTransactionSigOpCost(CTransaction(spendingTx), coins, flags) == 1);
@@ -201,10 +197,7 @@ BOOST_AUTO_TEST_CASE(GetTxSigOpCost)
CScript witnessScript = CScript() << 1 << ToByteVector(pubkey) << ToByteVector(pubkey) << 2 << OP_CHECKMULTISIGVERIFY;
CScript scriptPubKey = GetScriptForDestination(WitnessV0ScriptHash(witnessScript));
CScript scriptSig = CScript();
- CScriptWitness scriptWitness;
- scriptWitness.stack.emplace_back(0);
- scriptWitness.stack.emplace_back(0);
- scriptWitness.stack.emplace_back(witnessScript.begin(), witnessScript.end());
+ CScriptWitness scriptWitness{{{}, {}, ToByteVector(witnessScript)}};
BuildTxs(spendingTx, coins, creationTx, scriptPubKey, scriptSig, scriptWitness);
assert(GetTransactionSigOpCost(CTransaction(spendingTx), coins, flags) == 2);
@@ -218,10 +211,7 @@ BOOST_AUTO_TEST_CASE(GetTxSigOpCost)
CScript redeemScript = GetScriptForDestination(WitnessV0ScriptHash(witnessScript));
CScript scriptPubKey = GetScriptForDestination(ScriptHash(redeemScript));
CScript scriptSig = CScript() << ToByteVector(redeemScript);
- CScriptWitness scriptWitness;
- scriptWitness.stack.emplace_back(0);
- scriptWitness.stack.emplace_back(0);
- scriptWitness.stack.emplace_back(witnessScript.begin(), witnessScript.end());
+ CScriptWitness scriptWitness{{{}, {}, ToByteVector(witnessScript)}};
BuildTxs(spendingTx, coins, creationTx, scriptPubKey, scriptSig, scriptWitness);
assert(GetTransactionSigOpCost(CTransaction(spendingTx), coins, flags) == 2);
### src/test/span_tests.cpp
@@ -59,4 +59,21 @@ BOOST_AUTO_TEST_CASE(span_constructor_sfinae)
BOOST_CHECK(!Spannable(SpannableNo{}));
}
+BOOST_AUTO_TEST_CASE(same_span)
+{
+ const std::vector<int> a{1, 2, 3}, b{1, 2, 3};
+ const std::span<const int> span_a{a}, span_b{b};
+ // Spans over the same memory are the same, but spans over equal contents elsewhere are not.
+ BOOST_CHECK(SameSpan(span_a, std::span<const int>{a}));
+ BOOST_CHECK(!SameSpan(span_a, span_b));
+ // Both the start and the size matter.
+ BOOST_CHECK(!SameSpan(span_a, span_a.first(2)));
+ BOOST_CHECK(!SameSpan(span_a.first(2), span_a.last(2)));
+ BOOST_CHECK(SameSpan(span_a.subspan(1), span_a.last(2)));
+ // Empty spans are the same only if they are in the same place.
+ BOOST_CHECK(SameSpan(span_a.first(0), span_a.first(0)));
+ BOOST_CHECK(!SameSpan(span_a.first(0), span_a.last(0)));
+ BOOST_CHECK(SameSpan(std::span<const int>{}, std::span<const int>{}));
+}
+
BOOST_AUTO_TEST_SUITE_END()
### src/test/transaction_tests.cpp
@@ -449,7 +449,7 @@ static void CreateCreditAndSpend(const FillableSigningProvider& keystore, const
assert(input.vin[0] == inputm.vin[0]);
assert(input.vout.size() == 1);
assert(input.vout[0] == inputm.vout[0]);
- assert(input.vin[0].scriptWitness.stack == inputm.vin[0].scriptWitness.stack);
+ assert(input.vin[0].scriptWitness == inputm.vin[0].scriptWitness);
}
static void CheckWithFlag(const CTransactionRef& output, const CMutableTransaction& input, script_verify_flags flags, bool success)
@@ -1410,7 +1410,7 @@ BOOST_AUTO_TEST_CASE(tx_malformed_serialization)
// A transaction with one input, one output and a one-element witness.
CMutableTransaction mtx;
mtx.vin.resize(1);
- mtx.vin[0].scriptWitness.stack = {{0xaa}};
+ mtx.vin[0].scriptWitness = CScriptWitness{{{0xaa}}};
mtx.vout.emplace_back(1, CScript{} << OP_TRUE);
DataStream ser;
ser << TX_WITH_WITNESS(mtx);
@@ -1427,7 +1427,7 @@ BOOST_AUTO_TEST_CASE(tx_malformed_serialization)
// A flag other than 1 is unknown, including one without the witness bit.
DataStream bad_flag;
- bad_flag << mtx.version << uint8_t{0x00} << uint8_t{0x02} << mtx.vin << mtx.vout << mtx.vin[0].scriptWitness.stack << mtx.nLockTime;
+ bad_flag << mtx.version << uint8_t{0x00} << uint8_t{0x02} << mtx.vin << mtx.vout << mtx.vin[0].scriptWitness << mtx.nLockTime;
BOOST_CHECK_EXCEPTION(bad_flag >> TX_WITH_WITNESS(tx), std::ios_base::failure, HasReason{"Unknown transaction optional data"});
}
### src/test/txdownload_tests.cpp
@@ -104,7 +104,7 @@ static CTransactionRef CreatePlaceholderTx(bool segwit)
CMutableTransaction mtx;
mtx.vin.emplace_back(prevout_hash, 0);
// This makes txid != wtxid
- if (segwit) mtx.vin[0].scriptWitness.stack.push_back({1});
+ if (segwit) mtx.vin[0].scriptWitness = CScriptWitness{{{1}}};
mtx.vout.emplace_back(CENT, CScript());
auto ptx = MakeTransactionRef(mtx);
prevout_hash = ptx->GetHash();
### src/test/txpackage_tests.cpp
@@ -419,8 +419,7 @@ BOOST_AUTO_TEST_CASE(package_submission_tests)
// Parent and child package where transactions are invalid for reasons other than fee and
// missing inputs, so the package validation isn't expected to happen.
{
- CScriptWitness bad_witness;
- bad_witness.stack.emplace_back(1);
+ CScriptWitness bad_witness{{std::vector<unsigned char>(1)}};
CMutableTransaction mtx_parent_invalid{mtx_parent};
mtx_parent_invalid.vin[0].scriptWitness = bad_witness;
CTransactionRef tx_parent_invalid = MakeTransactionRef(mtx_parent_invalid);
@@ -644,13 +643,9 @@ BOOST_AUTO_TEST_CASE(package_witness_swap_tests)
CTransactionRef ptx_parent = MakeTransactionRef(mtx_parent);
// Make two children with the same txid but different witnesses.
- CScriptWitness witness1;
- witness1.stack.emplace_back(1);
- witness1.stack.emplace_back(witnessScript.begin(), witnessScript.end());
+ CScriptWitness witness1{{std::vector<unsigned char>(1), ToByteVector(witnessScript)}};
- CScriptWitness witness2(witness1);
- witness2.stack.emplace_back(2);
- witness2.stack.emplace_back(witnessScript.begin(), witnessScript.end());
+ CScriptWitness witness2{{std::vector<unsigned char>(1), ToByteVector(witnessScript), std::vector<unsigned char>(2), ToByteVector(witnessScript)}};
CKey child_key = GenerateRandomKey();
CScript child_locking_script = GetScriptForDestination(WitnessV0KeyHash(child_key.GetPubKey()));
@@ -753,8 +748,7 @@ BOOST_AUTO_TEST_CASE(package_witness_swap_tests)
// Give all the parents anyone-can-spend scripts so we don't have to deal with signing the child.
CScript acs_script = CScript() << OP_TRUE;
CScript acs_spk = GetScriptForDestination(WitnessV0ScriptHash(acs_script));
- CScriptWitness acs_witness;
- acs_witness.stack.emplace_back(acs_script.begin(), acs_script.end());
+ CScriptWitness acs_witness{{ToByteVector(acs_script)}};
// parent1 will already be in the mempool
auto mtx_parent1 = CreateValidMempoolTransaction(/*input_transaction=*/m_coinbase_txns[1], /*input_vout=*/0,
@@ -767,12 +761,8 @@ BOOST_AUTO_TEST_CASE(package_witness_swap_tests)
// parent2 will have a same-txid-different-witness tx already in the mempool
CScript grandparent2_script = CScript() << OP_DROP << OP_TRUE;
CScript grandparent2_spk = GetScriptForDestination(WitnessV0ScriptHash(grandparent2_script));
- CScriptWitness parent2_witness1;
- parent2_witness1.stack.emplace_back(1);
- parent2_witness1.stack.emplace_back(grandparent2_script.begin(), grandparent2_script.end());
- CScriptWitness parent2_witness2;
- parent2_witness2.stack.emplace_back(2);
- parent2_witness2.stack.emplace_back(grandparent2_script.begin(), grandparent2_script.end());
+ CScriptWitness parent2_witness1{{std::vector<unsigned char>(1), ToByteVector(grandparent2_script)}};
+ CScriptWitness parent2_witness2{{std::vector<unsigned char>(2), ToByteVector(grandparent2_script)}};
// Create grandparent2 creating an output with multiple spending paths. Submit to mempool.
auto mtx_grandparent2 = CreateValidMempoolTransaction(/*input_transaction=*/m_coinbase_txns[2], /*input_vout=*/0,
### src/test/txvalidation_tests.cpp
@@ -468,7 +468,7 @@ BOOST_FIXTURE_TEST_CASE(version3_tests, RegTestingSetup)
mtx_many_sigops.version = TRUC_VERSION;
for (const auto& outpoint : multisig_outpoints) {
mtx_many_sigops.vin.emplace_back(outpoint);
- mtx_many_sigops.vin.back().scriptWitness.stack.emplace_back(script_multisig.begin(), script_multisig.end());
+ mtx_many_sigops.vin.back().scriptWitness = CScriptWitness{{ToByteVector(script_multisig)}};
}
mtx_many_sigops.vout.resize(1);
mtx_many_sigops.vout.back().scriptPubKey = CScript() << OP_TRUE;
### src/test/txvalidationcache_tests.cpp
@@ -313,7 +313,7 @@ BOOST_FIXTURE_TEST_CASE(checkinputs_test, Dersig100Setup)
ValidateCheckInputsForAllFlags(CTransaction(valid_with_witness_tx), 0, true, m_node.chainman->ActiveChainstate().CoinsTip(), m_node.chainman->m_validation_cache);
// Remove the witness, and check that it is now invalid.
- valid_with_witness_tx.vin[0].scriptWitness.SetNull();
+ valid_with_witness_tx.vin[0].scriptWitness = {};
ValidateCheckInputsForAllFlags(CTransaction(valid_with_witness_tx), SCRIPT_VERIFY_WITNESS, true, m_node.chainman->ActiveChainstate().CoinsTip(), m_node.chainman->m_validation_cache);
}
@@ -331,13 +331,15 @@ BOOST_FIXTURE_TEST_CASE(checkinputs_test, Dersig100Setup)
};
std::map<int, bilingual_str> input_errors;
BOOST_REQUIRE(SignTransaction(tr_tx, &tr_keystore, coins, {.sighash_type = SIGHASH_DEFAULT}, input_errors));
- auto& witness_stack = tr_tx.vin[0].scriptWitness.stack;
+ auto witness_stack = tr_tx.vin[0].scriptWitness.ToVectors();
BOOST_REQUIRE(witness_stack.size() == 1 && witness_stack[0].size() == 64);
// Invalidate signature; an invalid Taproot key-path spend is only invalid if SCRIPT_VERIFY_TAPROOT is set
witness_stack[0][63] ^= 0x01; // damage signature
+ tr_tx.vin[0].scriptWitness = CScriptWitness{witness_stack};
ValidateCheckInputsForAllFlags(CTransaction(tr_tx), SCRIPT_VERIFY_TAPROOT, true, m_node.chainman->ActiveChainstate().CoinsTip(), m_node.chainman->m_validation_cache);
witness_stack[0][63] ^= 0x01; // repair signature
+ tr_tx.vin[0].scriptWitness = CScriptWitness{witness_stack};
// A valid Taproot key-path spend is valid under all flags
ValidateCheckInputsForAllFlags(CTransaction(tr_tx), 0, true, m_node.chainman->ActiveChainstate().CoinsTip(), m_node.chainman->m_validation_cache);
@@ -367,7 +369,7 @@ BOOST_FIXTURE_TEST_CASE(checkinputs_test, Dersig100Setup)
// Check that if the second input is invalid, but the first input is
// valid, the transaction is not cached.
// Invalidate vin[1]
- tx.vin[1].scriptWitness.SetNull();
+ tx.vin[1].scriptWitness = {};
TxValidationState state;
PrecomputedTransactionData txdata;
### src/test/validation_block_tests.cpp
@@ -105,7 +105,7 @@ std::shared_ptr<CBlock> MinerTestingSetup::Block(const uint256& prev_hash)
txCoinbase.vout[1].scriptPubKey = P2WSH_OP_TRUE;
txCoinbase.vout[1].nValue = txCoinbase.vout[0].nValue;
txCoinbase.vout[0].nValue = 0;
- txCoinbase.vin[0].scriptWitness.SetNull();
+ txCoinbase.vin[0].scriptWitness = {};
pblock->vtx[0] = MakeTransactionRef(std::move(txCoinbase));
return pblock;
@@ -272,7 +272,7 @@ BOOST_AUTO_TEST_CASE(mempool_locks_reorg)
for (int num_txs = 22; num_txs > 0; --num_txs) {
CMutableTransaction mtx;
mtx.vin.emplace_back(COutPoint{last_mined->vtx[0]->GetHash(), 1}, CScript{});
- mtx.vin[0].scriptWitness.stack.push_back(WITNESS_STACK_ELEM_OP_TRUE);
+ mtx.vin[0].scriptWitness = CScriptWitness{{WITNESS_STACK_ELEM_OP_TRUE}};
mtx.vout.push_back(last_mined->vtx[0]->vout[1]);
mtx.vout[0].nValue -= 1000;
txs.push_back(MakeTransactionRef(mtx));
### src/test/validation_tests.cpp
@@ -175,8 +175,7 @@ BOOST_AUTO_TEST_CASE(block_malleation)
CMutableTransaction coinbase;
coinbase.vin.resize(1);
if (include_witness) {
- coinbase.vin[0].scriptWitness.stack.resize(1);
- coinbase.vin[0].scriptWitness.stack[0] = std::vector<unsigned char>(32, 0x00);
+ coinbase.vin[0].scriptWitness = CScriptWitness{{std::vector<unsigned char>(32, 0x00)}};
}
coinbase.vout.resize(1);
@@ -312,8 +311,7 @@ BOOST_AUTO_TEST_CASE(block_malleation)
{
CMutableTransaction mtx;
mtx.vin.resize(1);
- mtx.vin[0].scriptWitness.stack.resize(1);
- mtx.vin[0].scriptWitness.stack[0] = {0};
+ mtx.vin[0].scriptWitness = CScriptWitness{{{0}}};
block.vtx.push_back(MakeTransactionRef(mtx));
}
block.hashMerkleRoot = BlockMerkleRoot(block);
@@ -334,8 +332,10 @@ BOOST_AUTO_TEST_CASE(block_malleation)
// Malleating witnesses should be caught by `IsBlockMutated`.
{
CMutableTransaction mtx{*block.vtx[1]};
- assert(!mtx.vin[0].scriptWitness.stack[0].empty());
- ++mtx.vin[0].scriptWitness.stack[0][0];
+ assert(!mtx.vin[0].scriptWitness[0].empty());
+ auto stack = mtx.vin[0].scriptWitness.ToVectors();
+ ++stack[0][0];
+ mtx.vin[0].scriptWitness = CScriptWitness{stack};
block.vtx[1] = MakeTransactionRef(mtx);
}
// Without also updating the witness commitment, the merkle root should
@@ -352,7 +352,7 @@ BOOST_AUTO_TEST_CASE(block_malleation)
// Test malleating the coinbase witness reserved value
{
CMutableTransaction mtx{*block.vtx[0]};
- mtx.vin[0].scriptWitness.stack.resize(0);
+ mtx.vin[0].scriptWitness = {};
block.vtx[0] = MakeTransactionRef(mtx);
block.hashMerkleRoot = BlockMerkleRoot(block);
}
### src/validation.cpp
@@ -3963,7 +3963,7 @@ static bool CheckWitnessMalleation(const CBlock& block, bool expect_witness_comm
int commitpos = GetWitnessCommitmentIndex(block);
if (commitpos != NO_WITNESS_COMMITMENT) {
assert(!block.vtx.empty() && !block.vtx[0]->vin.empty());
- const auto& witness_stack{block.vtx[0]->vin[0].scriptWitness.stack};
+ const auto& witness_stack{block.vtx[0]->vin[0].scriptWitness};
if (witness_stack.size() != 1 || witness_stack[0].size() != 32) {
return state.Invalid(
@@ -4076,8 +4076,8 @@ void ChainstateManager::UpdateUncommittedBlockStructures(CBlock& block, const CB
static const std::vector<unsigned char> nonce(32, 0x00);
if (commitpos != NO_WITNESS_COMMITMENT && DeploymentActiveAfter(pindexPrev, *this, Consensus::DEPLOYMENT_SEGWIT) && !block.vtx[0]->HasWitness()) {
CMutableTransaction tx(*block.vtx[0]);
- tx.vin[0].scriptWitness.stack.resize(1);
- tx.vin[0].scriptWitness.stack[0] = nonce;
+ // The coinbase witness consists of just the witness reserved value.
+ tx.vin[0].scriptWitness = CScriptWitness{{nonce}};
block.vtx[0] = MakeTransactionRef(std::move(tx));
}
}
### src/wallet/feebumper.cpp
@@ -292,7 +292,7 @@ Result CreateRateBumpTransaction(CWallet& wallet, const Txid& txid, const CCoinC
CMutableTransaction temp_mtx{*tx};
for (auto& txin : temp_mtx.vin) {
txin.scriptSig.clear();
- txin.scriptWitness.SetNull();
+ txin.scriptWitness = {};
}
temp_mtx.vout = txouts;
const int64_t maxTxSize{CalculateMaximumSignedTxSize(CTransaction(temp_mtx), &wallet, &new_coin_control).vsize};
### src/wallet/test/feebumper_tests.cpp
@@ -23,9 +23,12 @@ static void CheckMaxWeightComputation(const std::string& script_str, const std::
CScript script(script_data.begin(), script_data.end());
CTxIn input(Txid{}, 0, script);
+ std::vector<std::vector<unsigned char>> stack;
+ stack.reserve(witness_str_stack.size());
for (const auto& s : witness_str_stack) {
- input.scriptWitness.stack.push_back(ParseHex(s));
+ stack.push_back(ParseHex(s));
}
+ input.scriptWitness = CScriptWitness{stack};
std::vector prevout_script_data(ParseHex(prevout_script_str));
CScript prevout_script(prevout_script_data.begin(), prevout_script_data.end());
### src/wallet/test/fuzz/coincontrol.cpp
@@ -131,8 +131,8 @@ FUZZ_TARGET(coincontrol, .init = initialize_coincontrol)
const CScriptWitness script_wit{ConsumeScriptWitness(fuzzed_data_provider)};
input.SetScriptWitness(script_wit);
assert(input.HasScripts());
- assert(input.GetScripts().second->stack == script_wit.stack);
- assert(coin_control.GetScripts(out_point).second->stack == script_wit.stack);
+ assert(*input.GetScripts().second == script_wit);
+ assert(*coin_control.GetScripts(out_point).second == script_wit);
},
[&] {
auto& input = coin_control.Select(out_point);
### src/wallet/wallet.cpp
@@ -688,7 +688,7 @@ std::set<CWalletTx*, WalletTxOrderComparator> CWallet::GetMalleatedVariants(cons
if (wtx.IsCoinBase()) return txs;
// Only transactions that have non-witness inputs can be malleated
- if (std::ranges::none_of(wtx.GetTx()->vin, [](const CTxIn& in) { return in.scriptWitness.IsNull(); })) {
+ if (std::ranges::none_of(wtx.GetTx()->vin, [](const CTxIn& in) { return in.scriptWitness.empty(); })) {
return txs;
}
Why this scored 58/100
Community notes
Notes can correct, qualify, or add evidence to the AI analysis. Every note shown here has been validated by a human moderator.
The AI analysis stands alone for now. Submit a note if you can add evidence or important context.