Skip to content

Commit 11d28f2

Browse files
committed
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.
1 parent 1be688f commit 11d28f2

File tree

2 files changed

+36
-0
lines changed

2 files changed

+36
-0
lines changed

src/primitives/transaction.h

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -437,6 +437,20 @@ class GenTxid
437437
const uint256& GetHash() const LIFETIMEBOUND { return m_hash; }
438438
friend bool operator==(const GenTxid& a, const GenTxid& b) { return a.m_is_wtxid == b.m_is_wtxid && a.m_hash == b.m_hash; }
439439
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); }
440+
441+
GenTxidVariant ToVariant() const
442+
{
443+
return m_is_wtxid ?
444+
GenTxidVariant{Wtxid::FromUint256(m_hash)} :
445+
GenTxidVariant{Txid::FromUint256(m_hash)};
446+
}
447+
448+
static GenTxid FromVariant(const GenTxidVariant& variant)
449+
{
450+
return GenTxid{
451+
std::holds_alternative<::Wtxid>(variant),
452+
variant.ToUint256()};
453+
}
440454
};
441455

442456
#endif // BITCOIN_PRIMITIVES_TRANSACTION_H

src/util/transaction_identifier.h

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,10 @@
99
#include <uint256.h>
1010
#include <util/types.h>
1111

12+
#include <compare>
13+
#include <tuple>
14+
#include <variant>
15+
1216
/** transaction_identifier represents the two canonical transaction identifier
1317
* types (txid, wtxid).*/
1418
template <bool has_witness>
@@ -76,4 +80,22 @@ using Txid = transaction_identifier<false>;
7680
/** Wtxid commits to all transaction fields including the witness. */
7781
using Wtxid = transaction_identifier<true>;
7882

83+
class GenTxidVariant : public std::variant<Txid, Wtxid>
84+
{
85+
public:
86+
using variant::variant;
87+
88+
bool IsWtxid() const { return std::holds_alternative<Wtxid>(*this); }
89+
90+
const uint256& ToUint256() const LIFETIMEBOUND
91+
{
92+
return std::visit([](const auto& id) -> const uint256& { return id.ToUint256(); }, *this);
93+
}
94+
95+
friend auto operator<=>(const GenTxidVariant& a, const GenTxidVariant& b)
96+
{
97+
return std::tuple(a.IsWtxid(), a.ToUint256()) <=> std::tuple(b.IsWtxid(), b.ToUint256());
98+
}
99+
};
100+
79101
#endif // BITCOIN_UTIL_TRANSACTION_IDENTIFIER_H

0 commit comments

Comments
 (0)