From b1c53dd1245b9a6bb48a6f29f6d39ab6d17046f3 Mon Sep 17 00:00:00 2001 From: mr-pandabear <94190499+mr-pandabear@users.noreply.github.com> Date: Fri, 6 Oct 2023 02:30:07 -0700 Subject: [PATCH] finally use a proper logging library instead of hand-rolled sh*t: spdlog --- conanfile.txt | 1 + src/core/api.cpp | 1 - src/core/crypto.cpp | 6 +- src/core/header_chain.cpp | 10 +- src/core/host_manager.cpp | 34 +++---- src/core/logger.cpp | 7 -- src/core/logger.hpp | 73 -------------- src/server/block_store.cpp | 1 - src/server/blockchain.cpp | 42 ++++---- src/server/executor.cpp | 10 +- src/server/mempool.cpp | 4 +- src/server/request_manager.cpp | 8 +- src/server/server.cpp | 177 ++++++++++++++++----------------- src/tools/cli.cpp | 11 +- src/tools/keygen.cpp | 9 +- src/tools/loader.cpp | 11 +- src/tools/miner.cpp | 24 ++--- src/tools/server.cpp | 2 + 18 files changed, 176 insertions(+), 255 deletions(-) delete mode 100644 src/core/logger.cpp delete mode 100644 src/core/logger.hpp diff --git a/conanfile.txt b/conanfile.txt index 255f28f1..3cd5e44e 100644 --- a/conanfile.txt +++ b/conanfile.txt @@ -1,4 +1,5 @@ [requires] +spdlog/1.12.0 zlib/1.2.13 openssl/3.0.0 uwebsockets/19.3.0 diff --git a/src/core/api.cpp b/src/core/api.cpp index 46330abe..944a0d21 100644 --- a/src/core/api.cpp +++ b/src/core/api.cpp @@ -151,7 +151,6 @@ std::optional verifyTransaction(string host_url, Transaction &t) { std::string responseStr = std::string{response.body.begin(), response.body.end()}; - cout << "|" << responseStr << "|" << endl; return into_json(response.body); } diff --git a/src/core/crypto.cpp b/src/core/crypto.cpp index fe863567..8e520f81 100644 --- a/src/core/crypto.cpp +++ b/src/core/crypto.cpp @@ -1,12 +1,12 @@ #include "crypto.hpp" #include "helpers.hpp" -#include "logger.hpp" #include "constants.hpp" #include #include #include #include +#include "spdlog/spdlog.h" #include "../external/ed25519/ed25519.h" //https://github.com/orlp/ed25519 #include "../external/pufferfish/pufferfish.h" //https://github.com/epixoip/pufferfish #include "../external/sha256/sha2.hpp" @@ -36,7 +36,7 @@ SHA256Hash PUFFERFISH(const char* buffer, size_t len, bool useCache) { memset(hash, 0, PF_HASHSPACE); int ret = 0; if ((ret = pf_newhash((const void*) buffer, len, 0, 8, hash)) != 0) { - Logger::logStatus("PUFFERFISH failed to compute hash"); + spdlog::error("PUFFERFISH failed to compute hash"); } size_t sz = PF_HASHSPACE; @@ -278,7 +278,7 @@ SHA256Hash mineHash(SHA256Hash target, unsigned char challengeSize, bool usePuff if (hashes++ > 1024) { double hps = (double)hashes / ((double)(getTimeMilliseconds() - st) / 1000); - Logger::logStatus("[thread" + std::to_string(threadId) + "] mining at " + std::to_string(hps) + "h/sec"); + spdlog::info("[thread {}] mining at {} h/sec", std::to_string(threadId),std::to_string(hps)); hashes = 0; st = getTimeMilliseconds(); } diff --git a/src/core/header_chain.cpp b/src/core/header_chain.cpp index afc9cd8d..1d9b5541 100644 --- a/src/core/header_chain.cpp +++ b/src/core/header_chain.cpp @@ -1,7 +1,7 @@ #include "header_chain.hpp" #include "api.hpp" #include "block.hpp" -#include "logger.hpp" +#include "spdlog/spdlog.h" #include #include using namespace std; @@ -103,7 +103,7 @@ void HeaderChain::load() { if (this->bannedHashes.find(curr) != this->bannedHashes.end()) { // check if the current hash corresponds to a banned hash if (block.getHash() == this->bannedHashes[curr]) { - Logger::logStatus("Banned hash found for block: " + to_string(curr)); + spdlog::info("Banned hash found for block: {}", to_string(curr)); failure = true; break; } @@ -111,7 +111,7 @@ void HeaderChain::load() { if (this->checkPoints.find(curr) != this->checkPoints.end()) { // check the checkpoint hash: if (block.getHash() != this->checkPoints[curr]) { - // Logger::logStatus("Checkpoint hash failed for block: " + to_string(curr)); + // spdlog::info("Checkpoint hash failed for block: {}", to_string(curr)); failure = true; break; } @@ -132,7 +132,7 @@ void HeaderChain::load() { this->totalWork = totalWork; } if (failure) { - Logger::logStatus("header chain sync failed host=" + this->host); + spdlog::warn("header chain sync failed host={}", this->host); this->failed = true; this->reset(); return; @@ -149,7 +149,7 @@ void HeaderChain::load() { } this->failed = false; if (numBlocks != startBlocks) { - // Logger::logStatus("Chain for " + this->host + " updated to length=" + to_string(this->chainLength) + " total_work=" + to_string(this->totalWork)); + spdlog::info("Chain for {} updated to length= {} total_work= {}" , this->host, to_string(this->chainLength), to_string(this->totalWork)); } } diff --git a/src/core/host_manager.cpp b/src/core/host_manager.cpp index 572b6447..ff3bc28f 100644 --- a/src/core/host_manager.cpp +++ b/src/core/host_manager.cpp @@ -2,13 +2,14 @@ #include "helpers.hpp" #include "api.hpp" #include "constants.hpp" -#include "logger.hpp" #include "header_chain.hpp" #include "../external/http.hpp" +#include "spdlog/spdlog.h" #include #include #include #include +#include #include #include using namespace std; @@ -62,7 +63,7 @@ string HostManager::computeAddress() { } if (!found) { - Logger::logError("IP discovery", "Could not determine current IP address"); + spdlog::error("IP discovery {} Could not determine current IP address"); } } else { this->address = this->ip + ":" + to_string(this->port); @@ -92,14 +93,13 @@ void peer_sync(HostManager& hm) { void header_stats(HostManager& hm) { std::this_thread::sleep_for(std::chrono::seconds(30)); while(true) { - Logger::logStatus("================ Header Sync Status ==============="); + spdlog::info("================ Header Sync Status ==============="); map> stats = hm.getHeaderChainStats(); for(auto item : stats) { stringstream ss; - ss << "Host: " << item.first << ", blocks: " << item.second.first << ", node_ver: " << item.second.second; - Logger::logStatus(ss.str()); + spdlog::info("Host: {} blocks: {}, node_ver: {}", item.first, item.second.first, item.second.second); } - Logger::logStatus("==================================================="); + spdlog::info("==================================================="); std::this_thread::sleep_for(std::chrono::seconds(30)); } } @@ -137,7 +137,7 @@ HostManager::HostManager(json config) { blocked = blocked.substr(0, blocked.size() - 1); } this->blacklist.insert(blocked); - Logger::logStatus("Ignoring host " + blocked); + spdlog::info("Ignoring host {}", blocked); } } } @@ -153,7 +153,7 @@ HostManager::HostManager(json config) { enabled = enabled.substr(0, enabled.size() - 1); } this->whitelist.insert(enabled); - Logger::logStatus("Enabling host " + enabled); + spdlog::info("Enabling host {}", enabled); } } } @@ -327,7 +327,7 @@ set HostManager::sampleFreshHosts(int count) const { } if (freshHostsWithHeight.empty()) { - //Logger::logStatus("HostManager::sampleFreshHosts No fresh hosts found. Falling back to fixed hosts."); + spdlog::debug("HostManager::sampleFreshHosts No fresh hosts found. Falling back to fixed hosts."); return set(fixedHosts.begin(), fixedHosts.end()); } @@ -337,7 +337,7 @@ set HostManager::sampleFreshHosts(int count) const { return a.second > b.second; }); if (!freshHostsWithHeight.empty()) { - Logger::logStatus("HostManager::sampleFreshHosts Top-synced host: " + freshHostsWithHeight[0].first + " with block height: " + std::to_string(freshHostsWithHeight[0].second)); + spdlog::info("HostManager::sampleFreshHosts Top-synced host: {} with block height: {}", freshHostsWithHeight[0].first,std::to_string(freshHostsWithHeight[0].second)); } int numToPick = min(count, (int)freshHostsWithHeight.size()); @@ -376,7 +376,7 @@ void HostManager::addPeer(string addr, uint64_t time, string version, string net // add to our host list if (this->whitelist.size() == 0 || this->whitelist.find(addr) != this->whitelist.end()){ - Logger::logStatus("Added new peer: " + addr); + spdlog::info("Added new peer: {}", addr); hosts.push_back(addr); } else { return; @@ -399,7 +399,7 @@ void HostManager::addPeer(string addr, uint64_t time, string version, string net try { pingPeer(neighbor, addr, std::time(0), _version, networkName); } catch(...) { - Logger::logStatus("Could not add peer " + addr + " to " + neighbor); + spdlog::info("Could not add peer " + addr + " to " + neighbor); } })); } @@ -425,7 +425,7 @@ bool HostManager::isDisabled() { void HostManager::refreshHostList() { if (this->hostSources.size() == 0) return; - Logger::logStatus("Finding peers..."); + spdlog::info("Finding peers..."); set fullHostList; @@ -465,22 +465,22 @@ void HostManager::refreshHostList() { if (auto hostInfo{getName(hostUrl)}; hostInfo.has_value()) { auto v{extractHostVersion(*hostInfo)}; if (!v.has_value()){ - Logger::logStatus(RED + "[ BAD_JSON ] " + RESET + hostUrl); + spdlog::error("[ BAD_JSON ] {}", hostUrl); return; } std::string& version{*v}; if ((*hostInfo)["version"] < hm.minHostVersion) { - Logger::logStatus(RED + "[ DEPRECATED ] " + RESET + hostUrl); + spdlog::warn("[ DEPRECATED ] {}", hostUrl); return; } std::unique_lock ul(lock); if (hm.whitelist.size() == 0 || hm.whitelist.find(hostUrl) != hm.whitelist.end()){ hm.hosts.push_back(hostUrl); - Logger::logStatus(GREEN + "[ CONNECTED ] " + RESET + hostUrl); + spdlog::info("[ CONNECTED ] {}", hostUrl); hm.hostPingTimes[hostUrl] = std::time(0); } }else{ - Logger::logStatus(RED + "[ UNREACHABLE ] " + RESET + hostUrl); + spdlog::warn("[ UNREACHABLE ] {}", hostUrl); } }) ); diff --git a/src/core/logger.cpp b/src/core/logger.cpp deleted file mode 100644 index 73b932e3..00000000 --- a/src/core/logger.cpp +++ /dev/null @@ -1,7 +0,0 @@ -#include "logger.hpp" - -list Logger::buffer = list(); -ofstream Logger::file = ofstream(); -std::mutex Logger::console_lock; -std::mutex Logger::file_mutex; -std::mutex Logger::buffer_mutex; diff --git a/src/core/logger.hpp b/src/core/logger.hpp deleted file mode 100644 index 5df632e3..00000000 --- a/src/core/logger.hpp +++ /dev/null @@ -1,73 +0,0 @@ -#pragma once -#include -#include -#include -#include -#include -#include -#include -#include - -using namespace std; - -#define TIME_FORMAT "%m-%d-%Y %H:%M:%S" -#define MAX_LINES 1000 - -#define RESET std::string("\033[0m") -#define RED std::string("\033[31m") -#define GREEN std::string("\033[32m") - -class Logger { -public: - static list buffer; - static ofstream file; - static std::mutex console_lock; - static std::mutex file_mutex; - static std::mutex buffer_mutex; - - static void logToBuffer(string message) { - std::lock_guard lock(buffer_mutex); - if (Logger::buffer.size() > MAX_LINES) { - Logger::buffer.pop_front(); - } - Logger::buffer.push_back(message); - } - - static void logError(string endpoint, string message) { - auto t = std::time(0); - auto tm = *std::localtime(&t); - stringstream s; - s<<"[ERROR] "< ul(console_lock); - cout << s.str() << std::flush; - } else { - std::lock_guard lock(file_mutex); - file< ul(console_lock); - cout << s.str() << std::flush; - } else { - std::lock_guard lock(file_mutex); - file< Logger::buffer = list(); -//ofstream Logger::file = ofstream(); -//std::mutex Logger::console_lock; -//std::mutex Logger::file_mutex; -//std::mutex Logger::buffer_mutex; diff --git a/src/server/block_store.cpp b/src/server/block_store.cpp index 764cabba..b0ca3800 100644 --- a/src/server/block_store.cpp +++ b/src/server/block_store.cpp @@ -2,7 +2,6 @@ #include #include "../core/crypto.hpp" #include "../core/transaction.hpp" -#include "../core/logger.hpp" #include "block_store.hpp" using namespace std; diff --git a/src/server/blockchain.cpp b/src/server/blockchain.cpp index 6e76f846..3a2ea469 100644 --- a/src/server/blockchain.cpp +++ b/src/server/blockchain.cpp @@ -13,8 +13,8 @@ #include #include #include +#include "spdlog/spdlog.h" #include "../core/merkle_tree.hpp" -#include "../core/logger.hpp" #include "../core/helpers.hpp" #include "../core/api.hpp" #include "../core/user.hpp" @@ -38,16 +38,16 @@ void chain_sync(BlockChain& blockchain) { ExecutionStatus status = blockchain.startChainSync(); if (status != SUCCESS) { - Logger::logError(RED + "[SYNC ERROR]" + RESET, executionStatusAsString(status)); + spdlog::error("[SYNC ERROR]", executionStatusAsString(status)); blockchain.retries++; if (blockchain.retries > FORK_RESET_RETRIES) { - Logger::logError(RED + "[FATAL]" + RESET, "Max Rollback Tries Reached. Try deleting data dir and restarting."); + spdlog::critical("Max Rollback Tries Reached. Try deleting data dir and restarting."); exit(-1); } else { - Logger::logError(RED + "[ERROR]" + RESET, "Rollback retry #" + to_string(blockchain.retries)); + spdlog::warn("Rollback retry #" + to_string(blockchain.retries)); std::unique_lock ul(blockchain.lock); blockchain.isSyncing = true; for (uint64_t i = 0; i < FORK_CHAIN_POP_COUNT*blockchain.retries; i++) { @@ -59,15 +59,15 @@ void chain_sync(BlockChain& blockchain) { } else { - Logger::logStatus("Chain Sync Status: SUCCESS Top Block: " + to_string(blockchain.numBlocks)); + spdlog::info("Chain Sync Status: SUCCESS Top Block: {}", to_string(blockchain.numBlocks)); blockchain.retries = 0; } } else { - Logger::logStatus("Debug isSyncing: " + to_string(blockchain.isSyncing)); - Logger::logStatus("Debug hosts.getBlockCount: " + to_string(blockchain.hosts.getBlockCount())); - Logger::logStatus("Debug numBlocks: " + to_string(blockchain.numBlocks)); + spdlog::info("Debug isSyncing: {}", to_string(blockchain.isSyncing)); + spdlog::info("Debug hosts.getBlockCount: {}", to_string(blockchain.hosts.getBlockCount())); + spdlog::info("Debug numBlocks: {}", to_string(blockchain.numBlocks)); } } } @@ -94,7 +94,7 @@ BlockChain::~BlockChain() { void BlockChain::initChain() { this->isSyncing = false; if (this->blockStore->hasBlockCount()) { - Logger::logStatus("BlockStore exists, loading from disk"); + spdlog::info("BlockStore exists, loading from disk"); size_t count = this->blockStore->getBlockCount(); this->numBlocks = count; this->targetBlockCount = count; @@ -108,7 +108,7 @@ void BlockChain::initChain() { } void BlockChain::resetChain() { - Logger::logStatus("BlockStore does not exist"); + spdlog::info("BlockStore does not exist"); this->difficulty = 16; this->targetBlockCount = 1; this->numBlocks = 0; @@ -149,7 +149,7 @@ void BlockChain::resetChain() { try { genesisJson = readJsonFromFile("genesis.json"); } catch(...) { - Logger::logError(RED + "[FATAL]" + RESET, "Could not load genesis.json file."); + spdlog::critical("Could not load genesis.json file."); exit(-1); } @@ -382,7 +382,7 @@ ExecutionStatus BlockChain::addBlock(Block& block) { if (block.getId() != this->numBlocks + 1) return INVALID_BLOCK_ID; if (block.getDifficulty() != this->difficulty) { if (block.getId() >= 536100 && block.getId() <= 536200 && block.getDifficulty() == 27) { - Logger::logStatus("Skipping difficulty verification on known invalid difficulty"); + spdlog::info("Skipping difficulty verification on known invalid difficulty"); } else { return INVALID_DIFFICULTY; } @@ -438,8 +438,8 @@ ExecutionStatus BlockChain::addBlock(Block& block) { this->blockStore->setBlockCount(this->numBlocks); this->lastHash = block.getHash(); this->updateDifficulty(); - Logger::logStatus("Added block " + to_string(block.getId())); - Logger::logStatus("difficulty= " + to_string(block.getDifficulty())); + spdlog::info("Added block {}", to_string(block.getId())); + spdlog::info("difficulty= {}", to_string(block.getDifficulty())); } return status; } @@ -455,7 +455,7 @@ void BlockChain::recomputeLedger() { this->ledger.clear(); this->txdb.clear(); for(int i = 1; i <= this->numBlocks; i++) { - if (i % 10000 == 0) Logger::logStatus("Re-computing chain, finished block: " + to_string(i)); + if (i % 10000 == 0) spdlog::info("Re-computing chain, finished block: {}", to_string(i)); LedgerState deltas; Block block = this->getBlock(i); bool checkInvalid = NO_VALIDITY_CHECK_BEFORE_HEIGHT <= getBlockCount(); @@ -465,7 +465,7 @@ void BlockChain::recomputeLedger() { if (!t.isFee()) this->txdb.insertTransaction(t, block.getId()); } if (addResult != SUCCESS) { - Logger::logError(RED + "[FATAL]" + RESET, "Corrupt blockchain. Exiting. Please delete data dir and sync from scratch."); + spdlog::critical("Corrupt blockchain. Exiting. Please delete data dir and sync from scratch."); exit(-1); } } @@ -500,7 +500,7 @@ ExecutionStatus BlockChain::startChainSync() { int startCount = this->numBlocks; int needed = this->targetBlockCount - startCount; - if (needed > 0) Logger::logStatus("fetching target blockcount=" + to_string(this->targetBlockCount)); + if (needed > 0) spdlog::info("fetching target blockcount={}", to_string(this->targetBlockCount)); // download any remaining blocks in batches uint64_t start = std::time(0); for(int i = startCount + 1; i <= this->targetBlockCount; i+=BLOCKS_PER_FETCH) { @@ -517,18 +517,18 @@ ExecutionStatus BlockChain::startChainSync() { if (addResult != SUCCESS) { failure = true; status = addResult; - Logger::logError("Chain failed at blockID, recomputing ledger", std::to_string(b.getId())); + spdlog::error("Chain failed at blockID, recomputing ledger {}", std::to_string(b.getId())); break; } } if (failure) { - Logger::logError("BlockChain::startChainSync", executionStatusAsString(status)); + spdlog::error("BlockChain::startChainSync {}", executionStatusAsString(status)); this->isSyncing = false; return status; } } catch (const std::exception &e) { this->isSyncing = false; - Logger::logError("BlockChain::startChainSync", "Failed to load block" + string(e.what())); + spdlog::error("BlockChain::startChainSync, Failed to load block: {}" + string(e.what())); return UNKNOWN_ERROR; } } @@ -536,7 +536,7 @@ ExecutionStatus BlockChain::startChainSync() { uint64_t d = final - start; stringstream s; s<<"Downloaded " << needed <<" blocks in " << d << " seconds from " + bestHost; - if (needed > 1) Logger::logStatus(s.str()); + if (needed > 1) spdlog::info(s.str()); this->isSyncing = false; return SUCCESS; } diff --git a/src/server/executor.cpp b/src/server/executor.cpp index 53217777..df2b4e9d 100644 --- a/src/server/executor.cpp +++ b/src/server/executor.cpp @@ -6,8 +6,8 @@ #include #include #include "../core/block.hpp" -#include "../core/logger.hpp" #include "../core/helpers.hpp" +#include "spdlog/spdlog.h" #include "executor.hpp" using namespace std; @@ -38,12 +38,12 @@ void addInvalidTransaction(uint64_t blockId, PublicWalletAddress wallet) { if (outFile.is_open()) { outFile << invalidTransactions.dump(4); if (outFile.fail()) { - Logger::logError(RED + "[ERROR]" + RESET, "Failed to write to invalid.json."); + spdlog::error("Failed to write to invalid.json."); return; } outFile.close(); } else { - Logger::logError(RED + "[ERROR]" + RESET, "Failed to open invalid.json for writing."); + spdlog::error("Failed to open invalid.json for writing."); } std::string backupFileName = "./invalid_backup.json"; @@ -51,9 +51,9 @@ void addInvalidTransaction(uint64_t blockId, PublicWalletAddress wallet) { if (backupFile.is_open()) { backupFile << invalidTransactions.dump(4); backupFile.close(); - Logger::logStatus(GREEN + "[INFO]" + RESET + " Backup updated: " + backupFileName); + spdlog::info("Backup updated: {}"); } else { - Logger::logError(RED + "[ERROR]" + RESET, "Failed to update backup: " + backupFileName); + spdlog::error("Failed to update backup: {}", backupFileName); } } diff --git a/src/server/mempool.cpp b/src/server/mempool.cpp index de1bcbde..870a093c 100644 --- a/src/server/mempool.cpp +++ b/src/server/mempool.cpp @@ -7,10 +7,10 @@ #include #include #include -#include "../core/logger.hpp" #include "../core/api.hpp" #include "mempool.hpp" #include "blockchain.hpp" +#include "spdlog/spdlog.h" #define TX_BRANCH_FACTOR 10 #define MIN_FEE_TO_ENTER_MEMPOOL 1 @@ -81,7 +81,7 @@ void MemPool::mempool_sync() const { } return true; } catch (...) { - Logger::logError("Failed to send tx to ", peer); + spdlog::warn("Failed to send tx to {}", peer); return false; } }); diff --git a/src/server/request_manager.cpp b/src/server/request_manager.cpp index 291bed11..daa1a6bf 100644 --- a/src/server/request_manager.cpp +++ b/src/server/request_manager.cpp @@ -3,9 +3,9 @@ #include #include #include "../core/helpers.hpp" -#include "../core/logger.hpp" #include "../core/merkle_tree.hpp" #include "request_manager.hpp" +#include "spdlog/spdlog.h" using namespace std; #define NEW_BLOCK_PEER_FANOUT 8 @@ -33,13 +33,13 @@ RequestManager::RequestManager(HostManager& hosts, string ledgerPath, string blo mempoolInitSuccessful = true; break; // Successfully initialized mempool, break out of the loop } catch(const std::exception& e) { - Logger::logError("RequestManager::Failed to initialize mempool from host: ", bestHost); + spdlog::error("RequestManager::Failed to initialize mempool from host: {}", bestHost); } } } if (!mempoolInitSuccessful) { - Logger::logError("RequestManager::Constructor", "Failed to initialize mempool after trying with top-synced hosts."); + spdlog::error("RequestManager::Constructor Failed to initialize mempool after trying with top-synced hosts."); // TODO further actions here. } @@ -112,7 +112,7 @@ json RequestManager::submitProofOfWork(Block& newBlock) { Block a = newBlock; submitBlock(neighbor, a); } catch(...) { - Logger::logStatus("Could not forward new block to " + neighbor); + spdlog::warn("Could not forward new block to {}" + neighbor); } }}.detach(); } diff --git a/src/server/server.cpp b/src/server/server.cpp index de5fefba..38ebcad6 100644 --- a/src/server/server.cpp +++ b/src/server/server.cpp @@ -9,15 +9,14 @@ #include #include #include -#include "../core/logger.hpp" #include "../core/crypto.hpp" #include "../core/host_manager.hpp" #include "../core/helpers.hpp" #include "../core/api.hpp" #include "../core/crypto.hpp" #include "../core/config.hpp" -#include "../core/logger.hpp" #include "request_manager.hpp" +#include "spdlog/spdlog.h" #include "server.hpp" using namespace std; @@ -55,7 +54,7 @@ namespace { std::cerr << "Error: signal " << signal << std::endl; backtrace_symbols_fd(array, size, STDERR_FILENO); - Logger::logError(RED + "[FATAL]" + RESET, "Error: signal " + std::to_string(signal)); + spdlog::critical("Error: signal {}", std::to_string(signal)); } @@ -70,17 +69,17 @@ void PandaniteServer::run(json config) { std::filesystem::path data{ "data" }; if (!std::filesystem::exists(data)) { - Logger::logStatus("Creating data directory..."); + spdlog::info("Creating data directory..."); try { std::filesystem::create_directory(data); } catch (std::exception& e) { - std::cout << e.what() << std::endl; + spdlog::error(e.what()); } } - Logger::logStatus("Starting Server Version: "); + spdlog::info("Starting Server Version: "); HostManager hosts(config); @@ -94,9 +93,9 @@ void PandaniteServer::run(json config) { shutdown_handler = [&](int signal) { - Logger::logStatus("Shutting down server."); + spdlog::info("Shutting down server."); manager.exit(); - Logger::logStatus("FINISHED"); + spdlog::info("FINISHED"); }; signal(SIGINT, signal_handler); @@ -107,30 +106,30 @@ void PandaniteServer::run(json config) { if (config["rateLimiter"] == false) manager.enableRateLimiting(false); - Logger::logStatus("RequestManager ready..."); + spdlog::info("RequestManager ready..."); - Logger::logStatus("Server Ready."); + spdlog::info("Server Ready."); auto corsHandler = [&manager](auto *res, auto *req) { sendCorsHeaders(res); res->end(""); }; - auto logsHandler = [&manager](auto *res, auto *req) { - rateLimit(manager, res); - sendCorsHeaders(res); - try { - string s = ""; - for(auto str : Logger::buffer) { - s += str + "
"; - } - res->writeHeader("Content-Type", "text/html; charset=utf-8")->end(s); - } catch(const std::exception &e) { - Logger::logError("/logs", e.what()); - } catch(...) { - Logger::logError("/logs", "unknown"); - } - }; + // auto logsHandler = [&manager](auto *res, auto *req) { + // rateLimit(manager, res); + // sendCorsHeaders(res); + // try { + // string s = ""; + // for(auto str : LoggerDeprecated::buffer) { + // s += str + "
"; + // } + // res->writeHeader("Content-Type", "text/html; charset=utf-8")->end(s); + // } catch(const std::exception &e) { + // spdlog::error("/logs {}", e.what()); + // } catch(...) { + // spdlog::error("/logs {}", "unknown"); + // } + // }; auto statsHandler = [&manager](auto *res, auto *req) { rateLimit(manager, res); @@ -139,9 +138,9 @@ void PandaniteServer::run(json config) { json stats = manager.getStats(); res->writeHeader("Content-Type", "application/json; charset=utf-8")->end(stats.dump()); } catch(const std::exception &e) { - Logger::logError("/stats", e.what()); + spdlog::error("/stats {}", e.what()); } catch(...) { - Logger::logError("/stats", "unknown"); + spdlog::error("/stats {}", "unknown"); } }; @@ -152,9 +151,9 @@ void PandaniteServer::run(json config) { std::string count = manager.getTotalWork(); res->writeHeader("Content-Type", "text/html; charset=utf-8")->end(count); } catch(const std::exception &e) { - Logger::logError("/total_work", e.what()); + spdlog::error("/total_work {}", e.what()); } catch(...) { - Logger::logError("/total_work", "unknown"); + spdlog::error("/total_work {}", "unknown"); } }; @@ -182,9 +181,9 @@ void PandaniteServer::run(json config) { std::string count = manager.getBlockCount(); res->writeHeader("Content-Type", "text/html; charset=utf-8")->end(count); } catch(const std::exception &e) { - Logger::logError("/block_count", e.what()); + spdlog::error("/block_count {}", e.what()); } catch(...) { - Logger::logError("/block_count", "unknown"); + spdlog::error("/block_count {}", "unknown"); } }; @@ -197,10 +196,10 @@ void PandaniteServer::run(json config) { res->writeHeader("Content-Type", "application/json; charset=utf-8")->end(result.dump()); } catch(const std::exception &e) { result["error"] = "Unknown error"; - Logger::logError("/get_tx_json", e.what()); + spdlog::error("/get_tx_json {}", e.what()); res->end(""); } catch(...) { - Logger::logError("/get_tx_json", "unknown"); + spdlog::error("/get_tx_json {}", "unknown"); res->end(""); } }; @@ -226,10 +225,10 @@ void PandaniteServer::run(json config) { res->writeHeader("Content-Type", "application/json; charset=utf-8")->end(result.dump()); } catch(const std::exception &e) { result["error"] = "Unknown error"; - Logger::logError("/block", e.what()); + spdlog::error("/block {}", e.what()); res->end(""); } catch(...) { - Logger::logError("/block", "unknown"); + spdlog::error("/block {}", "unknown"); res->end(""); } }; @@ -255,10 +254,10 @@ void PandaniteServer::run(json config) { res->writeHeader("Content-Type", "application/json; charset=utf-8")->end(result.dump()); } catch(const std::exception &e) { result["error"] = "Unknown error"; - Logger::logError("/mine_status", e.what()); + spdlog::error("/mine_status {}", e.what()); res->end(""); } catch(...) { - Logger::logError("/mine_status", "unknown"); + spdlog::error("/mine_status {}", "unknown"); res->end(""); } }; @@ -277,9 +276,9 @@ void PandaniteServer::run(json config) { json ledger = manager.getLedger(w); res->writeHeader("Content-Type", "application/json; charset=utf-8")->end(ledger.dump()); } catch(const std::exception &e) { - Logger::logError("/ledger", e.what()); + spdlog::error("/ledger {}", e.what()); } catch(...) { - Logger::logError("/ledger", "unknown"); + spdlog::error("/ledger {}", "unknown"); } }; @@ -297,9 +296,9 @@ void PandaniteServer::run(json config) { json ret = manager.getTransactionsForWallet(w); res->writeHeader("Content-Type", "application/json; charset=utf-8")->end(ret.dump()); } catch(const std::exception &e) { - Logger::logError("/wallet", e.what()); + spdlog::error("/wallet {}", e.what()); } catch(...) { - Logger::logError("/wallet", "unknown"); + spdlog::error("/wallet {}", "unknown"); } }; @@ -312,9 +311,9 @@ void PandaniteServer::run(json config) { json ledger = manager.getLedger(w); res->writeHeader("Content-Type", "application/json; charset=utf-8")->end(ledger.dump()); } catch(const std::exception &e) { - Logger::logError("/ledger", e.what()); + spdlog::error("/ledger {}", e.what()); } catch(...) { - Logger::logError("/ledger", "unknown"); + spdlog::error("/ledger {}", "unknown"); } }; @@ -335,9 +334,9 @@ void PandaniteServer::run(json config) { key["privateKey"] = privKey; res->writeHeader("Content-Type", "application/json; charset=utf-8")->end(key.dump()); } catch (const std::exception& e) { - Logger::logError("/create_wallet", e.what()); + spdlog::error("/create_wallet {}", e.what()); } catch(...) { - Logger::logError("/create_wallet", "unknown"); + spdlog::error("/create_wallet {}", "unknown"); } }; @@ -367,9 +366,9 @@ void PandaniteServer::run(json config) { json result = t.toJson(); res->writeHeader("Content-Type", "application/json; charset=utf-8")->end(result.dump()); } catch(const std::exception &e) { - Logger::logError("/create_transaction", e.what()); + spdlog::error("/create_transaction {}", e.what()); } catch(...) { - Logger::logError("/create_transaction", "unknown"); + spdlog::error("/create_transaction {}", "unknown"); } } }); @@ -395,10 +394,10 @@ void PandaniteServer::run(json config) { json result = manager.addPeer(peerInfo["address"], peerInfo["time"], peerInfo["version"], peerInfo["networkName"]); res->writeHeader("Content-Type", "application/json; charset=utf-8")->end(result.dump()); } catch(const std::exception &e) { - Logger::logStatus(peerInfo.dump()); - Logger::logError("/add_peer", e.what()); + spdlog::info(peerInfo.dump()); + spdlog::error("/add_peer {}", e.what()); } catch(...) { - Logger::logError("/add_peer", "unknown"); + spdlog::error("/add_peer {}", "unknown"); } } }); @@ -420,7 +419,7 @@ void PandaniteServer::run(json config) { if (buffer.length() < BLOCKHEADER_BUFFER_SIZE + TRANSACTIONINFO_BUFFER_SIZE) { json response; response["error"] = "Malformed block"; - Logger::logError("/submit","Malformed block"); + spdlog::error("/submit {}","Malformed block"); res->end(response.dump()); } else { char * ptr = (char*)buffer.c_str(); @@ -429,7 +428,7 @@ void PandaniteServer::run(json config) { if (buffer.size() != BLOCKHEADER_BUFFER_SIZE + blockH.numTransactions*TRANSACTIONINFO_BUFFER_SIZE) { json response; response["error"] = "Malformed block"; - Logger::logError("/submit","Malformed block"); + spdlog::error("/submit {}","Malformed block"); res->end(response.dump()); return; } @@ -439,7 +438,7 @@ void PandaniteServer::run(json config) { json response; response["error"] = "Too many transactions"; res->end(response.dump()); - Logger::logError("/submit","Too many transactions"); + spdlog::error("/submit {}","Too many transactions"); } else { for(int j = 0; j < blockH.numTransactions; j++) { TransactionInfo t = transactionInfoFromBuffer(ptr); @@ -456,12 +455,12 @@ void PandaniteServer::run(json config) { json response; response["error"] = string(e.what()); res->end(response.dump()); - Logger::logError("/submit", e.what()); + spdlog::error("/submit {}", e.what()); } catch(...) { json response; response["error"] = "unknown"; res->end(response.dump()); - Logger::logError("/submit", "unknown"); + spdlog::error("/submit {}", "unknown"); } } @@ -479,9 +478,9 @@ void PandaniteServer::run(json config) { delete buffer.first; res->end(""); } catch(const std::exception &e) { - Logger::logError("/gettx", e.what()); + spdlog::error("/gettx {}", e.what()); } catch(...) { - Logger::logError("/gettx", "unknown"); + spdlog::error("/gettx {}", "unknown"); } res->onAborted([res]() { res->end("ABORTED"); @@ -495,9 +494,9 @@ void PandaniteServer::run(json config) { json response = manager.getSupply(); res->end(response.dump()); } catch(const std::exception &e) { - Logger::logError("/supply", e.what()); + spdlog::error("/supply {}", e.what()); } catch(...) { - Logger::logError("/supply", "unknown"); + spdlog::error("/supply {}", "unknown"); } }; @@ -508,9 +507,9 @@ void PandaniteServer::run(json config) { json response = manager.getProofOfWork(); res->end(response.dump()); } catch(const std::exception &e) { - Logger::logError("/mine", e.what()); + spdlog::error("/mine {}", e.what()); } catch(...) { - Logger::logError("/mine", "unknown"); + spdlog::error("/mine {}", "unknown"); } }; @@ -523,7 +522,7 @@ void PandaniteServer::run(json config) { int start = std::stoi(string(req->getParameter(0))); int end = std::stoi(string(req->getParameter(1))); if ((end-start) > BLOCKS_PER_FETCH) { - Logger::logError("/sync", "invalid range requested"); + spdlog::error("/sync {}", "invalid range requested"); res->end(""); } res->writeHeader("Content-Type", "application/octet-stream"); @@ -535,9 +534,9 @@ void PandaniteServer::run(json config) { } res->end(""); } catch(const std::exception &e) { - Logger::logError("/sync", e.what()); + spdlog::error("/sync {}", e.what()); } catch(...) { - Logger::logError("/sync", "unknown"); + spdlog::error("/sync {}", "unknown"); } res->onAborted([res]() { res->end("ABORTED"); @@ -551,7 +550,7 @@ void PandaniteServer::run(json config) { int start = std::stoi(string(req->getParameter(0))); int end = std::stoi(string(req->getParameter(1))); if ((end-start) > BLOCK_HEADERS_PER_FETCH) { - Logger::logError("/block_headers", "invalid range requested"); + spdlog::error("/block_headers {}", "invalid range requested"); res->end(""); } res->writeHeader("Content-Type", "application/octet-stream"); @@ -564,9 +563,9 @@ void PandaniteServer::run(json config) { } res->end(""); } catch(const std::exception &e) { - Logger::logError("/block_headers", e.what()); + spdlog::error("/block_headers {}", e.what()); } catch(...) { - Logger::logError("/block_headers", "unknown"); + spdlog::error("/block_headers {}", "unknown"); } res->onAborted([res]() { res->end("ABORTED"); @@ -588,10 +587,10 @@ void PandaniteServer::run(json config) { res->writeHeader("Content-Type", "application/json; charset=utf-8")->end(result.dump()); } catch(const std::exception &e) { result["error"] = "Unknown error"; - Logger::logError("/block", e.what()); + spdlog::error("/block {}", e.what()); res->end(""); } catch(...) { - Logger::logError("/block", "unknown"); + spdlog::error("/block {}", "unknown"); res->end(""); } }; @@ -611,10 +610,10 @@ void PandaniteServer::run(json config) { res->writeHeader("Content-Type", "application/json; charset=utf-8")->end(result.dump()); } catch(const std::exception &e) { result["error"] = "Unknown error"; - Logger::logError("/block", e.what()); + spdlog::error("/block {}", e.what()); res->end(""); } catch(...) { - Logger::logError("/block", "unknown"); + spdlog::error("/block {}", "unknown"); res->end(""); } }; @@ -634,7 +633,7 @@ void PandaniteServer::run(json config) { int start = std::stoi(string(req->getQuery("start"))); int end = std::stoi(string(req->getQuery("end"))); if ((end-start) > BLOCKS_PER_FETCH) { - Logger::logError("/v2/sync", "invalid range requested"); + spdlog::error("/v2/sync {}", "invalid range requested"); res->end(""); } res->writeHeader("Content-Type", "application/octet-stream"); @@ -646,9 +645,9 @@ void PandaniteServer::run(json config) { } res->end(""); } catch(const std::exception &e) { - Logger::logError("/v2/sync", e.what()); + spdlog::error("/v2/sync {}", e.what()); } catch(...) { - Logger::logError("/v2/sync", "unknown"); + spdlog::error("/v2/sync {}", "unknown"); } res->onAborted([res]() { res->end("ABORTED"); @@ -668,7 +667,7 @@ void PandaniteServer::run(json config) { int start = std::stoi(string(req->getQuery("start"))); int end = std::stoi(string(req->getQuery("end"))); if ((end-start) > BLOCK_HEADERS_PER_FETCH) { - Logger::logError("/v2/block_headers", "invalid range requested"); + spdlog::error("/v2/block_headers {}", "invalid range requested"); res->end(""); } res->writeHeader("Content-Type", "application/octet-stream"); @@ -681,9 +680,9 @@ void PandaniteServer::run(json config) { } res->end(""); } catch(const std::exception &e) { - Logger::logError("/v2/block_headers", e.what()); + spdlog::error("/v2/block_headers {}", e.what()); } catch(...) { - Logger::logError("/v2/block_headers", "unknown"); + spdlog::error("/v2/block_headers {}", "unknown"); } res->onAborted([res]() { res->end("ABORTED"); @@ -705,7 +704,7 @@ void PandaniteServer::run(json config) { if (buffer.length() < TRANSACTIONINFO_BUFFER_SIZE) { json response; response["error"] = "Malformed transaction"; - Logger::logError("/add_transaction","Malformed transaction"); + spdlog::error("/add_transaction {}","Malformed transaction"); res->end(response.dump()); } else { uint32_t numTransactions = buffer.length() / TRANSACTIONINFO_BUFFER_SIZE; @@ -719,9 +718,9 @@ void PandaniteServer::run(json config) { res->end(response.dump()); } } catch(const std::exception &e) { - Logger::logError("/add_transaction", e.what()); + spdlog::error("/add_transaction {}", e.what()); } catch(...) { - Logger::logError("/add_transaction", "unknown"); + spdlog::error("/add_transaction {}", "unknown"); } } }); @@ -760,9 +759,9 @@ void PandaniteServer::run(json config) { } res->end(response.dump()); } catch(const std::exception &e) { - Logger::logError("/add_transaction", e.what()); + spdlog::error("/add_transaction {}", e.what()); } catch(...) { - Logger::logError("/add_transaction", "unknown"); + spdlog::error("/add_transaction {}", "unknown"); } } }); @@ -791,9 +790,9 @@ void PandaniteServer::run(json config) { } res->end(response.dump()); } catch(const std::exception &e) { - Logger::logError("/verify_transaction", e.what()); + spdlog::error("/verify_transaction {}", e.what()); } catch(...) { - Logger::logError("/verify_transaction", "unknown"); + spdlog::error("/verify_transaction {}", "unknown"); } } }); @@ -806,9 +805,9 @@ void PandaniteServer::run(json config) { std::string hashrate = to_string(manager.getNetworkHashrate()); res->writeHeader("Content-Type", "text/html; charset=utf-8")->end(hashrate); } catch(const std::exception &e) { - Logger::logError("/getnetworkhashrate", e.what()); + spdlog::error("/getnetworkhashrate {}", e.what()); } catch(...) { - Logger::logError("/getnetworkhashrate", "unknown"); + spdlog::error("/getnetworkhashrate {}", "unknown"); } }; @@ -847,7 +846,7 @@ void PandaniteServer::run(json config) { .get("/total_work", totalWorkHandler) .get("/peers", peerHandler) .get("/block_count", blockCountHandler) - .get("/logs", logsHandler) + // .get("/logs", logsHandler) .get("/stats", statsHandler) .get("/block", blockHandler) .get("/tx_json", txJsonHandler) @@ -900,8 +899,6 @@ void PandaniteServer::run(json config) { .listen((int)config["port"], [&hosts](auto *token) { - Logger::logStatus("=========================================="); - Logger::logStatus("Started server: " + hosts.getAddress()); - Logger::logStatus("=========================================="); + spdlog::info("Started server: {}", hosts.getAddress()); }).run(); } diff --git a/src/tools/cli.cpp b/src/tools/cli.cpp index 08c410b8..5e0a9950 100644 --- a/src/tools/cli.cpp +++ b/src/tools/cli.cpp @@ -7,6 +7,7 @@ #include "../core/common.hpp" #include "../core/host_manager.hpp" #include "../core/config.hpp" +#include "spdlog/spdlog.h" using namespace std; int main(int argc, char** argv) { @@ -21,16 +22,16 @@ int main(int argc, char** argv) { PublicWalletAddress keyFromAddress = walletAddressFromPublicKey(stringToPublicKey(keys["publicKey"])); PublicWalletAddress statedFromAddress = stringToWalletAddress(keys["wallet"]); if (keyFromAddress != statedFromAddress) { - cout << "Wallet address does not match public key. Keyfile is likely corrupted." << endl; + spdlog::warn("Wallet address does not match public key. Keyfile is likely corrupted."); return 0; } } catch(...) { - cout << "Could not read ./keys.json" << endl; + spdlog::error("Could not read ./keys.json"); return 0; } if (keys.find("publicKey") == keys.end() || keys.find("privateKey") == keys.end()) { - cout << "Missing publicKey or privateKey in keys.json" << endl; + spdlog::error("Missing publicKey or privateKey in keys.json"); return 0; } @@ -49,7 +50,7 @@ int main(int argc, char** argv) { TransactionAmount amount; cin >> amount; if (cin.fail()) { - cout << "Invalid amount entered" << endl; + cerr << "Invalid amount entered" << endl; return 0; } @@ -57,7 +58,7 @@ int main(int argc, char** argv) { TransactionAmount fee; cin >> fee; if (cin.fail()) { - cout << "Invalid fee entered" << endl; + cerr << "Invalid fee entered" << endl; return 0; } diff --git a/src/tools/keygen.cpp b/src/tools/keygen.cpp index f39f6e63..432ac4c6 100644 --- a/src/tools/keygen.cpp +++ b/src/tools/keygen.cpp @@ -4,17 +4,18 @@ #include #include #include +#include "spdlog/spdlog.h" #include "../core/crypto.hpp" using namespace std; int main(int argc, char** argv) { - cout<<"=====GENERATE WALLET===="< 1) { filename = string(argv[1]); } - cout<<"Output will be written to ["< pair = generateKeyPair(); PublicKey publicKey = pair.first; @@ -29,11 +30,11 @@ int main(int argc, char** argv) { cout<<"Public Key :"< using namespace std; int main(int argc, char** argv) { - cout<<"=====LOAD BLOCKCHAIN===="<addBlock(b); - cout<<"Added block: " << data.dump() << endl; + spdlog::info("Added block: {}", data.dump()); } catch (...){ - cout<<"Error parsing data file. Please delete data dir and try again"< #include #include @@ -44,7 +44,7 @@ void get_work(PublicWalletAddress wallet, HostManager& hosts, string& customHost } if (host == "") { - Logger::logStatus("no host found"); + spdlog::info("no host found"); return; } @@ -60,7 +60,7 @@ void get_work(PublicWalletAddress wallet, HostManager& hosts, string& customHost vector transactions; readRawTransactions(host, transactions); - Logger::logStatus("[ NEW ] block = " + std::to_string(nextBlock) + ", difficulty = " + to_string(problem["challengeSize"]) + ", transactions = " + to_string(transactions.size()) + " - " + host); + spdlog::info("[ NEW ] block = {}, difficulty = {}, transactions = {} - {}", std::to_string(nextBlock), to_string(problem["challengeSize"]), to_string(transactions.size()), host ); string lastHashStr = problem["lastHash"]; SHA256Hash lastHash = stringToSHA256(lastHashStr); @@ -105,22 +105,22 @@ void get_work(PublicWalletAddress wallet, HostManager& hosts, string& customHost SHA256Hash solution = mineHash(newBlock.getHash(), challengeSize, newBlock.getId() > PUFFERFISH_START_BLOCK); newBlock.setNonce(solution); - Logger::logStatus("Submitting block..."); + spdlog::info("Submitting block..."); auto result{ submitBlock(host, newBlock)}; if (!result.has_value()) throw std::runtime_error("Cannot submit block"); if (result->contains("status") && string((*result)["status"]) == "SUCCESS") { - Logger::logStatus(GREEN + "[ ACCEPTED ] " + RESET ); + spdlog::info("[ ACCEPTED ]"); } else { - Logger::logStatus(RED + "[ REJECTED ] " + RESET); - Logger::logStatus(result->dump(4)); + spdlog::error("[ REJECTED ]"); + spdlog::error(result->dump(4)); } std::this_thread::sleep_for(std::chrono::milliseconds(1000)); } catch (const std::exception& e) { - Logger::logStatus("Exception: "s+e.what()); + spdlog::error("Exception: "s+e.what()); std::this_thread::sleep_for(std::chrono::milliseconds(1000)); } } @@ -141,16 +141,16 @@ int main(int argc, char **argv) { try { keys = readJsonFromFile("./keys.json"); } catch(...) { - Logger::logStatus("Could not read ./keys.json"); + spdlog::error("Could not read ./keys.json"); return 0; } wallet = stringToWalletAddress(keys["wallet"]); - Logger::logStatus("Running miner. Coins stored in : " + string(keys["wallet"])); + spdlog::info("Running miner. Coins stored in : {}", string(keys["wallet"])); } else { wallet = stringToWalletAddress(customWallet); - Logger::logStatus("Running miner. Coins stored in : " + customWallet); + spdlog::info("Running miner. Coins stored in : {}", customWallet); } - Logger::logStatus("Starting miner on single thread"); + spdlog::info("Starting miner on single thread"); get_work(wallet, hosts, customIp); } diff --git a/src/tools/server.cpp b/src/tools/server.cpp index fd3dbbd7..8ae083c2 100644 --- a/src/tools/server.cpp +++ b/src/tools/server.cpp @@ -1,9 +1,11 @@ #include "../server/server.hpp" #include "../core/config.hpp" +#include "spdlog/spdlog.h" int main(int argc, char **argv) { srand(time(0)); json config = getConfig(argc, argv); + spdlog::info("Starting server"); PandaniteServer* server = new PandaniteServer(); server->run(config); }