Skip to content
Merged
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
3 changes: 3 additions & 0 deletions src/Makefile.test.include
Original file line number Diff line number Diff line change
Expand Up @@ -145,6 +145,8 @@ BITCOIN_TESTS =\
test/governance_budget_tests.cpp \
test/governance_validators_tests.cpp \
test/governance_vote_sync_tests.cpp \
test/governance_vote_wire_tests.cpp \
test/coinjoin_inouts_tests.cpp \
test/hash_tests.cpp \
test/i2p_tests.cpp \
test/interfaces_tests.cpp \
Expand All @@ -164,6 +166,7 @@ BITCOIN_TESTS =\
test/llmq_chainlocks_tests.cpp \
test/llmq_formation_end_tests.cpp \
test/llmq_instantsend_tests.cpp \
test/instantsend_queue_tests.cpp \
test/llmq_invalid_type_tests.cpp \
test/llmq_quorum_base_tests.cpp \
test/logging_tests.cpp \
Expand Down
2 changes: 1 addition & 1 deletion src/coinjoin/coinjoin.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -129,7 +129,7 @@ bool CCoinJoinBroadcastTx::IsValidStructure() const
if (tx->vin.size() < size_t(CoinJoin::GetMinPoolParticipants())) {
return false;
}
if (tx->vin.size() > CoinJoin::GetMaxPoolParticipants() * COINJOIN_ENTRY_MAX_SIZE) {
if (tx->vin.size() > CoinJoin::GetMaxPoolInputOutputCount()) {
return false;
}
return ranges::all_of(tx->vout, [] (const auto& txOut){
Expand Down
34 changes: 28 additions & 6 deletions src/coinjoin/coinjoin.h
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
#include <netaddress.h>
#include <primitives/block.h>
#include <primitives/transaction.h>
#include <serialize.h>
#include <sync.h>
#include <timedata.h>
#include <univalue.h>
Expand Down Expand Up @@ -46,6 +47,15 @@ static constexpr int COINJOIN_SIGNING_TIMEOUT = 15;

static constexpr size_t COINJOIN_ENTRY_MAX_SIZE = 9;

namespace CoinJoin {
/// Get the minimum/maximum number of participants for the pool
int GetMinPoolParticipants();
int GetMaxPoolParticipants();

/// Maximum number of inputs or outputs across a full pool
inline size_t GetMaxPoolInputOutputCount() { return size_t(GetMaxPoolParticipants()) * COINJOIN_ENTRY_MAX_SIZE; }
} // namespace CoinJoin

// pool responses
enum PoolMessage : int32_t {
ERR_ALREADY_HAVE,
Expand Down Expand Up @@ -164,9 +174,25 @@ class CCoinJoinEntry
{
}

SERIALIZE_METHODS(CCoinJoinEntry, obj)
template <typename Stream>
void Serialize(Stream& s) const
{
s << vecTxDSIn << txCollateral << vecTxOut;
}

template <typename Stream>
void Unserialize(Stream& s)
{
READWRITE(obj.vecTxDSIn, obj.txCollateral, obj.vecTxOut);
const size_t max_count{CoinJoin::GetMaxPoolInputOutputCount()};
if (!UnserializeVectorWithMaxSize(s, vecTxDSIn, max_count)) {
throw std::ios_base::failure("CCoinJoinEntry::vecTxDSIn size too large");
}

s >> txCollateral;

if (!UnserializeVectorWithMaxSize(s, vecTxOut, max_count)) {
throw std::ios_base::failure("CCoinJoinEntry::vecTxOut size too large");
}
}

bool AddScriptSig(const CTxIn& txin);
Expand Down Expand Up @@ -361,10 +387,6 @@ namespace CoinJoin
{
bilingual_str GetMessageByID(PoolMessage nMessageID);

/// Get the minimum/maximum number of participants for the pool
int GetMinPoolParticipants();
int GetMaxPoolParticipants();

constexpr CAmount GetMaxPoolAmount() { return COINJOIN_ENTRY_MAX_SIZE * vecStandardDenominations.front(); }

/// If the collateral is valid given by a client
Expand Down
65 changes: 55 additions & 10 deletions src/coinjoin/server.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ PeerMsgRet CCoinJoinServer::ProcessMessage(CNode& peer, std::string_view msg_typ
} else if (msg_type == NetMsgType::DSVIN) {
ProcessDSVIN(peer, vRecv);
} else if (msg_type == NetMsgType::DSSIGNFINALTX) {
ProcessDSSIGNFINALTX(vRecv);
ProcessDSSIGNFINALTX(peer, vRecv);
}
return {};
}
Expand Down Expand Up @@ -218,10 +218,40 @@ void CCoinJoinServer::ProcessDSVIN(CNode& peer, CDataStream& vRecv)
}
}

void CCoinJoinServer::ProcessDSSIGNFINALTX(CDataStream& vRecv)
void CCoinJoinServer::ProcessDSSIGNFINALTX(CNode& peer, CDataStream& vRecv)
{
// Only accept signatures while we are actually collecting them, and only
// from peers that are active participants in this session. Otherwise a
// stray or unauthenticated peer could abort the session for everyone.
if (nState != POOL_STATE_SIGNING) {
LogPrint(BCLog::COINJOIN, "DSSIGNFINALTX -- wrong state, nState=%d, peer=%d\n",
nState.load(), peer.GetId());
PushStatus(peer, STATUS_REJECTED, ERR_SESSION);
return;
}
{
LOCK(cs_coinjoin);
const bool is_participant = ranges::any_of(
vecEntries, [&peer](const auto& entry) { return entry.addr == peer.addr; });
if (!is_participant) {
LogPrint(BCLog::COINJOIN, "DSSIGNFINALTX -- ignoring message from non-participant peer=%d\n",
peer.GetId());
PushStatus(peer, STATUS_REJECTED, ERR_INVALID_INPUT);
return;
}
}

const size_t max_txins{CoinJoin::GetMaxPoolInputOutputCount()};
std::vector<CTxIn> vecTxIn;
vRecv >> vecTxIn;
// Reject an over-cap count through this peer-local ERR_MAXIMUM path before a
// single CTxIn is decoded or allocated. A count above the generic MAX_SIZE cap
// is malformed and throws from ReadCompactSize, as it does for any other message.
if (!UnserializeVectorWithMaxSize(vRecv, vecTxIn, max_txins)) {
LogPrint(BCLog::COINJOIN, "DSSIGNFINALTX -- too many inputs. max=%d, peer=%d\n",
static_cast<int>(max_txins), peer.GetId());
PushStatus(peer, STATUS_REJECTED, ERR_MAXIMUM);
return;
}

LogPrint(BCLog::COINJOIN, "DSSIGNFINALTX -- vecTxIn.size() %s\n", vecTxIn.size());

Expand Down Expand Up @@ -583,16 +613,31 @@ bool CCoinJoinServer::AddEntry(const CCoinJoinEntry& entry, PoolMessage& nMessag
return false;
}

if (!CoinJoin::IsCollateralValid(m_chainman, m_isman, mempool, *entry.txCollateral)) {
LogPrint(BCLog::COINJOIN, "CCoinJoinServer::%s -- ERROR: collateral not valid!\n", __func__);
nMessageIDRet = ERR_INVALID_COLLATERAL;
if (entry.vecTxDSIn.size() > COINJOIN_ENTRY_MAX_SIZE || entry.vecTxOut.size() > COINJOIN_ENTRY_MAX_SIZE) {
LogPrint(BCLog::COINJOIN, /* Continued */
"CCoinJoinServer::%s -- ERROR: too many inputs or outputs! inputs=%s/%s, outputs=%s/%s\n", __func__,
entry.vecTxDSIn.size(), COINJOIN_ENTRY_MAX_SIZE, entry.vecTxOut.size(), COINJOIN_ENTRY_MAX_SIZE);
nMessageIDRet = ERR_MAXIMUM;

CTransactionRef txCollateralToConsume;
{
LOCK(cs_coinjoin);
const auto it = ranges::find_if(vecSessionCollaterals, [&entry](const auto& txCollateral) {
return *entry.txCollateral == *txCollateral;
});
if (it != vecSessionCollaterals.end()) {
txCollateralToConsume = *it;
}
}
if (txCollateralToConsume) {
ConsumeCollateral(txCollateralToConsume);
}
return false;
}

if (entry.vecTxDSIn.size() > COINJOIN_ENTRY_MAX_SIZE) {
LogPrint(BCLog::COINJOIN, "CCoinJoinServer::%s -- ERROR: too many inputs! %d/%d\n", __func__, entry.vecTxDSIn.size(), COINJOIN_ENTRY_MAX_SIZE);
nMessageIDRet = ERR_MAXIMUM;
ConsumeCollateral(entry.txCollateral);
if (!CoinJoin::IsCollateralValid(m_chainman, m_isman, mempool, *entry.txCollateral)) {
LogPrint(BCLog::COINJOIN, "CCoinJoinServer::%s -- ERROR: collateral not valid!\n", __func__);
nMessageIDRet = ERR_INVALID_COLLATERAL;
return false;
}

Expand Down
2 changes: 1 addition & 1 deletion src/coinjoin/server.h
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,7 @@ class CCoinJoinServer : public CCoinJoinBaseSession, public CCoinJoinBaseManager
void ProcessDSACCEPT(CNode& peer, CDataStream& vRecv) EXCLUSIVE_LOCKS_REQUIRED(!cs_vecqueue);
PeerMsgRet ProcessDSQUEUE(const CNode& peer, CDataStream& vRecv) EXCLUSIVE_LOCKS_REQUIRED(!cs_vecqueue);
void ProcessDSVIN(CNode& peer, CDataStream& vRecv) EXCLUSIVE_LOCKS_REQUIRED(!cs_coinjoin);
void ProcessDSSIGNFINALTX(CDataStream& vRecv) EXCLUSIVE_LOCKS_REQUIRED(!cs_coinjoin);
void ProcessDSSIGNFINALTX(CNode& peer, CDataStream& vRecv) EXCLUSIVE_LOCKS_REQUIRED(!cs_coinjoin);

void SetNull() override EXCLUSIVE_LOCKS_REQUIRED(cs_coinjoin);

Expand Down
2 changes: 1 addition & 1 deletion src/consensus/consensus.h
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
/** The maximum allowed size for a serialized block, in bytes (network rule) */
static const unsigned int MAX_LEGACY_BLOCK_SIZE = 1000000;
static const unsigned int MAX_DIP0001_BLOCK_SIZE = 2000000;
inline unsigned int MaxBlockSize(bool fDIP0001Active = true)
constexpr unsigned int MaxBlockSize(bool fDIP0001Active = true)
{
return fDIP0001Active ? MAX_DIP0001_BLOCK_SIZE : MAX_LEGACY_BLOCK_SIZE;
}
Expand Down
6 changes: 5 additions & 1 deletion src/governance/governance.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -326,7 +326,11 @@ PeerMsgRet CGovernanceManager::ProcessMessage(CNode& peer, CConnman& connman, Pe
// A NEW GOVERNANCE OBJECT VOTE HAS ARRIVED
else if (msg_type == NetMsgType::MNGOVERNANCEOBJECTVOTE) {
CGovernanceVote vote;
vRecv >> vote;
try {
vRecv >> vote;
} catch (const std::ios_base::failure&) {
return tl::unexpected{100};
}

uint256 nHash = vote.GetHash();
WITH_LOCK(::cs_main, peerman.EraseObjectRequest(peer.GetId(), CInv(MSG_GOVERNANCE_OBJECT_VOTE, nHash)));
Expand Down
4 changes: 4 additions & 0 deletions src/governance/vote.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
#include <masternode/node.h>
#include <masternode/sync.h>
#include <messagesigner.h>
#include <pubkey.h>
#include <net_processing.h>
#include <timedata.h>
#include <util/string.h>
Expand All @@ -19,6 +20,9 @@

#include <evo/deterministicmns.h>

static_assert(CGovernanceVote::COMPACT_SIG_SIZE == CPubKey::COMPACT_SIGNATURE_SIZE);
static_assert(CGovernanceVote::BLS_SIG_SIZE == CBLSSignature::SerSize);

namespace {
//! Hash the inputs that determine the verification result. Dropping any of them
//! breaks the memo; see CGovernanceVote::SignatureMemo.
Expand Down
17 changes: 16 additions & 1 deletion src/governance/vote.h
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
#define BITCOIN_GOVERNANCE_VOTE_H

#include <primitives/transaction.h>
#include <serialize.h>
#include <uint256.h>

#include <optional>
Expand Down Expand Up @@ -65,6 +66,10 @@ class CGovernanceVote

friend bool operator<(const CGovernanceVote& vote1, const CGovernanceVote& vote2);

public:
static constexpr size_t COMPACT_SIG_SIZE = 65;
static constexpr size_t BLS_SIG_SIZE = 96;

private:
COutPoint masternodeOutpoint;
uint256 nParentHash;
Expand Down Expand Up @@ -175,7 +180,17 @@ class CGovernanceVote
{
READWRITE(obj.masternodeOutpoint, obj.nParentHash, obj.nVoteOutcome, obj.nVoteSignal, obj.nTime);
if (!(s.GetType() & SER_GETHASH)) {
READWRITE(obj.vchSig);
// Network reads: cap the signature vector before allocation and require
// one of the two legitimate encodings. Other paths (disk, hash, write)
// keep the unbounded default.
if (ser_action.ForRead() && (s.GetType() & SER_NETWORK)) {
READWRITE(LIMITED_VECTOR(obj.vchSig, BLS_SIG_SIZE));
if (obj.vchSig.size() != COMPACT_SIG_SIZE && obj.vchSig.size() != BLS_SIG_SIZE) {
throw std::ios_base::failure("bad governance vote signature size");
}
} else {
READWRITE(obj.vchSig);
}
}
SER_READ(obj, obj.UpdateHash());
}
Expand Down
33 changes: 31 additions & 2 deletions src/llmq/instantsend.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -734,6 +734,11 @@ void CInstantSendManager::HandleNewInstantSendLockRecoveredSig(const llmq::CReco
return;
}
LOCK(cs_pendingLocks);
// A locally recovered lock is already verified and takes priority over
// a pending verification, just like a lock leaving the no-tx queue.
if (!pendingInstantSendLocks.count(hash) && pendingInstantSendLocks.size() >= MAX_PENDING_INSTANTSEND_LOCKS) {
pendingInstantSendLocks.erase(pendingInstantSendLocks.begin());
}
pendingInstantSendLocks.emplace(hash, std::make_pair(-1, islock));
}

Expand All @@ -751,6 +756,10 @@ PeerMsgRet CInstantSendManager::ProcessMessage(const CNode& pfrom, PeerManager&
PeerMsgRet CInstantSendManager::ProcessMessageInstantSendLock(const CNode& pfrom, PeerManager& peerman,
const llmq::CInstantSendLockPtr& islock)
{
// Apply the input ceiling before hashing or walking the input set.
if (islock->inputs.size() > CInstantSendLock::MAX_INPUTS) {
return tl::unexpected{100};
}
auto hash = ::SerializeHash(*islock);

WITH_LOCK(::cs_main, peerman.EraseObjectRequest(pfrom.GetId(), CInv(MSG_ISDLOCK, hash)));
Expand Down Expand Up @@ -785,6 +794,10 @@ PeerMsgRet CInstantSendManager::ProcessMessageInstantSendLock(const CNode& pfrom
islock->txid.ToString(), hash.ToString(), pfrom.GetId());

LOCK(cs_pendingLocks);
if (pendingInstantSendLocks.size() >= MAX_PENDING_INSTANTSEND_LOCKS) {
LogPrint(BCLog::INSTANTSEND, "CInstantSendManager::%s -- pending islock queue full, dropping islock=%s\n", __func__, hash.ToString());
return {};
}
pendingInstantSendLocks.emplace(hash, std::make_pair(pfrom.GetId(), islock));
return {};
}
Expand All @@ -795,7 +808,7 @@ PeerMsgRet CInstantSendManager::ProcessMessageInstantSendLock(const CNode& pfrom
*/
bool CInstantSendLock::TriviallyValid() const
{
if (txid.IsNull() || inputs.empty()) {
if (txid.IsNull() || inputs.empty() || inputs.size() > MAX_INPUTS) {
return false;
}

Expand Down Expand Up @@ -1079,7 +1092,11 @@ void CInstantSendManager::ProcessInstantSendLock(NodeId from, PeerManager& peerm
if (tx == nullptr) {
// put it in a separate pending map and try again later
LOCK(cs_pendingLocks);
pendingNoTxInstantSendLocks.try_emplace(hash, std::make_pair(from, islock));
if (pendingNoTxInstantSendLocks.size() < MAX_PENDING_INSTANTSEND_LOCKS) {
pendingNoTxInstantSendLocks.try_emplace(hash, std::make_pair(from, islock));
} else {
LogPrint(BCLog::INSTANTSEND, "CInstantSendManager::%s -- no-tx islock queue full, dropping islock=%s\n", __func__, hash.ToString());
}
} else {
db.WriteNewInstantSendLock(hash, *islock);
if (pindexMined) {
Expand Down Expand Up @@ -1128,6 +1145,12 @@ void CInstantSendManager::TransactionAddedToMempool(PeerManager& peerman, const
auto it = pendingNoTxInstantSendLocks.begin();
while (it != pendingNoTxInstantSendLocks.end()) {
if (it->second.second->txid == tx->GetHash()) {
// A verified lock whose transaction arrived takes priority over a
// pending verification. Do not strand it in the no-tx queue.
if (!pendingInstantSendLocks.count(it->first) &&
pendingInstantSendLocks.size() >= MAX_PENDING_INSTANTSEND_LOCKS) {
pendingInstantSendLocks.erase(pendingInstantSendLocks.begin());
}
// we received an islock earlier
LogPrint(BCLog::INSTANTSEND, "CInstantSendManager::%s -- txid=%s, islock=%s\n", __func__,
tx->GetHash().ToString(), it->first.ToString());
Expand Down Expand Up @@ -1219,6 +1242,12 @@ void CInstantSendManager::AddNonLockedTx(const CTransactionRef& tx, const CBlock
auto it = pendingNoTxInstantSendLocks.begin();
while (it != pendingNoTxInstantSendLocks.end()) {
if (it->second.second->txid == tx->GetHash()) {
// A verified lock whose transaction arrived takes priority over a
// pending verification. Do not strand it in the no-tx queue.
if (!pendingInstantSendLocks.count(it->first) &&
pendingInstantSendLocks.size() >= MAX_PENDING_INSTANTSEND_LOCKS) {
pendingInstantSendLocks.erase(pendingInstantSendLocks.begin());
}
// we received an islock earlier, let's put it back into pending and verify/lock
LogPrint(BCLog::INSTANTSEND, "CInstantSendManager::%s -- txid=%s, islock=%s\n", __func__,
tx->GetHash().ToString(), it->first.ToString());
Expand Down
6 changes: 6 additions & 0 deletions src/llmq/instantsend.h
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@

#include <llmq/signing.h>

#include <consensus/consensus.h>
#include <consensus/params.h>
#include <net_types.h>
#include <primitives/transaction.h>
Expand Down Expand Up @@ -38,6 +39,8 @@ class CSigSharesManager;
struct CInstantSendLock
{
static constexpr uint8_t CURRENT_VERSION{1};
// A valid transaction fits in a block and each serialized input needs at least 41 bytes.
static constexpr size_t MAX_INPUTS{MaxBlockSize() / 41};

uint8_t nVersion{CURRENT_VERSION};
std::vector<COutPoint> inputs;
Expand Down Expand Up @@ -195,6 +198,7 @@ class CInstantSendDb

class CInstantSendManager : public CRecoveredSigsListener
{
friend struct InstantSendQueueTest;
private:
CInstantSendDb db;

Expand Down Expand Up @@ -231,6 +235,8 @@ class CInstantSendManager : public CRecoveredSigsListener
// maps from txid to the in-progress islock
std::unordered_map<uint256, CInstantSendLock*, StaticSaltedHasher> txToCreatingInstantSendLocks GUARDED_BY(cs_creating);

// Bound both unverified locks and verified locks whose transaction has not arrived.
static constexpr size_t MAX_PENDING_INSTANTSEND_LOCKS{1024};
mutable Mutex cs_pendingLocks;
// Incoming and not verified yet
std::unordered_map<uint256, std::pair<NodeId, CInstantSendLockPtr>, StaticSaltedHasher> pendingInstantSendLocks GUARDED_BY(cs_pendingLocks);
Expand Down
Loading
Loading