Implement GenTxid as a variant

Reimplements the GenTxid class as a variant for better type safety.
Also adds two temporary functions to the old GenTxid class that
convert to and from the new variant.
This commit is contained in:
marcofleon
2025-03-31 12:37:38 +01:00
parent 1be688f575
commit 11d28f21bb
2 changed files with 36 additions and 0 deletions

View File

@@ -437,6 +437,20 @@ public:
const uint256& GetHash() const LIFETIMEBOUND { return m_hash; }
friend bool operator==(const GenTxid& a, const GenTxid& b) { return a.m_is_wtxid == b.m_is_wtxid && a.m_hash == b.m_hash; }
friend bool operator<(const GenTxid& a, const GenTxid& b) { return std::tie(a.m_is_wtxid, a.m_hash) < std::tie(b.m_is_wtxid, b.m_hash); }
GenTxidVariant ToVariant() const
{
return m_is_wtxid ?
GenTxidVariant{Wtxid::FromUint256(m_hash)} :
GenTxidVariant{Txid::FromUint256(m_hash)};
}
static GenTxid FromVariant(const GenTxidVariant& variant)
{
return GenTxid{
std::holds_alternative<::Wtxid>(variant),
variant.ToUint256()};
}
};
#endif // BITCOIN_PRIMITIVES_TRANSACTION_H

View File

@@ -9,6 +9,10 @@
#include <uint256.h>
#include <util/types.h>
#include <compare>
#include <tuple>
#include <variant>
/** transaction_identifier represents the two canonical transaction identifier
* types (txid, wtxid).*/
template <bool has_witness>
@@ -76,4 +80,22 @@ using Txid = transaction_identifier<false>;
/** Wtxid commits to all transaction fields including the witness. */
using Wtxid = transaction_identifier<true>;
class GenTxidVariant : public std::variant<Txid, Wtxid>
{
public:
using variant::variant;
bool IsWtxid() const { return std::holds_alternative<Wtxid>(*this); }
const uint256& ToUint256() const LIFETIMEBOUND
{
return std::visit([](const auto& id) -> const uint256& { return id.ToUint256(); }, *this);
}
friend auto operator<=>(const GenTxidVariant& a, const GenTxidVariant& b)
{
return std::tuple(a.IsWtxid(), a.ToUint256()) <=> std::tuple(b.IsWtxid(), b.ToUint256());
}
};
#endif // BITCOIN_UTIL_TRANSACTION_IDENTIFIER_H