Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
54 changes: 45 additions & 9 deletions src/bls/bls.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -15,9 +15,40 @@
#include <cstring>

namespace bls {
std::atomic<bool> bls_legacy_scheme = std::atomic<bool>(true);
std::atomic<bool> bls_legacy_scheme = std::atomic<bool>(true);

namespace {
//! Trivially destructible, like util/threadnames.cpp's thread-local name.
thread_local std::optional<bool> g_thread_legacy_scheme;
} // namespace

bool EffectiveLegacyScheme() { return g_thread_legacy_scheme ? *g_thread_legacy_scheme : bls_legacy_scheme.load(); }

void SetEffectiveLegacyScheme(bool legacy)
{
if (g_thread_legacy_scheme) {
g_thread_legacy_scheme = legacy;
} else {
bls_legacy_scheme.store(legacy);
}
}

ScopedLegacySchemeOverride::ScopedLegacySchemeOverride(bool legacy) noexcept :
m_saved{g_thread_legacy_scheme}
{
g_thread_legacy_scheme = legacy;
}

ScopedLegacySchemeOverride::~ScopedLegacySchemeOverride() noexcept
{
if (!m_committed || !m_saved) {
g_thread_legacy_scheme = m_saved;
}
}

bool ScopedLegacySchemeOverride::Active() noexcept { return g_thread_legacy_scheme.has_value(); }
} // namespace bls

static const std::unique_ptr<bls::CoreMPL> pSchemeLegacy{std::make_unique<bls::LegacySchemeMPL>()};
static const std::unique_ptr<bls::CoreMPL> pScheme(std::make_unique<bls::BasicSchemeMPL>());

