Skip to content

Commit 5d9f450

Browse files
committed
Merge bitcoin#28758: refactors for subpackage evaluation
b5a60ab MOVEONLY: CleanupTemporaryCoins into its own function (glozow) 10c0a86 [test util] CreateValidTransaction multi-in/out, configurable feerate, signal BIP125 (glozow) 6ff647a scripted-diff: rename CheckPackage to IsWellFormedPackage (glozow) da9aceb [refactor] move package checks into helper functions (glozow) Pull request description: This is part of bitcoin#27463. It splits off the more trivial changes from bitcoin#26711 for ease of review, as requested in bitcoin#26711 (comment). - Split package sanitization in policy/packages.h into helper functions - Add some tests for its quirks (bitcoin#26711 (comment)) - Rename `CheckPackage` to `IsPackageWellFormed` - Improve the `CreateValidTransaction` unit test utility to: - Configure the target feerate and return the fee paid - Signal BIP125 on transactions to enable RBF tests - Allow the specification of multiple inputs and outputs - Move `CleanupTemporaryCoins` into its own function to be reused later without duplication ACKs for top commit: dergoegge: Code review ACK b5a60ab instagibbs: ACK b5a60ab Tree-SHA512: 39d67a5f0041e381f0d0f802a98ccffbff11e44daa3a49611189d6306b03f18613d5ff16c618898d490c97a216753e99e0db231ff14d327f92c17ae4d269cfec
2 parents f23ac10 + b5a60ab commit 5d9f450

File tree

6 files changed

+281
-86
lines changed

6 files changed

+281
-86
lines changed

src/policy/packages.cpp

Lines changed: 72 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -6,16 +6,77 @@
66
#include <policy/policy.h>
77
#include <primitives/transaction.h>
88
#include <uint256.h>
9-
#include <util/hasher.h>
9+
#include <util/check.h>
1010

1111
#include <algorithm>
1212
#include <cassert>
1313
#include <iterator>
1414
#include <memory>
1515
#include <numeric>
16-
#include <unordered_set>
1716

18-
bool CheckPackage(const Package& txns, PackageValidationState& state)
17+
/** IsTopoSortedPackage where a set of txids has been pre-populated. The set is assumed to be correct and
18+
* is mutated within this function (even if return value is false). */
19+
bool IsTopoSortedPackage(const Package& txns, std::unordered_set<uint256, SaltedTxidHasher>& later_txids)
20+
{
21+
// Avoid misusing this function: later_txids should contain the txids of txns.
22+
Assume(txns.size() == later_txids.size());
23+
24+
// later_txids always contains the txids of this transaction and the ones that come later in
25+
// txns. If any transaction's input spends a tx in that set, we've found a parent placed later
26+
// than its child.
27+
for (const auto& tx : txns) {
28+
for (const auto& input : tx->vin) {
29+
if (later_txids.find(input.prevout.hash) != later_txids.end()) {
30+
// The parent is a subsequent transaction in the package.
31+
return false;
32+
}
33+
}
34+
// Avoid misusing this function: later_txids must contain every tx.
35+
Assume(later_txids.erase(tx->GetHash()) == 1);
36+
}
37+
38+
// Avoid misusing this function: later_txids should have contained the txids of txns.
39+
Assume(later_txids.empty());
40+
return true;
41+
}
42+
43+
bool IsTopoSortedPackage(const Package& txns)
44+
{
45+
std::unordered_set<uint256, SaltedTxidHasher> later_txids;
46+
std::transform(txns.cbegin(), txns.cend(), std::inserter(later_txids, later_txids.end()),
47+
[](const auto& tx) { return tx->GetHash(); });
48+
49+
return IsTopoSortedPackage(txns, later_txids);
50+
}
51+
52+
bool IsConsistentPackage(const Package& txns)
53+
{
54+
// Don't allow any conflicting transactions, i.e. spending the same inputs, in a package.
55+
std::unordered_set<COutPoint, SaltedOutpointHasher> inputs_seen;
56+
for (const auto& tx : txns) {
57+
if (tx->vin.empty()) {
58+
// This function checks consistency based on inputs, and we can't do that if there are
59+
// no inputs. Duplicate empty transactions are also not consistent with one another.
60+
// This doesn't create false negatives, as unconfirmed transactions are not allowed to
61+
// have no inputs.
62+
return false;
63+
}
64+
for (const auto& input : tx->vin) {
65+
if (inputs_seen.find(input.prevout) != inputs_seen.end()) {
66+
// This input is also present in another tx in the package.
67+
return false;
68+
}
69+
}
70+
// Batch-add all the inputs for a tx at a time. If we added them 1 at a time, we could
71+
// catch duplicate inputs within a single tx. This is a more severe, consensus error,
72+
// and we want to report that from CheckTransaction instead.
73+
std::transform(tx->vin.cbegin(), tx->vin.cend(), std::inserter(inputs_seen, inputs_seen.end()),
74+
[](const auto& input) { return input.prevout; });
75+
}
76+
return true;
77+
}
78+
79+
bool IsWellFormedPackage(const Package& txns, PackageValidationState& state, bool require_sorted)
1980
{
2081
const unsigned int package_count = txns.size();
2182

@@ -30,10 +91,6 @@ bool CheckPackage(const Package& txns, PackageValidationState& state)
3091
return state.Invalid(PackageValidationResult::PCKG_POLICY, "package-too-large");
3192
}
3293

