Merge bitcoin/bitcoin#33116: refactor: Convert uint256 to Txid

de0675f9de refactor: Move `transaction_identifier.h` to primitives (marcofleon)
6f068f65de Remove implicit uint256 conversion and comparison (marcofleon)
9c24cda72e refactor: Convert remaining instances from uint256 to Txid (marcofleon)
d2ecd6815d policy, refactor: Convert uint256 to Txid (marcofleon)
f6c0d1d231 mempool, refactor: Convert uint256 to Txid (marcofleon)
aeb0f78330 refactor: Convert `mini_miner` from uint256 to Txid (marcofleon)
326f244724 refactor: Convert RPCs and `merkleblock` from uint256 to Txid (marcofleon)
49b3d3a92a Clean up `FindTxForGetData` (marcofleon)

Pull request description:

  This is the final leg of the [type safety refactor](https://github.com/bitcoin/bitcoin/pull/32189).

  All of these changes are straightforward `uint256` --> `Txid` along with any necessary explicit conversions. Also, `transaction_identifier.h` is moved to primitives in the last commit, as `Txid` and `Wtxid` become fundamental types after this PR.

ACKs for top commit:
  stickies-v:
    re-ACK de0675f9de, no changes since a20724d926d5844168c6a13fa8293df8c8927efe except address review nits.
  janb84:
    re ACK de0675f9de
  dergoegge:
    re-ACK de0675f9de
  theStack:
    Code-review ACK de0675f9de

Tree-SHA512: 2413160fca7ab146a8d79d18ce3afcf7384cacc73c513d41928904aa453b4dd7a350064cee71e9c5d015da5904c7c81ac17603e50a47441ebc5b0c653235dd08
This commit is contained in:
merge-script committed 2025-08-13 14:50:51 -04:00
commit 9b1a7c3e8d
75 files changed
+323 -305

No files matched your search

+1 -1
View File
@@ -42,7 +42,7 @@ void CBlockHeaderAndShortTxIDs::FillShortTxIDSelector() const {
uint64_t CBlockHeaderAndShortTxIDs::GetShortID(const Wtxid& wtxid) const { uint64_t CBlockHeaderAndShortTxIDs::GetShortID(const Wtxid& wtxid) const {
static_assert(SHORTTXIDS_LENGTH == 6, "shorttxids calculation assumes 6-byte shorttxids"); static_assert(SHORTTXIDS_LENGTH == 6, "shorttxids calculation assumes 6-byte shorttxids");
return SipHashUint256(shorttxidk0, shorttxidk1, wtxid) & 0xffffffffffffL; return SipHashUint256(shorttxidk0, shorttxidk1, wtxid.ToUint256()) & 0xffffffffffffL;
} }
ReadStatus PartiallyDownloadedBlock::InitData(const CBlockHeaderAndShortTxIDs& cmpctblock, const std::vector<CTransactionRef>& extra_txn) { ReadStatus PartiallyDownloadedBlock::InitData(const CBlockHeaderAndShortTxIDs& cmpctblock, const std::vector<CTransactionRef>& extra_txn) {
+3 -3
View File
@@ -68,7 +68,7 @@ uint256 BlockMerkleRoot(const CBlock& block, bool* mutated)
std::vector<uint256> leaves; std::vector<uint256> leaves;
leaves.resize(block.vtx.size()); leaves.resize(block.vtx.size());
for (size_t s = 0; s < block.vtx.size(); s++) { for (size_t s = 0; s < block.vtx.size(); s++) {
leaves[s] = block.vtx[s]->GetHash(); leaves[s] = block.vtx[s]->GetHash().ToUint256();
} }
return ComputeMerkleRoot(std::move(leaves), mutated); return ComputeMerkleRoot(std::move(leaves), mutated);
} }
@@ -79,7 +79,7 @@ uint256 BlockWitnessMerkleRoot(const CBlock& block, bool* mutated)
leaves.resize(block.vtx.size()); leaves.resize(block.vtx.size());
leaves[0].SetNull(); // The witness hash of the coinbase is 0. leaves[0].SetNull(); // The witness hash of the coinbase is 0.
for (size_t s = 1; s < block.vtx.size(); s++) { for (size_t s = 1; s < block.vtx.size(); s++) {
leaves[s] = block.vtx[s]->GetWitnessHash(); leaves[s] = block.vtx[s]->GetWitnessHash().ToUint256();
} }
return ComputeMerkleRoot(std::move(leaves), mutated); return ComputeMerkleRoot(std::move(leaves), mutated);
} }
@@ -185,7 +185,7 @@ std::vector<uint256> TransactionMerklePath(const CBlock& block, uint32_t positio
std::vector<uint256> leaves; std::vector<uint256> leaves;
leaves.resize(block.vtx.size()); leaves.resize(block.vtx.size());
for (size_t s = 0; s < block.vtx.size(); s++) { for (size_t s = 0; s < block.vtx.size(); s++) {
leaves[s] = block.vtx[s]->GetHash(); leaves[s] = block.vtx[s]->GetHash().ToUint256();
} }
return ComputeMerklePath(leaves, position); return ComputeMerklePath(leaves, position);
} }
+1 -1
View File
@@ -48,7 +48,7 @@ HeadersSyncState::HeadersSyncState(NodeId id, const Consensus::Params& consensus
/** Free any memory in use, and mark this object as no longer usable. This is /** Free any memory in use, and mark this object as no longer usable. This is
* required to guarantee that we won't reuse this object with the same * required to guarantee that we won't reuse this object with the same
* SaltedTxidHasher for another sync. */ * SaltedUint256Hasher for another sync. */
void HeadersSyncState::Finalize() void HeadersSyncState::Finalize()
{ {
Assume(m_download_state != State::FINAL); Assume(m_download_state != State::FINAL);
+1 -1
View File
@@ -224,7 +224,7 @@ private:
arith_uint256 m_current_chain_work; arith_uint256 m_current_chain_work;
/** m_hasher is a salted hasher for making our 1-bit commitments to headers we've seen. */ /** m_hasher is a salted hasher for making our 1-bit commitments to headers we've seen. */
const SaltedTxidHasher m_hasher; const SaltedUint256Hasher m_hasher;
/** A queue of commitment bits, created during the 1st phase, and verified during the 2nd. */ /** A queue of commitment bits, created during the 1st phase, and verified during the 2nd. */
bitdeque<> m_header_commitments; bitdeque<> m_header_commitments;
+10 -9
View File
@@ -9,6 +9,7 @@
#include <index/disktxpos.h> #include <index/disktxpos.h>
#include <logging.h> #include <logging.h>
#include <node/blockstorage.h> #include <node/blockstorage.h>
#include <primitives/transaction_identifier.h>
#include <validation.h> #include <validation.h>
constexpr uint8_t DB_TXINDEX{'t'}; constexpr uint8_t DB_TXINDEX{'t'};
@@ -24,26 +25,26 @@ public:
/// Read the disk location of the transaction data with the given hash. Returns false if the /// Read the disk location of the transaction data with the given hash. Returns false if the
/// transaction hash is not indexed. /// transaction hash is not indexed.
bool ReadTxPos(const uint256& txid, CDiskTxPos& pos) const; bool ReadTxPos(const Txid& txid, CDiskTxPos& pos) const;
/// Write a batch of transaction positions to the DB. /// Write a batch of transaction positions to the DB.
[[nodiscard]] bool WriteTxs(const std::vector<std::pair<uint256, CDiskTxPos>>& v_pos); [[nodiscard]] bool WriteTxs(const std::vector<std::pair<Txid, CDiskTxPos>>& v_pos);
}; };
TxIndex::DB::DB(size_t n_cache_size, bool f_memory, bool f_wipe) : TxIndex::DB::DB(size_t n_cache_size, bool f_memory, bool f_wipe) :
BaseIndex::DB(gArgs.GetDataDirNet() / "indexes" / "txindex", n_cache_size, f_memory, f_wipe) BaseIndex::DB(gArgs.GetDataDirNet() / "indexes" / "txindex", n_cache_size, f_memory, f_wipe)
{} {}
bool TxIndex::DB::ReadTxPos(const uint256 &txid, CDiskTxPos& pos) const bool TxIndex::DB::ReadTxPos(const Txid& txid, CDiskTxPos& pos) const
{ {
return Read(std::make_pair(DB_TXINDEX, txid), pos); return Read(std::make_pair(DB_TXINDEX, txid.ToUint256()), pos);
} }
bool TxIndex::DB::WriteTxs(const std::vector<std::pair<uint256, CDiskTxPos>>& v_pos) bool TxIndex::DB::WriteTxs(const std::vector<std::pair<Txid, CDiskTxPos>>& v_pos)
{ {
CDBBatch batch(*this); CDBBatch batch(*this);
for (const auto& tuple : v_pos) { for (const auto& [txid, pos] : v_pos) {
batch.Write(std::make_pair(DB_TXINDEX, tuple.first), tuple.second); batch.Write(std::make_pair(DB_TXINDEX, txid.ToUint256()), pos);
} }
return WriteBatch(batch); return WriteBatch(batch);
} }
@@ -61,7 +62,7 @@ bool TxIndex::CustomAppend(const interfaces::BlockInfo& block)
assert(block.data); assert(block.data);
CDiskTxPos pos({block.file_number, block.data_pos}, GetSizeOfCompactSize(block.data->vtx.size())); CDiskTxPos pos({block.file_number, block.data_pos}, GetSizeOfCompactSize(block.data->vtx.size()));
std::vector<std::pair<uint256, CDiskTxPos>> vPos; std::vector<std::pair<Txid, CDiskTxPos>> vPos;
vPos.reserve(block.data->vtx.size()); vPos.reserve(block.data->vtx.size());
for (const auto& tx : block.data->vtx) { for (const auto& tx : block.data->vtx) {
vPos.emplace_back(tx->GetHash(), pos); vPos.emplace_back(tx->GetHash(), pos);
@@ -72,7 +73,7 @@ bool TxIndex::CustomAppend(const interfaces::BlockInfo& block)
BaseIndex::DB& TxIndex::GetDB() const { return *m_db; } BaseIndex::DB& TxIndex::GetDB() const { return *m_db; }
bool TxIndex::FindTx(const uint256& tx_hash, uint256& block_hash, CTransactionRef& tx) const bool TxIndex::FindTx(const Txid& tx_hash, uint256& block_hash, CTransactionRef& tx) const
{ {
CDiskTxPos postx; CDiskTxPos postx;
if (!m_db->ReadTxPos(tx_hash, postx)) { if (!m_db->ReadTxPos(tx_hash, postx)) {
+1 -1
View File
@@ -42,7 +42,7 @@ public:
/// @param[out] block_hash The hash of the block the transaction is found in. /// @param[out] block_hash The hash of the block the transaction is found in.
/// @param[out] tx The transaction itself. /// @param[out] tx The transaction itself.
/// @return true if transaction is found, false otherwise /// @return true if transaction is found, false otherwise
bool FindTx(const uint256& tx_hash, uint256& block_hash, CTransactionRef& tx) const; bool FindTx(const Txid& tx_hash, uint256& block_hash, CTransactionRef& tx) const;
}; };
/// The global transaction index, used in GetTransaction. May be null. /// The global transaction index, used in GetTransaction. May be null.
+2 -2
View File
@@ -211,7 +211,7 @@ public:
virtual bool isInMempool(const Txid& txid) = 0; virtual bool isInMempool(const Txid& txid) = 0;
//! Check if transaction has descendants in mempool. //! Check if transaction has descendants in mempool.
virtual bool hasDescendantsInMempool(const uint256& txid) = 0; virtual bool hasDescendantsInMempool(const Txid& txid) = 0;
//! Transaction is added to memory pool, if the transaction fee is below the //! Transaction is added to memory pool, if the transaction fee is below the
//! amount specified by max_tx_fee, and broadcast to all peers if relay is set to true. //! amount specified by max_tx_fee, and broadcast to all peers if relay is set to true.
@@ -222,7 +222,7 @@ public:
std::string& err_string) = 0; std::string& err_string) = 0;
//! Calculate mempool ancestor and descendant counts for the given transaction. //! Calculate mempool ancestor and descendant counts for the given transaction.
virtual void getTransactionAncestry(const uint256& txid, size_t& ancestors, size_t& descendants, size_t* ancestorsize = nullptr, CAmount* ancestorfees = nullptr) = 0; virtual void getTransactionAncestry(const Txid& txid, size_t& ancestors, size_t& descendants, size_t* ancestorsize = nullptr, CAmount* ancestorfees = nullptr) = 0;
//! For each outpoint, calculate the fee-bumping cost to spend this outpoint at the specified //! For each outpoint, calculate the fee-bumping cost to spend this outpoint at the specified
// feerate, including bumping its ancestors. For example, if the target feerate is 10sat/vbyte // feerate, including bumping its ancestors. For example, if the target feerate is 10sat/vbyte
+1 -1
View File
@@ -9,12 +9,12 @@
#include <common/signmessage.h> #include <common/signmessage.h>
#include <consensus/amount.h> #include <consensus/amount.h>
#include <interfaces/chain.h> #include <interfaces/chain.h>
#include <primitives/transaction_identifier.h>
#include <pubkey.h> #include <pubkey.h>
#include <script/script.h> #include <script/script.h>
#include <support/allocators/secure.h> #include <support/allocators/secure.h>
#include <util/fs.h> #include <util/fs.h>
#include <util/result.h> #include <util/result.h>
#include <util/transaction_identifier.h>
#include <util/ui_change_type.h> #include <util/ui_change_type.h>
#include <cstdint> #include <cstdint>
+3 -3
View File
@@ -98,7 +98,7 @@ static void ApplyHash(T& hash_obj, const Txid& hash, const std::map<uint32_t, Co
} }
} }
static void ApplyStats(CCoinsStats& stats, const uint256& hash, const std::map<uint32_t, Coin>& outputs) static void ApplyStats(CCoinsStats& stats, const std::map<uint32_t, Coin>& outputs)
{ {
assert(!outputs.empty()); assert(!outputs.empty());
stats.nTransactions++; stats.nTransactions++;
@@ -126,7 +126,7 @@ static bool ComputeUTXOStats(CCoinsView* view, CCoinsStats& stats, T hash_obj, c
Coin coin; Coin coin;
if (pcursor->GetKey(key) && pcursor->GetValue(coin)) { if (pcursor->GetKey(key) && pcursor->GetValue(coin)) {
if (!outputs.empty() && key.hash != prevkey) { if (!outputs.empty() && key.hash != prevkey) {
ApplyStats(stats, prevkey, outputs); ApplyStats(stats, outputs);
ApplyHash(hash_obj, prevkey, outputs); ApplyHash(hash_obj, prevkey, outputs);
outputs.clear(); outputs.clear();
} }
@@ -140,7 +140,7 @@ static bool ComputeUTXOStats(CCoinsView* view, CCoinsStats& stats, T hash_obj, c
pcursor->Next(); pcursor->Next();
} }
if (!outputs.empty()) { if (!outputs.empty()) {
ApplyStats(stats, prevkey, outputs); ApplyStats(stats, outputs);
ApplyHash(hash_obj, prevkey, outputs); ApplyHash(hash_obj, prevkey, outputs);
} }
+1 -1
View File
@@ -41,7 +41,7 @@ private:
const size_t m_max_mem_usage; const size_t m_max_mem_usage;
std::list<CTransactionRef> queuedTx; std::list<CTransactionRef> queuedTx;
using TxList = decltype(queuedTx); using TxList = decltype(queuedTx);
std::unordered_map<uint256, TxList::iterator, SaltedTxidHasher> iters_by_txid; std::unordered_map<Txid, TxList::iterator, SaltedTxidHasher> iters_by_txid;
/** Trim the earliest-added entries until we are within memory bounds. */ /** Trim the earliest-added entries until we are within memory bounds. */
std::vector<CTransactionRef> LimitMemoryUsage(); std::vector<CTransactionRef> LimitMemoryUsage();
+8 -8
View File
@@ -32,7 +32,7 @@ CMerkleBlock::CMerkleBlock(const CBlock& block, CBloomFilter* filter, const std:
header = block.GetBlockHeader(); header = block.GetBlockHeader();
std::vector<bool> vMatch; std::vector<bool> vMatch;
std::vector<uint256> vHashes; std::vector<Txid> vHashes;
vMatch.reserve(block.vtx.size()); vMatch.reserve(block.vtx.size());
vHashes.reserve(block.vtx.size()); vHashes.reserve(block.vtx.size());
@@ -55,13 +55,13 @@ CMerkleBlock::CMerkleBlock(const CBlock& block, CBloomFilter* filter, const std:
} }
// NOLINTNEXTLINE(misc-no-recursion) // NOLINTNEXTLINE(misc-no-recursion)
uint256 CPartialMerkleTree::CalcHash(int height, unsigned int pos, const std::vector<uint256> &vTxid) { uint256 CPartialMerkleTree::CalcHash(int height, unsigned int pos, const std::vector<Txid> &vTxid) {
//we can never have zero txs in a merkle block, we always need the coinbase tx //we can never have zero txs in a merkle block, we always need the coinbase tx
//if we do not have this assert, we can hit a memory access violation when indexing into vTxid //if we do not have this assert, we can hit a memory access violation when indexing into vTxid
assert(vTxid.size() != 0); assert(vTxid.size() != 0);
if (height == 0) { if (height == 0) {
// hash at height 0 is the txids themselves // hash at height 0 is the txids themselves
return vTxid[pos]; return vTxid[pos].ToUint256();
} else { } else {
// calculate left hash // calculate left hash
uint256 left = CalcHash(height-1, pos*2, vTxid), right; uint256 left = CalcHash(height-1, pos*2, vTxid), right;
@@ -76,7 +76,7 @@ uint256 CPartialMerkleTree::CalcHash(int height, unsigned int pos, const std::ve
} }
// NOLINTNEXTLINE(misc-no-recursion) // NOLINTNEXTLINE(misc-no-recursion)
void CPartialMerkleTree::TraverseAndBuild(int height, unsigned int pos, const std::vector<uint256> &vTxid, const std::vector<bool> &vMatch) { void CPartialMerkleTree::TraverseAndBuild(int height, unsigned int pos, const std::vector<Txid> &vTxid, const std::vector<bool> &vMatch) {
// determine whether this node is the parent of at least one matched txid // determine whether this node is the parent of at least one matched txid
bool fParentOfMatch = false; bool fParentOfMatch = false;
for (unsigned int p = pos << height; p < (pos+1) << height && p < nTransactions; p++) for (unsigned int p = pos << height; p < (pos+1) << height && p < nTransactions; p++)
@@ -95,7 +95,7 @@ void CPartialMerkleTree::TraverseAndBuild(int height, unsigned int pos, const st
} }
// NOLINTNEXTLINE(misc-no-recursion) // NOLINTNEXTLINE(misc-no-recursion)
uint256 CPartialMerkleTree::TraverseAndExtract(int height, unsigned int pos, unsigned int &nBitsUsed, unsigned int &nHashUsed, std::vector<uint256> &vMatch, std::vector<unsigned int> &vnIndex) { uint256 CPartialMerkleTree::TraverseAndExtract(int height, unsigned int pos, unsigned int &nBitsUsed, unsigned int &nHashUsed, std::vector<Txid> &vMatch, std::vector<unsigned int> &vnIndex) {
if (nBitsUsed >= vBits.size()) { if (nBitsUsed >= vBits.size()) {
// overflowed the bits array - failure // overflowed the bits array - failure
fBad = true; fBad = true;
@@ -111,7 +111,7 @@ uint256 CPartialMerkleTree::TraverseAndExtract(int height, unsigned int pos, uns
} }
const uint256 &hash = vHash[nHashUsed++]; const uint256 &hash = vHash[nHashUsed++];
if (height==0 && fParentOfMatch) { // in case of height 0, we have a matched txid if (height==0 && fParentOfMatch) { // in case of height 0, we have a matched txid
vMatch.push_back(hash); vMatch.push_back(Txid::FromUint256(hash));
vnIndex.push_back(pos); vnIndex.push_back(pos);
} }
return hash; return hash;
@@ -133,7 +133,7 @@ uint256 CPartialMerkleTree::TraverseAndExtract(int height, unsigned int pos, uns
} }
} }
CPartialMerkleTree::CPartialMerkleTree(const std::vector<uint256> &vTxid, const std::vector<bool> &vMatch) : nTransactions(vTxid.size()), fBad(false) { CPartialMerkleTree::CPartialMerkleTree(const std::vector<Txid> &vTxid, const std::vector<bool> &vMatch) : nTransactions(vTxid.size()), fBad(false) {
// reset state // reset state
vBits.clear(); vBits.clear();
vHash.clear(); vHash.clear();
@@ -149,7 +149,7 @@ CPartialMerkleTree::CPartialMerkleTree(const std::vector<uint256> &vTxid, const
CPartialMerkleTree::CPartialMerkleTree() : nTransactions(0), fBad(true) {} CPartialMerkleTree::CPartialMerkleTree() : nTransactions(0), fBad(true) {}
uint256 CPartialMerkleTree::ExtractMatches(std::vector<uint256> &vMatch, std::vector<unsigned int> &vnIndex) { uint256 CPartialMerkleTree::ExtractMatches(std::vector<Txid> &vMatch, std::vector<unsigned int> &vnIndex) {
vMatch.clear(); vMatch.clear();
// An empty set will not work // An empty set will not work
if (nTransactions == 0) if (nTransactions == 0)
+7 -6
View File
@@ -8,6 +8,7 @@
#include <common/bloom.h> #include <common/bloom.h>
#include <primitives/block.h> #include <primitives/block.h>
#include <primitives/transaction_identifier.h>
#include <serialize.h> #include <serialize.h>
#include <uint256.h> #include <uint256.h>
@@ -73,16 +74,16 @@ protected:
} }
/** calculate the hash of a node in the merkle tree (at leaf level: the txid's themselves) */ /** calculate the hash of a node in the merkle tree (at leaf level: the txid's themselves) */
uint256 CalcHash(int height, unsigned int pos, const std::vector<uint256> &vTxid); uint256 CalcHash(int height, unsigned int pos, const std::vector<Txid> &vTxid);
/** recursive function that traverses tree nodes, storing the data as bits and hashes */ /** recursive function that traverses tree nodes, storing the data as bits and hashes */
void TraverseAndBuild(int height, unsigned int pos, const std::vector<uint256> &vTxid, const std::vector<bool> &vMatch); void TraverseAndBuild(int height, unsigned int pos, const std::vector<Txid> &vTxid, const std::vector<bool> &vMatch);
/** /**
* recursive function that traverses tree nodes, consuming the bits and hashes produced by TraverseAndBuild. * recursive function that traverses tree nodes, consuming the bits and hashes produced by TraverseAndBuild.
* it returns the hash of the respective node and its respective index. * it returns the hash of the respective node and its respective index.
*/ */
uint256 TraverseAndExtract(int height, unsigned int pos, unsigned int &nBitsUsed, unsigned int &nHashUsed, std::vector<uint256> &vMatch, std::vector<unsigned int> &vnIndex); uint256 TraverseAndExtract(int height, unsigned int pos, unsigned int &nBitsUsed, unsigned int &nHashUsed, std::vector<Txid> &vMatch, std::vector<unsigned int> &vnIndex);
public: public:
@@ -97,7 +98,7 @@ public:
} }
/** Construct a partial merkle tree from a list of transaction ids, and a mask that selects a subset of them */ /** Construct a partial merkle tree from a list of transaction ids, and a mask that selects a subset of them */
CPartialMerkleTree(const std::vector<uint256> &vTxid, const std::vector<bool> &vMatch); CPartialMerkleTree(const std::vector<Txid> &vTxid, const std::vector<bool> &vMatch);
CPartialMerkleTree(); CPartialMerkleTree();
@@ -106,7 +107,7 @@ public:
* and their respective indices within the partial tree. * and their respective indices within the partial tree.
* returns the merkle root, or 0 in case of failure * returns the merkle root, or 0 in case of failure
*/ */
uint256 ExtractMatches(std::vector<uint256> &vMatch, std::vector<unsigned int> &vnIndex); uint256 ExtractMatches(std::vector<Txid> &vMatch, std::vector<unsigned int> &vnIndex);
/** Get number of transactions the merkle proof is indicating for cross-reference with /** Get number of transactions the merkle proof is indicating for cross-reference with
* local blockchain knowledge. * local blockchain knowledge.
@@ -135,7 +136,7 @@ public:
* Used only when a bloom filter is specified to allow * Used only when a bloom filter is specified to allow
* testing the transactions which matched the bloom filter. * testing the transactions which matched the bloom filter.
*/ */
std::vector<std::pair<unsigned int, uint256> > vMatchedTxn; std::vector<std::pair<unsigned int, Txid> > vMatchedTxn;
/** /**
* Create from a CBlock, filtering transactions according to filter * Create from a CBlock, filtering transactions according to filter
+13 -15
View File
@@ -1571,13 +1571,13 @@ void PeerManagerImpl::InitializeNode(const CNode& node, ServiceFlags our_service
void PeerManagerImpl::ReattemptInitialBroadcast(CScheduler& scheduler) void PeerManagerImpl::ReattemptInitialBroadcast(CScheduler& scheduler)
{ {
std::set<uint256> unbroadcast_txids = m_mempool.GetUnbroadcastTxs(); std::set<Txid> unbroadcast_txids = m_mempool.GetUnbroadcastTxs();
for (const auto& txid : unbroadcast_txids) { for (const auto& txid : unbroadcast_txids) {
CTransactionRef tx = m_mempool.get(txid); CTransactionRef tx = m_mempool.get(txid);
if (tx != nullptr) { if (tx != nullptr) {
RelayTransaction(Txid::FromUint256(txid), tx->GetWitnessHash()); RelayTransaction(txid, tx->GetWitnessHash());
} else { } else {
m_mempool.RemoveUnbroadcastTx(txid, true); m_mempool.RemoveUnbroadcastTx(txid, true);
} }
@@ -2320,9 +2320,8 @@ void PeerManagerImpl::ProcessGetBlockData(CNode& pfrom, Peer& peer, const CInv&
// they must either disconnect and retry or request the full block. // they must either disconnect and retry or request the full block.
// Thus, the protocol spec specified allows for us to provide duplicate txn here, // Thus, the protocol spec specified allows for us to provide duplicate txn here,
// however we MUST always provide at least what the remote peer needs // however we MUST always provide at least what the remote peer needs
typedef std::pair<unsigned int, uint256> PairType; for (const auto& [tx_idx, _] : merkleBlock.vMatchedTxn)
for (PairType& pair : merkleBlock.vMatchedTxn) MakeAndPushMessage(pfrom, NetMsgType::TX, TX_NO_WITNESS(*pblock->vtx[tx_idx]));
MakeAndPushMessage(pfrom, NetMsgType::TX, TX_NO_WITNESS(*pblock->vtx[pair.first]));
} }
// else // else
// no response // no response
@@ -2361,12 +2360,12 @@ void PeerManagerImpl::ProcessGetBlockData(CNode& pfrom, Peer& peer, const CInv&
CTransactionRef PeerManagerImpl::FindTxForGetData(const Peer::TxRelay& tx_relay, const GenTxid& gtxid) CTransactionRef PeerManagerImpl::FindTxForGetData(const Peer::TxRelay& tx_relay, const GenTxid& gtxid)
{ {
// If a tx was in the mempool prior to the last INV for this peer, permit the request.
auto txinfo{std::visit( auto txinfo{std::visit(
[&](const auto& id) EXCLUSIVE_LOCKS_REQUIRED(NetEventsInterface::g_msgproc_mutex) { [&](const auto& id) EXCLUSIVE_LOCKS_REQUIRED(NetEventsInterface::g_msgproc_mutex) {
return m_mempool.info_for_relay(id, tx_relay.m_last_inv_sequence); return m_mempool.info_for_relay(id, tx_relay.m_last_inv_sequence);
}, },
gtxid)}; gtxid)};
if (txinfo.tx) { if (txinfo.tx) {
return std::move(txinfo.tx); return std::move(txinfo.tx);
} }
@@ -2999,7 +2998,7 @@ std::optional<node::PackageToValidate> PeerManagerImpl::ProcessInvalidTx(NodeId
AddToCompactExtraTransactions(ptx); AddToCompactExtraTransactions(ptx);
} }
for (const Txid& parent_txid : unique_parents) { for (const Txid& parent_txid : unique_parents) {
if (peer) AddKnownTx(*peer, parent_txid); if (peer) AddKnownTx(*peer, parent_txid.ToUint256());
} }
return package_to_validate; return package_to_validate;
@@ -4247,12 +4246,11 @@ void PeerManagerImpl::ProcessMessage(CNode& pfrom, const std::string& msg_type,
CTransactionRef ptx; CTransactionRef ptx;
vRecv >> TX_WITH_WITNESS(ptx); vRecv >> TX_WITH_WITNESS(ptx);
const CTransaction& tx = *ptx;
const uint256& txid = ptx->GetHash(); const Txid& txid = ptx->GetHash();
const uint256& wtxid = ptx->GetWitnessHash(); const Wtxid& wtxid = ptx->GetWitnessHash();
const uint256& hash = peer->m_wtxid_relay ? wtxid : txid; const uint256& hash = peer->m_wtxid_relay ? wtxid.ToUint256() : txid.ToUint256();
AddKnownTx(*peer, hash); AddKnownTx(*peer, hash);
LOCK2(cs_main, m_tx_download_mutex); LOCK2(cs_main, m_tx_download_mutex);
@@ -4263,13 +4261,13 @@ void PeerManagerImpl::ProcessMessage(CNode& pfrom, const std::string& msg_type,
// Always relay transactions received from peers with forcerelay // Always relay transactions received from peers with forcerelay
// permission, even if they were already in the mempool, allowing // permission, even if they were already in the mempool, allowing
// the node to function as a gateway for nodes hidden behind it. // the node to function as a gateway for nodes hidden behind it.
if (!m_mempool.exists(tx.GetHash())) { if (!m_mempool.exists(txid)) {
LogPrintf("Not relaying non-mempool transaction %s (wtxid=%s) from forcerelay peer=%d\n", LogPrintf("Not relaying non-mempool transaction %s (wtxid=%s) from forcerelay peer=%d\n",
tx.GetHash().ToString(), tx.GetWitnessHash().ToString(), pfrom.GetId()); txid.ToString(), wtxid.ToString(), pfrom.GetId());
} else { } else {
LogPrintf("Force relaying tx %s (wtxid=%s) from peer=%d\n", LogPrintf("Force relaying tx %s (wtxid=%s) from peer=%d\n",
tx.GetHash().ToString(), tx.GetWitnessHash().ToString(), pfrom.GetId()); txid.ToString(), wtxid.ToString(), pfrom.GetId());
RelayTransaction(tx.GetHash(), tx.GetWitnessHash()); RelayTransaction(txid, wtxid);
} }
} }
+3 -3
View File
@@ -673,11 +673,11 @@ public:
LOCK(m_node.mempool->cs); LOCK(m_node.mempool->cs);
return m_node.mempool->exists(txid); return m_node.mempool->exists(txid);
} }
bool hasDescendantsInMempool(const uint256& txid) override bool hasDescendantsInMempool(const Txid& txid) override
{ {
if (!m_node.mempool) return false; if (!m_node.mempool) return false;
LOCK(m_node.mempool->cs); LOCK(m_node.mempool->cs);
const auto entry{m_node.mempool->GetEntry(Txid::FromUint256(txid))}; const auto entry{m_node.mempool->GetEntry(txid)};
if (entry == nullptr) return false; if (entry == nullptr) return false;
return entry->GetCountWithDescendants() > 1; return entry->GetCountWithDescendants() > 1;
} }
@@ -692,7 +692,7 @@ public:
// that Chain clients do not need to know about. // that Chain clients do not need to know about.
return TransactionError::OK == err; return TransactionError::OK == err;
} }
void getTransactionAncestry(const uint256& txid, size_t& ancestors, size_t& descendants, size_t* ancestorsize, CAmount* ancestorfees) override void getTransactionAncestry(const Txid& txid, size_t& ancestors, size_t& descendants, size_t* ancestorsize, CAmount* ancestorfees) override
{ {
ancestors = descendants = 0; ancestors = descendants = 0;
if (!m_node.mempool) return; if (!m_node.mempool) return;
+4 -4
View File
@@ -122,7 +122,7 @@ bool LoadMempool(CTxMemPool& pool, const fs::path& load_path, Chainstate& active
if (active_chainstate.m_chainman.m_interrupt) if (active_chainstate.m_chainman.m_interrupt)
return false; return false;
} }
std::map<uint256, CAmount> mapDeltas; std::map<Txid, CAmount> mapDeltas;
file >> mapDeltas; file >> mapDeltas;
if (opts.apply_fee_delta_priority) { if (opts.apply_fee_delta_priority) {
@@ -131,7 +131,7 @@ bool LoadMempool(CTxMemPool& pool, const fs::path& load_path, Chainstate& active
} }
} }
std::set<uint256> unbroadcast_txids; std::set<Txid> unbroadcast_txids;
file >> unbroadcast_txids; file >> unbroadcast_txids;
if (opts.apply_unbroadcast_set) { if (opts.apply_unbroadcast_set) {
unbroadcast = unbroadcast_txids.size(); unbroadcast = unbroadcast_txids.size();
@@ -154,9 +154,9 @@ bool DumpMempool(const CTxMemPool& pool, const fs::path& dump_path, FopenFn mock
{ {
auto start = SteadyClock::now(); auto start = SteadyClock::now();
std::map<uint256, CAmount> mapDeltas; std::map<Txid, CAmount> mapDeltas;
std::vector<TxMempoolInfo> vinfo; std::vector<TxMempoolInfo> vinfo;
std::set<uint256> unbroadcast_txids; std::set<Txid> unbroadcast_txids;
static Mutex dump_mutex; static Mutex dump_mutex;
LOCK(dump_mutex); LOCK(dump_mutex);
+5 -8
View File
@@ -16,6 +16,7 @@
#include <algorithm> #include <algorithm>
#include <numeric> #include <numeric>
#include <ranges>
#include <utility> #include <utility>
namespace node { namespace node {
@@ -61,12 +62,8 @@ MiniMiner::MiniMiner(const CTxMemPool& mempool, const std::vector<COutPoint>& ou
if (m_requested_outpoints_by_txid.empty()) return; if (m_requested_outpoints_by_txid.empty()) return;
// Calculate the cluster and construct the entry map. // Calculate the cluster and construct the entry map.
std::vector<uint256> txids_needed; auto txids_needed{m_requested_outpoints_by_txid | std::views::keys};
txids_needed.reserve(m_requested_outpoints_by_txid.size()); const auto cluster = mempool.GatherClusters({txids_needed.begin(), txids_needed.end()});
for (const auto& [txid, _]: m_requested_outpoints_by_txid) {
txids_needed.push_back(txid);
}
const auto cluster = mempool.GatherClusters(txids_needed);
if (cluster.empty()) { if (cluster.empty()) {
// An empty cluster means that at least one of the transactions is missing from the mempool // An empty cluster means that at least one of the transactions is missing from the mempool
// (should not be possible given processing above) or DoS limit was hit. // (should not be possible given processing above) or DoS limit was hit.
@@ -286,7 +283,7 @@ void MiniMiner::BuildMockTemplate(std::optional<CFeeRate> target_feerate)
} }
// Track the order in which transactions were selected. // Track the order in which transactions were selected.
for (const auto& ancestor : ancestors) { for (const auto& ancestor : ancestors) {
m_inclusion_order.emplace(Txid::FromUint256(ancestor->first), sequence_num); m_inclusion_order.emplace(ancestor->first, sequence_num);
} }
DeleteAncestorPackage(ancestors); DeleteAncestorPackage(ancestors);
SanityCheck(); SanityCheck();
@@ -409,7 +406,7 @@ std::optional<CAmount> MiniMiner::CalculateTotalBumpFees(const CFeeRate& target_
ancestors.insert(iter); ancestors.insert(iter);
} }
std::set<uint256> has_been_processed; std::set<Txid> has_been_processed;
while (!to_process.empty()) { while (!to_process.empty()) {
auto iter = to_process.begin(); auto iter = to_process.begin();
const CTransaction& tx = (*iter)->second.GetTx(); const CTransaction& tx = (*iter)->second.GetTx();
+6 -6
View File
@@ -83,12 +83,12 @@ class MiniMiner
// Set once per lifetime, fill in during initialization. // Set once per lifetime, fill in during initialization.
// txids of to-be-replaced transactions // txids of to-be-replaced transactions
std::set<uint256> m_to_be_replaced; std::set<Txid> m_to_be_replaced;
// If multiple argument outpoints correspond to the same transaction, cache them together in // If multiple argument outpoints correspond to the same transaction, cache them together in
// a single entry indexed by txid. Then we can just work with txids since all outpoints from // a single entry indexed by txid. Then we can just work with txids since all outpoints from
// the same tx will have the same bumpfee. Excludes non-mempool transactions. // the same tx will have the same bumpfee. Excludes non-mempool transactions.
std::map<uint256, std::vector<COutPoint>> m_requested_outpoints_by_txid; std::map<Txid, std::vector<COutPoint>> m_requested_outpoints_by_txid;
// Txid to a number representing the order in which this transaction was included (smaller // Txid to a number representing the order in which this transaction was included (smaller
// number = included earlier). Transactions included in an ancestor set together have the same // number = included earlier). Transactions included in an ancestor set together have the same
@@ -98,21 +98,21 @@ class MiniMiner
std::map<COutPoint, CAmount> m_bump_fees; std::map<COutPoint, CAmount> m_bump_fees;
// The constructed block template // The constructed block template
std::set<uint256> m_in_block; std::set<Txid> m_in_block;
// Information on the current status of the block // Information on the current status of the block
CAmount m_total_fees{0}; CAmount m_total_fees{0};
int32_t m_total_vsize{0}; int32_t m_total_vsize{0};
/** Main data structure holding the entries, can be indexed by txid */ /** Main data structure holding the entries, can be indexed by txid */
std::map<uint256, MiniMinerMempoolEntry> m_entries_by_txid; std::map<Txid, MiniMinerMempoolEntry> m_entries_by_txid;
using MockEntryMap = decltype(m_entries_by_txid); using MockEntryMap = decltype(m_entries_by_txid);
/** Vector of entries, can be sorted by ancestor feerate. */ /** Vector of entries, can be sorted by ancestor feerate. */
std::vector<MockEntryMap::iterator> m_entries; std::vector<MockEntryMap::iterator> m_entries;
/** Map of txid to its descendants. Should be inclusive. */ /** Map of txid to its descendants. Should be inclusive. */
std::map<uint256, std::vector<MockEntryMap::iterator>> m_descendant_set_by_txid; std::map<Txid, std::vector<MockEntryMap::iterator>> m_descendant_set_by_txid;
/** Consider this ancestor package "mined" so remove all these entries from our data structures. */ /** Consider this ancestor package "mined" so remove all these entries from our data structures. */
void DeleteAncestorPackage(const std::set<MockEntryMap::iterator, IteratorComparator>& ancestors); void DeleteAncestorPackage(const std::set<MockEntryMap::iterator, IteratorComparator>& ancestors);
@@ -129,7 +129,7 @@ public:
void BuildMockTemplate(std::optional<CFeeRate> target_feerate); void BuildMockTemplate(std::optional<CFeeRate> target_feerate);
/** Returns set of txids in the block template if one has been constructed. */ /** Returns set of txids in the block template if one has been constructed. */
std::set<uint256> GetMockTemplateTxids() const { return m_in_block; } std::set<Txid> GetMockTemplateTxids() const { return m_in_block; }
/** Constructor that takes a list of outpoints that may or may not belong to transactions in the /** Constructor that takes a list of outpoints that may or may not belong to transactions in the
* mempool. Copies out information about the relevant transactions in the mempool into * mempool. Copies out information about the relevant transactions in the mempool into
+1 -1
View File
@@ -123,7 +123,7 @@ TransactionError BroadcastTransaction(NodeContext& node, const CTransactionRef t
return TransactionError::OK; return TransactionError::OK;
} }
CTransactionRef GetTransaction(const CBlockIndex* const block_index, const CTxMemPool* const mempool, const uint256& hash, uint256& hashBlock, const BlockManager& blockman) CTransactionRef GetTransaction(const CBlockIndex* const block_index, const CTxMemPool* const mempool, const Txid& hash, uint256& hashBlock, const BlockManager& blockman)
{ {
if (mempool && !block_index) { if (mempool && !block_index) {
CTransactionRef ptx = mempool->get(hash); CTransactionRef ptx = mempool->get(hash);
+1 -1
View File
@@ -63,7 +63,7 @@ static const CAmount DEFAULT_MAX_BURN_AMOUNT{0};
* @param[out] hashBlock The block hash, if the tx was found via -txindex or block_index * @param[out] hashBlock The block hash, if the tx was found via -txindex or block_index
* @returns The tx if found, otherwise nullptr * @returns The tx if found, otherwise nullptr
*/ */
CTransactionRef GetTransaction(const CBlockIndex* const block_index, const CTxMemPool* const mempool, const uint256& hash, uint256& hashBlock, const BlockManager& blockman); CTransactionRef GetTransaction(const CBlockIndex* const block_index, const CTxMemPool* const mempool, const Txid& hash, uint256& hashBlock, const BlockManager& blockman);
} // namespace node } // namespace node
#endif // BITCOIN_NODE_TRANSACTION_H #endif // BITCOIN_NODE_TRANSACTION_H
+14 -14
View File
@@ -104,8 +104,8 @@ void TxDownloadManagerImpl::BlockConnected(const std::shared_ptr<const CBlock>&
if (ptx->HasWitness()) { if (ptx->HasWitness()) {
RecentConfirmedTransactionsFilter().insert(ptx->GetWitnessHash().ToUint256()); RecentConfirmedTransactionsFilter().insert(ptx->GetWitnessHash().ToUint256());
} }
m_txrequest.ForgetTxHash(ptx->GetHash()); m_txrequest.ForgetTxHash(ptx->GetHash().ToUint256());
m_txrequest.ForgetTxHash(ptx->GetWitnessHash()); m_txrequest.ForgetTxHash(ptx->GetWitnessHash().ToUint256());
} }
} }
@@ -324,8 +324,8 @@ void TxDownloadManagerImpl::MempoolAcceptedTx(const CTransactionRef& tx)
{ {
// As this version of the transaction was acceptable, we can forget about any requests for it. // As this version of the transaction was acceptable, we can forget about any requests for it.
// No-op if the tx is not in txrequest. // No-op if the tx is not in txrequest.
m_txrequest.ForgetTxHash(tx->GetHash()); m_txrequest.ForgetTxHash(tx->GetHash().ToUint256());
m_txrequest.ForgetTxHash(tx->GetWitnessHash()); m_txrequest.ForgetTxHash(tx->GetWitnessHash().ToUint256());
m_orphanage->AddChildrenToWorkSet(*tx, m_opts.m_rng); m_orphanage->AddChildrenToWorkSet(*tx, m_opts.m_rng);
// If it came from the orphanage, remove it. No-op if the tx is not in txorphanage. // If it came from the orphanage, remove it. No-op if the tx is not in txorphanage.
@@ -406,8 +406,8 @@ node::RejectedTxTodo TxDownloadManagerImpl::MempoolRejectedTx(const CTransaction
// //
// Search by txid and, if the tx has a witness, wtxid // Search by txid and, if the tx has a witness, wtxid
std::vector<NodeId> orphan_resolution_candidates{nodeid}; std::vector<NodeId> orphan_resolution_candidates{nodeid};
m_txrequest.GetCandidatePeers(ptx->GetHash(), orphan_resolution_candidates); m_txrequest.GetCandidatePeers(ptx->GetHash().ToUint256(), orphan_resolution_candidates);
if (ptx->HasWitness()) m_txrequest.GetCandidatePeers(ptx->GetWitnessHash(), orphan_resolution_candidates); if (ptx->HasWitness()) m_txrequest.GetCandidatePeers(ptx->GetWitnessHash().ToUint256(), orphan_resolution_candidates);
for (const auto& nodeid : orphan_resolution_candidates) { for (const auto& nodeid : orphan_resolution_candidates) {
if (MaybeAddOrphanResolutionCandidate(unique_parents, ptx->GetWitnessHash(), nodeid, now)) { if (MaybeAddOrphanResolutionCandidate(unique_parents, ptx->GetWitnessHash(), nodeid, now)) {
@@ -416,8 +416,8 @@ node::RejectedTxTodo TxDownloadManagerImpl::MempoolRejectedTx(const CTransaction
} }
// Once added to the orphan pool, a tx is considered AlreadyHave, and we shouldn't request it anymore. // Once added to the orphan pool, a tx is considered AlreadyHave, and we shouldn't request it anymore.
m_txrequest.ForgetTxHash(tx.GetHash()); m_txrequest.ForgetTxHash(tx.GetHash().ToUint256());
m_txrequest.ForgetTxHash(tx.GetWitnessHash()); m_txrequest.ForgetTxHash(tx.GetWitnessHash().ToUint256());
} else { } else {
unique_parents.clear(); unique_parents.clear();
LogDebug(BCLog::MEMPOOL, "not keeping orphan with rejected parents %s (wtxid=%s)\n", LogDebug(BCLog::MEMPOOL, "not keeping orphan with rejected parents %s (wtxid=%s)\n",
@@ -431,8 +431,8 @@ node::RejectedTxTodo TxDownloadManagerImpl::MempoolRejectedTx(const CTransaction
// from any of our non-wtxidrelay peers. // from any of our non-wtxidrelay peers.
RecentRejectsFilter().insert(tx.GetHash().ToUint256()); RecentRejectsFilter().insert(tx.GetHash().ToUint256());
RecentRejectsFilter().insert(tx.GetWitnessHash().ToUint256()); RecentRejectsFilter().insert(tx.GetWitnessHash().ToUint256());
m_txrequest.ForgetTxHash(tx.GetHash()); m_txrequest.ForgetTxHash(tx.GetHash().ToUint256());
m_txrequest.ForgetTxHash(tx.GetWitnessHash()); m_txrequest.ForgetTxHash(tx.GetWitnessHash().ToUint256());
} }
} }
} else if (state.GetResult() == TxValidationResult::TX_WITNESS_STRIPPED) { } else if (state.GetResult() == TxValidationResult::TX_WITNESS_STRIPPED) {
@@ -467,7 +467,7 @@ node::RejectedTxTodo TxDownloadManagerImpl::MempoolRejectedTx(const CTransaction
} else { } else {
RecentRejectsFilter().insert(ptx->GetWitnessHash().ToUint256()); RecentRejectsFilter().insert(ptx->GetWitnessHash().ToUint256());
} }
m_txrequest.ForgetTxHash(ptx->GetWitnessHash()); m_txrequest.ForgetTxHash(ptx->GetWitnessHash().ToUint256());
// If the transaction failed for TX_INPUTS_NOT_STANDARD, // If the transaction failed for TX_INPUTS_NOT_STANDARD,
// then we know that the witness was irrelevant to the policy // then we know that the witness was irrelevant to the policy
// failure, since this check depends only on the txid // failure, since this check depends only on the txid
@@ -480,7 +480,7 @@ node::RejectedTxTodo TxDownloadManagerImpl::MempoolRejectedTx(const CTransaction
// rolling bloom filter. // rolling bloom filter.
if (state.GetResult() == TxValidationResult::TX_INPUTS_NOT_STANDARD && ptx->HasWitness()) { if (state.GetResult() == TxValidationResult::TX_INPUTS_NOT_STANDARD && ptx->HasWitness()) {
RecentRejectsFilter().insert(ptx->GetHash().ToUint256()); RecentRejectsFilter().insert(ptx->GetHash().ToUint256());
m_txrequest.ForgetTxHash(ptx->GetHash()); m_txrequest.ForgetTxHash(ptx->GetHash().ToUint256());
} }
} }
@@ -508,8 +508,8 @@ std::pair<bool, std::optional<PackageToValidate>> TxDownloadManagerImpl::Receive
const Wtxid& wtxid = ptx->GetWitnessHash(); const Wtxid& wtxid = ptx->GetWitnessHash();
// Mark that we have received a response // Mark that we have received a response
m_txrequest.ReceivedResponse(nodeid, txid); m_txrequest.ReceivedResponse(nodeid, txid.ToUint256());
if (ptx->HasWitness()) m_txrequest.ReceivedResponse(nodeid, wtxid); if (ptx->HasWitness()) m_txrequest.ReceivedResponse(nodeid, wtxid.ToUint256());
// First check if we should drop this tx. // First check if we should drop this tx.
// We do the AlreadyHaveTx() check using wtxid, rather than txid - in the // We do the AlreadyHaveTx() check using wtxid, rather than txid - in the
+3 -3
View File
@@ -519,16 +519,16 @@ void TxConfirmStats::removeTx(unsigned int entryHeight, unsigned int nBestSeenHe
} }
} }
bool CBlockPolicyEstimator::removeTx(uint256 hash) bool CBlockPolicyEstimator::removeTx(Txid hash)
{ {
LOCK(m_cs_fee_estimator); LOCK(m_cs_fee_estimator);
return _removeTx(hash, /*inBlock=*/false); return _removeTx(hash, /*inBlock=*/false);
} }
bool CBlockPolicyEstimator::_removeTx(const uint256& hash, bool inBlock) bool CBlockPolicyEstimator::_removeTx(const Txid& hash, bool inBlock)
{ {
AssertLockHeld(m_cs_fee_estimator); AssertLockHeld(m_cs_fee_estimator);
std::map<uint256, TxStatsInfo>::iterator pos = mapMemPoolTxs.find(hash); std::map<Txid, TxStatsInfo>::iterator pos = mapMemPoolTxs.find(hash);
if (pos != mapMemPoolTxs.end()) { if (pos != mapMemPoolTxs.end()) {
feeStats->removeTx(pos->second.blockHeight, nBestSeenHeight, pos->second.bucketIndex, inBlock); feeStats->removeTx(pos->second.blockHeight, nBestSeenHeight, pos->second.bucketIndex, inBlock);
shortStats->removeTx(pos->second.blockHeight, nBestSeenHeight, pos->second.bucketIndex, inBlock); shortStats->removeTx(pos->second.blockHeight, nBestSeenHeight, pos->second.bucketIndex, inBlock);
+3 -3
View File
@@ -212,7 +212,7 @@ public:
EXCLUSIVE_LOCKS_REQUIRED(!m_cs_fee_estimator); EXCLUSIVE_LOCKS_REQUIRED(!m_cs_fee_estimator);
/** Remove a transaction from the mempool tracking stats for non BLOCK removal reasons*/ /** Remove a transaction from the mempool tracking stats for non BLOCK removal reasons*/
bool removeTx(uint256 hash) bool removeTx(Txid hash)
EXCLUSIVE_LOCKS_REQUIRED(!m_cs_fee_estimator); EXCLUSIVE_LOCKS_REQUIRED(!m_cs_fee_estimator);
/** DEPRECATED. Return a feerate estimate */ /** DEPRECATED. Return a feerate estimate */
@@ -287,7 +287,7 @@ private:
}; };
// map of txids to information about that transaction // map of txids to information about that transaction
std::map<uint256, TxStatsInfo> mapMemPoolTxs GUARDED_BY(m_cs_fee_estimator); std::map<Txid, TxStatsInfo> mapMemPoolTxs GUARDED_BY(m_cs_fee_estimator);
/** Classes to track historical data on transaction confirmations */ /** Classes to track historical data on transaction confirmations */
std::unique_ptr<TxConfirmStats> feeStats PT_GUARDED_BY(m_cs_fee_estimator); std::unique_ptr<TxConfirmStats> feeStats PT_GUARDED_BY(m_cs_fee_estimator);
@@ -315,7 +315,7 @@ private:
unsigned int MaxUsableEstimate() const EXCLUSIVE_LOCKS_REQUIRED(m_cs_fee_estimator); unsigned int MaxUsableEstimate() const EXCLUSIVE_LOCKS_REQUIRED(m_cs_fee_estimator);
/** A non-thread-safe helper for the removeTx function */ /** A non-thread-safe helper for the removeTx function */
bool _removeTx(const uint256& hash, bool inBlock) bool _removeTx(const Txid& hash, bool inBlock)
EXCLUSIVE_LOCKS_REQUIRED(m_cs_fee_estimator); EXCLUSIVE_LOCKS_REQUIRED(m_cs_fee_estimator);
}; };
+5 -5
View File
@@ -16,7 +16,7 @@
/** IsTopoSortedPackage where a set of txids has been pre-populated. The set is assumed to be correct and /** IsTopoSortedPackage where a set of txids has been pre-populated. The set is assumed to be correct and
* is mutated within this function (even if return value is false). */ * is mutated within this function (even if return value is false). */
bool IsTopoSortedPackage(const Package& txns, std::unordered_set<uint256, SaltedTxidHasher>& later_txids) bool IsTopoSortedPackage(const Package& txns, std::unordered_set<Txid, SaltedTxidHasher>& later_txids)
{ {
// Avoid misusing this function: later_txids should contain the txids of txns. // Avoid misusing this function: later_txids should contain the txids of txns.
Assume(txns.size() == later_txids.size()); Assume(txns.size() == later_txids.size());
@@ -42,7 +42,7 @@ bool IsTopoSortedPackage(const Package& txns, std::unordered_set<uint256, Salted
bool IsTopoSortedPackage(const Package& txns) bool IsTopoSortedPackage(const Package& txns)
{ {
std::unordered_set<uint256, SaltedTxidHasher> later_txids; std::unordered_set<Txid, SaltedTxidHasher> later_txids;
std::transform(txns.cbegin(), txns.cend(), std::inserter(later_txids, later_txids.end()), std::transform(txns.cbegin(), txns.cend(), std::inserter(later_txids, later_txids.end()),
[](const auto& tx) { return tx->GetHash(); }); [](const auto& tx) { return tx->GetHash(); });
@@ -91,7 +91,7 @@ bool IsWellFormedPackage(const Package& txns, PackageValidationState& state, boo
return state.Invalid(PackageValidationResult::PCKG_POLICY, "package-too-large"); return state.Invalid(PackageValidationResult::PCKG_POLICY, "package-too-large");
} }
std::unordered_set<uint256, SaltedTxidHasher> later_txids; std::unordered_set<Txid, SaltedTxidHasher> later_txids;
std::transform(txns.cbegin(), txns.cend(), std::inserter(later_txids, later_txids.end()), std::transform(txns.cbegin(), txns.cend(), std::inserter(later_txids, later_txids.end()),
[](const auto& tx) { return tx->GetHash(); }); [](const auto& tx) { return tx->GetHash(); });
@@ -123,7 +123,7 @@ bool IsChildWithParents(const Package& package)
// The package is expected to be sorted, so the last transaction is the child. // The package is expected to be sorted, so the last transaction is the child.
const auto& child = package.back(); const auto& child = package.back();
std::unordered_set<uint256, SaltedTxidHasher> input_txids; std::unordered_set<Txid, SaltedTxidHasher> input_txids;
std::transform(child->vin.cbegin(), child->vin.cend(), std::transform(child->vin.cbegin(), child->vin.cend(),
std::inserter(input_txids, input_txids.end()), std::inserter(input_txids, input_txids.end()),
[](const auto& input) { return input.prevout.hash; }); [](const auto& input) { return input.prevout.hash; });
@@ -136,7 +136,7 @@ bool IsChildWithParents(const Package& package)
bool IsChildWithParentsTree(const Package& package) bool IsChildWithParentsTree(const Package& package)
{ {
if (!IsChildWithParents(package)) return false; if (!IsChildWithParents(package)) return false;
std::unordered_set<uint256, SaltedTxidHasher> parent_txids; std::unordered_set<Txid, SaltedTxidHasher> parent_txids;
std::transform(package.cbegin(), package.cend() - 1, std::inserter(parent_txids, parent_txids.end()), std::transform(package.cbegin(), package.cend() - 1, std::inserter(parent_txids, parent_txids.end()),
[](const auto& ptx) { return ptx->GetHash(); }); [](const auto& ptx) { return ptx->GetHash(); });
// Each parent must not have an input who is one of the other parents. // Each parent must not have an input who is one of the other parents.
+5 -6
View File
@@ -62,7 +62,6 @@ std::optional<std::string> GetEntriesForConflicts(const CTransaction& tx,
CTxMemPool::setEntries& all_conflicts) CTxMemPool::setEntries& all_conflicts)
{ {
AssertLockHeld(pool.cs); AssertLockHeld(pool.cs);
const uint256 txid = tx.GetHash();
uint64_t nConflictingCount = 0; uint64_t nConflictingCount = 0;
for (const auto& mi : iters_conflicting) { for (const auto& mi : iters_conflicting) {
nConflictingCount += mi->GetCountWithDescendants(); nConflictingCount += mi->GetCountWithDescendants();
@@ -72,7 +71,7 @@ std::optional<std::string> GetEntriesForConflicts(const CTransaction& tx,
// times), but we just want to be conservative to avoid doing too much work. // times), but we just want to be conservative to avoid doing too much work.
if (nConflictingCount > MAX_REPLACEMENT_CANDIDATES) { if (nConflictingCount > MAX_REPLACEMENT_CANDIDATES) {
return strprintf("rejecting replacement %s; too many potential replacements (%d > %d)", return strprintf("rejecting replacement %s; too many potential replacements (%d > %d)",
txid.ToString(), tx.GetHash().ToString(),
nConflictingCount, nConflictingCount,
MAX_REPLACEMENT_CANDIDATES); MAX_REPLACEMENT_CANDIDATES);
} }
@@ -89,7 +88,7 @@ std::optional<std::string> HasNoNewUnconfirmed(const CTransaction& tx,
const CTxMemPool::setEntries& iters_conflicting) const CTxMemPool::setEntries& iters_conflicting)
{ {
AssertLockHeld(pool.cs); AssertLockHeld(pool.cs);
std::set<uint256> parents_of_conflicts; std::set<Txid> parents_of_conflicts;
for (const auto& mi : iters_conflicting) { for (const auto& mi : iters_conflicting) {
for (const CTxIn& txin : mi->GetTx().vin) { for (const CTxIn& txin : mi->GetTx().vin) {
parents_of_conflicts.insert(txin.prevout.hash); parents_of_conflicts.insert(txin.prevout.hash);
@@ -118,7 +117,7 @@ std::optional<std::string> HasNoNewUnconfirmed(const CTransaction& tx,
std::optional<std::string> EntriesAndTxidsDisjoint(const CTxMemPool::setEntries& ancestors, std::optional<std::string> EntriesAndTxidsDisjoint(const CTxMemPool::setEntries& ancestors,
const std::set<Txid>& direct_conflicts, const std::set<Txid>& direct_conflicts,
const uint256& txid) const Txid& txid)
{ {
for (CTxMemPool::txiter ancestorIt : ancestors) { for (CTxMemPool::txiter ancestorIt : ancestors) {
const Txid& hashAncestor = ancestorIt->GetTx().GetHash(); const Txid& hashAncestor = ancestorIt->GetTx().GetHash();
@@ -133,7 +132,7 @@ std::optional<std::string> EntriesAndTxidsDisjoint(const CTxMemPool::setEntries&
std::optional<std::string> PaysMoreThanConflicts(const CTxMemPool::setEntries& iters_conflicting, std::optional<std::string> PaysMoreThanConflicts(const CTxMemPool::setEntries& iters_conflicting,
CFeeRate replacement_feerate, CFeeRate replacement_feerate,
const uint256& txid) const Txid& txid)
{ {
for (const auto& mi : iters_conflicting) { for (const auto& mi : iters_conflicting) {
// Don't allow the replacement to reduce the feerate of the mempool. // Don't allow the replacement to reduce the feerate of the mempool.
@@ -161,7 +160,7 @@ std::optional<std::string> PaysForRBF(CAmount original_fees,
CAmount replacement_fees, CAmount replacement_fees,
size_t replacement_vsize, size_t replacement_vsize,
CFeeRate relay_fee, CFeeRate relay_fee,
const uint256& txid) const Txid& txid)
{ {
// Rule #3: The replacement fees must be greater than or equal to fees of the // Rule #3: The replacement fees must be greater than or equal to fees of the
// transactions it replaces, otherwise the bandwidth used by those conflicting transactions // transactions it replaces, otherwise the bandwidth used by those conflicting transactions
+3 -3
View File
@@ -90,7 +90,7 @@ std::optional<std::string> HasNoNewUnconfirmed(const CTransaction& tx, const CTx
*/ */
std::optional<std::string> EntriesAndTxidsDisjoint(const CTxMemPool::setEntries& ancestors, std::optional<std::string> EntriesAndTxidsDisjoint(const CTxMemPool::setEntries& ancestors,
const std::set<Txid>& direct_conflicts, const std::set<Txid>& direct_conflicts,
const uint256& txid); const Txid& txid);
/** Check that the feerate of the replacement transaction(s) is higher than the feerate of each /** Check that the feerate of the replacement transaction(s) is higher than the feerate of each
* of the transactions in iters_conflicting. * of the transactions in iters_conflicting.
@@ -98,7 +98,7 @@ std::optional<std::string> EntriesAndTxidsDisjoint(const CTxMemPool::setEntries&
* @returns error message if fees insufficient, otherwise std::nullopt. * @returns error message if fees insufficient, otherwise std::nullopt.
*/ */
std::optional<std::string> PaysMoreThanConflicts(const CTxMemPool::setEntries& iters_conflicting, std::optional<std::string> PaysMoreThanConflicts(const CTxMemPool::setEntries& iters_conflicting,
CFeeRate replacement_feerate, const uint256& txid); CFeeRate replacement_feerate, const Txid& txid);
/** The replacement transaction must pay more fees than the original transactions. The additional /** The replacement transaction must pay more fees than the original transactions. The additional
* fees must pay for the replacement's bandwidth at or above the incremental relay feerate. * fees must pay for the replacement's bandwidth at or above the incremental relay feerate.
@@ -113,7 +113,7 @@ std::optional<std::string> PaysForRBF(CAmount original_fees,
CAmount replacement_fees, CAmount replacement_fees,
size_t replacement_vsize, size_t replacement_vsize,
CFeeRate relay_fee, CFeeRate relay_fee,
const uint256& txid); const Txid& txid);
/** /**
* The replacement transaction must improve the feerate diagram of the mempool. * The replacement transaction must improve the feerate diagram of the mempool.
+1 -1
View File
@@ -8,11 +8,11 @@
#include <consensus/amount.h> #include <consensus/amount.h>
#include <crypto/hex_base.h> #include <crypto/hex_base.h>
#include <hash.h> #include <hash.h>
#include <primitives/transaction_identifier.h>
#include <script/script.h> #include <script/script.h>
#include <serialize.h> #include <serialize.h>
#include <tinyformat.h> #include <tinyformat.h>
#include <uint256.h> #include <uint256.h>
#include <util/transaction_identifier.h>
#include <algorithm> #include <algorithm>
#include <cassert> #include <cassert>
+1 -1
View File
@@ -8,10 +8,10 @@
#include <attributes.h> #include <attributes.h>
#include <consensus/amount.h> #include <consensus/amount.h>
#include <primitives/transaction_identifier.h> // IWYU pragma: export
#include <script/script.h> #include <script/script.h>
#include <serialize.h> #include <serialize.h>
#include <uint256.h> #include <uint256.h>
#include <util/transaction_identifier.h> // IWYU pragma: export
#include <cstddef> #include <cstddef>
#include <cstdint> #include <cstdint>
@@ -2,8 +2,8 @@
// Distributed under the MIT software license, see the accompanying // Distributed under the MIT software license, see the accompanying
// file COPYING or https://opensource.org/license/mit. // file COPYING or https://opensource.org/license/mit.
#ifndef BITCOIN_UTIL_TRANSACTION_IDENTIFIER_H #ifndef BITCOIN_PRIMITIVES_TRANSACTION_IDENTIFIER_H
#define BITCOIN_UTIL_TRANSACTION_IDENTIFIER_H #define BITCOIN_PRIMITIVES_TRANSACTION_IDENTIFIER_H
#include <attributes.h> #include <attributes.h>
#include <uint256.h> #include <uint256.h>
@@ -24,9 +24,6 @@ class transaction_identifier
// Note: Use FromUint256 externally instead. // Note: Use FromUint256 externally instead.
transaction_identifier(const uint256& wrapped) : m_wrapped{wrapped} {} transaction_identifier(const uint256& wrapped) : m_wrapped{wrapped} {}
// TODO: Comparisons with uint256 should be disallowed once we have
// converted most of the code to using the new txid types.
constexpr int Compare(const uint256& other) const { return m_wrapped.Compare(other); }
constexpr int Compare(const transaction_identifier<has_witness>& other) const { return m_wrapped.Compare(other.m_wrapped); } constexpr int Compare(const transaction_identifier<has_witness>& other) const { return m_wrapped.Compare(other.m_wrapped); }
template <typename Other> template <typename Other>
constexpr int Compare(const Other& other) const constexpr int Compare(const Other& other) const
@@ -65,15 +62,6 @@ public:
constexpr const std::byte* end() const { return reinterpret_cast<const std::byte*>(m_wrapped.end()); } constexpr const std::byte* end() const { return reinterpret_cast<const std::byte*>(m_wrapped.end()); }
template <typename Stream> void Serialize(Stream& s) const { m_wrapped.Serialize(s); } template <typename Stream> void Serialize(Stream& s) const { m_wrapped.Serialize(s); }
template <typename Stream> void Unserialize(Stream& s) { m_wrapped.Unserialize(s); } template <typename Stream> void Unserialize(Stream& s) { m_wrapped.Unserialize(s); }
/** Conversion function to `uint256`.
*
* Note: new code should use `ToUint256`.
*
* TODO: This should be removed once the majority of the code has switched
* to using the Txid and Wtxid types. Until then it makes for a smoother
* transition to allow this conversion. */
operator const uint256&() const LIFETIMEBOUND { return m_wrapped; }
}; };
/** Txid commits to all transaction fields except the witness. */ /** Txid commits to all transaction fields except the witness. */
@@ -103,4 +91,4 @@ public:
} }
}; };
#endif // BITCOIN_UTIL_TRANSACTION_IDENTIFIER_H #endif // BITCOIN_PRIMITIVES_TRANSACTION_IDENTIFIER_H
+1 -1
View File
@@ -5,9 +5,9 @@
#ifndef BITCOIN_QT_SENDCOINSDIALOG_H #ifndef BITCOIN_QT_SENDCOINSDIALOG_H
#define BITCOIN_QT_SENDCOINSDIALOG_H #define BITCOIN_QT_SENDCOINSDIALOG_H
#include <primitives/transaction_identifier.h>
#include <qt/clientmodel.h> #include <qt/clientmodel.h>
#include <qt/walletmodel.h> #include <qt/walletmodel.h>
#include <util/transaction_identifier.h>
#include <QDialog> #include <QDialog>
#include <QMessageBox> #include <QMessageBox>
+1 -1
View File
@@ -6,8 +6,8 @@
#define BITCOIN_QT_TRANSACTIONRECORD_H #define BITCOIN_QT_TRANSACTIONRECORD_H
#include <consensus/amount.h> #include <consensus/amount.h>
#include <primitives/transaction_identifier.h>
#include <uint256.h> #include <uint256.h>
#include <util/transaction_identifier.h>
#include <QList> #include <QList>
#include <QString> #include <QString>
+1 -1
View File
@@ -7,8 +7,8 @@
#include <qt/guiutil.h> #include <qt/guiutil.h>
#include <primitives/transaction_identifier.h>
#include <uint256.h> #include <uint256.h>
#include <util/transaction_identifier.h>
#include <QWidget> #include <QWidget>
#include <QKeyEvent> #include <QKeyEvent>
+1 -1
View File
@@ -10,8 +10,8 @@
#include <qt/walletmodeltransaction.h> #include <qt/walletmodeltransaction.h>
#include <interfaces/wallet.h> #include <interfaces/wallet.h>
#include <primitives/transaction_identifier.h>
#include <support/allocators/secure.h> #include <support/allocators/secure.h>
#include <util/transaction_identifier.h>
#include <vector> #include <vector>
+1 -1
View File
@@ -817,7 +817,7 @@ static bool rest_tx(const std::any& context, HTTPRequest* req, const std::string
std::string hashStr; std::string hashStr;
const RESTResponseFormat rf = ParseDataFormat(hashStr, uri_part); const RESTResponseFormat rf = ParseDataFormat(hashStr, uri_part);
auto hash{uint256::FromHex(hashStr)}; auto hash{Txid::FromHex(hashStr)};
if (!hash) { if (!hash) {
return RESTERR(req, HTTP_BAD_REQUEST, "Invalid hash: " + hashStr); return RESTERR(req, HTTP_BAD_REQUEST, "Invalid hash: " + hashStr);
} }
+9 -11
View File
@@ -461,12 +461,12 @@ static RPCHelpMan getmempoolancestors()
if (!request.params[1].isNull()) if (!request.params[1].isNull())
fVerbose = request.params[1].get_bool(); fVerbose = request.params[1].get_bool();
uint256 hash = ParseHashV(request.params[0], "parameter 1"); auto txid{Txid::FromUint256(ParseHashV(request.params[0], "txid"))};
const CTxMemPool& mempool = EnsureAnyMemPool(request.context); const CTxMemPool& mempool = EnsureAnyMemPool(request.context);
LOCK(mempool.cs); LOCK(mempool.cs);
const auto entry{mempool.GetEntry(Txid::FromUint256(hash))}; const auto entry{mempool.GetEntry(txid)};
if (entry == nullptr) { if (entry == nullptr) {
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Transaction not in mempool"); throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Transaction not in mempool");
} }
@@ -483,10 +483,9 @@ static RPCHelpMan getmempoolancestors()
UniValue o(UniValue::VOBJ); UniValue o(UniValue::VOBJ);
for (CTxMemPool::txiter ancestorIt : ancestors) { for (CTxMemPool::txiter ancestorIt : ancestors) {
const CTxMemPoolEntry &e = *ancestorIt; const CTxMemPoolEntry &e = *ancestorIt;
const uint256& _hash = e.GetTx().GetHash();
UniValue info(UniValue::VOBJ); UniValue info(UniValue::VOBJ);
entryToJSON(mempool, info, e); entryToJSON(mempool, info, e);
o.pushKV(_hash.ToString(), std::move(info)); o.pushKV(e.GetTx().GetHash().ToString(), std::move(info));
} }
return o; return o;
} }
@@ -523,7 +522,7 @@ static RPCHelpMan getmempooldescendants()
if (!request.params[1].isNull()) if (!request.params[1].isNull())
fVerbose = request.params[1].get_bool(); fVerbose = request.params[1].get_bool();
Txid txid{Txid::FromUint256(ParseHashV(request.params[0], "parameter 1"))}; auto txid{Txid::FromUint256(ParseHashV(request.params[0], "txid"))};
const CTxMemPool& mempool = EnsureAnyMemPool(request.context); const CTxMemPool& mempool = EnsureAnyMemPool(request.context);
LOCK(mempool.cs); LOCK(mempool.cs);
@@ -549,10 +548,9 @@ static RPCHelpMan getmempooldescendants()
UniValue o(UniValue::VOBJ); UniValue o(UniValue::VOBJ);
for (CTxMemPool::txiter descendantIt : setDescendants) { for (CTxMemPool::txiter descendantIt : setDescendants) {
const CTxMemPoolEntry &e = *descendantIt; const CTxMemPoolEntry &e = *descendantIt;
const uint256& _hash = e.GetTx().GetHash();
UniValue info(UniValue::VOBJ); UniValue info(UniValue::VOBJ);
entryToJSON(mempool, info, e); entryToJSON(mempool, info, e);
o.pushKV(_hash.ToString(), std::move(info)); o.pushKV(e.GetTx().GetHash().ToString(), std::move(info));
} }
return o; return o;
} }
@@ -576,12 +574,12 @@ static RPCHelpMan getmempoolentry()
}, },
[&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
{ {
uint256 hash = ParseHashV(request.params[0], "parameter 1"); auto txid{Txid::FromUint256(ParseHashV(request.params[0], "txid"))};
const CTxMemPool& mempool = EnsureAnyMemPool(request.context); const CTxMemPool& mempool = EnsureAnyMemPool(request.context);
LOCK(mempool.cs); LOCK(mempool.cs);
const auto entry{mempool.GetEntry(Txid::FromUint256(hash))}; const auto entry{mempool.GetEntry(txid)};
if (entry == nullptr) { if (entry == nullptr) {
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Transaction not in mempool"); throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Transaction not in mempool");
} }
@@ -1080,7 +1078,7 @@ static RPCHelpMan submitpackage()
UniValue rpc_result{UniValue::VOBJ}; UniValue rpc_result{UniValue::VOBJ};
rpc_result.pushKV("package_msg", package_msg); rpc_result.pushKV("package_msg", package_msg);
UniValue tx_result_map{UniValue::VOBJ}; UniValue tx_result_map{UniValue::VOBJ};
std::set<uint256> replaced_txids; std::set<Txid> replaced_txids;
for (const auto& tx : txns) { for (const auto& tx : txns) {
UniValue result_inner{UniValue::VOBJ}; UniValue result_inner{UniValue::VOBJ};
result_inner.pushKV("txid", tx->GetHash().GetHex()); result_inner.pushKV("txid", tx->GetHash().GetHex());
@@ -1124,7 +1122,7 @@ static RPCHelpMan submitpackage()
} }
rpc_result.pushKV("tx-results", std::move(tx_result_map)); rpc_result.pushKV("tx-results", std::move(tx_result_map));
UniValue replaced_list(UniValue::VARR); UniValue replaced_list(UniValue::VARR);
for (const uint256& hash : replaced_txids) replaced_list.push_back(hash.ToString()); for (const auto& txid : replaced_txids) replaced_list.push_back(txid.ToString());
rpc_result.pushKV("replaced-transactions", std::move(replaced_list)); rpc_result.pushKV("replaced-transactions", std::move(replaced_list));
return rpc_result; return rpc_result;
}, },
+7 -7
View File
@@ -353,8 +353,8 @@ static RPCHelpMan generateblock()
const auto& str{raw_txs_or_txids[i].get_str()}; const auto& str{raw_txs_or_txids[i].get_str()};
CMutableTransaction mtx; CMutableTransaction mtx;
if (auto hash{uint256::FromHex(str)}) { if (auto txid{Txid::FromHex(str)}) {
const auto tx{mempool.get(*hash)}; const auto tx{mempool.get(*txid)};
if (!tx) { if (!tx) {
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, strprintf("Transaction %s not in mempool.", str)); throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, strprintf("Transaction %s not in mempool.", str));
} }
@@ -517,7 +517,7 @@ static RPCHelpMan prioritisetransaction()
{ {
LOCK(cs_main); LOCK(cs_main);
uint256 hash(ParseHashV(request.params[0], "txid")); auto txid{Txid::FromUint256(ParseHashV(request.params[0], "txid"))};
const auto dummy{self.MaybeArg<double>("dummy")}; const auto dummy{self.MaybeArg<double>("dummy")};
CAmount nAmount = request.params[2].getInt<int64_t>(); CAmount nAmount = request.params[2].getInt<int64_t>();
@@ -528,12 +528,12 @@ static RPCHelpMan prioritisetransaction()
CTxMemPool& mempool = EnsureAnyMemPool(request.context); CTxMemPool& mempool = EnsureAnyMemPool(request.context);
// Non-0 fee dust transactions are not allowed for entry, and modification not allowed afterwards // Non-0 fee dust transactions are not allowed for entry, and modification not allowed afterwards
const auto& tx = mempool.get(hash); const auto& tx = mempool.get(txid);
if (mempool.m_opts.require_standard && tx && !GetDust(*tx, mempool.m_opts.dust_relay_feerate).empty()) { if (mempool.m_opts.require_standard && tx && !GetDust(*tx, mempool.m_opts.dust_relay_feerate).empty()) {
throw JSONRPCError(RPC_INVALID_PARAMETER, "Priority is not supported for transactions with dust outputs."); throw JSONRPCError(RPC_INVALID_PARAMETER, "Priority is not supported for transactions with dust outputs.");
} }
mempool.PrioritiseTransaction(hash, nAmount); mempool.PrioritiseTransaction(txid, nAmount);
return true; return true;
}, },
}; };
@@ -887,14 +887,14 @@ static RPCHelpMan getblocktemplate()
UniValue aCaps(UniValue::VARR); aCaps.push_back("proposal"); UniValue aCaps(UniValue::VARR); aCaps.push_back("proposal");
UniValue transactions(UniValue::VARR); UniValue transactions(UniValue::VARR);
std::map<uint256, int64_t> setTxIndex; std::map<Txid, int64_t> setTxIndex;
std::vector<CAmount> tx_fees{block_template->getTxFees()}; std::vector<CAmount> tx_fees{block_template->getTxFees()};
std::vector<CAmount> tx_sigops{block_template->getTxSigops()}; std::vector<CAmount> tx_sigops{block_template->getTxSigops()};
int i = 0; int i = 0;
for (const auto& it : block.vtx) { for (const auto& it : block.vtx) {
const CTransaction& tx = *it; const CTransaction& tx = *it;
uint256 txHash = tx.GetHash(); Txid txHash = tx.GetHash();
setTxIndex[txHash] = i++; setTxIndex[txHash] = i++;
if (tx.IsCoinBase()) if (tx.IsCoinBase())
+3 -3
View File
@@ -322,10 +322,10 @@ static RPCHelpMan getrawtransaction()
const NodeContext& node = EnsureAnyNodeContext(request.context); const NodeContext& node = EnsureAnyNodeContext(request.context);
ChainstateManager& chainman = EnsureChainman(node); ChainstateManager& chainman = EnsureChainman(node);
uint256 hash = ParseHashV(request.params[0], "parameter 1"); auto txid{Txid::FromUint256(ParseHashV(request.params[0], "parameter 1"))};
const CBlockIndex* blockindex = nullptr; const CBlockIndex* blockindex = nullptr;
if (hash == chainman.GetParams().GenesisBlock().hashMerkleRoot) { if (txid.ToUint256() == chainman.GetParams().GenesisBlock().hashMerkleRoot) {
// Special exception for the genesis block coinbase transaction // Special exception for the genesis block coinbase transaction
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "The genesis block coinbase is not considered an ordinary transaction and cannot be retrieved"); throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "The genesis block coinbase is not considered an ordinary transaction and cannot be retrieved");
} }
@@ -348,7 +348,7 @@ static RPCHelpMan getrawtransaction()
} }
uint256 hash_block; uint256 hash_block;
const CTransactionRef tx = GetTransaction(blockindex, node.mempool.get(), hash, hash_block, chainman.m_blockman); const CTransactionRef tx = GetTransaction(blockindex, node.mempool.get(), txid, hash_block, chainman.m_blockman);
if (!tx) { if (!tx) {
std::string errmsg; std::string errmsg;
if (blockindex) { if (blockindex) {
+3 -3
View File
@@ -150,7 +150,7 @@ static RPCHelpMan verifytxoutproof()
UniValue res(UniValue::VARR); UniValue res(UniValue::VARR);
std::vector<uint256> vMatch; std::vector<Txid> vMatch;
std::vector<unsigned int> vIndex; std::vector<unsigned int> vIndex;
if (merkleBlock.txn.ExtractMatches(vMatch, vIndex) != merkleBlock.header.hashMerkleRoot) if (merkleBlock.txn.ExtractMatches(vMatch, vIndex) != merkleBlock.header.hashMerkleRoot)
return res; return res;
@@ -165,8 +165,8 @@ static RPCHelpMan verifytxoutproof()
// Check if proof is valid, only add results if so // Check if proof is valid, only add results if so
if (pindex->nTx == merkleBlock.txn.GetNumTransactions()) { if (pindex->nTx == merkleBlock.txn.GetNumTransactions()) {
for (const uint256& hash : vMatch) { for (const auto& txid : vMatch) {
res.push_back(hash.GetHex()); res.push_back(txid.GetHex());
} }
} }
+2 -2
View File
@@ -59,9 +59,9 @@ static uint256 ComputeModifiedMerkleRoot(const CMutableTransaction& cb, const CB
{ {
std::vector<uint256> leaves; std::vector<uint256> leaves;
leaves.resize(block.vtx.size()); leaves.resize(block.vtx.size());
leaves[0] = cb.GetHash(); leaves[0] = cb.GetHash().ToUint256();
for (size_t s = 1; s < block.vtx.size(); ++s) { for (size_t s = 1; s < block.vtx.size(); ++s) {
leaves[s] = block.vtx[s]->GetHash(); leaves[s] = block.vtx[s]->GetHash().ToUint256();
} }
return ComputeMerkleRoot(std::move(leaves)); return ComputeMerkleRoot(std::move(leaves));
} }
+2 -2
View File
@@ -154,7 +154,7 @@ BOOST_AUTO_TEST_CASE(NonCoinbasePreforwardRTTest)
AddToMempool(pool, entry.FromTx(block.vtx[2])); AddToMempool(pool, entry.FromTx(block.vtx[2]));
BOOST_CHECK_EQUAL(pool.get(block.vtx[2]->GetHash()).use_count(), SHARED_TX_OFFSET + 0); BOOST_CHECK_EQUAL(pool.get(block.vtx[2]->GetHash()).use_count(), SHARED_TX_OFFSET + 0);
uint256 txhash; Txid txhash;
// Test with pre-forwarding tx 1, but not coinbase // Test with pre-forwarding tx 1, but not coinbase
{ {
@@ -225,7 +225,7 @@ BOOST_AUTO_TEST_CASE(SufficientPreforwardRTTest)
AddToMempool(pool, entry.FromTx(block.vtx[1])); AddToMempool(pool, entry.FromTx(block.vtx[1]));
BOOST_CHECK_EQUAL(pool.get(block.vtx[1]->GetHash()).use_count(), SHARED_TX_OFFSET + 0); BOOST_CHECK_EQUAL(pool.get(block.vtx[1]->GetHash()).use_count(), SHARED_TX_OFFSET + 0);
uint256 txhash; Txid txhash;
// Test with pre-forwarding coinbase + tx 2 with tx 1 in mempool // Test with pre-forwarding coinbase + tx 2 with tx 1 in mempool
{ {
+21 -21
View File
@@ -181,12 +181,12 @@ BOOST_AUTO_TEST_CASE(merkle_block_1)
BOOST_CHECK_EQUAL(merkleBlock.header.GetHash().GetHex(), block.GetHash().GetHex()); BOOST_CHECK_EQUAL(merkleBlock.header.GetHash().GetHex(), block.GetHash().GetHex());
BOOST_CHECK_EQUAL(merkleBlock.vMatchedTxn.size(), 1U); BOOST_CHECK_EQUAL(merkleBlock.vMatchedTxn.size(), 1U);
std::pair<unsigned int, uint256> pair = merkleBlock.vMatchedTxn[0]; std::pair<unsigned int, Txid> pair = merkleBlock.vMatchedTxn[0];
BOOST_CHECK(merkleBlock.vMatchedTxn[0].second == uint256{"74d681e0e03bafa802c8aa084379aa98d9fcd632ddc2ed9782b586ec87451f20"}); BOOST_CHECK(merkleBlock.vMatchedTxn[0].second == Txid::FromUint256(uint256{"74d681e0e03bafa802c8aa084379aa98d9fcd632ddc2ed9782b586ec87451f20"}));
BOOST_CHECK(merkleBlock.vMatchedTxn[0].first == 8); BOOST_CHECK(merkleBlock.vMatchedTxn[0].first == 8);
std::vector<uint256> vMatched; std::vector<Txid> vMatched;
std::vector<unsigned int> vIndex; std::vector<unsigned int> vIndex;
BOOST_CHECK(merkleBlock.txn.ExtractMatches(vMatched, vIndex) == block.hashMerkleRoot); BOOST_CHECK(merkleBlock.txn.ExtractMatches(vMatched, vIndex) == block.hashMerkleRoot);
BOOST_CHECK(vMatched.size() == merkleBlock.vMatchedTxn.size()); BOOST_CHECK(vMatched.size() == merkleBlock.vMatchedTxn.size());
@@ -202,7 +202,7 @@ BOOST_AUTO_TEST_CASE(merkle_block_1)
BOOST_CHECK(merkleBlock.vMatchedTxn[1] == pair); BOOST_CHECK(merkleBlock.vMatchedTxn[1] == pair);
BOOST_CHECK(merkleBlock.vMatchedTxn[0].second == uint256{"dd1fd2a6fc16404faf339881a90adbde7f4f728691ac62e8f168809cdfae1053"}); BOOST_CHECK(merkleBlock.vMatchedTxn[0].second == Txid::FromUint256(uint256{"dd1fd2a6fc16404faf339881a90adbde7f4f728691ac62e8f168809cdfae1053"}));
BOOST_CHECK(merkleBlock.vMatchedTxn[0].first == 7); BOOST_CHECK(merkleBlock.vMatchedTxn[0].first == 7);
BOOST_CHECK(merkleBlock.txn.ExtractMatches(vMatched, vIndex) == block.hashMerkleRoot); BOOST_CHECK(merkleBlock.txn.ExtractMatches(vMatched, vIndex) == block.hashMerkleRoot);
@@ -229,12 +229,12 @@ BOOST_AUTO_TEST_CASE(merkle_block_2)
BOOST_CHECK(merkleBlock.header.GetHash() == block.GetHash()); BOOST_CHECK(merkleBlock.header.GetHash() == block.GetHash());
BOOST_CHECK(merkleBlock.vMatchedTxn.size() == 1); BOOST_CHECK(merkleBlock.vMatchedTxn.size() == 1);
std::pair<unsigned int, uint256> pair = merkleBlock.vMatchedTxn[0]; std::pair<unsigned int, Txid> pair = merkleBlock.vMatchedTxn[0];
BOOST_CHECK(merkleBlock.vMatchedTxn[0].second == uint256{"e980fe9f792d014e73b95203dc1335c5f9ce19ac537a419e6df5b47aecb93b70"}); BOOST_CHECK(merkleBlock.vMatchedTxn[0].second == Txid::FromUint256(uint256{"e980fe9f792d014e73b95203dc1335c5f9ce19ac537a419e6df5b47aecb93b70"}));
BOOST_CHECK(merkleBlock.vMatchedTxn[0].first == 0); BOOST_CHECK(merkleBlock.vMatchedTxn[0].first == 0);
std::vector<uint256> vMatched; std::vector<Txid> vMatched;
std::vector<unsigned int> vIndex; std::vector<unsigned int> vIndex;
BOOST_CHECK(merkleBlock.txn.ExtractMatches(vMatched, vIndex) == block.hashMerkleRoot); BOOST_CHECK(merkleBlock.txn.ExtractMatches(vMatched, vIndex) == block.hashMerkleRoot);
BOOST_CHECK(vMatched.size() == merkleBlock.vMatchedTxn.size()); BOOST_CHECK(vMatched.size() == merkleBlock.vMatchedTxn.size());
@@ -253,13 +253,13 @@ BOOST_AUTO_TEST_CASE(merkle_block_2)
BOOST_CHECK(pair == merkleBlock.vMatchedTxn[0]); BOOST_CHECK(pair == merkleBlock.vMatchedTxn[0]);
BOOST_CHECK(merkleBlock.vMatchedTxn[1].second == uint256{"28204cad1d7fc1d199e8ef4fa22f182de6258a3eaafe1bbe56ebdcacd3069a5f"}); BOOST_CHECK(merkleBlock.vMatchedTxn[1].second == Txid::FromUint256(uint256{"28204cad1d7fc1d199e8ef4fa22f182de6258a3eaafe1bbe56ebdcacd3069a5f"}));
BOOST_CHECK(merkleBlock.vMatchedTxn[1].first == 1); BOOST_CHECK(merkleBlock.vMatchedTxn[1].first == 1);
BOOST_CHECK(merkleBlock.vMatchedTxn[2].second == uint256{"6b0f8a73a56c04b519f1883e8aafda643ba61a30bd1439969df21bea5f4e27e2"}); BOOST_CHECK(merkleBlock.vMatchedTxn[2].second == Txid::FromUint256(uint256{"6b0f8a73a56c04b519f1883e8aafda643ba61a30bd1439969df21bea5f4e27e2"}));
BOOST_CHECK(merkleBlock.vMatchedTxn[2].first == 2); BOOST_CHECK(merkleBlock.vMatchedTxn[2].first == 2);
BOOST_CHECK(merkleBlock.vMatchedTxn[3].second == uint256{"3c1d7e82342158e4109df2e0b6348b6e84e403d8b4046d7007663ace63cddb23"}); BOOST_CHECK(merkleBlock.vMatchedTxn[3].second == Txid::FromUint256(uint256{"3c1d7e82342158e4109df2e0b6348b6e84e403d8b4046d7007663ace63cddb23"}));
BOOST_CHECK(merkleBlock.vMatchedTxn[3].first == 3); BOOST_CHECK(merkleBlock.vMatchedTxn[3].first == 3);
BOOST_CHECK(merkleBlock.txn.ExtractMatches(vMatched, vIndex) == block.hashMerkleRoot); BOOST_CHECK(merkleBlock.txn.ExtractMatches(vMatched, vIndex) == block.hashMerkleRoot);
@@ -286,12 +286,12 @@ BOOST_AUTO_TEST_CASE(merkle_block_2_with_update_none)
BOOST_CHECK(merkleBlock.header.GetHash() == block.GetHash()); BOOST_CHECK(merkleBlock.header.GetHash() == block.GetHash());
BOOST_CHECK(merkleBlock.vMatchedTxn.size() == 1); BOOST_CHECK(merkleBlock.vMatchedTxn.size() == 1);
std::pair<unsigned int, uint256> pair = merkleBlock.vMatchedTxn[0]; std::pair<unsigned int, Txid> pair = merkleBlock.vMatchedTxn[0];
BOOST_CHECK(merkleBlock.vMatchedTxn[0].second == uint256{"e980fe9f792d014e73b95203dc1335c5f9ce19ac537a419e6df5b47aecb93b70"}); BOOST_CHECK(merkleBlock.vMatchedTxn[0].second == Txid::FromUint256(uint256{"e980fe9f792d014e73b95203dc1335c5f9ce19ac537a419e6df5b47aecb93b70"}));
BOOST_CHECK(merkleBlock.vMatchedTxn[0].first == 0); BOOST_CHECK(merkleBlock.vMatchedTxn[0].first == 0);
std::vector<uint256> vMatched; std::vector<Txid> vMatched;
std::vector<unsigned int> vIndex; std::vector<unsigned int> vIndex;
BOOST_CHECK(merkleBlock.txn.ExtractMatches(vMatched, vIndex) == block.hashMerkleRoot); BOOST_CHECK(merkleBlock.txn.ExtractMatches(vMatched, vIndex) == block.hashMerkleRoot);
BOOST_CHECK(vMatched.size() == merkleBlock.vMatchedTxn.size()); BOOST_CHECK(vMatched.size() == merkleBlock.vMatchedTxn.size());
@@ -310,10 +310,10 @@ BOOST_AUTO_TEST_CASE(merkle_block_2_with_update_none)
BOOST_CHECK(pair == merkleBlock.vMatchedTxn[0]); BOOST_CHECK(pair == merkleBlock.vMatchedTxn[0]);
BOOST_CHECK(merkleBlock.vMatchedTxn[1].second == uint256{"28204cad1d7fc1d199e8ef4fa22f182de6258a3eaafe1bbe56ebdcacd3069a5f"}); BOOST_CHECK(merkleBlock.vMatchedTxn[1].second == Txid::FromUint256(uint256{"28204cad1d7fc1d199e8ef4fa22f182de6258a3eaafe1bbe56ebdcacd3069a5f"}));
BOOST_CHECK(merkleBlock.vMatchedTxn[1].first == 1); BOOST_CHECK(merkleBlock.vMatchedTxn[1].first == 1);
BOOST_CHECK(merkleBlock.vMatchedTxn[2].second == uint256{"3c1d7e82342158e4109df2e0b6348b6e84e403d8b4046d7007663ace63cddb23"}); BOOST_CHECK(merkleBlock.vMatchedTxn[2].second == Txid::FromUint256(uint256{"3c1d7e82342158e4109df2e0b6348b6e84e403d8b4046d7007663ace63cddb23"}));
BOOST_CHECK(merkleBlock.vMatchedTxn[2].first == 3); BOOST_CHECK(merkleBlock.vMatchedTxn[2].first == 3);
BOOST_CHECK(merkleBlock.txn.ExtractMatches(vMatched, vIndex) == block.hashMerkleRoot); BOOST_CHECK(merkleBlock.txn.ExtractMatches(vMatched, vIndex) == block.hashMerkleRoot);
@@ -341,10 +341,10 @@ BOOST_AUTO_TEST_CASE(merkle_block_3_and_serialize)
BOOST_CHECK(merkleBlock.vMatchedTxn.size() == 1); BOOST_CHECK(merkleBlock.vMatchedTxn.size() == 1);
BOOST_CHECK(merkleBlock.vMatchedTxn[0].second == uint256{"63194f18be0af63f2c6bc9dc0f777cbefed3d9415c4af83f3ee3a3d669c00cb5"}); BOOST_CHECK(merkleBlock.vMatchedTxn[0].second == Txid::FromUint256(uint256{"63194f18be0af63f2c6bc9dc0f777cbefed3d9415c4af83f3ee3a3d669c00cb5"}));
BOOST_CHECK(merkleBlock.vMatchedTxn[0].first == 0); BOOST_CHECK(merkleBlock.vMatchedTxn[0].first == 0);
std::vector<uint256> vMatched; std::vector<Txid> vMatched;
std::vector<unsigned int> vIndex; std::vector<unsigned int> vIndex;
BOOST_CHECK(merkleBlock.txn.ExtractMatches(vMatched, vIndex) == block.hashMerkleRoot); BOOST_CHECK(merkleBlock.txn.ExtractMatches(vMatched, vIndex) == block.hashMerkleRoot);
BOOST_CHECK(vMatched.size() == merkleBlock.vMatchedTxn.size()); BOOST_CHECK(vMatched.size() == merkleBlock.vMatchedTxn.size());
@@ -376,12 +376,12 @@ BOOST_AUTO_TEST_CASE(merkle_block_4)
BOOST_CHECK(merkleBlock.header.GetHash() == block.GetHash()); BOOST_CHECK(merkleBlock.header.GetHash() == block.GetHash());
BOOST_CHECK(merkleBlock.vMatchedTxn.size() == 1); BOOST_CHECK(merkleBlock.vMatchedTxn.size() == 1);
std::pair<unsigned int, uint256> pair = merkleBlock.vMatchedTxn[0]; std::pair<unsigned int, Txid> pair = merkleBlock.vMatchedTxn[0];
BOOST_CHECK(merkleBlock.vMatchedTxn[0].second == uint256{"0a2a92f0bda4727d0a13eaddf4dd9ac6b5c61a1429e6b2b818f19b15df0ac154"}); BOOST_CHECK(merkleBlock.vMatchedTxn[0].second == Txid::FromUint256(uint256{"0a2a92f0bda4727d0a13eaddf4dd9ac6b5c61a1429e6b2b818f19b15df0ac154"}));
BOOST_CHECK(merkleBlock.vMatchedTxn[0].first == 6); BOOST_CHECK(merkleBlock.vMatchedTxn[0].first == 6);
std::vector<uint256> vMatched; std::vector<Txid> vMatched;
std::vector<unsigned int> vIndex; std::vector<unsigned int> vIndex;
BOOST_CHECK(merkleBlock.txn.ExtractMatches(vMatched, vIndex) == block.hashMerkleRoot); BOOST_CHECK(merkleBlock.txn.ExtractMatches(vMatched, vIndex) == block.hashMerkleRoot);
BOOST_CHECK(vMatched.size() == merkleBlock.vMatchedTxn.size()); BOOST_CHECK(vMatched.size() == merkleBlock.vMatchedTxn.size());
@@ -395,7 +395,7 @@ BOOST_AUTO_TEST_CASE(merkle_block_4)
BOOST_CHECK(merkleBlock.vMatchedTxn.size() == 2); BOOST_CHECK(merkleBlock.vMatchedTxn.size() == 2);
BOOST_CHECK(merkleBlock.vMatchedTxn[0].second == uint256{"02981fa052f0481dbc5868f4fc2166035a10f27a03cfd2de67326471df5bc041"}); BOOST_CHECK(merkleBlock.vMatchedTxn[0].second == Txid::FromUint256(uint256{"02981fa052f0481dbc5868f4fc2166035a10f27a03cfd2de67326471df5bc041"}));
BOOST_CHECK(merkleBlock.vMatchedTxn[0].first == 3); BOOST_CHECK(merkleBlock.vMatchedTxn[0].first == 3);
BOOST_CHECK(merkleBlock.vMatchedTxn[1] == pair); BOOST_CHECK(merkleBlock.vMatchedTxn[1] == pair);
+1 -1
View File
@@ -22,7 +22,7 @@ BOOST_AUTO_TEST_CASE(disconnectpool_memory_limits)
// is within an expected range. // is within an expected range.
// Overhead for the hashmap depends on number of buckets // Overhead for the hashmap depends on number of buckets
std::unordered_map<uint256, CTransaction*, SaltedTxidHasher> temp_map; std::unordered_map<Txid, CTransaction*, SaltedTxidHasher> temp_map;
temp_map.reserve(1); temp_map.reserve(1);
const size_t MAP_1{memusage::DynamicUsage(temp_map)}; const size_t MAP_1{memusage::DynamicUsage(temp_map)};
temp_map.reserve(100); temp_map.reserve(100);
+1 -1
View File
@@ -4,13 +4,13 @@
#include <core_io.h> #include <core_io.h>
#include <primitives/block.h> #include <primitives/block.h>
#include <primitives/transaction_identifier.h>
#include <pubkey.h> #include <pubkey.h>
#include <rpc/util.h> #include <rpc/util.h>
#include <test/fuzz/fuzz.h> #include <test/fuzz/fuzz.h>
#include <uint256.h> #include <uint256.h>
#include <univalue.h> #include <univalue.h>
#include <util/strencodings.h> #include <util/strencodings.h>
#include <util/transaction_identifier.h>
#include <algorithm> #include <algorithm>
#include <cassert> #include <cassert>
+2 -2
View File
@@ -19,7 +19,7 @@ uint256 ComputeMerkleRootFromPath(const CBlock& block, uint32_t position, const
throw std::out_of_range("Position out of range"); throw std::out_of_range("Position out of range");
} }
uint256 current_hash = block.vtx[position]->GetHash(); uint256 current_hash = block.vtx[position]->GetHash().ToUint256();
for (const uint256& sibling : merkle_path) { for (const uint256& sibling : merkle_path) {
if (position % 2 == 0) { if (position % 2 == 0) {
@@ -47,7 +47,7 @@ FUZZ_TARGET(merkle)
tx_hashes.reserve(num_txs); tx_hashes.reserve(num_txs);
for (size_t i = 0; i < num_txs; ++i) { for (size_t i = 0; i < num_txs; ++i) {
tx_hashes.push_back(block->vtx[i]->GetHash()); tx_hashes.push_back(block->vtx[i]->GetHash().ToUint256());
} }
// Test ComputeMerkleRoot // Test ComputeMerkleRoot
+1 -1
View File
@@ -43,7 +43,7 @@ FUZZ_TARGET(merkleblock)
partial_merkle_tree = merkle_block.txn; partial_merkle_tree = merkle_block.txn;
}); });
(void)partial_merkle_tree.GetNumTransactions(); (void)partial_merkle_tree.GetNumTransactions();
std::vector<uint256> matches; std::vector<Txid> matches;
std::vector<unsigned int> indices; std::vector<unsigned int> indices;
(void)partial_merkle_tree.ExtractMatches(matches, indices); (void)partial_merkle_tree.ExtractMatches(matches, indices);
} }
+1 -1
View File
@@ -139,7 +139,7 @@ CBlock ConsumeBlock(FuzzedDataProvider& fuzzed_data_provider, const uint256& pre
tx.vout[0].nValue = 0; tx.vout[0].nValue = 0;
tx.vin[0].scriptSig.resize(2); tx.vin[0].scriptSig.resize(2);
block.vtx.push_back(MakeTransactionRef(tx)); block.vtx.push_back(MakeTransactionRef(tx));
block.hashMerkleRoot = block.vtx[0]->GetHash(); block.hashMerkleRoot = block.vtx[0]->GetHash().ToUint256();
return block; return block;
} }
+2 -2
View File
@@ -314,7 +314,7 @@ FUZZ_TARGET(ephemeral_package_eval, .init = initialize_tx_pool)
if (tx_pool.exists(txid)) { if (tx_pool.exists(txid)) {
const auto tx_info{tx_pool.info(txid)}; const auto tx_info{tx_pool.info(txid)};
if (GetDust(*tx_info.tx, tx_pool.m_opts.dust_relay_feerate).empty()) { if (GetDust(*tx_info.tx, tx_pool.m_opts.dust_relay_feerate).empty()) {
tx_pool.PrioritiseTransaction(txid.ToUint256(), delta); tx_pool.PrioritiseTransaction(txid, delta);
} }
} }
} }
@@ -477,7 +477,7 @@ FUZZ_TARGET(tx_package_eval, .init = initialize_tx_pool)
txs.back()->GetHash() : txs.back()->GetHash() :
PickValue(fuzzed_data_provider, mempool_outpoints).hash; PickValue(fuzzed_data_provider, mempool_outpoints).hash;
const auto delta = fuzzed_data_provider.ConsumeIntegralInRange<CAmount>(-50 * COIN, +50 * COIN); const auto delta = fuzzed_data_provider.ConsumeIntegralInRange<CAmount>(-50 * COIN, +50 * COIN);
tx_pool.PrioritiseTransaction(txid.ToUint256(), delta); tx_pool.PrioritiseTransaction(txid, delta);
} }
// Remember all added transactions // Remember all added transactions
+1 -1
View File
@@ -85,7 +85,7 @@ FUZZ_TARGET(policy_estimator, .init = initialize_policy_estimator)
block_policy_estimator.processBlock(txs, current_height); block_policy_estimator.processBlock(txs, current_height);
}, },
[&] { [&] {
(void)block_policy_estimator.removeTx(ConsumeUInt256(fuzzed_data_provider)); (void)block_policy_estimator.removeTx(Txid::FromUint256(ConsumeUInt256(fuzzed_data_provider)));
}, },
[&] { [&] {
block_policy_estimator.FlushUnconfirmed(); block_policy_estimator.FlushUnconfirmed();
+1 -1
View File
@@ -160,7 +160,7 @@ FUZZ_TARGET(package_rbf, .init = initialize_package_rbf)
} }
if (fuzzed_data_provider.ConsumeBool()) { if (fuzzed_data_provider.ConsumeBool()) {
pool.PrioritiseTransaction(mempool_txs.back().GetHash().ToUint256(), fuzzed_data_provider.ConsumeIntegralInRange<int32_t>(-100000, 100000)); pool.PrioritiseTransaction(mempool_txs.back().GetHash(), fuzzed_data_provider.ConsumeIntegralInRange<int32_t>(-100000, 100000));
} }
} }
+2 -2
View File
@@ -288,7 +288,7 @@ FUZZ_TARGET(tx_pool_standard, .init = initialize_tx_pool)
tx->GetHash() : tx->GetHash() :
PickValue(fuzzed_data_provider, outpoints_rbf).hash; PickValue(fuzzed_data_provider, outpoints_rbf).hash;
const auto delta = fuzzed_data_provider.ConsumeIntegralInRange<CAmount>(-50 * COIN, +50 * COIN); const auto delta = fuzzed_data_provider.ConsumeIntegralInRange<CAmount>(-50 * COIN, +50 * COIN);
tx_pool.PrioritiseTransaction(txid.ToUint256(), delta); tx_pool.PrioritiseTransaction(txid, delta);
} }
// Remember all removed and added transactions // Remember all removed and added transactions
@@ -409,7 +409,7 @@ FUZZ_TARGET(tx_pool, .init = initialize_tx_pool)
mut_tx.GetHash() : mut_tx.GetHash() :
PickValue(fuzzed_data_provider, txids); PickValue(fuzzed_data_provider, txids);
const auto delta = fuzzed_data_provider.ConsumeIntegralInRange<CAmount>(-50 * COIN, +50 * COIN); const auto delta = fuzzed_data_provider.ConsumeIntegralInRange<CAmount>(-50 * COIN, +50 * COIN);
tx_pool.PrioritiseTransaction(txid.ToUint256(), delta); tx_pool.PrioritiseTransaction(txid, delta);
} }
const auto tx = MakeTransactionRef(mut_tx); const auto tx = MakeTransactionRef(mut_tx);
+4 -4
View File
@@ -29,7 +29,7 @@ static uint256 BlockBuildMerkleTree(const CBlock& block, bool* fMutated, std::ve
vMerkleTree.clear(); vMerkleTree.clear();
vMerkleTree.reserve(block.vtx.size() * 2 + 16); // Safe upper bound for the number of total nodes. vMerkleTree.reserve(block.vtx.size() * 2 + 16); // Safe upper bound for the number of total nodes.
for (std::vector<CTransactionRef>::const_iterator it(block.vtx.begin()); it != block.vtx.end(); ++it) for (std::vector<CTransactionRef>::const_iterator it(block.vtx.begin()); it != block.vtx.end(); ++it)
vMerkleTree.push_back((*it)->GetHash()); vMerkleTree.push_back((*it)->GetHash().ToUint256());
int j = 0; int j = 0;
bool mutated = false; bool mutated = false;
for (int nSize = block.vtx.size(); nSize > 1; nSize = (nSize + 1) / 2) for (int nSize = block.vtx.size(); nSize > 1; nSize = (nSize + 1) / 2)
@@ -138,7 +138,7 @@ BOOST_AUTO_TEST_CASE(merkle_test)
std::vector<uint256> newBranch = TransactionMerklePath(block, mtx); std::vector<uint256> newBranch = TransactionMerklePath(block, mtx);
std::vector<uint256> oldBranch = BlockGetMerkleBranch(block, merkleTree, mtx); std::vector<uint256> oldBranch = BlockGetMerkleBranch(block, merkleTree, mtx);
BOOST_CHECK(oldBranch == newBranch); BOOST_CHECK(oldBranch == newBranch);
BOOST_CHECK(ComputeMerkleRootFromBranch(block.vtx[mtx]->GetHash(), newBranch, mtx) == oldRoot); BOOST_CHECK(ComputeMerkleRootFromBranch(block.vtx[mtx]->GetHash().ToUint256(), newBranch, mtx) == oldRoot);
} }
} }
} }
@@ -166,7 +166,7 @@ BOOST_AUTO_TEST_CASE(merkle_test_oneTx_block)
mtx.nLockTime = 0; mtx.nLockTime = 0;
block.vtx[0] = MakeTransactionRef(std::move(mtx)); block.vtx[0] = MakeTransactionRef(std::move(mtx));
uint256 root = BlockMerkleRoot(block, &mutated); uint256 root = BlockMerkleRoot(block, &mutated);
BOOST_CHECK_EQUAL(root, block.vtx[0]->GetHash()); BOOST_CHECK_EQUAL(root, block.vtx[0]->GetHash().ToUint256());
BOOST_CHECK_EQUAL(mutated, false); BOOST_CHECK_EQUAL(mutated, false);
} }
@@ -239,7 +239,7 @@ BOOST_AUTO_TEST_CASE(merkle_test_BlockWitness)
std::vector<uint256> hashes; std::vector<uint256> hashes;
hashes.resize(block.vtx.size()); hashes.resize(block.vtx.size());
hashes[0].SetNull(); hashes[0].SetNull();
hashes[1] = block.vtx[1]->GetHash(); hashes[1] = block.vtx[1]->GetHash().ToUint256();
uint256 merkleRootofHashes = ComputeMerkleRoot(hashes); uint256 merkleRootofHashes = ComputeMerkleRoot(hashes);
+4 -4
View File
@@ -39,17 +39,17 @@ BOOST_AUTO_TEST_CASE(merkleblock_construct_from_txids_found)
// vMatchedTxn is only used when bloom filter is specified. // vMatchedTxn is only used when bloom filter is specified.
BOOST_CHECK_EQUAL(merkleBlock.vMatchedTxn.size(), 0U); BOOST_CHECK_EQUAL(merkleBlock.vMatchedTxn.size(), 0U);
std::vector<uint256> vMatched; std::vector<Txid> vMatched;
std::vector<unsigned int> vIndex; std::vector<unsigned int> vIndex;
BOOST_CHECK_EQUAL(merkleBlock.txn.ExtractMatches(vMatched, vIndex).GetHex(), block.hashMerkleRoot.GetHex()); BOOST_CHECK_EQUAL(merkleBlock.txn.ExtractMatches(vMatched, vIndex).GetHex(), block.hashMerkleRoot.GetHex());
BOOST_CHECK_EQUAL(vMatched.size(), 2U); BOOST_CHECK_EQUAL(vMatched.size(), 2U);
// Ordered by occurrence in depth-first tree traversal. // Ordered by occurrence in depth-first tree traversal.
BOOST_CHECK_EQUAL(vMatched[0].ToString(), txhash2.ToString()); BOOST_CHECK_EQUAL(vMatched[0], txhash2);
BOOST_CHECK_EQUAL(vIndex[0], 1U); BOOST_CHECK_EQUAL(vIndex[0], 1U);
BOOST_CHECK_EQUAL(vMatched[1].ToString(), txhash1.ToString()); BOOST_CHECK_EQUAL(vMatched[1], txhash1);
BOOST_CHECK_EQUAL(vIndex[1], 8U); BOOST_CHECK_EQUAL(vIndex[1], 8U);
} }
@@ -69,7 +69,7 @@ BOOST_AUTO_TEST_CASE(merkleblock_construct_from_txids_not_found)
BOOST_CHECK_EQUAL(merkleBlock.header.GetHash().GetHex(), block.GetHash().GetHex()); BOOST_CHECK_EQUAL(merkleBlock.header.GetHash().GetHex(), block.GetHash().GetHex());
BOOST_CHECK_EQUAL(merkleBlock.vMatchedTxn.size(), 0U); BOOST_CHECK_EQUAL(merkleBlock.vMatchedTxn.size(), 0U);
std::vector<uint256> vMatched; std::vector<Txid> vMatched;
std::vector<unsigned int> vIndex; std::vector<unsigned int> vIndex;
BOOST_CHECK_EQUAL(merkleBlock.txn.ExtractMatches(vMatched, vIndex).GetHex(), block.hashMerkleRoot.GetHex()); BOOST_CHECK_EQUAL(merkleBlock.txn.ExtractMatches(vMatched, vIndex).GetHex(), block.hashMerkleRoot.GetHex());
+1 -1
View File
@@ -596,7 +596,7 @@ void MinerTestingSetup::TestPrioritisedMining(const CScript& scriptPubKey, const
tx.vin[0].scriptSig = CScript() << OP_1; tx.vin[0].scriptSig = CScript() << OP_1;
tx.vout.resize(1); tx.vout.resize(1);
tx.vout[0].nValue = 5000000000LL; // 0 fee tx.vout[0].nValue = 5000000000LL; // 0 fee
uint256 hashFreePrioritisedTx = tx.GetHash(); Txid hashFreePrioritisedTx = tx.GetHash();
AddToMempool(tx_mempool, entry.Fee(0).Time(Now<NodeSeconds>()).SpendsCoinbase(true).FromTx(tx)); AddToMempool(tx_mempool, entry.Fee(0).Time(Now<NodeSeconds>()).SpendsCoinbase(true).FromTx(tx));
tx_mempool.PrioritiseTransaction(hashFreePrioritisedTx, 5 * COIN); tx_mempool.PrioritiseTransaction(hashFreePrioritisedTx, 5 * COIN);
+4 -12
View File
@@ -103,7 +103,7 @@ BOOST_FIXTURE_TEST_CASE(miniminer_negative, TestChain100Setup)
mini_miner_no_target.BuildMockTemplate(std::nullopt); mini_miner_no_target.BuildMockTemplate(std::nullopt);
const auto template_txids{mini_miner_no_target.GetMockTemplateTxids()}; const auto template_txids{mini_miner_no_target.GetMockTemplateTxids()};
BOOST_CHECK_EQUAL(template_txids.size(), 1); BOOST_CHECK_EQUAL(template_txids.size(), 1);
BOOST_CHECK(template_txids.count(tx_mod_negative->GetHash().ToUint256()) > 0); BOOST_CHECK(template_txids.count(tx_mod_negative->GetHash()) > 0);
} }
BOOST_FIXTURE_TEST_CASE(miniminer_1p1c, TestChain100Setup) BOOST_FIXTURE_TEST_CASE(miniminer_1p1c, TestChain100Setup)
@@ -177,7 +177,7 @@ BOOST_FIXTURE_TEST_CASE(miniminer_1p1c, TestChain100Setup)
struct TxDimensions { struct TxDimensions {
int32_t vsize; CAmount mod_fee; CFeeRate feerate; int32_t vsize; CAmount mod_fee; CFeeRate feerate;
}; };
std::map<uint256, TxDimensions> tx_dims; std::map<Txid, TxDimensions> tx_dims;
for (const auto& tx : all_transactions) { for (const auto& tx : all_transactions) {
const auto& entry{*Assert(pool.GetEntry(tx->GetHash()))}; const auto& entry{*Assert(pool.GetEntry(tx->GetHash()))};
tx_dims.emplace(tx->GetHash(), TxDimensions{entry.GetTxSize(), entry.GetModifiedFee(), tx_dims.emplace(tx->GetHash(), TxDimensions{entry.GetTxSize(), entry.GetModifiedFee(),
@@ -590,14 +590,6 @@ BOOST_FIXTURE_TEST_CASE(calculate_cluster, TestChain100Setup)
CTxMemPool& pool = *Assert(m_node.mempool); CTxMemPool& pool = *Assert(m_node.mempool);
LOCK2(cs_main, pool.cs); LOCK2(cs_main, pool.cs);
// TODO this can be removed once the mempool interface uses Txid, Wtxid
auto convert_to_uint256_vec = [](const std::vector<Txid>& vec) -> std::vector<uint256> {
std::vector<uint256> out;
std::transform(vec.begin(), vec.end(), std::back_inserter(out),
[](const Txid& txid) { return txid.ToUint256(); });
return out;
};
// Add chain of size 500 // Add chain of size 500
TestMemPoolEntryHelper entry; TestMemPoolEntryHelper entry;
std::vector<Txid> chain_txids; std::vector<Txid> chain_txids;
@@ -611,7 +603,7 @@ BOOST_FIXTURE_TEST_CASE(calculate_cluster, TestChain100Setup)
const auto cluster_500tx = pool.GatherClusters({lasttx->GetHash()}); const auto cluster_500tx = pool.GatherClusters({lasttx->GetHash()});
CTxMemPool::setEntries cluster_500tx_set{cluster_500tx.begin(), cluster_500tx.end()}; CTxMemPool::setEntries cluster_500tx_set{cluster_500tx.begin(), cluster_500tx.end()};
BOOST_CHECK_EQUAL(cluster_500tx.size(), cluster_500tx_set.size()); BOOST_CHECK_EQUAL(cluster_500tx.size(), cluster_500tx_set.size());
const auto vec_iters_500 = pool.GetIterVec(convert_to_uint256_vec(chain_txids)); const auto vec_iters_500 = pool.GetIterVec(chain_txids);
for (const auto& iter : vec_iters_500) BOOST_CHECK(cluster_500tx_set.count(iter)); for (const auto& iter : vec_iters_500) BOOST_CHECK(cluster_500tx_set.count(iter));
// GatherClusters stops at 500 transactions. // GatherClusters stops at 500 transactions.
@@ -637,7 +629,7 @@ BOOST_FIXTURE_TEST_CASE(calculate_cluster, TestChain100Setup)
AddToMempool(pool, entry.Fee(CENT).FromTx(txc)); AddToMempool(pool, entry.Fee(CENT).FromTx(txc));
zigzag_txids.push_back(txc->GetHash()); zigzag_txids.push_back(txc->GetHash());
} }
const auto vec_iters_zigzag = pool.GetIterVec(convert_to_uint256_vec(zigzag_txids)); const auto vec_iters_zigzag = pool.GetIterVec(zigzag_txids);
// It doesn't matter which tx we calculate cluster for, everybody is in it. // It doesn't matter which tx we calculate cluster for, everybody is in it.
const std::vector<size_t> indices{0, 22, 72, zigzag_txids.size() - 1}; const std::vector<size_t> indices{0, 22, 72, zigzag_txids.size() - 1};
for (const auto index : indices) { for (const auto index : indices) {
+11 -11
View File
@@ -48,7 +48,7 @@ BOOST_AUTO_TEST_CASE(pmt_test1)
// calculate actual merkle root and height // calculate actual merkle root and height
uint256 merkleRoot1 = BlockMerkleRoot(block); uint256 merkleRoot1 = BlockMerkleRoot(block);
std::vector<uint256> vTxid(nTx, uint256()); std::vector<Txid> vTxid(nTx);
for (unsigned int j=0; j<nTx; j++) for (unsigned int j=0; j<nTx; j++)
vTxid[j] = block.vtx[j]->GetHash(); vTxid[j] = block.vtx[j]->GetHash();
int nHeight = 1, nTx_ = nTx; int nHeight = 1, nTx_ = nTx;
@@ -61,7 +61,7 @@ BOOST_AUTO_TEST_CASE(pmt_test1)
for (int att = 1; att < 15; att++) { for (int att = 1; att < 15; att++) {
// build random subset of txid's // build random subset of txid's
std::vector<bool> vMatch(nTx, false); std::vector<bool> vMatch(nTx, false);
std::vector<uint256> vMatchTxid1; std::vector<Txid> vMatchTxid1;
for (unsigned int j=0; j<nTx; j++) { for (unsigned int j=0; j<nTx; j++) {
bool fInclude = m_rng.randbits(att / 2) == 0; bool fInclude = m_rng.randbits(att / 2) == 0;
vMatch[j] = fInclude; vMatch[j] = fInclude;
@@ -85,7 +85,7 @@ BOOST_AUTO_TEST_CASE(pmt_test1)
ss >> pmt2; ss >> pmt2;
// extract merkle root and matched txids from copy // extract merkle root and matched txids from copy
std::vector<uint256> vMatchTxid2; std::vector<Txid> vMatchTxid2;
std::vector<unsigned int> vIndex; std::vector<unsigned int> vIndex;
uint256 merkleRoot2 = pmt2.ExtractMatches(vMatchTxid2, vIndex); uint256 merkleRoot2 = pmt2.ExtractMatches(vMatchTxid2, vIndex);
@@ -100,7 +100,7 @@ BOOST_AUTO_TEST_CASE(pmt_test1)
for (int j=0; j<4; j++) { for (int j=0; j<4; j++) {
CPartialMerkleTreeTester pmt3(pmt2); CPartialMerkleTreeTester pmt3(pmt2);
pmt3.Damage(); pmt3.Damage();
std::vector<uint256> vMatchTxid3; std::vector<Txid> vMatchTxid3;
uint256 merkleRoot3 = pmt3.ExtractMatches(vMatchTxid3, vIndex); uint256 merkleRoot3 = pmt3.ExtractMatches(vMatchTxid3, vIndex);
BOOST_CHECK(merkleRoot3 != merkleRoot1); BOOST_CHECK(merkleRoot3 != merkleRoot1);
} }
@@ -110,13 +110,13 @@ BOOST_AUTO_TEST_CASE(pmt_test1)
BOOST_AUTO_TEST_CASE(pmt_malleability) BOOST_AUTO_TEST_CASE(pmt_malleability)
{ {
std::vector<uint256> vTxid{ std::vector<Txid> vTxid{
uint256{1}, uint256{2}, Txid::FromUint256(uint256{1}), Txid::FromUint256(uint256{2}),
uint256{3}, uint256{4}, Txid::FromUint256(uint256{3}), Txid::FromUint256(uint256{4}),
uint256{5}, uint256{6}, Txid::FromUint256(uint256{5}), Txid::FromUint256(uint256{6}),
uint256{7}, uint256{8}, Txid::FromUint256(uint256{7}), Txid::FromUint256(uint256{8}),
uint256{9}, uint256{10}, Txid::FromUint256(uint256{9}), Txid::FromUint256(uint256{10}),
uint256{9}, uint256{10}, Txid::FromUint256(uint256{9}), Txid::FromUint256(uint256{10}),
}; };
std::vector<bool> vMatch = {false, false, false, false, false, false, false, false, false, true, true, false}; std::vector<bool> vMatch = {false, false, false, false, false, false, false, false, false, true, true, false};
+4 -7
View File
@@ -37,7 +37,7 @@ BOOST_AUTO_TEST_CASE(BlockPolicyEstimates)
// added to the mempool by their associate fee // added to the mempool by their associate fee
// txHashes[j] is populated with transactions either of // txHashes[j] is populated with transactions either of
// fee = basefee * (j+1) // fee = basefee * (j+1)
std::vector<uint256> txHashes[10]; std::vector<Txid> txHashes[10];
// Create a transaction template // Create a transaction template
CScript garbage; CScript garbage;
@@ -77,8 +77,7 @@ BOOST_AUTO_TEST_CASE(BlockPolicyEstimates)
/*has_no_mempool_parents=*/true)}; /*has_no_mempool_parents=*/true)};
m_node.validation_signals->TransactionAddedToMempool(tx_info, mpool.GetAndIncrementSequence()); m_node.validation_signals->TransactionAddedToMempool(tx_info, mpool.GetAndIncrementSequence());
} }
uint256 hash = tx.GetHash(); txHashes[j].push_back(tx.GetHash());
txHashes[j].push_back(hash);
} }
} }
//Create blocks where higher fee txs are included more often //Create blocks where higher fee txs are included more often
@@ -178,8 +177,7 @@ BOOST_AUTO_TEST_CASE(BlockPolicyEstimates)
/*has_no_mempool_parents=*/true)}; /*has_no_mempool_parents=*/true)};
m_node.validation_signals->TransactionAddedToMempool(tx_info, mpool.GetAndIncrementSequence()); m_node.validation_signals->TransactionAddedToMempool(tx_info, mpool.GetAndIncrementSequence());
} }
uint256 hash = tx.GetHash(); txHashes[j].push_back(tx.GetHash());
txHashes[j].push_back(hash);
} }
} }
{ {
@@ -242,8 +240,7 @@ BOOST_AUTO_TEST_CASE(BlockPolicyEstimates)
/*has_no_mempool_parents=*/true)}; /*has_no_mempool_parents=*/true)};
m_node.validation_signals->TransactionAddedToMempool(tx_info, mpool.GetAndIncrementSequence()); m_node.validation_signals->TransactionAddedToMempool(tx_info, mpool.GetAndIncrementSequence());
} }
uint256 hash = tx.GetHash(); CTransactionRef ptx = mpool.get(tx.GetHash());
CTransactionRef ptx = mpool.get(hash);
if (ptx) if (ptx)
block.push_back(ptx); block.push_back(ptx);
+1 -1
View File
@@ -196,7 +196,7 @@ BOOST_FIXTURE_TEST_CASE(rbf_helper_functions, TestChain100Setup)
entry5_low, entry6_low_prioritised, entry7_high, entry8_high}; entry5_low, entry6_low_prioritised, entry7_high, entry8_high};
CTxMemPool::setEntries empty_set; CTxMemPool::setEntries empty_set;
const auto unused_txid{GetRandHash()}; const auto unused_txid = Txid::FromUint256(GetRandHash());
// Tests for PaysMoreThanConflicts // Tests for PaysMoreThanConflicts
// These tests use feerate, not absolute fee. // These tests use feerate, not absolute fee.
+1 -1
View File
@@ -16,6 +16,7 @@
#include <key.h> #include <key.h>
#include <policy/policy.h> #include <policy/policy.h>
#include <policy/settings.h> #include <policy/settings.h>
#include <primitives/transaction_identifier.h>
#include <script/script.h> #include <script/script.h>
#include <script/script_error.h> #include <script/script_error.h>
#include <script/sigcache.h> #include <script/sigcache.h>
@@ -29,7 +30,6 @@
#include <test/util/transaction_utils.h> #include <test/util/transaction_utils.h>
#include <util/strencodings.h> #include <util/strencodings.h>
#include <util/string.h> #include <util/string.h>
#include <util/transaction_identifier.h>
#include <validation.h> #include <validation.h>
#include <functional> #include <functional>
+1 -1
View File
@@ -2,11 +2,11 @@
// Distributed under the MIT software license, see the accompanying // Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php. // file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <primitives/transaction_identifier.h>
#include <streams.h> #include <streams.h>
#include <test/util/setup_common.h> #include <test/util/setup_common.h>
#include <uint256.h> #include <uint256.h>
#include <util/strencodings.h> #include <util/strencodings.h>
#include <util/transaction_identifier.h>
#include <boost/test/unit_test.hpp> #include <boost/test/unit_test.hpp>
+8
View File
@@ -629,3 +629,11 @@ std::ostream& operator<<(std::ostream& os, const uint256& num)
{ {
return os << num.ToString(); return os << num.ToString();
} }
std::ostream& operator<<(std::ostream& os, const Txid& txid) {
return os << txid.ToString();
}
std::ostream& operator<<(std::ostream& os, const Wtxid& wtxid) {
return os << wtxid.ToString();
}
+2
View File
@@ -291,6 +291,8 @@ inline std::ostream& operator<<(std::ostream& os, const std::optional<T>& v)
std::ostream& operator<<(std::ostream& os, const arith_uint256& num); std::ostream& operator<<(std::ostream& os, const arith_uint256& num);
std::ostream& operator<<(std::ostream& os, const uint160& num); std::ostream& operator<<(std::ostream& os, const uint160& num);
std::ostream& operator<<(std::ostream& os, const uint256& num); std::ostream& operator<<(std::ostream& os, const uint256& num);
std::ostream& operator<<(std::ostream& os, const Txid& txid);
std::ostream& operator<<(std::ostream& os, const Wtxid& wtxid);
// @} // @}
/** /**
+4 -4
View File
@@ -214,9 +214,9 @@ BOOST_AUTO_TEST_CASE(block_malleation)
// Block with a single coinbase tx is mutated if the merkle root is not // Block with a single coinbase tx is mutated if the merkle root is not
// equal to the coinbase tx's hash. // equal to the coinbase tx's hash.
block.vtx.push_back(create_coinbase_tx()); block.vtx.push_back(create_coinbase_tx());
BOOST_CHECK(block.vtx[0]->GetHash() != block.hashMerkleRoot); BOOST_CHECK(block.vtx[0]->GetHash().ToUint256() != block.hashMerkleRoot);
BOOST_CHECK(is_mutated(block, /*check_witness_root=*/false)); BOOST_CHECK(is_mutated(block, /*check_witness_root=*/false));
block.hashMerkleRoot = block.vtx[0]->GetHash(); block.hashMerkleRoot = block.vtx[0]->GetHash().ToUint256();
BOOST_CHECK(is_not_mutated(block, /*check_witness_root=*/false)); BOOST_CHECK(is_not_mutated(block, /*check_witness_root=*/false));
// Block with two transactions is mutated if the merkle root does not // Block with two transactions is mutated if the merkle root does not
@@ -248,7 +248,7 @@ BOOST_AUTO_TEST_CASE(block_malleation)
mtx.vout.resize(1); mtx.vout.resize(1);
mtx.vout[0].scriptPubKey.resize(4); mtx.vout[0].scriptPubKey.resize(4);
block.vtx.push_back(MakeTransactionRef(mtx)); block.vtx.push_back(MakeTransactionRef(mtx));
block.hashMerkleRoot = block.vtx.back()->GetHash(); block.hashMerkleRoot = block.vtx.back()->GetHash().ToUint256();
assert(block.vtx.back()->IsCoinBase()); assert(block.vtx.back()->IsCoinBase());
assert(GetSerializeSize(TX_NO_WITNESS(block.vtx.back())) == 64); assert(GetSerializeSize(TX_NO_WITNESS(block.vtx.back())) == 64);
} }
@@ -285,7 +285,7 @@ BOOST_AUTO_TEST_CASE(block_malleation)
HashWriter hasher; HashWriter hasher;
hasher.write(tx1.GetHash()); hasher.write(tx1.GetHash());
hasher.write(tx2.GetHash()); hasher.write(tx2.GetHash());
assert(hasher.GetHash() == tx3.GetHash()); assert(hasher.GetHash() == tx3.GetHash().ToUint256());
// Verify that tx3 is 64 bytes in size (without witness). // Verify that tx3 is 64 bytes in size (without witness).
assert(GetSerializeSize(TX_NO_WITNESS(tx3)) == 64); assert(GetSerializeSize(TX_NO_WITNESS(tx3)) == 64);
} }
+24 -25
View File
@@ -55,7 +55,7 @@ bool TestLockPointValidity(CChain& active_chain, const LockPoints& lp)
} }
void CTxMemPool::UpdateForDescendants(txiter updateIt, cacheMap& cachedDescendants, void CTxMemPool::UpdateForDescendants(txiter updateIt, cacheMap& cachedDescendants,
const std::set<uint256>& setExclude, std::set<uint256>& descendants_to_remove) const std::set<Txid>& setExclude, std::set<Txid>& descendants_to_remove)
{ {
CTxMemPoolEntry::Children stageEntries, descendants; CTxMemPoolEntry::Children stageEntries, descendants;
stageEntries = updateIt->GetMemPoolChildrenConst(); stageEntries = updateIt->GetMemPoolChildrenConst();
@@ -105,7 +105,7 @@ void CTxMemPool::UpdateForDescendants(txiter updateIt, cacheMap& cachedDescendan
mapTx.modify(updateIt, [=](CTxMemPoolEntry& e) { e.UpdateDescendantState(modifySize, modifyFee, modifyCount); }); mapTx.modify(updateIt, [=](CTxMemPoolEntry& e) { e.UpdateDescendantState(modifySize, modifyFee, modifyCount); });
} }
void CTxMemPool::UpdateTransactionsFromBlock(const std::vector<uint256>& vHashesToUpdate) void CTxMemPool::UpdateTransactionsFromBlock(const std::vector<Txid>& vHashesToUpdate)
{ {
AssertLockHeld(cs); AssertLockHeld(cs);
// For each entry in vHashesToUpdate, store the set of in-mempool, but not // For each entry in vHashesToUpdate, store the set of in-mempool, but not
@@ -115,29 +115,29 @@ void CTxMemPool::UpdateTransactionsFromBlock(const std::vector<uint256>& vHashes
// Use a set for lookups into vHashesToUpdate (these entries are already // Use a set for lookups into vHashesToUpdate (these entries are already
// accounted for in the state of their ancestors) // accounted for in the state of their ancestors)
std::set<uint256> setAlreadyIncluded(vHashesToUpdate.begin(), vHashesToUpdate.end()); std::set<Txid> setAlreadyIncluded(vHashesToUpdate.begin(), vHashesToUpdate.end());
std::set<uint256> descendants_to_remove; std::set<Txid> descendants_to_remove;
// Iterate in reverse, so that whenever we are looking at a transaction // Iterate in reverse, so that whenever we are looking at a transaction
// we are sure that all in-mempool descendants have already been processed. // we are sure that all in-mempool descendants have already been processed.
// This maximizes the benefit of the descendant cache and guarantees that // This maximizes the benefit of the descendant cache and guarantees that
// CTxMemPoolEntry::m_children will be updated, an assumption made in // CTxMemPoolEntry::m_children will be updated, an assumption made in
// UpdateForDescendants. // UpdateForDescendants.
for (const uint256& hash : vHashesToUpdate | std::views::reverse) { for (const Txid& hash : vHashesToUpdate | std::views::reverse) {
// calculate children from mapNextTx // calculate children from mapNextTx
txiter it = mapTx.find(hash); txiter it = mapTx.find(hash);
if (it == mapTx.end()) { if (it == mapTx.end()) {
continue; continue;
} }
auto iter = mapNextTx.lower_bound(COutPoint(Txid::FromUint256(hash), 0)); auto iter = mapNextTx.lower_bound(COutPoint(hash, 0));
// First calculate the children, and update CTxMemPoolEntry::m_children to // First calculate the children, and update CTxMemPoolEntry::m_children to
// include them, and update their CTxMemPoolEntry::m_parents to include this tx. // include them, and update their CTxMemPoolEntry::m_parents to include this tx.
// we cache the in-mempool children to avoid duplicate updates // we cache the in-mempool children to avoid duplicate updates
{ {
WITH_FRESH_EPOCH(m_epoch); WITH_FRESH_EPOCH(m_epoch);
for (; iter != mapNextTx.end() && iter->first->hash == hash; ++iter) { for (; iter != mapNextTx.end() && iter->first->hash == hash; ++iter) {
const uint256 &childHash = iter->second->GetHash(); const Txid &childHash = iter->second->GetHash();
txiter childIter = mapTx.find(childHash); txiter childIter = mapTx.find(childHash);
assert(childIter != mapTx.end()); assert(childIter != mapTx.end());
// We can skip updating entries we've encountered before or that // We can skip updating entries we've encountered before or that
@@ -154,7 +154,7 @@ void CTxMemPool::UpdateTransactionsFromBlock(const std::vector<uint256>& vHashes
for (const auto& txid : descendants_to_remove) { for (const auto& txid : descendants_to_remove) {
// This txid may have been removed already in a prior call to removeRecursive. // This txid may have been removed already in a prior call to removeRecursive.
// Therefore we ensure it is not yet removed already. // Therefore we ensure it is not yet removed already.
if (const std::optional<txiter> txiter = GetIter(Txid::FromUint256(txid))) { if (const std::optional<txiter> txiter = GetIter(txid)) {
removeRecursive((*txiter)->GetTx(), MemPoolRemovalReason::SIZELIMIT); removeRecursive((*txiter)->GetTx(), MemPoolRemovalReason::SIZELIMIT);
} }
} }
@@ -780,12 +780,11 @@ void CTxMemPool::check(const CCoinsViewCache& active_coins_tip, int64_t spendhei
for (const auto& input: tx.vin) mempoolDuplicate.SpendCoin(input.prevout); for (const auto& input: tx.vin) mempoolDuplicate.SpendCoin(input.prevout);
AddCoins(mempoolDuplicate, tx, std::numeric_limits<int>::max()); AddCoins(mempoolDuplicate, tx, std::numeric_limits<int>::max());
} }
for (auto it = mapNextTx.cbegin(); it != mapNextTx.cend(); it++) { for (const auto& [_, next_tx] : mapNextTx) {
uint256 hash = it->second->GetHash(); auto it = mapTx.find(next_tx->GetHash());
indexed_transaction_set::const_iterator it2 = mapTx.find(hash); const CTransaction& tx = it->GetTx();
const CTransaction& tx = it2->GetTx(); assert(it != mapTx.end());
assert(it2 != mapTx.end()); assert(&tx == next_tx);
assert(&tx == it->second);
} }
assert(totalTxSize == checkTotal); assert(totalTxSize == checkTotal);
@@ -876,7 +875,7 @@ const CTxMemPoolEntry* CTxMemPool::GetEntry(const Txid& txid) const
return i == mapTx.end() ? nullptr : &(*i); return i == mapTx.end() ? nullptr : &(*i);
} }
CTransactionRef CTxMemPool::get(const uint256& hash) const CTransactionRef CTxMemPool::get(const Txid& hash) const
{ {
LOCK(cs); LOCK(cs);
indexed_transaction_set::const_iterator i = mapTx.find(hash); indexed_transaction_set::const_iterator i = mapTx.find(hash);
@@ -885,7 +884,7 @@ CTransactionRef CTxMemPool::get(const uint256& hash) const
return i->GetSharedTx(); return i->GetSharedTx();
} }
void CTxMemPool::PrioritiseTransaction(const uint256& hash, const CAmount& nFeeDelta) void CTxMemPool::PrioritiseTransaction(const Txid& hash, const CAmount& nFeeDelta)
{ {
{ {
LOCK(cs); LOCK(cs);
@@ -921,17 +920,17 @@ void CTxMemPool::PrioritiseTransaction(const uint256& hash, const CAmount& nFeeD
} }
} }
void CTxMemPool::ApplyDelta(const uint256& hash, CAmount &nFeeDelta) const void CTxMemPool::ApplyDelta(const Txid& hash, CAmount &nFeeDelta) const
{ {
AssertLockHeld(cs); AssertLockHeld(cs);
std::map<uint256, CAmount>::const_iterator pos = mapDeltas.find(hash); std::map<Txid, CAmount>::const_iterator pos = mapDeltas.find(hash);
if (pos == mapDeltas.end()) if (pos == mapDeltas.end())
return; return;
const CAmount &delta = pos->second; const CAmount &delta = pos->second;
nFeeDelta += delta; nFeeDelta += delta;
} }
void CTxMemPool::ClearPrioritisation(const uint256& hash) void CTxMemPool::ClearPrioritisation(const Txid& hash)
{ {
AssertLockHeld(cs); AssertLockHeld(cs);
mapDeltas.erase(hash); mapDeltas.erase(hash);
@@ -962,7 +961,7 @@ const CTransaction* CTxMemPool::GetConflictTx(const COutPoint& prevout) const
std::optional<CTxMemPool::txiter> CTxMemPool::GetIter(const Txid& txid) const std::optional<CTxMemPool::txiter> CTxMemPool::GetIter(const Txid& txid) const
{ {
AssertLockHeld(cs); AssertLockHeld(cs);
auto it = mapTx.find(txid.ToUint256()); auto it = mapTx.find(txid);
return it != mapTx.end() ? std::make_optional(it) : std::nullopt; return it != mapTx.end() ? std::make_optional(it) : std::nullopt;
} }
@@ -983,13 +982,13 @@ CTxMemPool::setEntries CTxMemPool::GetIterSet(const std::set<Txid>& hashes) cons
return ret; return ret;
} }
std::vector<CTxMemPool::txiter> CTxMemPool::GetIterVec(const std::vector<uint256>& txids) const std::vector<CTxMemPool::txiter> CTxMemPool::GetIterVec(const std::vector<Txid>& txids) const
{ {
AssertLockHeld(cs); AssertLockHeld(cs);
std::vector<txiter> ret; std::vector<txiter> ret;
ret.reserve(txids.size()); ret.reserve(txids.size());
for (const auto& txid : txids) { for (const auto& txid : txids) {
const auto it{GetIter(Txid::FromUint256(txid))}; const auto it{GetIter(txid)};
if (!it) return {}; if (!it) return {};
ret.push_back(*it); ret.push_back(*it);
} }
@@ -1048,7 +1047,7 @@ size_t CTxMemPool::DynamicMemoryUsage() const {
return memusage::MallocUsage(sizeof(CTxMemPoolEntry) + 15 * sizeof(void*)) * mapTx.size() + memusage::DynamicUsage(mapNextTx) + memusage::DynamicUsage(mapDeltas) + memusage::DynamicUsage(txns_randomized) + cachedInnerUsage; return memusage::MallocUsage(sizeof(CTxMemPoolEntry) + 15 * sizeof(void*)) * mapTx.size() + memusage::DynamicUsage(mapNextTx) + memusage::DynamicUsage(mapDeltas) + memusage::DynamicUsage(txns_randomized) + cachedInnerUsage;
} }
void CTxMemPool::RemoveUnbroadcastTx(const uint256& txid, const bool unchecked) { void CTxMemPool::RemoveUnbroadcastTx(const Txid& txid, const bool unchecked) {
LOCK(cs); LOCK(cs);
if (m_unbroadcast_txids.erase(txid)) if (m_unbroadcast_txids.erase(txid))
@@ -1203,7 +1202,7 @@ uint64_t CTxMemPool::CalculateDescendantMaximum(txiter entry) const {
return maximum; return maximum;
} }
void CTxMemPool::GetTransactionAncestry(const uint256& txid, size_t& ancestors, size_t& descendants, size_t* const ancestorsize, CAmount* const ancestorfees) const { void CTxMemPool::GetTransactionAncestry(const Txid& txid, size_t& ancestors, size_t& descendants, size_t* const ancestorsize, CAmount* const ancestorfees) const {
LOCK(cs); LOCK(cs);
auto it = mapTx.find(txid); auto it = mapTx.find(txid);
ancestors = descendants = 0; ancestors = descendants = 0;
@@ -1227,7 +1226,7 @@ void CTxMemPool::SetLoadTried(bool load_tried)
m_load_tried = load_tried; m_load_tried = load_tried;
} }
std::vector<CTxMemPool::txiter> CTxMemPool::GatherClusters(const std::vector<uint256>& txids) const std::vector<CTxMemPool::txiter> CTxMemPool::GatherClusters(const std::vector<Txid>& txids) const
{ {
AssertLockHeld(cs); AssertLockHeld(cs);
std::vector<txiter> clustered_txs{GetIterVec(txids)}; std::vector<txiter> clustered_txs{GetIterVec(txids)};
+21 -21
View File
@@ -17,12 +17,12 @@
#include <policy/feerate.h> #include <policy/feerate.h>
#include <policy/packages.h> #include <policy/packages.h>
#include <primitives/transaction.h> #include <primitives/transaction.h>
#include <primitives/transaction_identifier.h>
#include <sync.h> #include <sync.h>
#include <util/epochguard.h> #include <util/epochguard.h>
#include <util/feefrac.h> #include <util/feefrac.h>
#include <util/hasher.h> #include <util/hasher.h>
#include <util/result.h> #include <util/result.h>
#include <util/transaction_identifier.h>
#include <boost/multi_index/hashed_index.hpp> #include <boost/multi_index/hashed_index.hpp>
#include <boost/multi_index/identity.hpp> #include <boost/multi_index/identity.hpp>
@@ -57,7 +57,7 @@ bool TestLockPointValidity(CChain& active_chain, const LockPoints& lp) EXCLUSIVE
// extracts a transaction hash from CTxMemPoolEntry or CTransactionRef // extracts a transaction hash from CTxMemPoolEntry or CTransactionRef
struct mempoolentry_txid struct mempoolentry_txid
{ {
typedef uint256 result_type; typedef Txid result_type;
result_type operator() (const CTxMemPoolEntry &entry) const result_type operator() (const CTxMemPoolEntry &entry) const
{ {
return entry.GetTx().GetHash(); return entry.GetTx().GetHash();
@@ -72,7 +72,7 @@ struct mempoolentry_txid
// extracts a transaction witness-hash from CTxMemPoolEntry or CTransactionRef // extracts a transaction witness-hash from CTxMemPoolEntry or CTransactionRef
struct mempoolentry_wtxid struct mempoolentry_wtxid
{ {
typedef uint256 result_type; typedef Wtxid result_type;
result_type operator() (const CTxMemPoolEntry &entry) const result_type operator() (const CTxMemPoolEntry &entry) const
{ {
return entry.GetTx().GetWitnessHash(); return entry.GetTx().GetWitnessHash();
@@ -313,7 +313,7 @@ public:
boost::multi_index::hashed_unique< boost::multi_index::hashed_unique<
boost::multi_index::tag<index_by_wtxid>, boost::multi_index::tag<index_by_wtxid>,
mempoolentry_wtxid, mempoolentry_wtxid,
SaltedTxidHasher SaltedWtxidHasher
>, >,
// sorted by fee rate // sorted by fee rate
boost::multi_index::ordered_non_unique< boost::multi_index::ordered_non_unique<
@@ -387,7 +387,7 @@ private:
/** /**
* Track locally submitted transactions to periodically retry initial broadcast. * Track locally submitted transactions to periodically retry initial broadcast.
*/ */
std::set<uint256> m_unbroadcast_txids GUARDED_BY(cs); std::set<Txid> m_unbroadcast_txids GUARDED_BY(cs);
/** /**
@@ -414,7 +414,7 @@ private:
public: public:
indirectmap<COutPoint, const CTransaction*> mapNextTx GUARDED_BY(cs); indirectmap<COutPoint, const CTransaction*> mapNextTx GUARDED_BY(cs);
std::map<uint256, CAmount> mapDeltas GUARDED_BY(cs); std::map<Txid, CAmount> mapDeltas GUARDED_BY(cs);
using Options = kernel::MemPoolOptions; using Options = kernel::MemPoolOptions;
@@ -459,9 +459,9 @@ public:
bool HasNoInputsOf(const CTransaction& tx) const EXCLUSIVE_LOCKS_REQUIRED(cs); bool HasNoInputsOf(const CTransaction& tx) const EXCLUSIVE_LOCKS_REQUIRED(cs);
/** Affect CreateNewBlock prioritisation of transactions */ /** Affect CreateNewBlock prioritisation of transactions */
void PrioritiseTransaction(const uint256& hash, const CAmount& nFeeDelta); void PrioritiseTransaction(const Txid& hash, const CAmount& nFeeDelta);
void ApplyDelta(const uint256& hash, CAmount &nFeeDelta) const EXCLUSIVE_LOCKS_REQUIRED(cs); void ApplyDelta(const Txid& hash, CAmount &nFeeDelta) const EXCLUSIVE_LOCKS_REQUIRED(cs);
void ClearPrioritisation(const uint256& hash) EXCLUSIVE_LOCKS_REQUIRED(cs); void ClearPrioritisation(const Txid& hash) EXCLUSIVE_LOCKS_REQUIRED(cs);
struct delta_info { struct delta_info {
/** Whether this transaction is in the mempool. */ /** Whether this transaction is in the mempool. */
@@ -471,7 +471,7 @@ public:
/** The modified fee (base fee + delta) of this entry. Only present if in_mempool=true. */ /** The modified fee (base fee + delta) of this entry. Only present if in_mempool=true. */
std::optional<CAmount> modified_fee; std::optional<CAmount> modified_fee;
/** The prioritised transaction's txid. */ /** The prioritised transaction's txid. */
const uint256 txid; const Txid txid;
}; };
/** Return a vector of all entries in mapDeltas with their corresponding delta_info. */ /** Return a vector of all entries in mapDeltas with their corresponding delta_info. */
std::vector<delta_info> GetPrioritisedTransactions() const EXCLUSIVE_LOCKS_REQUIRED(!cs); std::vector<delta_info> GetPrioritisedTransactions() const EXCLUSIVE_LOCKS_REQUIRED(!cs);
@@ -491,7 +491,7 @@ public:
/** Translate a list of hashes into a list of mempool iterators to avoid repeated lookups. /** Translate a list of hashes into a list of mempool iterators to avoid repeated lookups.
* The nth element in txids becomes the nth element in the returned vector. If any of the txids * The nth element in txids becomes the nth element in the returned vector. If any of the txids
* don't actually exist in the mempool, returns an empty vector. */ * don't actually exist in the mempool, returns an empty vector. */
std::vector<txiter> GetIterVec(const std::vector<uint256>& txids) const EXCLUSIVE_LOCKS_REQUIRED(cs); std::vector<txiter> GetIterVec(const std::vector<Txid>& txids) const EXCLUSIVE_LOCKS_REQUIRED(cs);
/** UpdateTransactionsFromBlock is called when adding transactions from a /** UpdateTransactionsFromBlock is called when adding transactions from a
* disconnected block back to the mempool, new mempool entries may have * disconnected block back to the mempool, new mempool entries may have
@@ -506,7 +506,7 @@ public:
* @param[in] vHashesToUpdate The set of txids from the * @param[in] vHashesToUpdate The set of txids from the
* disconnected block that have been accepted back into the mempool. * disconnected block that have been accepted back into the mempool.
*/ */
void UpdateTransactionsFromBlock(const std::vector<uint256>& vHashesToUpdate) EXCLUSIVE_LOCKS_REQUIRED(cs, cs_main) LOCKS_EXCLUDED(m_epoch); void UpdateTransactionsFromBlock(const std::vector<Txid>& vHashesToUpdate) EXCLUSIVE_LOCKS_REQUIRED(cs, cs_main) LOCKS_EXCLUDED(m_epoch);
/** /**
* Try to calculate all in-mempool ancestors of entry. * Try to calculate all in-mempool ancestors of entry.
@@ -548,7 +548,7 @@ public:
* All txids must correspond to transaction entries in the mempool, otherwise this returns an * All txids must correspond to transaction entries in the mempool, otherwise this returns an
* empty vector. This call will also exit early and return an empty vector if it collects 500 or * empty vector. This call will also exit early and return an empty vector if it collects 500 or
* more transactions as a DoS protection. */ * more transactions as a DoS protection. */
std::vector<txiter> GatherClusters(const std::vector<uint256>& txids) const EXCLUSIVE_LOCKS_REQUIRED(cs); std::vector<txiter> GatherClusters(const std::vector<Txid>& txids) const EXCLUSIVE_LOCKS_REQUIRED(cs);
/** Calculate all in-mempool ancestors of a set of transactions not already in the mempool and /** Calculate all in-mempool ancestors of a set of transactions not already in the mempool and
* check ancestor and descendant limits. Heuristics are used to estimate the ancestor and * check ancestor and descendant limits. Heuristics are used to estimate the ancestor and
@@ -595,7 +595,7 @@ public:
* When ancestors is non-zero (ie, the transaction itself is in the mempool), * When ancestors is non-zero (ie, the transaction itself is in the mempool),
* ancestorsize and ancestorfees will also be set to the appropriate values. * ancestorsize and ancestorfees will also be set to the appropriate values.
*/ */
void GetTransactionAncestry(const uint256& txid, size_t& ancestors, size_t& descendants, size_t* ancestorsize = nullptr, CAmount* ancestorfees = nullptr) const; void GetTransactionAncestry(const Txid& txid, size_t& ancestors, size_t& descendants, size_t* ancestorsize = nullptr, CAmount* ancestorfees = nullptr) const;
/** /**
* @returns true if an initial attempt to load the persisted mempool was made, regardless of * @returns true if an initial attempt to load the persisted mempool was made, regardless of
@@ -641,7 +641,7 @@ public:
const CTxMemPoolEntry* GetEntry(const Txid& txid) const LIFETIMEBOUND EXCLUSIVE_LOCKS_REQUIRED(cs); const CTxMemPoolEntry* GetEntry(const Txid& txid) const LIFETIMEBOUND EXCLUSIVE_LOCKS_REQUIRED(cs);
CTransactionRef get(const uint256& hash) const; CTransactionRef get(const Txid& hash) const;
template <TxidOrWtxid T> template <TxidOrWtxid T>
TxMempoolInfo info(const T& id) const TxMempoolInfo info(const T& id) const
@@ -666,26 +666,26 @@ public:
size_t DynamicMemoryUsage() const; size_t DynamicMemoryUsage() const;
/** Adds a transaction to the unbroadcast set */ /** Adds a transaction to the unbroadcast set */
void AddUnbroadcastTx(const uint256& txid) void AddUnbroadcastTx(const Txid& txid)
{ {
LOCK(cs); LOCK(cs);
// Sanity check the transaction is in the mempool & insert into // Sanity check the transaction is in the mempool & insert into
// unbroadcast set. // unbroadcast set.
if (exists(Txid::FromUint256(txid))) m_unbroadcast_txids.insert(txid); if (exists(txid)) m_unbroadcast_txids.insert(txid);
}; };
/** Removes a transaction from the unbroadcast set */ /** Removes a transaction from the unbroadcast set */
void RemoveUnbroadcastTx(const uint256& txid, const bool unchecked = false); void RemoveUnbroadcastTx(const Txid& txid, const bool unchecked = false);
/** Returns transactions in unbroadcast set */ /** Returns transactions in unbroadcast set */
std::set<uint256> GetUnbroadcastTxs() const std::set<Txid> GetUnbroadcastTxs() const
{ {
LOCK(cs); LOCK(cs);
return m_unbroadcast_txids; return m_unbroadcast_txids;
} }
/** Returns whether a txid is in the unbroadcast set */ /** Returns whether a txid is in the unbroadcast set */
bool IsUnbroadcastTx(const uint256& txid) const EXCLUSIVE_LOCKS_REQUIRED(cs) bool IsUnbroadcastTx(const Txid& txid) const EXCLUSIVE_LOCKS_REQUIRED(cs)
{ {
AssertLockHeld(cs); AssertLockHeld(cs);
return m_unbroadcast_txids.count(txid) != 0; return m_unbroadcast_txids.count(txid) != 0;
@@ -744,7 +744,7 @@ private:
* removeRecursive them. * removeRecursive them.
*/ */
void UpdateForDescendants(txiter updateIt, cacheMap& cachedDescendants, void UpdateForDescendants(txiter updateIt, cacheMap& cachedDescendants,
const std::set<uint256>& setExclude, std::set<uint256>& descendants_to_remove) EXCLUSIVE_LOCKS_REQUIRED(cs); const std::set<Txid>& setExclude, std::set<Txid>& descendants_to_remove) EXCLUSIVE_LOCKS_REQUIRED(cs);
/** Update ancestors of hash to add/remove it as a descendant transaction. */ /** Update ancestors of hash to add/remove it as a descendant transaction. */
void UpdateAncestorsOf(bool add, txiter hash, setEntries &setAncestors) EXCLUSIVE_LOCKS_REQUIRED(cs); void UpdateAncestorsOf(bool add, txiter hash, setEntries &setAncestors) EXCLUSIVE_LOCKS_REQUIRED(cs);
/** Set ancestor state for an entry */ /** Set ancestor state for an entry */
+8
View File
@@ -7,10 +7,18 @@
#include <span.h> #include <span.h>
#include <util/hasher.h> #include <util/hasher.h>
SaltedUint256Hasher::SaltedUint256Hasher() :
k0{FastRandomContext().rand64()},
k1{FastRandomContext().rand64()} {}
SaltedTxidHasher::SaltedTxidHasher() : SaltedTxidHasher::SaltedTxidHasher() :
k0{FastRandomContext().rand64()}, k0{FastRandomContext().rand64()},
k1{FastRandomContext().rand64()} {} k1{FastRandomContext().rand64()} {}
SaltedWtxidHasher::SaltedWtxidHasher() :
k0{FastRandomContext().rand64()},
k1{FastRandomContext().rand64()} {}
SaltedOutpointHasher::SaltedOutpointHasher(bool deterministic) : SaltedOutpointHasher::SaltedOutpointHasher(bool deterministic) :
k0{deterministic ? 0x8e819f2607a18de6 : FastRandomContext().rand64()}, k0{deterministic ? 0x8e819f2607a18de6 : FastRandomContext().rand64()},
k1{deterministic ? 0xf4020d2e3983b0eb : FastRandomContext().rand64()} k1{deterministic ? 0xf4020d2e3983b0eb : FastRandomContext().rand64()}
+33 -3
View File
@@ -11,9 +11,24 @@
#include <span.h> #include <span.h>
#include <uint256.h> #include <uint256.h>
#include <concepts>
#include <cstdint> #include <cstdint>
#include <cstring> #include <cstring>
class SaltedUint256Hasher
{
private:
/** Salt */
const uint64_t k0, k1;
public:
SaltedUint256Hasher();
size_t operator()(const uint256& hash) const {
return SipHashUint256(k0, k1, hash);
}
};
class SaltedTxidHasher class SaltedTxidHasher
{ {
private: private:
@@ -23,11 +38,26 @@ private:
public: public:
SaltedTxidHasher(); SaltedTxidHasher();
size_t operator()(const uint256& txid) const { size_t operator()(const Txid& txid) const {
return SipHashUint256(k0, k1, txid); return SipHashUint256(k0, k1, txid.ToUint256());
} }
}; };
class SaltedWtxidHasher
{
private:
/** Salt */
const uint64_t k0, k1;
public:
SaltedWtxidHasher();
size_t operator()(const Wtxid& wtxid) const {
return SipHashUint256(k0, k1, wtxid.ToUint256());
}
};
class SaltedOutpointHasher class SaltedOutpointHasher
{ {
private: private:
@@ -47,7 +77,7 @@ public:
* @see https://gcc.gnu.org/onlinedocs/gcc-13.2.0/libstdc++/manual/manual/unordered_associative.html * @see https://gcc.gnu.org/onlinedocs/gcc-13.2.0/libstdc++/manual/manual/unordered_associative.html
*/ */
size_t operator()(const COutPoint& id) const noexcept { size_t operator()(const COutPoint& id) const noexcept {
return SipHashUint256Extra(k0, k1, id.hash, id.n); return SipHashUint256Extra(k0, k1, id.hash.ToUint256(), id.n);
} }
}; };
+4 -4
View File
@@ -303,7 +303,7 @@ void Chainstate::MaybeUpdateMempoolForReorg(
AssertLockHeld(cs_main); AssertLockHeld(cs_main);
AssertLockHeld(m_mempool->cs); AssertLockHeld(m_mempool->cs);
std::vector<uint256> vHashUpdate; std::vector<Txid> vHashUpdate;
{ {
// disconnectpool is ordered so that the front is the most recently-confirmed // disconnectpool is ordered so that the front is the most recently-confirmed
// transaction (the last tx of the block at the tip) in the disconnected chain. // transaction (the last tx of the block at the tip) in the disconnected chain.
@@ -1088,7 +1088,7 @@ bool MemPoolAccept::ReplacementChecks(Workspace& ws)
AssertLockHeld(m_pool.cs); AssertLockHeld(m_pool.cs);
const CTransaction& tx = *ws.m_ptx; const CTransaction& tx = *ws.m_ptx;
const uint256& hash = ws.m_hash; const Txid& hash = ws.m_hash;
TxValidationState& state = ws.m_state; TxValidationState& state = ws.m_state;
CFeeRate newFeeRate(ws.m_modified_fees, ws.m_vsize); CFeeRate newFeeRate(ws.m_modified_fees, ws.m_vsize);
@@ -1270,7 +1270,7 @@ bool MemPoolAccept::ConsensusScriptChecks(const ATMPArgs& args, Workspace& ws)
AssertLockHeld(cs_main); AssertLockHeld(cs_main);
AssertLockHeld(m_pool.cs); AssertLockHeld(m_pool.cs);
const CTransaction& tx = *ws.m_ptx; const CTransaction& tx = *ws.m_ptx;
const uint256& hash = ws.m_hash; const Txid& hash = ws.m_hash;
TxValidationState& state = ws.m_state; TxValidationState& state = ws.m_state;
// Check again against the current block tip's script verification // Check again against the current block tip's script verification
@@ -1317,7 +1317,7 @@ void MemPoolAccept::FinalizeSubpackage(const ATMPArgs& args)
const bool replaced_with_tx{m_subpackage.m_changeset->GetTxCount() == 1}; const bool replaced_with_tx{m_subpackage.m_changeset->GetTxCount() == 1};
if (replaced_with_tx) { if (replaced_with_tx) {
const CTransaction& tx = m_subpackage.m_changeset->GetAddedTxn(0); const CTransaction& tx = m_subpackage.m_changeset->GetAddedTxn(0);
tx_or_package_hash = tx.GetHash(); tx_or_package_hash = tx.GetHash().ToUint256();
log_string += strprintf("New tx %s (wtxid=%s, fees=%s, vsize=%s)", log_string += strprintf("New tx %s (wtxid=%s, fees=%s, vsize=%s)",
tx.GetHash().ToString(), tx.GetHash().ToString(),
tx.GetWitnessHash().ToString(), tx.GetWitnessHash().ToString(),
+1 -1
View File
@@ -6,7 +6,7 @@
#define BITCOIN_WALLET_RECEIVE_H #define BITCOIN_WALLET_RECEIVE_H
#include <consensus/amount.h> #include <consensus/amount.h>
#include <util/transaction_identifier.h> #include <primitives/transaction_identifier.h>
#include <wallet/transaction.h> #include <wallet/transaction.h>
#include <wallet/types.h> #include <wallet/types.h>
#include <wallet/wallet.h> #include <wallet/wallet.h>
+2 -2
View File
@@ -60,7 +60,7 @@ RPCHelpMan importprunedfunds()
ssMB >> merkleBlock; ssMB >> merkleBlock;
//Search partial merkle tree in proof for our transaction and index in valid block //Search partial merkle tree in proof for our transaction and index in valid block
std::vector<uint256> vMatch; std::vector<Txid> vMatch;
std::vector<unsigned int> vIndex; std::vector<unsigned int> vIndex;
if (merkleBlock.txn.ExtractMatches(vMatch, vIndex) != merkleBlock.header.hashMerkleRoot) { if (merkleBlock.txn.ExtractMatches(vMatch, vIndex) != merkleBlock.header.hashMerkleRoot) {
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Something wrong with merkleblock"); throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Something wrong with merkleblock");
@@ -72,7 +72,7 @@ RPCHelpMan importprunedfunds()
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found in chain"); throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found in chain");
} }
std::vector<uint256>::const_iterator it; std::vector<Txid>::const_iterator it;
if ((it = std::find(vMatch.begin(), vMatch.end(), tx.GetHash())) == vMatch.end()) { if ((it = std::find(vMatch.begin(), vMatch.end(), tx.GetHash())) == vMatch.end()) {
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Transaction given doesn't exist in proof"); throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Transaction given doesn't exist in proof");
} }
+1 -1
View File
@@ -5,9 +5,9 @@
#include <core_io.h> #include <core_io.h>
#include <key_io.h> #include <key_io.h>
#include <policy/rbf.h> #include <policy/rbf.h>
#include <primitives/transaction_identifier.h>
#include <rpc/util.h> #include <rpc/util.h>
#include <rpc/blockchain.h> #include <rpc/blockchain.h>
#include <util/transaction_identifier.h>
#include <util/vector.h> #include <util/vector.h>
#include <wallet/receive.h> #include <wallet/receive.h>
#include <wallet/rpc/util.h> #include <wallet/rpc/util.h>
+2 -2
View File
@@ -13,6 +13,7 @@
#include <numeric> #include <numeric>
#include <policy/policy.h> #include <policy/policy.h>
#include <primitives/transaction.h> #include <primitives/transaction.h>
#include <primitives/transaction_identifier.h>
#include <script/script.h> #include <script/script.h>
#include <script/signingprovider.h> #include <script/signingprovider.h>
#include <script/solver.h> #include <script/solver.h>
@@ -21,7 +22,6 @@
#include <util/rbf.h> #include <util/rbf.h>
#include <util/trace.h> #include <util/trace.h>
#include <util/translation.h> #include <util/translation.h>
#include <util/transaction_identifier.h>
#include <wallet/coincontrol.h> #include <wallet/coincontrol.h>
#include <wallet/fees.h> #include <wallet/fees.h>
#include <wallet/receive.h> #include <wallet/receive.h>
@@ -327,7 +327,7 @@ CoinsResult AvailableCoins(const CWallet& wallet,
std::set<Txid> trusted_parents; std::set<Txid> trusted_parents;
// Cache for whether each tx passes the tx level checks (first bool), and whether the transaction is "safe" (second bool) // Cache for whether each tx passes the tx level checks (first bool), and whether the transaction is "safe" (second bool)
std::unordered_map<uint256, std::pair<bool, bool>, SaltedTxidHasher> tx_safe_cache; std::unordered_map<Txid, std::pair<bool, bool>, SaltedTxidHasher> tx_safe_cache;
for (const auto& [outpoint, txo] : wallet.GetTXOs()) { for (const auto& [outpoint, txo] : wallet.GetTXOs()) {
const CWalletTx& wtx = txo.GetWalletTx(); const CWalletTx& wtx = txo.GetWalletTx();
const CTxOut& output = txo.GetTxOut(); const CTxOut& output = txo.GetTxOut();
+1 -1
View File
@@ -2319,7 +2319,7 @@ util::Result<void> CWallet::RemoveTxs(WalletBatch& batch, std::vector<Txid>& txs
for (const auto& txin : it->second.tx->vin) for (const auto& txin : it->second.tx->vin)
mapTxSpends.erase(txin.prevout); mapTxSpends.erase(txin.prevout);
for (unsigned int i = 0; i < it->second.tx->vout.size(); ++i) { for (unsigned int i = 0; i < it->second.tx->vout.size(); ++i) {
m_txos.erase(COutPoint(Txid::FromUint256(hash), i)); m_txos.erase(COutPoint(hash, i));
} }
mapWallet.erase(it); mapWallet.erase(it);
NotifyTransactionChanged(hash, CT_DELETED); NotifyTransactionChanged(hash, CT_DELETED);
+1 -1
View File
@@ -15,6 +15,7 @@
#include <outputtype.h> #include <outputtype.h>
#include <policy/feerate.h> #include <policy/feerate.h>
#include <primitives/transaction.h> #include <primitives/transaction.h>
#include <primitives/transaction_identifier.h>
#include <script/interpreter.h> #include <script/interpreter.h>
#include <script/script.h> #include <script/script.h>
#include <support/allocators/secure.h> #include <support/allocators/secure.h>
@@ -26,7 +27,6 @@
#include <util/result.h> #include <util/result.h>
#include <util/string.h> #include <util/string.h>
#include <util/time.h> #include <util/time.h>
#include <util/transaction_identifier.h>
#include <util/ui_change_type.h> #include <util/ui_change_type.h>
#include <wallet/crypter.h> #include <wallet/crypter.h>
#include <wallet/db.h> #include <wallet/db.h>
+1 -1
View File
@@ -9,6 +9,7 @@
#include <common/system.h> #include <common/system.h>
#include <key_io.h> #include <key_io.h>
#include <primitives/transaction_identifier.h>
#include <protocol.h> #include <protocol.h>
#include <script/script.h> #include <script/script.h>
#include <serialize.h> #include <serialize.h>
@@ -16,7 +17,6 @@
#include <util/bip32.h> #include <util/bip32.h>
#include <util/check.h> #include <util/check.h>
#include <util/fs.h> #include <util/fs.h>
#include <util/transaction_identifier.h>
#include <util/time.h> #include <util/time.h>
#include <util/translation.h> #include <util/translation.h>
#include <wallet/migrate.h> #include <wallet/migrate.h>
+1 -1
View File
@@ -7,8 +7,8 @@
#define BITCOIN_WALLET_WALLETDB_H #define BITCOIN_WALLET_WALLETDB_H
#include <key.h> #include <key.h>
#include <primitives/transaction_identifier.h>
#include <script/sign.h> #include <script/sign.h>
#include <util/transaction_identifier.h>
#include <wallet/db.h> #include <wallet/db.h>
#include <wallet/walletutil.h> #include <wallet/walletutil.h>
+4 -4
View File
@@ -230,7 +230,7 @@ bool CZMQPublishHashBlockNotifier::NotifyBlock(const CBlockIndex *pindex)
bool CZMQPublishHashTransactionNotifier::NotifyTransaction(const CTransaction &transaction) bool CZMQPublishHashTransactionNotifier::NotifyTransaction(const CTransaction &transaction)
{ {
uint256 hash = transaction.GetHash(); uint256 hash = transaction.GetHash().ToUint256();
LogDebug(BCLog::ZMQ, "Publish hashtx %s to %s\n", hash.GetHex(), this->address); LogDebug(BCLog::ZMQ, "Publish hashtx %s to %s\n", hash.GetHex(), this->address);
uint8_t data[32]; uint8_t data[32];
for (unsigned int i = 0; i < 32; i++) { for (unsigned int i = 0; i < 32; i++) {
@@ -254,7 +254,7 @@ bool CZMQPublishRawBlockNotifier::NotifyBlock(const CBlockIndex *pindex)
bool CZMQPublishRawTransactionNotifier::NotifyTransaction(const CTransaction &transaction) bool CZMQPublishRawTransactionNotifier::NotifyTransaction(const CTransaction &transaction)
{ {
uint256 hash = transaction.GetHash(); uint256 hash = transaction.GetHash().ToUint256();
LogDebug(BCLog::ZMQ, "Publish rawtx %s to %s\n", hash.GetHex(), this->address); LogDebug(BCLog::ZMQ, "Publish rawtx %s to %s\n", hash.GetHex(), this->address);
DataStream ss; DataStream ss;
ss << TX_WITH_WITNESS(transaction); ss << TX_WITH_WITNESS(transaction);
@@ -290,14 +290,14 @@ bool CZMQPublishSequenceNotifier::NotifyBlockDisconnect(const CBlockIndex *pinde
bool CZMQPublishSequenceNotifier::NotifyTransactionAcceptance(const CTransaction &transaction, uint64_t mempool_sequence) bool CZMQPublishSequenceNotifier::NotifyTransactionAcceptance(const CTransaction &transaction, uint64_t mempool_sequence)
{ {
uint256 hash = transaction.GetHash(); uint256 hash = transaction.GetHash().ToUint256();
LogDebug(BCLog::ZMQ, "Publish hashtx mempool acceptance %s to %s\n", hash.GetHex(), this->address); LogDebug(BCLog::ZMQ, "Publish hashtx mempool acceptance %s to %s\n", hash.GetHex(), this->address);
return SendSequenceMsg(*this, hash, /* Mempool (A)cceptance */ 'A', mempool_sequence); return SendSequenceMsg(*this, hash, /* Mempool (A)cceptance */ 'A', mempool_sequence);
} }
bool CZMQPublishSequenceNotifier::NotifyTransactionRemoval(const CTransaction &transaction, uint64_t mempool_sequence) bool CZMQPublishSequenceNotifier::NotifyTransactionRemoval(const CTransaction &transaction, uint64_t mempool_sequence)
{ {
uint256 hash = transaction.GetHash(); uint256 hash = transaction.GetHash().ToUint256();
LogDebug(BCLog::ZMQ, "Publish hashtx mempool removal %s to %s\n", hash.GetHex(), this->address); LogDebug(BCLog::ZMQ, "Publish hashtx mempool removal %s to %s\n", hash.GetHex(), this->address);
return SendSequenceMsg(*this, hash, /* Mempool (R)emoval */ 'R', mempool_sequence); return SendSequenceMsg(*this, hash, /* Mempool (R)emoval */ 'R', mempool_sequence);
} }