Expand Down Expand Up @@ -145,7 +176,7 @@ void CBLSPublicKey::AggregateInsecure(const CBLSPublicKey& o)
{
assert(IsValid() && o.IsValid());
try {
impl = Scheme(bls::bls_legacy_scheme.load())->Aggregate({impl, o.impl});
impl = Scheme(bls::EffectiveLegacyScheme())->Aggregate({impl, o.impl});
} catch (...) {
fValid = false;
}
Expand All @@ -166,7 +197,7 @@ CBLSPublicKey CBLSPublicKey::AggregateInsecure(Span<CBLSPublicKey> pks)

CBLSPublicKey ret;
try {
ret.impl = Scheme(bls::bls_legacy_scheme.load())->Aggregate(vecPublicKeys);
ret.impl = Scheme(bls::EffectiveLegacyScheme())->Aggregate(vecPublicKeys);
ret.fValid = true;
} catch (...) {
ret.fValid = false;
Expand Down Expand Up @@ -230,7 +261,7 @@ void CBLSSignature::AggregateInsecure(const CBLSSignature& o)
{
assert(IsValid() && o.IsValid());
try {
impl = Scheme(bls::bls_legacy_scheme.load())->Aggregate({impl, o.impl});
impl = Scheme(bls::EffectiveLegacyScheme())->Aggregate({impl, o.impl});
} catch (...) {
fValid = false;
}
Expand All @@ -251,7 +282,7 @@ CBLSSignature CBLSSignature::AggregateInsecure(Span<CBLSSignature> sigs)

CBLSSignature ret;
try {
ret.impl = Scheme(bls::bls_legacy_scheme.load())->Aggregate(v);
ret.impl = Scheme(bls::EffectiveLegacyScheme())->Aggregate(v);
ret.fValid = true;
} catch (...) {
ret.fValid = false;
Expand Down Expand Up @@ -283,7 +314,7 @@ CBLSSignature CBLSSignature::AggregateSecure(Span<CBLSSignature> sigs,

CBLSSignature ret;
try {
ret.impl = Scheme(bls::bls_legacy_scheme.load())->AggregateSecure(vecPublicKeys, vecSignatures, bls::Bytes(hash.begin(), hash.size()));
ret.impl = Scheme(bls::EffectiveLegacyScheme())->AggregateSecure(vecPublicKeys, vecSignatures, bls::Bytes(hash.begin(), hash.size()));
ret.fValid = true;
} catch (...) {
ret.fValid = false;
Expand Down Expand Up @@ -322,7 +353,7 @@ bool CBLSSignature::VerifyInsecure(const CBLSPublicKey& pubKey, const uint256& h

bool CBLSSignature::VerifyInsecure(const CBLSPublicKey& pubKey, const uint256& hash) const
{
return VerifyInsecure(pubKey, hash, bls::bls_legacy_scheme.load());
return VerifyInsecure(pubKey, hash, bls::EffectiveLegacyScheme());
}

bool CBLSSignature::VerifyInsecureAggregated(Span<CBLSPublicKey> pubKeys, Span<uint256> hashes) const
Expand All @@ -346,13 +377,18 @@ bool CBLSSignature::VerifyInsecureAggregated(Span<CBLSPublicKey> pubKeys, Span<u
}

try {
return Scheme(bls::bls_legacy_scheme.load())->AggregateVerify(pubKeyVec, hashes2, impl);
return Scheme(bls::EffectiveLegacyScheme())->AggregateVerify(pubKeyVec, hashes2, impl);
} catch (...) {
return false;
}
}

bool CBLSSignature::VerifySecureAggregated(Span<CBLSPublicKey> pks, const uint256& hash) const
{
return VerifySecureAggregated(pks, hash, bls::EffectiveLegacyScheme());
}

bool CBLSSignature::VerifySecureAggregated(Span<CBLSPublicKey> pks, const uint256& hash, const bool specificLegacyScheme) const
{
if (pks.empty()) {
return false;
Expand All @@ -365,7 +401,7 @@ bool CBLSSignature::VerifySecureAggregated(Span<CBLSPublicKey> pks, const uint25
}

try {
return Scheme(bls::bls_legacy_scheme.load())->VerifySecure(vecPublicKeys, impl, bls::Bytes(hash.begin(), hash.size()));
return Scheme(specificLegacyScheme)->VerifySecure(vecPublicKeys, impl, bls::Bytes(hash.begin(), hash.size()));
} catch (...) {
return false;
}
Expand Down
50 changes: 44 additions & 6 deletions src/bls/bls.h
Original file line number Diff line number Diff line change
Expand Up @@ -19,12 +19,48 @@
#include <array>
#include <atomic>
#include <mutex>
#include <optional>
#include <ranges>
#include <type_traits>

namespace bls {
extern std::atomic<bool> bls_legacy_scheme;
}
//! Process-wide default scheme of BLS operations that are not given one. It
//! follows the active chainstate's tip only: other threads read it outside
//! cs_main, so work for any other chain context (a background chainstate, a dry
//! run) sets a ScopedLegacySchemeOverride instead.
extern std::atomic<bool> bls_legacy_scheme;

//! The scheme of BLS operations on this thread that are not given one: the
//! innermost ScopedLegacySchemeOverride if one is set, else bls_legacy_scheme.
bool EffectiveLegacyScheme();

//! Switches EffectiveLegacyScheme(): this thread's override if one is set,
//! else bls_legacy_scheme.
void SetEffectiveLegacyScheme(bool legacy);

//! Sets EffectiveLegacyScheme() on this thread only, for the object's lifetime.
//! Work handed to another thread does not see it and must capture the scheme.
class ScopedLegacySchemeOverride
{
public:
explicit ScopedLegacySchemeOverride(bool legacy) noexcept;
~ScopedLegacySchemeOverride() noexcept;

ScopedLegacySchemeOverride(const ScopedLegacySchemeOverride&) = delete;
ScopedLegacySchemeOverride& operator=(const ScopedLegacySchemeOverride&) = delete;

//! Leaves the scheme in force at scope exit to the enclosing override. The
//! outermost override always ends with its scope.
void Commit() noexcept { m_committed = true; }

//! Whether an override is set on this thread.
static bool Active() noexcept;

private:
const std::optional<bool> m_saved;
bool m_committed{false};
};
} // namespace bls

// reversed BLS12-381
constexpr int BLS_CURVE_ID_SIZE{32};
Expand Down Expand Up @@ -181,7 +217,7 @@ class CBLSWrapper
template <typename Stream>
inline void Serialize(Stream& s) const
{
Serialize(s, bls::bls_legacy_scheme.load());
Serialize(s, bls::EffectiveLegacyScheme());
Comment thread
PastaPastaPasta marked this conversation as resolved.
Resolved
}

template <typename Stream>
Expand Down Expand Up @@ -209,7 +245,7 @@ class CBLSWrapper
template <typename Stream>
inline void Unserialize(Stream& s)
{
Unserialize(s, bls::bls_legacy_scheme.load());
Unserialize(s, bls::EffectiveLegacyScheme());
}

inline bool CheckMalleable(Span<uint8_t> vecBytes, const bool specificLegacyScheme) const
Expand All @@ -232,7 +268,7 @@ class CBLSWrapper

inline std::string ToString() const
{
return ToString(bls::bls_legacy_scheme.load());
return ToString(bls::EffectiveLegacyScheme());
}
};

Expand Down Expand Up @@ -371,6 +407,8 @@ class CBLSSignature : public CBLSWrapper<bls::G2Element, BLS_CURVE_SIG_SIZE, CBL
[[nodiscard]] bool VerifyInsecure(const CBLSPublicKey& pubKey, const uint256& hash) const;
[[nodiscard]] bool VerifyInsecureAggregated(Span<CBLSPublicKey> pubKeys, Span<uint256> hashes) const;

[[nodiscard]] bool VerifySecureAggregated(Span<CBLSPublicKey> pks, const uint256& hash,
const bool specificLegacyScheme) const;
[[nodiscard]] bool VerifySecureAggregated(Span<CBLSPublicKey> pks, const uint256& hash) const;

bool Recover(Span<CBLSSignature> sigs, Span<CBLSId> ids);
Expand Down Expand Up @@ -414,7 +452,7 @@ class CBLSLazyWrapper

public:
CBLSLazyWrapper() :
bufLegacyScheme(bls::bls_legacy_scheme.load())
bufLegacyScheme(bls::EffectiveLegacyScheme())
{}

explicit CBLSLazyWrapper(const CBLSLazyWrapper& r)
Expand Down
6 changes: 3 additions & 3 deletions src/chainlock/clsig.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -86,9 +86,9 @@ class DecodedSignatureCache
CBLSSignature Decode(const std::array<uint8_t, CBLSSignature::SerSize>& bytes) EXCLUSIVE_LOCKS_REQUIRED(!m_mutex)
{
// Decode exactly as the coinbase payload was always decoded: under the
// process-wide scheme flag, including its opposite-scheme rejection. The
// flag is part of the key so a transient value cannot leak into later calls.
const bool legacy = bls::bls_legacy_scheme.load();
// effective scheme, including its opposite-scheme rejection. The scheme is
// part of the key so another context's value cannot leak into later calls.
const bool legacy = bls::EffectiveLegacyScheme();
const uint256 key = (CHashWriter(SER_GETHASH, 0) << Span{bytes} << legacy).GetHash();
CBLSSignature sig;
{
Expand Down
8 changes: 4 additions & 4 deletions src/evo/mnhftx.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -387,10 +387,10 @@ bool CMNHFManager::ForceSignalDBUpdate(const CBlockIndex* tip)
// force ehf signals db update
auto dbTx = m_evoDb.BeginTransaction();

const bool last_legacy = bls::bls_legacy_scheme.load();
bls::bls_legacy_scheme.store(false);
GetSignalsStage(tip);
bls::bls_legacy_scheme.store(last_legacy);
{
const bls::ScopedLegacySchemeOverride basic_scheme{/*legacy=*/false};
GetSignalsStage(tip);
}

dbTx->Commit();
// flush it to disk
Expand Down
16 changes: 8 additions & 8 deletions src/evo/specialtxman.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1100,11 +1100,11 @@ bool CSpecialTxProcessor::ProcessSpecialTxsInBlock(Chainstate& chainstate, const
LogPrint(BCLog::BENCHMARK, " - m_mnhfman->ProcessBlock: %.2fms [%.2fs]\n", Ticks<MillisecondsDouble>(nTime8 - nTime7),
Ticks<SecondsDouble>(nTimeMnehf));

if (DeploymentActiveAfter(pindex, m_consensus_params, Consensus::DEPLOYMENT_V19) && bls::bls_legacy_scheme.load()) {
if (DeploymentActiveAfter(pindex, m_consensus_params, Consensus::DEPLOYMENT_V19) && bls::EffectiveLegacyScheme()) {
// NOTE: The block next to the activation is the one that is using new rules.
// V19 activated just activated, so we must switch to the new rules here.
bls::bls_legacy_scheme.store(false);
LogPrintf("CSpecialTxProcessor::%s -- bls_legacy_scheme=%d\n", __func__, bls::bls_legacy_scheme.load());
bls::SetEffectiveLegacyScheme(false);
LogPrintf("CSpecialTxProcessor::%s -- bls_legacy_scheme=%d\n", __func__, bls::EffectiveLegacyScheme());
}
} catch (const EvoDbInconsistencyError& e) {
// Local EvoDB corruption detected below (the node is already
Expand All @@ -1122,14 +1122,14 @@ bool CSpecialTxProcessor::UndoSpecialTxsInBlock(const Chainstate& chainstate, co
{
AssertLockHeld(::cs_main);

auto bls_legacy_scheme = bls::bls_legacy_scheme.load();
const bool bls_legacy_scheme{bls::EffectiveLegacyScheme()};

try {
if (!DeploymentActiveAt(*pindex, m_consensus_params, Consensus::DEPLOYMENT_V19) && !bls_legacy_scheme) {
// NOTE: The block next to the activation is the one that is using new rules.
// Removing the activation block here, so we must switch back to the old rules.
bls::bls_legacy_scheme.store(true);
LogPrintf("CSpecialTxProcessor::%s -- bls_legacy_scheme=%d\n", __func__, bls::bls_legacy_scheme.load());
bls::SetEffectiveLegacyScheme(true);
LogPrintf("CSpecialTxProcessor::%s -- bls_legacy_scheme=%d\n", __func__, bls::EffectiveLegacyScheme());
}

if (!m_mnhfman->UndoBlock(block, pindex)) {
Expand All @@ -1144,8 +1144,8 @@ bool CSpecialTxProcessor::UndoSpecialTxsInBlock(const Chainstate& chainstate, co
return false;
}
} catch (const std::exception& e) {
bls::bls_legacy_scheme.store(bls_legacy_scheme);
LogPrintf("CSpecialTxProcessor::%s -- bls_legacy_scheme=%d\n", __func__, bls::bls_legacy_scheme.load());
bls::SetEffectiveLegacyScheme(bls_legacy_scheme);
LogPrintf("CSpecialTxProcessor::%s -- bls_legacy_scheme=%d\n", __func__, bls::EffectiveLegacyScheme());
LogError("CSpecialTxProcessor::%s -- FAILURE! %s\n", __func__, e.what());
return false;
}
Expand Down
2 changes: 1 addition & 1 deletion src/llmq/dkgmessages.h
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ class CDKGContribution
s >> quorumHash;
s >> proTxHash;
// Decode the whole vvec under one scheme, so that vvecLegacyScheme describes every point in it
vvecLegacyScheme = bls::bls_legacy_scheme.load();
vvecLegacyScheme = bls::EffectiveLegacyScheme();
for (uint64_t i = 0, size = ReadCompactSize(s); i < size; i++) {
s >> CBLSPublicKeyVersionWrapper(tmp1.emplace_back(), vvecLegacyScheme);
}
Expand Down
2 changes: 1 addition & 1 deletion src/llmq/signing.h
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ class CRecoveredSig : virtual public CSigBase
CRecoveredSig(Consensus::LLMQType _llmqType, const uint256& _quorumHash, const uint256& _id, const uint256& _msgHash, const CBLSLazySignature& _sig) :
CSigBase(_llmqType, _quorumHash, _id, _msgHash), sig(_sig) {UpdateHash();};
CRecoveredSig(Consensus::LLMQType _llmqType, const uint256& _quorumHash, const uint256& _id, const uint256& _msgHash, const CBLSSignature& _sig) :
CSigBase(_llmqType, _quorumHash, _id, _msgHash) {const_cast<CBLSLazySignature&>(sig).Set(_sig, bls::bls_legacy_scheme.load()); UpdateHash();};
CSigBase(_llmqType, _quorumHash, _id, _msgHash) {const_cast<CBLSLazySignature&>(sig).Set(_sig, bls::EffectiveLegacyScheme()); UpdateHash();};

private:
// only in-memory
Expand Down
4 changes: 2 additions & 2 deletions src/llmq/signing_shares.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1569,7 +1569,7 @@ std::optional<CSigShare> CSigSharesManager::CreateSigShareForSingleMember(const

// TODO: This one should be SIGN by QUORUM key, not by OPERATOR key
// see TODO in CDKGSession::FinalizeSingleCommitment for details
auto bls_scheme = bls::bls_legacy_scheme.load();
auto bls_scheme = bls::EffectiveLegacyScheme();
sigShare.sigShare.Set(m_mn_activeman.Sign(signHash, bls_scheme), bls_scheme);

if (!sigShare.sigShare.Get().IsValid()) {
Expand Down Expand Up @@ -1624,7 +1624,7 @@ std::optional<CSigShare> CSigSharesManager::CreateSigShare(const CQuorum& quorum
CSigShare sigShare(quorum.params.type, quorum.qc->quorumHash, id, msgHash, static_cast<uint16_t>(memberIdx), {});
uint256 signHash = sigShare.buildSignHash().Get();

auto bls_scheme = bls::bls_legacy_scheme.load();
auto bls_scheme = bls::EffectiveLegacyScheme();
sigShare.sigShare.Set(skShare.Sign(signHash, bls_scheme), bls_scheme);
if (!sigShare.sigShare.Get().IsValid()) {
LogPrintf("CSigSharesManager::%s -- failed to sign sigShare. signHash=%s, id=%s, msgHash=%s, time=%s\n", __func__,
Expand Down
5 changes: 3 additions & 2 deletions src/llmq/utils.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -629,12 +629,12 @@ BlsCheck::~BlsCheck() = default;
bool BlsCheck::operator()()
{
if (m_pubkeys.size() > 1) {
if (!m_sig.VerifySecureAggregated(m_pubkeys, m_msg_hash)) {
if (!m_sig.VerifySecureAggregated(m_pubkeys, m_msg_hash, m_legacy_scheme)) {
LogPrint(BCLog::LLMQ, "%s\n", m_id_string);
return false;
}
} else if (m_pubkeys.size() == 1) {
if (!m_sig.VerifyInsecure(m_pubkeys.back(), m_msg_hash)) {
if (!m_sig.VerifyInsecure(m_pubkeys.back(), m_msg_hash, m_legacy_scheme)) {
LogPrint(BCLog::LLMQ, "%s\n", m_id_string);
return false;
}
Expand All @@ -652,6 +652,7 @@ void BlsCheck::swap(BlsCheck& obj) noexcept
std::swap(m_pubkeys, obj.m_pubkeys);
std::swap(m_msg_hash, obj.m_msg_hash);
std::swap(m_id_string, obj.m_id_string);
std::swap(m_legacy_scheme, obj.m_legacy_scheme);
}

std::optional<std::vector<CDeterministicMNCPtr>> ComputeQuorumMembersFromWorkBlock(
Expand Down
2 changes: 2 additions & 0 deletions src/llmq/utils.h
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,8 @@ struct BlsCheck {
std::vector<CBLSPublicKey> m_pubkeys;
uint256 m_msg_hash;
std::string m_id_string;
//! The building thread's scheme; CCheckQueue runs the check on another thread
bool m_legacy_scheme{bls::EffectiveLegacyScheme()};

public:
BlsCheck();
Expand Down
7 changes: 0 additions & 7 deletions src/node/chainstate.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -449,13 +449,6 @@ ChainstateLoadResult VerifyLoadedChainstate(ChainstateManager& chainman, const C
break;
} // no default case, so the compiler can warn about missing cases

// VerifyDB() disconnects blocks which might result in us switching back to legacy.
// Make sure we use the right scheme.
if (v19active && bls::bls_legacy_scheme.load()) {
bls::bls_legacy_scheme.store(false);
if (notify_bls_state) notify_bls_state(bls::bls_legacy_scheme.load());
}

if (options.check_level >= 3) {
chainstate->ResetBlockFailureFlags(nullptr);
}
Expand Down
2 changes: 1 addition & 1 deletion src/node/miner.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -361,7 +361,7 @@ std::unique_ptr<CBlockTemplate> BlockAssembler::CreateNewBlock(const CScript& sc
if (fV20Active_context) {
CBLSSignature best_cl_sig;
const bool has_best_cl{CalcCbTxBestChainlock(m_chainlocks, m_chainstate.m_blockman, pindexPrev, cbTx.bestCLHeightDiff, best_cl_sig)};
cbTx.bestCLSignature.Set(best_cl_sig, bls::bls_legacy_scheme.load());
cbTx.bestCLSignature.Set(best_cl_sig, bls::EffectiveLegacyScheme());
if (has_best_cl) {
LogPrintf("CreateNewBlock() h[%d] CbTx bestCLHeightDiff[%d] CLSig[%s]\n", nHeight, cbTx.bestCLHeightDiff, cbTx.bestCLSignature.ToString());
} else {
Expand Down
2 changes: 1 addition & 1 deletion src/rpc/quorums.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -701,7 +701,7 @@ static RPCHelpMan quorum_verify()
const uint256 id(ParseHashV(request.params[1], "id"));
const uint256 msgHash(ParseHashV(request.params[2], "msgHash"));

const bool use_bls_legacy = bls::bls_legacy_scheme.load();
const bool use_bls_legacy = bls::EffectiveLegacyScheme();
CBLSSignature sig;
if (!sig.SetHexStr(request.params[3].get_str(), use_bls_legacy)) {
throw JSONRPCError(RPC_INVALID_PARAMETER, "invalid signature format");
Expand Down
Loading
Loading