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
2 changes: 2 additions & 0 deletions csnode/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,7 @@ add_library(csnode
include/csnode/configholder.hpp
include/csnode/multiwallets.hpp
include/csnode/statedigest.hpp
include/csnode/blockverifier.hpp
include/csnode/sendcachedata.hpp
include/csnode/eventreport.hpp
include/csnode/idatastream.hpp
Expand Down Expand Up @@ -109,6 +110,7 @@ add_library(csnode
src/configholder.cpp
src/multiwallets.cpp
src/statedigest.cpp
src/blockverifier.cpp
src/sendcachedata.cpp
src/eventreport.cpp
src/poolcache.cpp
Expand Down
37 changes: 37 additions & 0 deletions csnode/include/csnode/blockverifier.hpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
#ifndef BLOCKVERIFIER_HPP
#define BLOCKVERIFIER_HPP

#include <string>

#include <csdb/pool.hpp>
#include <csnode/nodecore.hpp>
#include <lib/system/common.hpp>

namespace cs {

// Checks a block that comes from outside the consensus (a snapshot, or a block below the lowest
// stored one) before it is stored, with the rules the node applies to blocks it stores itself.
// Used by the snapshot importer and by backward sync.
class BlockVerifier {
public:
// the block parses, has the expected sequence and, when expectedHash is not empty, the hash
// computed from its bytes is expectedHash; for sequence >= 1 its signatures verify against its
// own confidants with the real trusted mask (as tryFlushDeferredBlock does). Block 0 has none.
// An empty expectedHash proves only that the block is consistent with itself (anyone can sign a
// block with confidants of their own): the caller must anchor it, e.g. check that it links to
// a block it already trusts (previous_hash), as storeBlock does.
static bool verify(const csdb::Pool& block, cs::Sequence expectedSequence, const csdb::PoolHash& expectedHash, std::string& reason);

// the pool signatures alone: outside the hashed part, so the only thing a sender could alter
// without changing the block's hash
static bool verifySignatures(const csdb::Pool& block, std::string& reason);

// the round confirmations of a block (sequence >= 2) against the confidants of the block before
// it, with finalizeBlock's exceptions: bootstrap blocks and one-entry masks are not checked.
// They are inside the hashed part: a failure is not the sender's doing.
static bool verifyConfirmations(const csdb::Pool& block, const cs::PublicKeys& previousConfidants, std::string& reason);
};

} // namespace cs

#endif // BLOCKVERIFIER_HPP
110 changes: 110 additions & 0 deletions csnode/src/blockverifier.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,110 @@
#include <csnode/blockverifier.hpp>

#include <algorithm>

#include <cscrypto/cscrypto.hpp>
#include <csnode/blockchain.hpp>
#include <csnode/nodeutils.hpp>
#include <csnode/odatastream.hpp>
#include <lib/system/utils.hpp>

namespace cs {

bool BlockVerifier::verify(const csdb::Pool& block, cs::Sequence expectedSequence, const csdb::PoolHash& expectedHash, std::string& reason) {
if (!block.is_valid()) {
reason = "does not parse";
return false;
}
if (block.sequence() != expectedSequence) {
reason = "has sequence " + std::to_string(block.sequence()) + ", " + std::to_string(expectedSequence) + " expected";
return false;
}
if (!expectedHash.is_empty() && block.hash() != expectedHash) {
reason = "has another hash than the chain expects";
return false;
}
return verifySignatures(block, reason);
}

bool BlockVerifier::verifySignatures(const csdb::Pool& block, std::string& reason) {
// a block that does not parse reads as sequence 0: never take it for the genesis block
if (!block.is_valid()) {
reason = "does not parse";
return false;
}
if (block.sequence() == 0) {
return true;
}
const auto& confidants = block.confidants();
if (confidants.empty() || block.signatures().empty()) {
reason = "has no confidants or no signatures";
return false;
}
cs::Hash hash{};
const auto bytes = block.hash().to_binary();
if (bytes.size() != hash.size()) {
reason = "has no hash";
return false;
}
std::copy(bytes.begin(), bytes.end(), hash.begin());
const auto mask = cs::Utils::bitsToMask(block.numberTrusted(), block.realTrusted());
// the counts are checked here, with a reason: checkGroupSignature logs them as errors, and the
// block comes from an untrusted sender
if (mask.size() != confidants.size()) {
reason = "has a trusted mask of another size than its confidants";
return false;
}
if (block.signatures().size() != NodeUtils::realTrustedValue(mask)) {
reason = "has " + std::to_string(block.signatures().size()) + " signatures for " +
std::to_string(NodeUtils::realTrustedValue(mask)) + " real trusted";
return false;
}
if (!NodeUtils::checkGroupSignature(confidants, mask, block.signatures(), hash)) {
reason = "has signatures that do not verify against its confidants";
return false;
}
return true;
}

bool BlockVerifier::verifyConfirmations(const csdb::Pool& block, const cs::PublicKeys& previousConfidants, std::string& reason) {
if (!block.is_valid()) {
reason = "does not parse";
return false;
}
if (block.sequence() < 2) {
return true;
}
if (BlockChain::isBootstrap(block)) {
return true;
}
// as storeBlock: a block of a normal round carries the previous round's confirmations
if (block.numberConfirmations() == 0 || block.roundConfirmations().empty()) {
reason = "has no round confirmations";
return false;
}
const auto confMask = cs::Utils::bitsToMask(block.numberConfirmations(), block.roundConfirmationMask());
if (confMask.size() <= 1) {
return true;
}
if (confMask.size() != previousConfidants.size()) {
reason = "has a confirmation mask of another size than the previous block's confidants";
return false;
}
if (block.roundConfirmations().size() != NodeUtils::realTrustedValue(confMask)) {
reason = "has " + std::to_string(block.roundConfirmations().size()) + " round confirmations for " +
std::to_string(NodeUtils::realTrustedValue(confMask)) + " confirming confidants";
return false;
}
cs::Bytes trustedToHash;
cs::ODataStream stream(trustedToHash);
stream << block.sequence();
stream << block.confidants();
const cs::Hash trustedHash = cscrypto::calculateHash(trustedToHash.data(), trustedToHash.size());
if (!NodeUtils::checkGroupSignature(previousConfidants, confMask, block.roundConfirmations(), trustedHash)) {
reason = "has round confirmations that do not verify against the previous block's confidants";
return false;
}
return true;
}

} // namespace cs
169 changes: 169 additions & 0 deletions tests/csnode/blockverifier_tests.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,169 @@
#include <gtest/gtest.h>

#include <string>
#include <vector>

#include <cscrypto/cscrypto.hpp>
#include <csdb/pool.hpp>
#include <csnode/blockverifier.hpp>
#include <csnode/odatastream.hpp>

namespace {
struct Keys {
std::vector<cs::PublicKey> pub;
std::vector<cs::PrivateKey> priv;
};

Keys makeKeys(size_t n) {
// keys live in sodium's guarded memory: the library must be initialised first
EXPECT_TRUE(cscrypto::cryptoInit());
Keys k;
for (size_t i = 0; i < n; ++i) {
cs::PublicKey p;
k.priv.push_back(cscrypto::generateKeyPair(p));
k.pub.push_back(p);
}
return k;
}

cs::Hash toHash(const csdb::PoolHash& h) {
cs::Hash out{};
const auto b = h.to_binary();
std::copy(b.begin(), b.end(), out.begin());
return out;
}

// a block of `seq` whose confidants are `keys`, signed by those in `signers` (bit i = confidant i),
// confirmed by the previous round's confidants `prev` (all of them), parsed back from its bytes
csdb::Pool signedBlock(cs::Sequence seq, const Keys& keys, uint64_t signers, const Keys* prev = nullptr,
const std::string& payload = "payload") {
csdb::Pool p(csdb::PoolHash{}, seq);
p.set_confidants(keys.pub);
p.add_number_trusted(static_cast<uint8_t>(keys.pub.size()));
p.add_real_trusted(signers);
p.add_user_field(1, payload);
if (prev) {
cs::Bytes trustedToHash;
cs::ODataStream stream(trustedToHash);
stream << seq;
stream << keys.pub;
const cs::Hash h = cscrypto::calculateHash(trustedToHash.data(), trustedToHash.size());
std::vector<cs::Signature> confirmations;
for (const auto& k : prev->priv) {
confirmations.push_back(cscrypto::generateSignature(k, h.data(), h.size()));
}
p.add_number_confirmations(static_cast<uint8_t>(prev->pub.size()));
p.add_confirmation_mask((1ull << prev->pub.size()) - 1);
p.add_round_confirmations(confirmations);
}
// the signatures are outside the hashed part: the hash of a composed copy is the block's hash,
// and the signatures are set before the block itself is composed (it is read-only after)
auto probe = p.clone();
EXPECT_TRUE(probe.compose());
const cs::Hash hash = toHash(probe.hash());
std::vector<cs::Signature> sigs;
for (size_t i = 0; i < keys.priv.size(); ++i) {
if (signers >> i & 1) {
sigs.push_back(cscrypto::generateSignature(keys.priv[i], hash.data(), hash.size()));
}
}
p.set_signatures(sigs);
EXPECT_TRUE(p.compose());
return csdb::Pool::from_binary(p.to_binary());
}
} // namespace

TEST(BlockVerifier, ValidBlockPasses) {
const auto keys = makeKeys(5);
const auto block = signedBlock(10, keys, 0b10111);
std::string reason;
EXPECT_TRUE(cs::BlockVerifier::verify(block, 10, block.hash(), reason)) << reason;
EXPECT_TRUE(cs::BlockVerifier::verify(block, 10, csdb::PoolHash{}, reason)) << reason;
}

TEST(BlockVerifier, WrongSequenceOrHashFails) {
const auto keys = makeKeys(3);
const auto block = signedBlock(10, keys, 0b111);
const auto other = signedBlock(10, keys, 0b111, nullptr, "another payload");
std::string reason;
EXPECT_FALSE(cs::BlockVerifier::verify(block, 11, block.hash(), reason));
EXPECT_FALSE(cs::BlockVerifier::verify(block, 10, other.hash(), reason));
}

TEST(BlockVerifier, AlteredOrMissingSignatureFails) {
const auto keys = makeKeys(3);
const auto block = signedBlock(10, keys, 0b111);
std::string reason;

// the pool signatures follow the hashed part and its length (a size_t): flip a bit of the first
auto bytes = block.to_binary();
bytes[block.hashingLength() + sizeof(size_t)] ^= 1;
const auto altered = csdb::Pool::from_binary(std::move(bytes));
ASSERT_TRUE(altered.is_valid());
EXPECT_EQ(altered.hash(), block.hash()); // outside the hash: only the signature check sees it
EXPECT_FALSE(cs::BlockVerifier::verifySignatures(altered, reason));

// signatures by keys other than the confidants'
auto wrongKeys = makeKeys(3);
wrongKeys.pub = keys.pub;
EXPECT_FALSE(cs::BlockVerifier::verifySignatures(signedBlock(10, wrongKeys, 0b111), reason));

// more signatures than the mask has entries: realTrusted with a bit beyond numberTrusted
{
auto four = makeKeys(4);
csdb::Pool p(csdb::PoolHash{}, 10);
p.set_confidants(keys.pub);
p.add_number_trusted(3);
p.add_real_trusted(0b1111);
auto probe = p.clone();
ASSERT_TRUE(probe.compose());
const cs::Hash hash = toHash(probe.hash());
std::vector<cs::Signature> sigs;
for (size_t i = 0; i < 3; ++i) {
sigs.push_back(cscrypto::generateSignature(keys.priv[i], hash.data(), hash.size()));
}
sigs.push_back(cscrypto::generateSignature(four.priv[3], hash.data(), hash.size()));
p.set_signatures(sigs);
ASSERT_TRUE(p.compose());
const auto extra = csdb::Pool::from_binary(p.to_binary());
ASSERT_TRUE(extra.is_valid());
EXPECT_FALSE(cs::BlockVerifier::verifySignatures(extra, reason));
}

// no confidants, no signatures
{
csdb::Pool p(csdb::PoolHash{}, 10);
p.add_number_trusted(0);
p.add_real_trusted(0);
ASSERT_TRUE(p.compose());
const auto empty = csdb::Pool::from_binary(p.to_binary());
ASSERT_TRUE(empty.is_valid());
EXPECT_FALSE(cs::BlockVerifier::verifySignatures(empty, reason));
EXPECT_NE(reason.find("no confidants"), std::string::npos) << reason;
}

// a block that does not parse is never taken for the genesis block
EXPECT_FALSE(cs::BlockVerifier::verifySignatures(csdb::Pool{}, reason));
EXPECT_FALSE(cs::BlockVerifier::verify(csdb::Pool{}, 0, csdb::PoolHash{}, reason));
}

TEST(BlockVerifier, GenesisNeedsNoSignature) {
csdb::Pool genesis(csdb::PoolHash{}, 0);
ASSERT_TRUE(genesis.compose());
const auto parsed = csdb::Pool::from_binary(genesis.to_binary());
std::string reason;
EXPECT_TRUE(cs::BlockVerifier::verify(parsed, 0, parsed.hash(), reason)) << reason;
}

TEST(BlockVerifier, RoundConfirmationsAgainstThePreviousConfidants) {
const auto previous = makeKeys(3);
const auto keys = makeKeys(3);
const auto block = signedBlock(20, keys, 0b111, &previous);
std::string reason;
EXPECT_TRUE(cs::BlockVerifier::verifyConfirmations(block, previous.pub, reason)) << reason;
EXPECT_FALSE(cs::BlockVerifier::verifyConfirmations(block, keys.pub, reason));
// a normal round's block without confirmations is refused, as storeBlock does
EXPECT_FALSE(cs::BlockVerifier::verifyConfirmations(signedBlock(20, keys, 0b111), previous.pub, reason));
// confirmations from a set of another size
EXPECT_FALSE(cs::BlockVerifier::verifyConfirmations(block, makeKeys(4).pub, reason));
}
Loading