33-
// Require the package to be sorted in order of dependency, i.e. parents appear before children.
34-
// An unsorted package will fail anyway on missing-inputs, but it's better to quit earlier and
35-
// fail on something less ambiguous (missing-inputs could also be an orphan or trying to
36-
// spend nonexistent coins).
3794
std::unordered_set<uint256, SaltedTxidHasher> later_txids;
3895
std::transform(txns.cbegin(), txns.cend(), std::inserter(later_txids, later_txids.end()),
3996
[](const auto& tx) { return tx->GetHash(); });
@@ -44,30 +101,17 @@ bool CheckPackage(const Package& txns, PackageValidationState& state)
44101
return state.Invalid(PackageValidationResult::PCKG_POLICY, "package-contains-duplicates");
45102
}
46103

47-
for (const auto& tx : txns) {
48-
for (const auto& input : tx->vin) {
49-
if (later_txids.find(input.prevout.hash) != later_txids.end()) {
50-
// The parent is a subsequent transaction in the package.
51-
return state.Invalid(PackageValidationResult::PCKG_POLICY, "package-not-sorted");
52-
}
53-
}
54-
later_txids.erase(tx->GetHash());
104+
// Require the package to be sorted in order of dependency, i.e. parents appear before children.
105+
// An unsorted package will fail anyway on missing-inputs, but it's better to quit earlier and
106+
// fail on something less ambiguous (missing-inputs could also be an orphan or trying to
107+
// spend nonexistent coins).
108+
if (require_sorted && !IsTopoSortedPackage(txns, later_txids)) {
109+
return state.Invalid(PackageValidationResult::PCKG_POLICY, "package-not-sorted");
55110
}
56111

57112
// Don't allow any conflicting transactions, i.e. spending the same inputs, in a package.
58-
std::unordered_set<COutPoint, SaltedOutpointHasher> inputs_seen;
59-
for (const auto& tx : txns) {
60-
for (const auto& input : tx->vin) {
61-
if (inputs_seen.find(input.prevout) != inputs_seen.end()) {
62-
// This input is also present in another tx in the package.
63-
return state.Invalid(PackageValidationResult::PCKG_POLICY, "conflict-in-package");
64-
}
65-
}
66-
// Batch-add all the inputs for a tx at a time. If we added them 1 at a time, we could
67-
// catch duplicate inputs within a single tx. This is a more severe, consensus error,
68-
// and we want to report that from CheckTransaction instead.
69-
std::transform(tx->vin.cbegin(), tx->vin.cend(), std::inserter(inputs_seen, inputs_seen.end()),
70-
[](const auto& input) { return input.prevout; });
113+
if (!IsConsistentPackage(txns)) {
114+
return state.Invalid(PackageValidationResult::PCKG_POLICY, "conflict-in-package");
71115
}
72116
return true;
73117
}

src/policy/packages.h

Lines changed: 22 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,8 +9,10 @@
99
#include <consensus/validation.h>
1010
#include <policy/policy.h>
1111
#include <primitives/transaction.h>
12+
#include <util/hasher.h>
1213

1314
#include <cstdint>
15+
#include <unordered_set>
1416
#include <vector>
1517

1618
/** Default maximum number of transactions in a package. */
@@ -49,13 +51,32 @@ using Package = std::vector<CTransactionRef>;
4951

5052
class PackageValidationState : public ValidationState<PackageValidationResult> {};
5153

54+
/** If any direct dependencies exist between transactions (i.e. a child spending the output of a
55+
* parent), checks that all parents appear somewhere in the list before their respective children.
56+
* No other ordering is enforced. This function cannot detect indirect dependencies (e.g. a
57+
* transaction's grandparent if its parent is not present).
58+
* @returns true if sorted. False if any tx spends the output of a tx that appears later in txns.
59+
*/
60+
bool IsTopoSortedPackage(const Package& txns);
61+
62+
/** Checks that these transactions don't conflict, i.e., spend the same prevout. This includes
63+
* checking that there are no duplicate transactions. Since these checks require looking at the inputs
64+
* of a transaction, returns false immediately if any transactions have empty vin.
65+
*
66+
* Does not check consistency of a transaction with oneself; does not check if a transaction spends
67+
* the same prevout multiple times (see bad-txns-inputs-duplicate in CheckTransaction()).
68+
*
69+
* @returns true if there are no conflicts. False if any two transactions spend the same prevout.
70+
* */
71+
bool IsConsistentPackage(const Package& txns);
72+
5273
/** Context-free package policy checks:
5374
* 1. The number of transactions cannot exceed MAX_PACKAGE_COUNT.
5475
* 2. The total weight cannot exceed MAX_PACKAGE_WEIGHT.
5576
* 3. If any dependencies exist between transactions, parents must appear before children.
5677
* 4. Transactions cannot conflict, i.e., spend the same inputs.
5778
*/
58-
bool CheckPackage(const Package& txns, PackageValidationState& state);
79+
bool IsWellFormedPackage(const Package& txns, PackageValidationState& state, bool require_sorted);
5980

6081
/** Context-free check that a package is exactly one child and its parents; not all parents need to
6182
* be present, but the package must not contain any transactions that are not the child's parents.

src/test/txpackage_tests.cpp

Lines changed: 39 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99
#include <primitives/transaction.h>
1010
#include <script/script.h>
1111
#include <test/util/random.h>
12+
#include <test/util/script.h>
1213
#include <test/util/setup_common.h>
1314
#include <validation.h>
1415

@@ -47,7 +48,7 @@ BOOST_FIXTURE_TEST_CASE(package_sanitization_tests, TestChain100Setup)
4748
package_too_many.emplace_back(create_placeholder_tx(1, 1));
4849
}
4950
PackageValidationState state_too_many;
50-
BOOST_CHECK(!CheckPackage(package_too_many, state_too_many));
51+
BOOST_CHECK(!IsWellFormedPackage(package_too_many, state_too_many, /*require_sorted=*/true));
5152
BOOST_CHECK_EQUAL(state_too_many.GetResult(), PackageValidationResult::PCKG_POLICY);
5253
BOOST_CHECK_EQUAL(state_too_many.GetRejectReason(), "package-too-many-transactions");
5354

