diff --git a/csnode/include/csnode/blockchain.hpp b/csnode/include/csnode/blockchain.hpp index f08c874b6..4495eb6d7 100644 --- a/csnode/include/csnode/blockchain.hpp +++ b/csnode/include/csnode/blockchain.hpp @@ -402,6 +402,14 @@ public slots: void tryFlushDeferredBlock(); void addIncorrectBlockNumber(cs::Sequence seq); + // the state the caches hold now: wallets digest, wallet count and consensus settings hash, as a + // checkpoint saves it (state_digest.bin) + cs::CheckpointDigest checkpointDigest() const; + // hash of the consensus settings a checkpoint carries: block reward, mining coefficient, staking + // and mining flags, minimal stage-1 time, pending settings, DPOS start and the recorded special + // orders (the initial confidants come from the node's configuration and are not included) + std::array consensusSettingsDigest() const; + csdb::Amount getBlockReward() { return csdb::Amount(blockRewardIntegral_, blockRewardFraction_); } diff --git a/csnode/include/csnode/caches_serialization_manager.hpp b/csnode/include/csnode/caches_serialization_manager.hpp index 68c6a0a45..b42bb7b00 100644 --- a/csnode/include/csnode/caches_serialization_manager.hpp +++ b/csnode/include/csnode/caches_serialization_manager.hpp @@ -6,6 +6,7 @@ #include #include +#include #include class BlockChain; @@ -51,7 +52,8 @@ class CachesSerializationManager { void clear(size_t version = 0); - bool save(size_t version, const CheckpointHead& head); + // digest: the state the caches hold, written as state_digest.bin next to them + bool save(size_t version, const CheckpointHead& head, const std::optional& digest = std::nullopt); bool save(size_t version = 0); // legacy: no chain-binding (qs/0 from pre-A nodes) // Optional verifier is called after each candidate's hashes pass; if it // returns false (e.g. chain-binding mismatch), the candidate is @@ -64,6 +66,9 @@ class CachesSerializationManager { std::optional getLoadedHead() const; // the version load() took the caches from, if any std::optional getLoadedVersion() const; + // the state_digest.bin of the version being loaded or loaded, nullopt when it has none; set + // before the ChainVerifier is called, so that the verifier can compare it with the caches + std::optional getLoadedDigest() const; // moves a version aside to qs/.bad, so that load() no longer takes it void quarantine(size_t version); // Sticky bit indicating the caches have been validated by a full diff --git a/csnode/include/csnode/multiwallets.hpp b/csnode/include/csnode/multiwallets.hpp index 0719948de..e37b61561 100644 --- a/csnode/include/csnode/multiwallets.hpp +++ b/csnode/include/csnode/multiwallets.hpp @@ -62,6 +62,8 @@ class MultiWallets { // order-independent digest of every wallet's balance-relevant state (ECMH, see statedigest.hpp); // computed in full on the first call, then kept up to date on every wallet update MultisetHash::Digest stateDigest() const; + // the wallets were replaced as a whole (a checkpoint loaded): the next stateDigest() recomputes + void invalidateStateDigest(); void iterate(std::function func); protected: diff --git a/csnode/include/csnode/statedigest.hpp b/csnode/include/csnode/statedigest.hpp index 9e69608f1..cd4cd842c 100644 --- a/csnode/include/csnode/statedigest.hpp +++ b/csnode/include/csnode/statedigest.hpp @@ -3,6 +3,9 @@ #include #include +#include +#include +#include #include #include @@ -41,6 +44,34 @@ class MultisetHash { // records do not change the digest. cs::Bytes serializeWalletState(const WalletsCache::WalletData& wallet); +// The state a checkpoint holds, saved with it as state_digest.bin: the digest of the wallets +// (MultiWallets::stateDigest), their number, and a hash of the consensus settings the checkpoint +// carries (BlockChain::consensusSettingsDigest). A snapshot made from the checkpoint declares the +// same values, and a node that loads the checkpoint recomputes and compares them. +struct CheckpointDigest { + static constexpr uint8_t kVersion = 1; + static constexpr const char* kFileName = "state_digest.bin"; + + MultisetHash::Digest digest{}; + uint64_t wallets = 0; + std::array settings{}; + + bool write(const std::filesystem::path& file) const; + // nullopt for a missing, truncated or unknown-version file + static std::optional read(const std::filesystem::path& file); + + bool operator==(const CheckpointDigest& other) const { + return digest == other.digest && wallets == other.wallets && settings == other.settings; + } + bool operator!=(const CheckpointDigest& other) const { + return !(*this == other); + } +}; + +// "STATE DIGEST # wallets ": the form every digest line of the log has, so that +// scripts read the same fields from the periodic, the start-up and the checkpoint lines +std::string stateDigestLine(cs::Sequence sequence, const MultisetHash::Digest& digest, uint64_t wallets); + } // namespace cs #endif // STATEDIGEST_HPP diff --git a/csnode/include/csnode/walletscache_serializer.hpp b/csnode/include/csnode/walletscache_serializer.hpp index 07d967e1d..093b49fbd 100644 --- a/csnode/include/csnode/walletscache_serializer.hpp +++ b/csnode/include/csnode/walletscache_serializer.hpp @@ -29,6 +29,7 @@ using namespace boost::multi_index; namespace cs { class WalletsCache; +class MultiWallets; class WalletsCache_Serializer { public: @@ -218,6 +219,8 @@ class WalletsCache_Serializer { #endif CurrentDelegations *currentDelegations_ = nullptr; MiningDelegations *miningDelegations_ = nullptr; + // its state digest is kept up to date incrementally: replacing the wallets invalidates it + MultiWallets *multiWallets_ = nullptr; }; } // namespace cs #endif // WALLETS_CACHE_SERIALIZER_HPP diff --git a/csnode/src/blockchain.cpp b/csnode/src/blockchain.cpp index 94288229f..d1daa1183 100644 --- a/csnode/src/blockchain.cpp +++ b/csnode/src/blockchain.cpp @@ -97,16 +97,33 @@ bool BlockChain::tryQuickStart( // trust the caches only if their head is still the block this node has at that sequence cs::Sequence loadedHead = 0; bool ok = serializationManPtr_->load([this, &loadedHead](const cs::CheckpointHead& head) { - if (cs::isCheckpointOnChain(head, [this](cs::Sequence seq) { return blockHashes_->find(seq).to_binary(); })) { - loadedHead = head.sequence; - return true; + if (!cs::isCheckpointOnChain(head, [this](cs::Sequence seq) { return blockHashes_->find(seq).to_binary(); })) { + cswarning() << "QUICK START: checkpoint head #" << head.sequence << " is not on this chain, skip it"; + return false; } - cswarning() << "QUICK START: checkpoint head #" << head.sequence << " is not on this chain, skip it"; - return false; + // the caches must hold the state the checkpoint was saved with (no file: saved by an earlier build) + if (const auto saved = serializationManPtr_->getLoadedDigest(); saved.has_value()) { + const auto loaded = checkpointDigest(); + if (loaded != *saved) { + // no "STATE DIGEST #" here: scripts take the digest of a block from lines with that prefix + cserror() << "QUICK START: checkpoint #" << head.sequence << " declares state " + << cs::Utils::byteStreamToHex(saved->digest.data(), saved->digest.size()) << " (" << saved->wallets << " wallets)" + << ", its caches hold " << cs::Utils::byteStreamToHex(loaded.digest.data(), loaded.digest.size()) + << " (" << loaded.wallets << " wallets)" + << (loaded.settings != saved->settings ? " and other consensus settings" : "") << ", skip it"; + return false; + } + } + loadedHead = head.sequence; + return true; }); if (ok) { cslog() << "Caches for QUICK START loaded successfully!"; + if (loadedHead != 0) { + const auto loaded = checkpointDigest(); + cslog() << cs::stateDigestLine(loadedHead, loaded.digest, loaded.wallets) << " checkpoint loaded"; + } // The caches hold the head block. A live checkpoint of an earlier build was saved before // recordBlock advanced lastSequence_ to that block, so it reads one less: reading the database // from there would apply the head block a second time and change the balances. @@ -422,7 +439,9 @@ void BlockChain::onReadFromDB(csdb::Pool block, bool* shouldStop) { head.sequence = blockSeq; head.head_hash = block.hash().to_binary(); head.prev_hash = block.previous_hash().to_binary(); - if (serializationManPtr_->save(blockSeq, head)) { + const auto digest = checkpointDigest(); + if (serializationManPtr_->save(blockSeq, head, digest)) { + cslog() << cs::stateDigestLine(blockSeq, digest.digest, digest.wallets) << " checkpoint"; serializationManPtr_->pruneCheckpoints(sto.checkpointKeep); lastCheckpointWallClock_ = now; if (byCount) { @@ -1030,7 +1049,9 @@ void BlockChain::saveLiveCheckpoint(const csdb::Pool& pool) { head.sequence = pool.sequence(); head.head_hash = pool.hash().to_binary(); head.prev_hash = pool.previous_hash().to_binary(); - if (serializationManPtr_->save(pool.sequence(), head)) { + const auto digest = checkpointDigest(); + if (serializationManPtr_->save(pool.sequence(), head, digest)) { + cslog() << cs::stateDigestLine(pool.sequence(), digest.digest, digest.wallets) << " checkpoint"; serializationManPtr_->pruneCheckpoints(sto.checkpointKeep); lastCheckpointWallClock_ = now; if (byCount) { @@ -1043,6 +1064,35 @@ void BlockChain::saveLiveCheckpoint(const csdb::Pool& pool) { } } +cs::CheckpointDigest BlockChain::checkpointDigest() const { + cs::CheckpointDigest result; + const auto& wallets = multiWallets(); + result.digest = wallets.stateDigest(); + result.wallets = wallets.size(); + result.settings = consensusSettingsDigest(); + return result; +} + +std::array BlockChain::consensusSettingsDigest() const { + cs::Bytes data; + cs::ODataStream stream(data); + stream << blockRewardIntegral_ << blockRewardFraction_ << miningCoefficientIntegral_ << miningCoefficientFraction_; + stream << static_cast(stakingOn_) << static_cast(miningOn_) << TimeMinStage1_; + const auto& pending = pendingConsensusSettings_; + stream << pending.round << static_cast(pending.stakingOn) << static_cast(pending.miningOn); + stream << pending.blockReward.integral() << pending.blockReward.fraction(); + stream << pending.miningCoefficient.integral() << pending.miningCoefficient.fraction(); + stream << startingDPOS_; + stream << static_cast(specialOrders_.size()); + for (const auto& [kind, payload] : specialOrders_) { + stream << kind << payload; + } + const cs::Hash hash = cscrypto::calculateHash(data.data(), data.size()); + std::array result{}; + std::copy(hash.begin(), hash.end(), result.begin()); + return result; +} + csdb::PoolHash BlockChain::getHashBySequence(cs::Sequence seq) const { std::lock_guard lock(dbLock_); @@ -1343,8 +1393,10 @@ void BlockChain::close() { csinfo() << "Blockchain: try to save caches for QUICK START."; - if (serializationManPtr_->save(0, headInfo)) { + const auto digest = checkpointDigest(); + if (serializationManPtr_->save(0, headInfo, digest)) { csinfo() << "Blockchain: caches for QUICK START saved successfully."; + cslog() << cs::stateDigestLine(headInfo.sequence, digest.digest, digest.wallets) << " checkpoint"; } else { csinfo() << "~Blockchain: couldn't save caches for QUICK START."; diff --git a/csnode/src/caches_serialization_manager.cpp b/csnode/src/caches_serialization_manager.cpp index 95a36da46..58d67565f 100644 --- a/csnode/src/caches_serialization_manager.cpp +++ b/csnode/src/caches_serialization_manager.cpp @@ -4,6 +4,7 @@ #include #include #include +#include #include #include #include @@ -92,6 +93,7 @@ struct CachesSerializationManager::Impl { const std::vector hashesDivisions = {"blockchain", "smartcontracts","walletscache","walletsIds","roundstat","tokensmaster","apihandler"}; std::optional loadedHead_{}; + std::optional loadedDigest_{}; std::optional loadedVersion_{}; bool completedFromGenesis_ = false; bool loadedFromCompleted_ = false; @@ -391,6 +393,7 @@ struct CachesSerializationManager::Impl { bool loadVersion(size_t version, const std::function& verify) { csinfo() << "CachesSerializationManager: try to load version " << version; + loadedDigest_.reset(); try { std::filesystem::path p(kQuickStartRoot); p /= std::to_string(version); @@ -429,6 +432,7 @@ struct CachesSerializationManager::Impl { return false; } loadedHead_ = loadHead(p); // nullopt for legacy (no head.bin) + loadedDigest_ = CheckpointDigest::read(p / CheckpointDigest::kFileName); // nullopt before it existed loadedFromCompleted_ = loadSentinel(p); // a completed snapshot remains completed after a successful reload if (loadedFromCompleted_) completedFromGenesis_ = true; @@ -436,6 +440,7 @@ struct CachesSerializationManager::Impl { cserror() << "CachesSerializationManager: chain-binding verification failed for version " << version << "; quarantining"; loadedHead_.reset(); + loadedDigest_.reset(); loadedFromCompleted_ = false; clearInMem(); quarantineVersion(version); @@ -544,7 +549,7 @@ bool CachesSerializationManager::save(size_t version) { return save(version, CheckpointHead{}); } -bool CachesSerializationManager::save(size_t version, const CheckpointHead& head) { +bool CachesSerializationManager::save(size_t version, const CheckpointHead& head, const std::optional& digest) { if (!pImpl_->bindingsReady()) { cserror() << "CachesSerializationManager: save error: " << "bindings are not ready"; @@ -579,6 +584,9 @@ bool CachesSerializationManager::save(size_t version, const CheckpointHead& head if (!head.head_hash.empty()) { pImpl_->saveHead(tmp_path, head); } + if (digest.has_value() && !digest->write(tmp_path / CheckpointDigest::kFileName)) { + throw std::runtime_error("cannot write state digest"); + } } catch (const std::exception& e) { cserror() << "CachesSerializationManager: error on save: " << e.what(); std::filesystem::remove_all(tmp_path, ec); @@ -651,6 +659,7 @@ bool CachesSerializationManager::load(const ChainVerifier& verify) { } pImpl_->loadedHead_.reset(); + pImpl_->loadedDigest_.reset(); pImpl_->loadedVersion_.reset(); pImpl_->loadedFromCompleted_ = false; @@ -721,6 +730,10 @@ std::optional CachesSerializationManager::getLoadedHead() const return pImpl_->loadedHead_; } +std::optional CachesSerializationManager::getLoadedDigest() const { + return pImpl_->loadedDigest_; +} + std::optional CachesSerializationManager::getLoadedVersion() const { return pImpl_->loadedVersion_; } diff --git a/csnode/src/multiwallets.cpp b/csnode/src/multiwallets.cpp index a2d6f122e..4a878ff37 100644 --- a/csnode/src/multiwallets.cpp +++ b/csnode/src/multiwallets.cpp @@ -95,6 +95,11 @@ void cs::MultiWallets::onWalletCacheUpdated(const cs::WalletsCache::WalletData& } } +void cs::MultiWallets::invalidateStateDigest() { + cs::Lock lock(mutex_); + digestReady_ = false; +} + cs::MultisetHash::Digest cs::MultiWallets::stateDigest() const { cs::Lock lock(mutex_); diff --git a/csnode/src/node.cpp b/csnode/src/node.cpp index ea266fea1..62d210f80 100644 --- a/csnode/src/node.cpp +++ b/csnode/src/node.cpp @@ -4475,9 +4475,7 @@ void Node::logStateDigest(const csdb::Pool& pool) { void Node::logStateDigest(cs::Sequence sequence) { const auto& wallets = blockChain_.multiWallets(); - const auto digest = wallets.stateDigest(); - cslog() << "STATE DIGEST #" << sequence << " " << cs::Utils::byteStreamToHex(digest.data(), digest.size()) - << " wallets " << wallets.size(); + cslog() << cs::stateDigestLine(sequence, wallets.stateDigest(), wallets.size()); } void Node::validateBlock(const csdb::Pool& block, bool* shouldStop) { diff --git a/csnode/src/statedigest.cpp b/csnode/src/statedigest.cpp index a2a75db8b..5d6434cc8 100644 --- a/csnode/src/statedigest.cpp +++ b/csnode/src/statedigest.cpp @@ -1,12 +1,15 @@ #include #include +#include +#include #include #include #include #include +#include namespace { static_assert(crypto_core_ristretto255_BYTES == 32, "ristretto255 element size"); @@ -125,4 +128,44 @@ cs::Bytes serializeWalletState(const WalletsCache::WalletData& wallet) { return out; } +bool CheckpointDigest::write(const std::filesystem::path& file) const { + cs::Bytes out; + putU8(out, kVersion); + out.insert(out.end(), digest.begin(), digest.end()); + putU64(out, wallets); + out.insert(out.end(), settings.begin(), settings.end()); + std::ofstream f(file, std::ios::binary | std::ios::trunc); + f.write(reinterpret_cast(out.data()), static_cast(out.size())); + f.flush(); + return static_cast(f); +} + +std::optional CheckpointDigest::read(const std::filesystem::path& file) { + std::ifstream f(file, std::ios::binary); + if (!f.is_open()) { + return std::nullopt; + } + constexpr size_t kSize = 1 + 32 + 8 + 32; + std::array in{}; + f.read(reinterpret_cast(in.data()), static_cast(in.size())); + if (static_cast(f.gcount()) != kSize || in[0] != kVersion) { + return std::nullopt; + } + CheckpointDigest result; + std::copy(in.begin() + 1, in.begin() + 33, result.digest.begin()); + for (int i = 0; i < 8; ++i) { + result.wallets |= static_cast(in[33 + i]) << (8 * i); + } + std::copy(in.begin() + 41, in.begin() + 73, result.settings.begin()); + return result; +} + +std::string stateDigestLine(cs::Sequence sequence, const MultisetHash::Digest& digest, uint64_t wallets) { + std::ostringstream os; + os << "STATE DIGEST #" << sequence << " " << cs::Utils::byteStreamToHex(digest.data(), digest.size()) + << " wallets " << wallets; + return os.str(); +} + } // namespace cs + diff --git a/csnode/src/walletscache_serializer.cpp b/csnode/src/walletscache_serializer.cpp index 609d67659..18a6d347b 100644 --- a/csnode/src/walletscache_serializer.cpp +++ b/csnode/src/walletscache_serializer.cpp @@ -26,6 +26,7 @@ void WalletsCache_Serializer::bind(WalletsCache& wCache) { canceledSmarts_ = reinterpret_cast(&wCache.canceledSmarts_); static_assert(sizeof(WalletData) == sizeof(WalletsCache::WalletData), "WalletData mirror must match WalletsCache::WalletData"); wallets_ = reinterpret_cast(&wCache.multiWallets_->indexes_); + multiWallets_ = wCache.multiWallets_.get(); #ifdef MONITOR_NODE trusted_info_ = reinterpret_cast(&wCache.trusted_info_); #endif @@ -44,6 +45,7 @@ void WalletsCache_Serializer::clear(const std::filesystem::path& rootDir) { #endif currentDelegations_->clear(); miningDelegations_->clear(); + multiWallets_->invalidateStateDigest(); } void WalletsCache_Serializer::save(const std::filesystem::path& rootDir) { @@ -108,5 +110,6 @@ void WalletsCache_Serializer::load(const std::filesystem::path& rootDir) { #endif ia >> *currentDelegations_; ia >> *miningDelegations_; + multiWallets_->invalidateStateDigest(); } } // namespace cs diff --git a/docs/differences.md b/docs/differences.md index 546eef112..f6156a22b 100644 --- a/docs/differences.md +++ b/docs/differences.md @@ -93,6 +93,10 @@ quick-starts after a conversion. `STATE DIGEST # `. It is a digest of all wallet state, so nodes, builds and backends can be compared: two nodes that agree on the chain must print the same digest at the same sequence. + Every checkpoint saves the digest of the state it holds, with a hash of the consensus settings, + as `qs//state_digest.bin`, and logs it (`STATE DIGEST # ... checkpoint`). A + quick start recomputes it from the loaded caches, logs `... checkpoint loaded`, and moves a + checkpoint whose caches do not match it aside to `qs/.bad`. - **Stopping on errors.** Some errors that the official node can survive in an inconsistent state now stop the node, and are logged with `cserror`: - a block that cannot be stored; diff --git a/tests/csnode/blockchain_tests.cpp b/tests/csnode/blockchain_tests.cpp index b380833cb..e9f15a4c9 100644 --- a/tests/csnode/blockchain_tests.cpp +++ b/tests/csnode/blockchain_tests.cpp @@ -3,7 +3,10 @@ #include "clientconfigmock.hpp" #include "gtest/gtest.h" +#include #include +#include +#include #include #include @@ -235,3 +238,82 @@ TEST(BlockChain, SpecialOrdersSurviveCheckpoint) { std::filesystem::remove_all(dir); } + +namespace { +void setEverySetting(BlockChain& chain) { + chain.setBlockReward(csdb::Amount{ 3 }); + chain.setMiningCoefficient(csdb::Amount{ 2 }); + chain.setStakingOn(true); + chain.setMiningOn(true); + chain.setTimeMinStage1(700); + BlockChain::PendingConsensusSettings pending; + pending.round = 900; + pending.stakingOn = true; + pending.blockReward = csdb::Amount{ 5 }; + chain.setPendingConsensusSettings(pending); + chain.setStartingDPOS(450); + csdb::Pool orders; + orders.add_transaction(specialOrderTransaction(1, 26, 1000)); + orders.add_transaction(specialOrderTransaction(2, 35, 777)); + chain.recordSpecialOrders(orders); +} +} // namespace + +// a checkpoint saves the hash of the consensus settings with the caches, and a quick start +// rejects the checkpoint when the loaded settings hash differently: every field must come back +// from blockchain.dat and consensus_pending.dat exactly +TEST(BlockChain, ConsensusSettingsDigestSurvivesCheckpoint) { + const csdb::Address genesis = csdb::Address::from_string("0000000000000000000000000000000000000000000000000000000000000001"); + const csdb::Address start = csdb::Address::from_string("0000000000000000000000000000000000000000000000000000000000000002"); + const auto dir = std::filesystem::temp_directory_path() / "cs_settings_digest_test"; + std::filesystem::remove_all(dir); + std::filesystem::create_directories(dir); + + std::set confidants; + std::array savedDigest{}; + { + BlockChain saved(genesis, start); + setEverySetting(saved); + savedDigest = saved.consensusSettingsDigest(); + ASSERT_EQ(saved.checkpointDigest().settings, savedDigest); + cs::BlockChain_Serializer serializer; + serializer.bind(saved, confidants); + serializer.save(dir); + } + + BlockChain loaded(genesis, start); + ASSERT_NE(loaded.consensusSettingsDigest(), savedDigest); + cs::BlockChain_Serializer serializer; + serializer.bind(loaded, confidants); + serializer.load(dir); + ASSERT_EQ(loaded.consensusSettingsDigest(), savedDigest); + + std::filesystem::remove_all(dir); +} + +TEST(BlockChain, ConsensusSettingsDigestCoversEverySetting) { + const csdb::Address genesis = csdb::Address::from_string("0000000000000000000000000000000000000000000000000000000000000001"); + const csdb::Address start = csdb::Address::from_string("0000000000000000000000000000000000000000000000000000000000000002"); + BlockChain base(genesis, start); + setEverySetting(base); + const auto digest = base.consensusSettingsDigest(); + + const std::vector> changes = { + [](BlockChain& c) { c.setBlockReward(csdb::Amount{ 4 }); }, + [](BlockChain& c) { c.setMiningCoefficient(csdb::Amount{ 1 }); }, + [](BlockChain& c) { c.setStakingOn(false); }, + [](BlockChain& c) { c.setMiningOn(false); }, + [](BlockChain& c) { c.setTimeMinStage1(800); }, + [](BlockChain& c) { auto p = c.getPendingConsensusSettings(); p.round = 901; c.setPendingConsensusSettings(p); }, + [](BlockChain& c) { auto p = c.getPendingConsensusSettings(); p.miningCoefficient = csdb::Amount{ 9 }; c.setPendingConsensusSettings(p); }, + [](BlockChain& c) { c.setStartingDPOS(451); }, + [](BlockChain& c) { csdb::Pool o; o.add_transaction(specialOrderTransaction(3, 26, 2000)); c.recordSpecialOrders(o); }, + }; + for (size_t i = 0; i < changes.size(); ++i) { + BlockChain changed(genesis, start); + setEverySetting(changed); + ASSERT_EQ(changed.consensusSettingsDigest(), digest); + changes[i](changed); + EXPECT_NE(changed.consensusSettingsDigest(), digest) << "change " << i; + } +} diff --git a/tests/csnode/statedigest_tests.cpp b/tests/csnode/statedigest_tests.cpp index 45d4410a0..b05d1cff9 100644 --- a/tests/csnode/statedigest_tests.cpp +++ b/tests/csnode/statedigest_tests.cpp @@ -1,5 +1,9 @@ #include +#include +#include +#include + #include #include @@ -77,3 +81,77 @@ TEST(WalletState, DelegationOrderDoesNotMatter) { ASSERT_EQ(cs::serializeWalletState(w1), cs::serializeWalletState(w2)); } + +namespace { +cs::CheckpointDigest sampleCheckpointDigest() { + cs::CheckpointDigest d; + for (size_t i = 0; i < d.digest.size(); ++i) { + d.digest[i] = static_cast(i); + d.settings[i] = static_cast(255 - i); + } + d.wallets = 147463; + return d; +} + +std::filesystem::path tempFile(const char* name) { + return std::filesystem::temp_directory_path() / name; +} +} // namespace + +TEST(CheckpointDigest, WriteReadRoundTrip) { + const auto file = tempFile("state_digest_roundtrip.bin"); + const auto d = sampleCheckpointDigest(); + ASSERT_TRUE(d.write(file)); + const auto read = cs::CheckpointDigest::read(file); + ASSERT_TRUE(read.has_value()); + EXPECT_EQ(*read, d); + std::filesystem::remove(file); +} + +TEST(CheckpointDigest, MissingFileReadsNothing) { + EXPECT_FALSE(cs::CheckpointDigest::read(tempFile("state_digest_missing.bin")).has_value()); +} + +TEST(CheckpointDigest, TruncatedOrLongerFileRejected) { + const auto file = tempFile("state_digest_truncated.bin"); + ASSERT_TRUE(sampleCheckpointDigest().write(file)); + const auto size = std::filesystem::file_size(file); + std::filesystem::resize_file(file, size - 1); + EXPECT_FALSE(cs::CheckpointDigest::read(file).has_value()); + std::filesystem::resize_file(file, size + 1); + EXPECT_FALSE(cs::CheckpointDigest::read(file).has_value()); + std::filesystem::remove(file); +} + +TEST(CheckpointDigest, UnknownVersionRejected) { + const auto file = tempFile("state_digest_version.bin"); + ASSERT_TRUE(sampleCheckpointDigest().write(file)); + { + std::fstream f(file, std::ios::binary | std::ios::in | std::ios::out); + const char version = 2; + f.write(&version, 1); + } + EXPECT_FALSE(cs::CheckpointDigest::read(file).has_value()); + std::filesystem::remove(file); +} + +TEST(CheckpointDigest, ComparesEveryField) { + const auto d = sampleCheckpointDigest(); + auto other = d; + other.wallets += 1; + EXPECT_NE(d, other); + other = d; + other.settings[0] ^= 1; + EXPECT_NE(d, other); + other = d; + other.digest[31] ^= 1; + EXPECT_NE(d, other); +} + +TEST(CheckpointDigest, LogLineHasTheScriptsFormat) { + const auto d = sampleCheckpointDigest(); + const auto line = cs::stateDigestLine(186400000, d.digest, d.wallets); + EXPECT_EQ(line.rfind("STATE DIGEST #186400000 000102", 0), 0u); + EXPECT_EQ(line.substr(line.size() - std::string(" wallets 147463").size()), " wallets 147463"); + EXPECT_EQ(line.size(), std::string("STATE DIGEST #186400000 ").size() + 64 + std::string(" wallets 147463").size()); +}