Skip to content
Open
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
7 changes: 5 additions & 2 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -236,8 +236,11 @@ Be extra careful around:
- governance object and superblock payment logic;
- EvoDB, credit-pool, asset-lock, and Platform integration code;
- network-message serialization, checksums, and partial-send paths;
- BLS scheme transitions across connect, disconnect, undo, and activation
boundaries;
- BLS schemes: an unnamed scheme is basic; legacy is selected by a payload's
version (encoding) or by the block being validated (signature verification).
Uniqueness checks also probe both encodings, and RPC or log code may print or
parse a key or signature in either one. See "BLS schemes" in
`doc/developer-notes.md`;
- future DKG/quorum prediction, which must evaluate quorum availability at the
relevant future work/cycle base instead of only the current tip;
- time, mocktime, scheduler, and interrupt/shutdown behavior.
Expand Down
38 changes: 38 additions & 0 deletions doc/developer-notes.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ Developer Notes
- [DEBUG_LOCKORDER](#debug_lockorder)
- [DEBUG_LOCKCONTENTION](#debug_lockcontention)
- [Assertions and Checks](#assertions-and-checks)
- [BLS schemes](#bls-schemes)
- [Valgrind suppressions file](#valgrind-suppressions-file)
- [Compiling for test coverage](#compiling-for-test-coverage)
- [Performance profiling with perf](#performance-profiling-with-perf)
Expand Down Expand Up @@ -502,6 +503,43 @@ assert; use `Assume` for our *own* bookkeeping while still handling the
violated case; and reserve `assert` for the narrow spot where continuing would
corrupt EvoDB, the block index, or the wallet.

### BLS schemes

BLS public keys and signatures have two encodings and two signature schemes: the
legacy one used before v19, and the basic one used since. Which one applies is a
property of the data or of the block, never of the node:

- A call that names no scheme is basic. That is the right choice for everything
that is not historical: P2P messages, DKG, signing, ChainLocks, InstantSend,
governance, and any new payload or message.
- The encoding of a key or signature inside a versioned structure follows that
structure's version. Use the helper of its owner (`ProTxVersion::GetBLSScheme()`,
`CFinalCommitment::GetBLSScheme()`, `OperatorKeyScheme()`) rather than comparing
versions inline.
- The scheme an operator signature in a provider transaction, or a signature of
a mined quorum commitment, is *verified* under follows the block, not the
version of the payload carrying it: `BLSSchemeAfter(pindexPrev, params)`, which
provider transaction checks receive as `SpecialTxRules::bls_scheme`. A
legacy-encoded payload mined after v19 is verified under basic.
- Signatures a quorum recovers (ChainLocks, InstantSend locks, EHF signals, asset
unlocks) are always verified under basic, in a block or out of one.
- Production code cannot sign under the legacy scheme. Tests that need a legacy
signature for historical validation use `SignBLS()` from `test/util/bls.h`.
- An operator key (`CBLSLazyPublicKey`) has no encoding of its own, so
serializing, hashing or printing one always names the scheme, taken from the
payload or masternode state that owns it.
- Two other kinds of code name legacy explicitly: operator-key uniqueness
checks, which probe both encodings, and RPC or log code that prints or parses
a key or signature in either encoding.

`test/lint/lint-bls-scheme.py` rejects a line outside `src/bls`, the tests and
the benchmarks that names `BLSScheme::Legacy`, unless the line carries
`// NOLINT(bls-legacy-scheme)` or the line before it carries
`// NOLINTNEXTLINE(bls-legacy-scheme)`. A marker left on a line that no longer
names it is rejected as well. The marked lines are version and block selection,
those uniqueness probes, legacy-diff migration, and the RPC or log code that
prints or parses either encoding.

### Valgrind suppressions file

Valgrind is a programming tool for memory debugging, memory leak detection, and
Expand Down
42 changes: 20 additions & 22 deletions src/active/dkgsession.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -31,8 +31,7 @@ ActiveDKGSession::ActiveDKGSession(CBLSWorker& bls_worker, CDeterministicMNManag
CDKGSession(bls_worker, dmnman, dkgdbgman, qdkgsman, qsnapman, chainman, base_block_index, llmq_params),
m_mn_metaman{mn_metaman},
m_mn_activeman{mn_activeman},
m_sporkman{sporkman},
m_use_legacy_bls{!DeploymentActiveAfter(m_quorum_base_block_index, Params().GetConsensus(), Consensus::DEPLOYMENT_V19)}
m_sporkman{sporkman}
{
}

Expand Down Expand Up @@ -125,7 +124,7 @@ std::optional<CDKGContribution> ActiveDKGSession::SendContributions()

logger.Batch("encrypted contributions. time=%d", t1.count());

qc.sig = m_mn_activeman.Sign(qc.GetSignHash(), m_use_legacy_bls);
qc.sig = m_mn_activeman.Sign(qc.GetSignHash());

logger.Flush();

Expand Down Expand Up @@ -157,7 +156,6 @@ void ActiveDKGSession::VerifyPendingContributions()
std::vector<size_t> memberIndexes;
std::vector<BLSVerificationVectorPtr> vvecs;
std::vector<CBLSSecretKey> skContributions;
bool anyLegacyVvec{false};

for (const auto& idx : pendingContributionVerifications) {
const auto& m = members[idx];
Expand All @@ -166,7 +164,6 @@ void ActiveDKGSession::VerifyPendingContributions()
}
memberIndexes.emplace_back(idx);
vvecs.emplace_back(receivedVvecs[idx]);
anyLegacyVvec |= receivedVvecsLegacyScheme[idx];
skContributions.emplace_back(receivedSkContributions[idx]);
// Write here to definitely store one contribution for each member no matter if
// our share is valid or not, could be that others are still correct
Expand All @@ -184,9 +181,8 @@ void ActiveDKGSession::VerifyPendingContributions()
return;
}

// Weighted aggregation needs points that passed subgroup checks, which legacy-scheme deserialization skips
auto result = blsWorker.VerifyContributionShares(myId, vvecs, skContributions, /*parallel=*/true,
/*aggregated=*/!anyLegacyVvec);
/*aggregated=*/true);
if (result.size() != memberIndexes.size()) {
logger.Batch("VerifyContributionShares returned result of size %d but size %d was expected, something is wrong", result.size(), memberIndexes.size());
return;
Expand Down Expand Up @@ -348,7 +344,7 @@ std::optional<CDKGComplaint> ActiveDKGSession::SendComplaint()

logger.Batch("sending complaint. badCount=%d, complaintCount=%d", badCount, complaintCount);

qc.sig = m_mn_activeman.Sign(qc.GetSignHash(), m_use_legacy_bls);
qc.sig = m_mn_activeman.Sign(qc.GetSignHash());

logger.Flush();

Expand Down Expand Up @@ -438,7 +434,7 @@ std::optional<CDKGJustification> ActiveDKGSession::SendJustification(const Uint2
return std::nullopt;
}

qj.sig = m_mn_activeman.Sign(qj.GetSignHash(), m_use_legacy_bls);
qj.sig = m_mn_activeman.Sign(qj.GetSignHash());

logger.Flush();

Expand Down Expand Up @@ -595,23 +591,24 @@ std::optional<CDKGPrematureCommitment> ActiveDKGSession::SendCommitment()
(*qc.quorumVvecHash.begin())++;
}

uint256 commitmentHash = BuildCommitmentHash(qc.llmqType, qc.quorumHash, qc.validMembers, qc.quorumPublicKey, qc.quorumVvecHash);
uint256 commitmentHash = BuildCommitmentHash(qc.llmqType, qc.quorumHash, qc.validMembers, qc.quorumPublicKey,
qc.quorumVvecHash, BLSScheme::Basic);

if (lieType == 2) {
(*commitmentHash.begin())++;
}

qc.sig = m_mn_activeman.Sign(commitmentHash, m_use_legacy_bls);
qc.quorumSig = skShare.Sign(commitmentHash, m_use_legacy_bls);
qc.sig = m_mn_activeman.Sign(commitmentHash);
qc.quorumSig = skShare.Sign(commitmentHash);

if (lieType == 3) {
auto buf = qc.sig.ToBytes(m_use_legacy_bls);
auto buf = qc.sig.ToBytes();
buf[5]++;
qc.sig.SetBytes(buf, m_use_legacy_bls);
qc.sig.SetBytes(buf);
} else if (lieType == 4) {
auto buf = qc.quorumSig.ToBytes(m_use_legacy_bls);
auto buf = qc.quorumSig.ToBytes();
buf[5]++;
qc.quorumSig.SetBytes(buf, m_use_legacy_bls);
qc.quorumSig.SetBytes(buf);
}

t3.stop();
Expand Down Expand Up @@ -686,7 +683,8 @@ std::vector<CFinalCommitment> ActiveDKGSession::FinalizeCommitments()
fqc.nVersion = CFinalCommitment::GetVersion(isQuorumRotationEnabled, DeploymentActiveAfter(m_quorum_base_block_index, m_chainman.GetConsensus(), Consensus::DEPLOYMENT_V19));
fqc.quorumIndex = isQuorumRotationEnabled ? quorumIndex : 0;

uint256 commitmentHash = BuildCommitmentHash(fqc.llmqType, fqc.quorumHash, fqc.validMembers, fqc.quorumPublicKey, fqc.quorumVvecHash);
uint256 commitmentHash = BuildCommitmentHash(fqc.llmqType, fqc.quorumHash, fqc.validMembers,
fqc.quorumPublicKey, fqc.quorumVvecHash, BLSScheme::Basic);

std::vector<CBLSSignature> aggSigs;
std::vector<CBLSPublicKey> aggPks;
Expand Down Expand Up @@ -722,7 +720,7 @@ std::vector<CFinalCommitment> ActiveDKGSession::FinalizeCommitments()
t2.stop();

cxxtimer::Timer t3(true);
if (!fqc.Verify({m_dmnman, m_qsnapman, m_chainman, m_quorum_base_block_index}, true)) {
if (!fqc.Verify({m_dmnman, m_qsnapman, m_chainman, m_quorum_base_block_index}, BLSScheme::Basic)) {
logger.Batch("failed to verify final commitment");
continue;
}
Expand Down Expand Up @@ -773,16 +771,16 @@ CFinalCommitment ActiveDKGSession::FinalizeSingleCommitment()
fqc.quorumIndex = 0;

uint256 commitmentHash = BuildCommitmentHash(fqc.llmqType, fqc.quorumHash, fqc.validMembers, fqc.quorumPublicKey,
fqc.quorumVvecHash);
fqc.quorumSig = sk1.Sign(commitmentHash, m_use_legacy_bls);
fqc.quorumVvecHash, BLSScheme::Basic);
fqc.quorumSig = sk1.Sign(commitmentHash);

fqc.membersSig = m_mn_activeman.Sign(commitmentHash, m_use_legacy_bls);
fqc.membersSig = m_mn_activeman.Sign(commitmentHash);

if (workaround_qpublic_key) {
fqc.quorumSig = fqc.membersSig;
}

if (!fqc.Verify({m_dmnman, m_qsnapman, m_chainman, m_quorum_base_block_index}, true)) {
if (!fqc.Verify({m_dmnman, m_qsnapman, m_chainman, m_quorum_base_block_index}, BLSScheme::Basic)) {
logger.Batch("failed to verify final commitment");
assert(false);
}
Expand Down
1 change: 0 additions & 1 deletion src/active/dkgsession.h
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,6 @@ class ActiveDKGSession final : public llmq::CDKGSession
CMasternodeMetaMan& m_mn_metaman;
const CActiveMasternodeManager& m_mn_activeman;
const CSporkManager& m_sporkman;
const bool m_use_legacy_bls{false};

public:
ActiveDKGSession() = delete;
Expand Down
5 changes: 5 additions & 0 deletions src/active/dkgsessionhandler.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,11 @@ bool ActiveDKGSessionHandler::InitNewQuorum(gsl::not_null<const CBlockIndex*> pQ
if (!DeploymentDIP0003Enforced(pQuorumBaseBlockIndex->nHeight, Params().GetConsensus())) {
return false;
}
if (!DeploymentActiveAfter(pQuorumBaseBlockIndex, Params().GetConsensus(), Consensus::DEPLOYMENT_V19)) {
LogPrint(BCLog::LLMQ_DKG, "%s -- no DKG for quorum base %d: v19 is not active\n", __func__,
pQuorumBaseBlockIndex->nHeight);
return false;
}

auto next_session = std::make_shared<ActiveDKGSession>(m_bls_worker, m_dmnman, m_dkgdbgman, m_qdkgsman,
m_mn_metaman, m_qsnapman, m_mn_activeman, m_chainman,
Expand Down
14 changes: 7 additions & 7 deletions src/active/masternode.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -59,8 +59,8 @@ CActiveMasternodeManager::CActiveMasternodeManager(CConnman& connman, CDetermini
{
assert(sk.IsValid()); /* We can assume pk is valid if sk is valid */
LogPrintf("MASTERNODE:\n blsPubKeyOperator legacy: %s\n blsPubKeyOperator basic: %s\n",
m_operator_pk.ToString(/*specificLegacyScheme=*/true),
m_operator_pk.ToString(/*specificLegacyScheme=*/false));
// NOLINTNEXTLINE(bls-legacy-scheme)
m_operator_pk.ToString(BLSScheme::Legacy), m_operator_pk.ToString(BLSScheme::Basic));
}

CActiveMasternodeManager::~CActiveMasternodeManager() = default;
Expand Down Expand Up @@ -288,21 +288,21 @@ template bool CActiveMasternodeManager::Decrypt(const CBLSIESEncryptedObject<CBL
template bool CActiveMasternodeManager::Decrypt(const CBLSIESMultiRecipientObjects<CBLSSecretKey>& obj, size_t idx,
CBLSSecretKey& ret_obj, int version) const;

[[nodiscard]] CBLSSignature CActiveMasternodeManager::Sign(const uint256& hash, const bool is_legacy) const
[[nodiscard]] CBLSSignature CActiveMasternodeManager::Sign(const uint256& hash) const
{
AssertLockNotHeld(cs);
return WITH_READ_LOCK(cs, return m_operator_sk.Sign(hash, is_legacy));
return WITH_READ_LOCK(cs, return m_operator_sk.Sign(hash));
}

[[nodiscard]] std::vector<uint8_t> CActiveMasternodeManager::SignBasic(const uint256& hash) const
{
AssertLockNotHeld(cs);
auto sig = Sign(hash, /*is_legacy=*/false);
auto sig = Sign(hash);
assert(sig.IsValid());
return sig.ToByteVector(/*specificLegacyScheme=*/false);
return sig.ToByteVector();
}

// We need to pass a copy as opposed to a const ref because CBLSPublicKeyVersionWrapper
// We need to pass a copy as opposed to a const ref because BLSEncoded
// does not accept a const ref in its construction args
[[nodiscard]] CBLSPublicKey CActiveMasternodeManager::GetPubKey() const
{
Expand Down
2 changes: 1 addition & 1 deletion src/active/masternode.h
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ class CActiveMasternodeManager
template <template <typename> class EncryptedObj, typename Obj>
[[nodiscard]] bool Decrypt(const EncryptedObj<Obj>& obj, size_t idx, Obj& ret_obj, int version) const
EXCLUSIVE_LOCKS_REQUIRED(!cs);
[[nodiscard]] CBLSSignature Sign(const uint256& hash, const bool is_legacy) const EXCLUSIVE_LOCKS_REQUIRED(!cs);
[[nodiscard]] CBLSSignature Sign(const uint256& hash) const EXCLUSIVE_LOCKS_REQUIRED(!cs);
[[nodiscard]] std::vector<uint8_t> SignBasic(const uint256& hash) const EXCLUSIVE_LOCKS_REQUIRED(!cs);

[[nodiscard]] COutPoint GetOutPoint() const { READ_LOCK(cs); return m_outpoint; }
Expand Down
1 change: 0 additions & 1 deletion src/bench/bench_bitcoin.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,6 @@ int main(int argc, char** argv)
SapphireAutoDetect();
SHA256AutoDetect();
BLSInit();
bls::bls_legacy_scheme.store(false);
std::string error;
if (!argsman.ParseParameters(argc, argv, error)) {
tfm::format(std::cerr, "Error parsing command line arguments: %s\n", error);
Expand Down
10 changes: 5 additions & 5 deletions src/bench/bls.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -33,12 +33,12 @@ static void BuildTestVectors(size_t count, size_t invalidCount,
secKeys[i].MakeNewKey();
pubKeys[i] = secKeys[i].GetPublicKey();
msgHashes[i] = GetRandHash();
sigs[i] = secKeys[i].Sign(msgHashes[i], false);
sigs[i] = secKeys[i].Sign(msgHashes[i]);

if (invalid[i]) {
CBLSSecretKey s;
s.MakeNewKey();
sigs[i] = s.Sign(msgHashes[i], false);
sigs[i] = s.Sign(msgHashes[i]);
}
}
}
Expand Down Expand Up @@ -75,8 +75,8 @@ static void BLS_SignatureAggregate_Normal(benchmark::Bench& bench)
CBLSSecretKey secKey1, secKey2;
secKey1.MakeNewKey();
secKey2.MakeNewKey();
CBLSSignature sig1 = secKey1.Sign(hash, false);
CBLSSignature sig2 = secKey2.Sign(hash, false);
CBLSSignature sig1 = secKey1.Sign(hash);
CBLSSignature sig2 = secKey2.Sign(hash);

// Benchmark.
bench.run([&] {
Expand All @@ -93,7 +93,7 @@ static void BLS_Sign_Normal(benchmark::Bench& bench)
// Benchmark.
bench.minEpochIterations(100).run([&] {
uint256 hash = GetRandHash();
sig = secKey.Sign(hash, false);
sig = secKey.Sign(hash);
});
}

Expand Down
6 changes: 3 additions & 3 deletions src/bench/bls_dkg.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -120,7 +120,7 @@ class DKG
}
const auto vvec = blsWorker.BuildQuorumVerificationVector(vvecs);
const auto skShare = blsWorker.AggregateSecretKeys(receivedSkShares);
const auto sig = skShare.Sign(::SerializeHash(*vvec), false);
const auto sig = skShare.Sign(::SerializeHash(*vvec));
assert(sig.IsValid());
});
}
Expand All @@ -131,11 +131,11 @@ class DKG
ReceiveVvecs();
ReceiveShares(0);
const uint256 hash = ::SerializeHash(*quorumVvec);
const auto sig = blsWorker.AggregateSecretKeys(receivedSkShares).Sign(hash, false);
const auto sig = blsWorker.AggregateSecretKeys(receivedSkShares).Sign(hash);

bench.run([&] {
const bool valid = ::SerializeHash(*quorumVvec) == hash &&
sig.VerifyInsecure(CBLSWorker::BuildPubKeyShare(quorumVvec, ids[0]), hash, false);
sig.VerifyInsecure(CBLSWorker::BuildPubKeyShare(quorumVvec, ids[0]), hash);
assert(valid);
});
}
Expand Down
Loading
Loading