@@ -62,7 +63,7 @@ BOOST_FIXTURE_TEST_CASE(package_sanitization_tests, TestChain100Setup)
6263
}
6364
BOOST_CHECK(package_too_large.size() <= MAX_PACKAGE_COUNT);
6465
PackageValidationState state_too_large;
65-
BOOST_CHECK(!CheckPackage(package_too_large, state_too_large));
66+
BOOST_CHECK(!IsWellFormedPackage(package_too_large, state_too_large, /*require_sorted=*/true));
6667
BOOST_CHECK_EQUAL(state_too_large.GetResult(), PackageValidationResult::PCKG_POLICY);
6768
BOOST_CHECK_EQUAL(state_too_large.GetRejectReason(), "package-too-large");
6869

@@ -73,9 +74,39 @@ BOOST_FIXTURE_TEST_CASE(package_sanitization_tests, TestChain100Setup)
7374
package_duplicate_txids_empty.emplace_back(MakeTransactionRef(empty_tx));
7475
}
7576
PackageValidationState state_duplicates;
76-
BOOST_CHECK(!CheckPackage(package_duplicate_txids_empty, state_duplicates));
77+
BOOST_CHECK(!IsWellFormedPackage(package_duplicate_txids_empty, state_duplicates, /*require_sorted=*/true));
7778
BOOST_CHECK_EQUAL(state_duplicates.GetResult(), PackageValidationResult::PCKG_POLICY);
7879
BOOST_CHECK_EQUAL(state_duplicates.GetRejectReason(), "package-contains-duplicates");
80+
BOOST_CHECK(!IsConsistentPackage(package_duplicate_txids_empty));
81+
82+
// Packages can't have transactions spending the same prevout
83+
CMutableTransaction tx_zero_1;
84+
CMutableTransaction tx_zero_2;
85+
COutPoint same_prevout{InsecureRand256(), 0};
86+
tx_zero_1.vin.emplace_back(same_prevout);
87+
tx_zero_2.vin.emplace_back(same_prevout);
88+
// Different vouts (not the same tx)
89+
tx_zero_1.vout.emplace_back(CENT, P2WSH_OP_TRUE);
90+
tx_zero_2.vout.emplace_back(2 * CENT, P2WSH_OP_TRUE);
91+
Package package_conflicts{MakeTransactionRef(tx_zero_1), MakeTransactionRef(tx_zero_2)};
92+
BOOST_CHECK(!IsConsistentPackage(package_conflicts));
93+
// Transactions are considered sorted when they have no dependencies.
94+
BOOST_CHECK(IsTopoSortedPackage(package_conflicts));
95+
PackageValidationState state_conflicts;
96+
BOOST_CHECK(!IsWellFormedPackage(package_conflicts, state_conflicts, /*require_sorted=*/true));
97+
BOOST_CHECK_EQUAL(state_conflicts.GetResult(), PackageValidationResult::PCKG_POLICY);
98+
BOOST_CHECK_EQUAL(state_conflicts.GetRejectReason(), "conflict-in-package");
99+
100+
// IsConsistentPackage only cares about conflicts between transactions, not about a transaction
101+
// conflicting with itself (i.e. duplicate prevouts in vin).
102+
CMutableTransaction dup_tx;
103+
const COutPoint rand_prevout{InsecureRand256(), 0};
104+
dup_tx.vin.emplace_back(rand_prevout);
105+
dup_tx.vin.emplace_back(rand_prevout);
106+
Package package_with_dup_tx{MakeTransactionRef(dup_tx)};
107+
BOOST_CHECK(IsConsistentPackage(package_with_dup_tx));
108+
package_with_dup_tx.emplace_back(create_placeholder_tx(1, 1));
109+
BOOST_CHECK(IsConsistentPackage(package_with_dup_tx));
79110
}
80111

81112
BOOST_FIXTURE_TEST_CASE(package_validation_tests, TestChain100Setup)
@@ -157,8 +188,8 @@ BOOST_FIXTURE_TEST_CASE(noncontextual_package_tests, TestChain100Setup)
157188
CTransactionRef tx_child = MakeTransactionRef(mtx_child);
158189

159190
PackageValidationState state;
160-
BOOST_CHECK(CheckPackage({tx_parent, tx_child}, state));
161-
BOOST_CHECK(!CheckPackage({tx_child, tx_parent}, state));
191+
BOOST_CHECK(IsWellFormedPackage({tx_parent, tx_child}, state, /*require_sorted=*/true));
192+
BOOST_CHECK(!IsWellFormedPackage({tx_child, tx_parent}, state, /*require_sorted=*/true));
162193
BOOST_CHECK_EQUAL(state.GetResult(), PackageValidationResult::PCKG_POLICY);
163194
BOOST_CHECK_EQUAL(state.GetRejectReason(), "package-not-sorted");
164195
BOOST_CHECK(IsChildWithParents({tx_parent, tx_child}));
@@ -186,7 +217,7 @@ BOOST_FIXTURE_TEST_CASE(noncontextual_package_tests, TestChain100Setup)
186217
package.push_back(MakeTransactionRef(child));
187218

188219
PackageValidationState state;
189-
BOOST_CHECK(CheckPackage(package, state));
220+
BOOST_CHECK(IsWellFormedPackage(package, state, /*require_sorted=*/true));
190221
BOOST_CHECK(IsChildWithParents(package));
191222
BOOST_CHECK(IsChildWithParentsTree(package));
192223

@@ -224,8 +255,8 @@ BOOST_FIXTURE_TEST_CASE(noncontextual_package_tests, TestChain100Setup)
224255
BOOST_CHECK(!IsChildWithParentsTree({tx_parent, tx_parent_also_child, tx_child}));
225256
// IsChildWithParents does not detect unsorted parents.
226257
BOOST_CHECK(IsChildWithParents({tx_parent_also_child, tx_parent, tx_child}));
227-
BOOST_CHECK(CheckPackage({tx_parent, tx_parent_also_child, tx_child}, state));
228-
BOOST_CHECK(!CheckPackage({tx_parent_also_child, tx_parent, tx_child}, state));
258+
BOOST_CHECK(IsWellFormedPackage({tx_parent, tx_parent_also_child, tx_child}, state, /*require_sorted=*/true));
259+
BOOST_CHECK(!IsWellFormedPackage({tx_parent_also_child, tx_parent, tx_child}, state, /*require_sorted=*/true));
229260
BOOST_CHECK_EQUAL(state.GetResult(), PackageValidationResult::PCKG_POLICY);
230261
BOOST_CHECK_EQUAL(state.GetRejectReason(), "package-not-sorted");
231262
}

0 commit comments

Comments
 (0)