From fa796a2eb593f60eb72679860e8d7c55ba3df0ab Mon Sep 17 00:00:00 2001 From: Nik Bougalis Date: Fri, 18 Sep 2015 12:15:12 -0700 Subject: [PATCH] Inject Config: * Use dependency injections instead * Remove deprecated fee interfaces --- src/ripple/app/ledger/Consensus.h | 3 +- src/ripple/app/ledger/Ledger.cpp | 65 +--- src/ripple/app/ledger/Ledger.h | 53 +-- src/ripple/app/ledger/OrderBookDB.cpp | 2 +- src/ripple/app/ledger/impl/ConsensusImp.cpp | 9 +- src/ripple/app/ledger/impl/ConsensusImp.h | 2 +- src/ripple/app/ledger/impl/InboundLedger.cpp | 14 +- .../app/ledger/impl/LedgerConsensusImp.cpp | 20 +- src/ripple/app/ledger/impl/LedgerMaster.cpp | 6 +- src/ripple/app/main/Application.cpp | 109 +++--- src/ripple/app/main/Application.h | 2 +- src/ripple/app/main/LocalCredentials.cpp | 12 +- src/ripple/app/main/Main.cpp | 316 +++++++++--------- src/ripple/app/misc/FeeVoteImpl.cpp | 18 +- src/ripple/app/misc/NetworkOPs.cpp | 40 +-- src/ripple/app/misc/SHAMapStoreImp.cpp | 23 +- src/ripple/app/misc/UniqueNodeList.cpp | 36 +- src/ripple/app/paths/PathRequest.cpp | 18 +- src/ripple/app/tx/impl/Payment.cpp | 2 +- src/ripple/app/tx/impl/Transaction.cpp | 3 +- src/ripple/basics/BasicConfig.h | 2 +- src/ripple/basics/Sustain.h | 6 +- src/ripple/basics/impl/Sustain.cpp | 6 +- src/ripple/core/Config.h | 63 ++-- src/ripple/core/ConfigSections.h | 2 - src/ripple/core/impl/Config.cpp | 70 +--- src/ripple/core/tests/LoadFeeTrack.test.cpp | 1 - src/ripple/ledger/tests/SkipList_test.cpp | 2 +- src/ripple/ledger/tests/View_test.cpp | 6 +- src/ripple/net/HTTPClient.h | 3 +- src/ripple/net/RPCCall.h | 35 +- src/ripple/net/RPCSub.h | 15 +- src/ripple/net/impl/HTTPClient.cpp | 28 +- src/ripple/net/impl/RPCCall.cpp | 29 +- src/ripple/net/impl/RPCSub.cpp | 14 +- .../nodestore/backend/RocksDBFactory.cpp | 17 +- src/ripple/overlay/impl/OverlayImpl.cpp | 16 +- src/ripple/overlay/impl/PeerImp.cpp | 4 +- src/ripple/rpc/handlers/Connect.cpp | 2 +- src/ripple/rpc/handlers/LedgerAccept.cpp | 2 +- src/ripple/rpc/handlers/RipplePathFind.cpp | 4 +- src/ripple/rpc/handlers/SignFor.cpp | 2 +- src/ripple/rpc/handlers/SubmitMultiSigned.cpp | 2 +- src/ripple/rpc/handlers/Subscribe.cpp | 16 +- src/ripple/rpc/handlers/UnlLoad.cpp | 4 +- src/ripple/rpc/handlers/ValidationSeed.cpp | 60 ++-- src/ripple/rpc/impl/LookupLedger.cpp | 8 +- src/ripple/rpc/impl/RPCHandler.cpp | 2 +- src/ripple/rpc/impl/TransactionSign.cpp | 17 +- src/ripple/rpc/impl/TransactionSign.h | 1 + src/ripple/rpc/tests/JSONRPC.test.cpp | 10 +- src/ripple/server/impl/JSONRPCUtil.cpp | 2 +- src/ripple/test/jtx/Env.h | 1 - src/ripple/test/jtx/impl/Env.cpp | 3 +- src/ripple/websocket/Connection.h | 5 + src/ripple/websocket/WebSocket02.cpp | 9 +- src/ripple/websocket/WebSocket04.cpp | 7 +- 57 files changed, 541 insertions(+), 688 deletions(-) diff --git a/src/ripple/app/ledger/Consensus.h b/src/ripple/app/ledger/Consensus.h index c1cf7e523f..7d329088a4 100644 --- a/src/ripple/app/ledger/Consensus.h +++ b/src/ripple/app/ledger/Consensus.h @@ -25,6 +25,7 @@ #include #include #include +#include #include // @@ -84,7 +85,7 @@ public: }; std::unique_ptr -make_Consensus (); +make_Consensus (Config const& config); } diff --git a/src/ripple/app/ledger/Ledger.cpp b/src/ripple/app/ledger/Ledger.cpp index 12d331507e..95d7db431c 100644 --- a/src/ripple/app/ledger/Ledger.cpp +++ b/src/ripple/app/ledger/Ledger.cpp @@ -190,7 +190,7 @@ Ledger::Ledger (create_genesis_t, Config const& config, Family& family) stateMap_->flushDirty (hotACCOUNT_NODE, info_.seq); updateHash(); setClosed(); - setImmutable(); + setImmutable(config); setup(config); } @@ -243,11 +243,11 @@ Ledger::Ledger (uint256 const& parentHash, if (! setup(config)) loaded = false; - + if (! loaded) { updateHash (); - getApp().family().missing_node (info_.hash); + family.missing_node (info_.hash); } } @@ -335,7 +335,7 @@ Ledger::~Ledger () { } -void Ledger::setImmutable () +void Ledger::setImmutable (Config const& config) { // Force update, since this is the only // place the hash transitions to valid @@ -346,7 +346,7 @@ void Ledger::setImmutable () txMap_->setImmutable (); if (stateMap_) stateMap_->setImmutable (); - setup(getConfig ()); + setup(config); } void Ledger::updateHash() @@ -406,7 +406,8 @@ void Ledger::addRaw (Serializer& s) const } void Ledger::setAccepted ( - std::uint32_t closeTime, int closeResolution, bool correctCloseTime) + std::uint32_t closeTime, int closeResolution, bool correctCloseTime, + Config const& config) { // Used when we witnessed the consensus. Rounds the close time, updates the // hash, and sets the ledger accepted and immutable. @@ -415,7 +416,7 @@ void Ledger::setAccepted ( info_.closeTime = closeTime; info_.closeTimeResolution = closeResolution; info_.closeFlags = correctCloseTime ? 0 : sLCF_NoConsensusTime; - setImmutable (); + setImmutable (config); } bool Ledger::addSLE (SLE const& sle) @@ -1178,46 +1179,6 @@ qualityDirDescriber ( } } -void Ledger::deprecatedUpdateCachedFees() const -{ - if (mBaseFee) - return; - std::uint64_t baseFee = getConfig ().FEE_DEFAULT; - std::uint32_t referenceFeeUnits = getConfig ().TRANSACTION_FEE_BASE; - std::uint32_t reserveBase = getConfig ().FEE_ACCOUNT_RESERVE; - std::int64_t reserveIncrement = getConfig ().FEE_OWNER_RESERVE; - - // VFALCO NOTE this doesn't go through the CachedSLEs - auto const sle = this->read(keylet::fees()); - if (sle) - { - if (sle->getFieldIndex (sfBaseFee) != -1) - baseFee = sle->getFieldU64 (sfBaseFee); - - if (sle->getFieldIndex (sfReferenceFeeUnits) != -1) - referenceFeeUnits = sle->getFieldU32 (sfReferenceFeeUnits); - - if (sle->getFieldIndex (sfReserveBase) != -1) - reserveBase = sle->getFieldU32 (sfReserveBase); - - if (sle->getFieldIndex (sfReserveIncrement) != -1) - reserveIncrement = sle->getFieldU32 (sfReserveIncrement); - } - - { - // VFALCO Why not do this before calling getASNode? - std::lock_guard< - std::mutex> lock(mutex_); - if (mBaseFee == 0) - { - mBaseFee = baseFee; - mReferenceFeeUnits = referenceFeeUnits; - mReserveBase = reserveBase; - mReserveIncrement = reserveIncrement; - } - } -} - std::vector Ledger::getNeededTransactionHashes ( int max, SHAMapSyncFilter* filter) const @@ -1325,7 +1286,7 @@ loadLedgerHelper(std::string const& sqlSuffix, Application& app) closeResolution.value_or(0), ledgerSeq, loaded, - getConfig(), + app.config(), app.family()); if (!loaded) @@ -1334,13 +1295,13 @@ loadLedgerHelper(std::string const& sqlSuffix, Application& app) return std::make_tuple (ledger, ledgerSeq, ledgerHash); } -void finishLoadByIndexOrHash(Ledger::pointer& ledger) +void finishLoadByIndexOrHash(Ledger::pointer& ledger, Config const& config) { if (!ledger) return; ledger->setClosed (); - ledger->setImmutable (); + ledger->setImmutable (config); WriteLog (lsTRACE, Ledger) << "Loaded ledger: " << to_string (ledger->getHash ()); @@ -1359,7 +1320,7 @@ loadByIndex (std::uint32_t ledgerIndex, Application& app) loadLedgerHelper (s.str (), app); } - finishLoadByIndexOrHash (ledger); + finishLoadByIndexOrHash (ledger, app.config()); return ledger; } @@ -1374,7 +1335,7 @@ loadByHash (uint256 const& ledgerHash, Application& app) loadLedgerHelper (s.str (), app); } - finishLoadByIndexOrHash (ledger); + finishLoadByIndexOrHash (ledger, app.config()); assert (!ledger || ledger->getHash () == ledgerHash); diff --git a/src/ripple/app/ledger/Ledger.h b/src/ripple/app/ledger/Ledger.h index 17a55ee05f..fa974983d8 100644 --- a/src/ripple/app/ledger/Ledger.h +++ b/src/ripple/app/ledger/Ledger.h @@ -237,9 +237,10 @@ public: } void setAccepted (std::uint32_t closeTime, - int closeResolution, bool correctCloseTime); + int closeResolution, bool correctCloseTime, + Config const& config); - void setImmutable (); + void setImmutable (Config const& config); bool isImmutable () const { @@ -329,36 +330,6 @@ public: std::vector getNeededAccountStateHashes ( int max, SHAMapSyncFilter* filter) const; - std::uint32_t getReferenceFeeUnits() const - { - // Returns the cost of the reference transaction in fee units - deprecatedUpdateCachedFees (); - return mReferenceFeeUnits; - } - - std::uint64_t getBaseFee() const - { - // Returns the cost of the reference transaction in drops - deprecatedUpdateCachedFees (); - return mBaseFee; - } - - // DEPRECATED use fees() - std::uint64_t getReserve (int increments) const - { - // Returns the required reserve in drops - deprecatedUpdateCachedFees (); - return static_cast (increments) * mReserveIncrement - + mReserveBase; - } - - // DEPRECATED use fees() - std::uint64_t getReserveInc () const - { - deprecatedUpdateCachedFees (); - return mReserveIncrement; - } - bool walkLedger () const; bool assertSane (); @@ -378,13 +349,6 @@ private: void updateHash(); - // Updates the fees cached in the ledger. - // Safe to call concurrently. We shouldn't be storing - // fees in the Ledger object, they should be a local side-structure - // associated with a particular module (rpc, tx processing, consensus) - // - void deprecatedUpdateCachedFees() const; - // The basic Ledger structure, can be opened, closed, or synching bool mValidHash = false; @@ -399,17 +363,6 @@ private: Fees fees_; Rules rules_; LedgerInfo info_; - - // Ripple cost of the reference transaction - std::uint64_t mutable mBaseFee = 0; - - // Fee units for the reference transaction - std::uint32_t mutable mReferenceFeeUnits = 0; - - // Reserve base in drops - std::uint32_t mutable mReserveBase = 0; - // Reserve increment in drops - std::uint32_t mutable mReserveIncrement = 0; }; /** A ledger wrapped in a CachedView. */ diff --git a/src/ripple/app/ledger/OrderBookDB.cpp b/src/ripple/app/ledger/OrderBookDB.cpp index a31d0895ec..513ecd266e 100644 --- a/src/ripple/app/ledger/OrderBookDB.cpp +++ b/src/ripple/app/ledger/OrderBookDB.cpp @@ -65,7 +65,7 @@ void OrderBookDB::setup( mSeq = seq; } - if (getConfig().RUN_STANDALONE) + if (app_.config().RUN_STANDALONE) update(ledger); else app_.getJobQueue().addJob( diff --git a/src/ripple/app/ledger/impl/ConsensusImp.cpp b/src/ripple/app/ledger/impl/ConsensusImp.cpp index c990d7cf0d..addeddbb86 100644 --- a/src/ripple/app/ledger/impl/ConsensusImp.cpp +++ b/src/ripple/app/ledger/impl/ConsensusImp.cpp @@ -26,9 +26,9 @@ namespace ripple { -ConsensusImp::ConsensusImp () +ConsensusImp::ConsensusImp (FeeVote::Setup const& voteSetup) : journal_ (deprecatedLogs().journal("Consensus")) - , feeVote_ (make_FeeVote (setup_FeeVote (getConfig().section ("voting")), + , feeVote_ (make_FeeVote (voteSetup, deprecatedLogs().journal("FeeVote"))) , proposing_ (false) , validating_ (false) @@ -174,9 +174,10 @@ ConsensusImp::peekStoredProposals () //============================================================================== std::unique_ptr -make_Consensus () +make_Consensus (Config const& config) { - return std::make_unique (); + return std::make_unique ( + setup_FeeVote (config.section ("voting"))); } } diff --git a/src/ripple/app/ledger/impl/ConsensusImp.h b/src/ripple/app/ledger/impl/ConsensusImp.h index dcab04f9ca..26ab2ae2e3 100644 --- a/src/ripple/app/ledger/impl/ConsensusImp.h +++ b/src/ripple/app/ledger/impl/ConsensusImp.h @@ -35,7 +35,7 @@ class ConsensusImp : public Consensus { public: - ConsensusImp (); + ConsensusImp (FeeVote::Setup const& voteSetup); ~ConsensusImp () = default; diff --git a/src/ripple/app/ledger/impl/InboundLedger.cpp b/src/ripple/app/ledger/impl/InboundLedger.cpp index 2b8adc47d1..fe1ec63800 100644 --- a/src/ripple/app/ledger/impl/InboundLedger.cpp +++ b/src/ripple/app/ledger/impl/InboundLedger.cpp @@ -129,7 +129,7 @@ void InboundLedger::init (ScopedLockType& collectionLock) if (m_journal.debug) m_journal.debug << "Acquiring ledger we already have locally: " << getHash (); mLedger->setClosed (); - mLedger->setImmutable (); + mLedger->setImmutable (app_.config()); if (mReason != fcHISTORY) app_.getLedgerMaster ().storeLedger (mLedger); @@ -166,7 +166,8 @@ bool InboundLedger::tryLocal () if (m_journal.trace) m_journal.trace << "Ledger header found in fetch pack"; mLedger = std::make_shared ( - data.data(), data.size(), true, getConfig(), app_.family()); + data.data(), data.size(), true, + app_.config(), app_.family()); app_.getNodeStore ().store ( hotLEDGER, std::move (data), mHash); } @@ -174,7 +175,7 @@ bool InboundLedger::tryLocal () { mLedger = std::make_shared( node->getData().data(), node->getData().size(), - true, getConfig(), app_.family()); + true, app_.config(), app_.family()); } if (mLedger->getHash () != mHash) @@ -250,7 +251,7 @@ bool InboundLedger::tryLocal () "Had everything locally"; mComplete = true; mLedger->setClosed (); - mLedger->setImmutable (); + mLedger->setImmutable (app_.config()); } return mComplete; @@ -363,7 +364,7 @@ void InboundLedger::done () if (isComplete () && !isFailed () && mLedger) { mLedger->setClosed (); - mLedger->setImmutable (); + mLedger->setImmutable (app_.config()); if (mReason != fcHISTORY) app_.getLedgerMaster ().storeLedger (mLedger); app_.getInboundLedgers().onLedgerFetched(mReason); @@ -769,7 +770,8 @@ bool InboundLedger::takeHeader (std::string const& data) return true; mLedger = std::make_shared( - data.data(), data.size(), false, getConfig(), app_.family()); + data.data(), data.size(), false, + app_.config(), app_.family()); if (mLedger->getHash () != mHash) { diff --git a/src/ripple/app/ledger/impl/LedgerConsensusImp.cpp b/src/ripple/app/ledger/impl/LedgerConsensusImp.cpp index d604a88256..8583bf4bb5 100644 --- a/src/ripple/app/ledger/impl/LedgerConsensusImp.cpp +++ b/src/ripple/app/ledger/impl/LedgerConsensusImp.cpp @@ -228,8 +228,8 @@ LedgerConsensusImp::LedgerConsensusImp ( , mCloseTime (closeTime) , mPrevLedgerHash (prevLCLHash) , mPreviousLedger (previousLedger) - , mValPublic (getConfig ().VALIDATION_PUB) - , mValPrivate (getConfig ().VALIDATION_PRIV) + , mValPublic (app_.config().VALIDATION_PUB) + , mValPrivate (app_.config().VALIDATION_PRIV) , mConsensusFail (false) , mCurrentMSeconds (0) , mClosePercent (0) @@ -722,7 +722,7 @@ void LedgerConsensusImp::timerEntry () void LedgerConsensusImp::statePreClose () { // it is shortly before ledger close time - bool anyTransactions = ! getApp().openLedger().empty(); + bool anyTransactions = ! app_.openLedger().empty(); int proposersClosed = mPeerPositions.size (); int proposersValidated = app_.getValidations ().getTrustedValidationCount @@ -1061,7 +1061,7 @@ void LedgerConsensusImp::accept (std::shared_ptr set) tmf << " transaction nodes"; // Accept ledger - newLCL->setAccepted (closeTime, mCloseResolution, closeTimeCorrect); + newLCL->setAccepted (closeTime, mCloseResolution, closeTimeCorrect, app_.config()); // And stash the ledger in the ledger master if (ledgerMaster_.storeLedger (newLCL)) @@ -1199,7 +1199,7 @@ void LedgerConsensusImp::accept (std::shared_ptr set) state_ = State::accepted; assert (ledgerMaster_.getClosedLedger()->getHash() == newLCL->getHash()); - assert (getApp().openLedger().current()->info().parentHash == newLCL->getHash()); + assert (app_.openLedger().current()->info().parentHash == newLCL->getHash()); if (mValidating) { @@ -1424,7 +1424,7 @@ void LedgerConsensusImp::takeInitialPosition ( std::shared_ptr const& initialLedger) { std::shared_ptr initialSet = std::make_shared ( - SHAMapType::TRANSACTION, getApp().family(), deprecatedLogs().journal("SHAMap")); + SHAMapType::TRANSACTION, app_.family(), deprecatedLogs().journal("SHAMap")); // Build SHAMap containing all transactions in our open ledger for (auto const& tx : initialLedger->txs) @@ -1435,11 +1435,11 @@ void LedgerConsensusImp::takeInitialPosition ( SHAMapItem (tx.first->getTransactionID(), std::move (s)), true, false); } - if ((getConfig ().RUN_STANDALONE || (mProposing && mHaveCorrectLCL)) + if ((app_.config().RUN_STANDALONE || (mProposing && mHaveCorrectLCL)) && ((mPreviousLedger->info().seq % 256) == 0)) { // previous ledger was flag ledger, add pseudo-transactions - ValidationSet parentSet = getApp().getValidations().getValidations ( + ValidationSet parentSet = app_.getValidations().getValidations ( mPreviousLedger->info().parentHash); m_feeVote.doVoting (mPreviousLedger, parentSet, initialSet); app_.getAmendmentTable ().doVoting ( @@ -1706,7 +1706,7 @@ void LedgerConsensusImp::closeLedger () consensus_.setLastCloseTime (mCloseTime); statusChange (protocol::neCLOSING_LEDGER, *mPreviousLedger); ledgerMaster_.applyHeldTransactions (); - takeInitialPosition (getApp().openLedger().current()); + takeInitialPosition (app_.openLedger().current()); } void LedgerConsensusImp::checkOurValidation () @@ -1829,7 +1829,7 @@ applyTransaction (Application& app, OpenView& view, { auto const result = apply(app, view, *txn, flags, app.getHashRouter().sigVerify(), - getConfig(), deprecatedLogs(). + app.config(), deprecatedLogs(). journal("LedgerConsensus")); if (result.second) { diff --git a/src/ripple/app/ledger/impl/LedgerMaster.cpp b/src/ripple/app/ledger/impl/LedgerMaster.cpp index f44ef6b339..ea5cdccb2f 100644 --- a/src/ripple/app/ledger/impl/LedgerMaster.cpp +++ b/src/ripple/app/ledger/impl/LedgerMaster.cpp @@ -181,7 +181,7 @@ public: LedgerIndex getCurrentLedgerIndex () override { - return getApp().openLedger().current()->info().seq; + return app_.openLedger().current()->info().seq; } LedgerIndex getValidLedgerIndex () override @@ -388,7 +388,7 @@ public: // VFALCO NOTE The hash for an open ledger is undefined so we use // something that is a reasonable substitute. mHeldTransactions.reset ( - getApp().openLedger().current()->info().parentHash); + app_.openLedger().current()->info().parentHash); } LedgerIndex getBuildingLedger () override @@ -1188,7 +1188,7 @@ public: } else if (mPathFindNewRequest) { // We have a new request but no new ledger - lastLedger = getApp().openLedger().current(); + lastLedger = app_.openLedger().current(); } else { // Nothing to do diff --git a/src/ripple/app/main/Application.cpp b/src/ripple/app/main/Application.cpp index 8ffc90d6d7..539d32c49e 100644 --- a/src/ripple/app/main/Application.cpp +++ b/src/ripple/app/main/Application.cpp @@ -301,7 +301,7 @@ private: }; public: - Config const& config_; + std::unique_ptr config_; Logs& m_logs; beast::Journal m_journal; Application::MutexType m_masterMutex; @@ -375,10 +375,10 @@ public: //-------------------------------------------------------------------------- - ApplicationImp (Config const& config, Logs& logs) + ApplicationImp (std::unique_ptr config, Logs& logs) : RootStoppable ("Application") - , BasicApp (numberOfThreads(config)) - , config_ (config) + , BasicApp (numberOfThreads(*config)) + , config_ (std::move(config)) , m_logs (logs) , m_journal (m_logs.journal("Application")) @@ -390,10 +390,10 @@ public: , m_nodeStoreScheduler (*this) - , m_shaMapStore (make_SHAMapStore (*this, setup_SHAMapStore ( - config_), *this, m_nodeStoreScheduler, - m_logs.journal ("SHAMapStore"), m_logs.journal ("NodeObject"), - m_txMaster, config_)) + , m_shaMapStore (make_SHAMapStore (*this, setup_SHAMapStore (*config_), + *this, m_nodeStoreScheduler, + m_logs.journal ("SHAMapStore"), m_logs.journal ("NodeObject"), + m_txMaster, *config_)) , m_nodeStore (m_shaMapStore->makeDatabase ("NodeStore.main", 4)) @@ -403,7 +403,7 @@ public: m_logs.journal("TaggedCache")) , m_collectorManager (CollectorManager::New ( - config_.section (SECTION_INSIGHT), m_logs.journal("Collector"))) + config_->section (SECTION_INSIGHT), m_logs.journal("Collector"))) , family_ (*this, *m_nodeStore, *m_collectorManager) @@ -453,7 +453,7 @@ public: m_logs.journal("TaggedCache")) , m_networkOPs (make_NetworkOPs (*this, stopwatch(), - config_.RUN_STANDALONE, config_.NETWORK_QUORUM, + config_->RUN_STANDALONE, config_->NETWORK_QUORUM, *m_jobQueue, *m_ledgerMaster, *m_jobQueue, m_logs.journal("NetworkOPs"))) @@ -548,7 +548,7 @@ public: Config const& config() const override { - return config_; + return *config_; } boost::asio::io_service& getIOService () override @@ -723,7 +723,7 @@ public: assert (mLedgerDB.get () == nullptr); assert (mWalletDB.get () == nullptr); - DatabaseCon::Setup setup = setup_DatabaseCon (config_); + DatabaseCon::Setup setup = setup_DatabaseCon (*config_); mTxnDB = std::make_unique (setup, "transaction.db", TxnDBInit, TxnDBCount); mLedgerDB = std::make_unique (setup, "ledger.db", @@ -763,7 +763,7 @@ public: void setup () override { // VFALCO NOTE: 0 means use heuristics to determine the thread count. - m_jobQueue->setThreadCount (0, config_.RUN_STANDALONE); + m_jobQueue->setThreadCount (0, config_->RUN_STANDALONE); // We want to intercept and wait for CTRL-C to terminate the process m_signals.add (SIGINT); @@ -773,7 +773,7 @@ public: assert (mTxnDB == nullptr); - auto debug_log = config_.getDebugLogFile (); + auto debug_log = config_->getDebugLogFile (); if (!debug_log.empty ()) { @@ -787,8 +787,8 @@ public: m_logs.severity (beast::Journal::kDebug); } - if (!config_.RUN_STANDALONE) - timeKeeper_->run(config_.SNTP_SERVERS); + if (!config_->RUN_STANDALONE) + timeKeeper_->run(config_->SNTP_SERVERS); if (!initSqliteDbs ()) { @@ -798,25 +798,25 @@ public: getLedgerDB ().getSession () << boost::str (boost::format ("PRAGMA cache_size=-%d;") % - (config_.getSize (siLgrDBCache) * 1024)); + (config_->getSize (siLgrDBCache) * 1024)); getTxnDB ().getSession () << boost::str (boost::format ("PRAGMA cache_size=-%d;") % - (config_.getSize (siTxnDBCache) * 1024)); + (config_->getSize (siTxnDBCache) * 1024)); mTxnDB->setupCheckpointing (m_jobQueue.get()); mLedgerDB->setupCheckpointing (m_jobQueue.get()); - if (!config_.RUN_STANDALONE) + if (!config_->RUN_STANDALONE) updateTables (); m_amendmentTable->addInitial ( - config_.section (SECTION_AMENDMENTS)); + config_->section (SECTION_AMENDMENTS)); initializePathfinding (); - m_ledgerMaster->setMinValidations (config_.VALIDATION_QUORUM); + m_ledgerMaster->setMinValidations (config_->VALIDATION_QUORUM); - auto const startUp = config_.START_UP; + auto const startUp = config_->START_UP; if (startUp == Config::FRESH) { m_journal.info << "Starting new Ledger"; @@ -829,7 +829,7 @@ public: { m_journal.info << "Loading specified Ledger"; - if (!loadOldLedger (config_.START_LEDGER, + if (!loadOldLedger (config_->START_LEDGER, startUp == Config::REPLAY, startUp == Config::LOAD_FILE)) { @@ -839,7 +839,7 @@ public: else if (startUp == Config::NETWORK) { // This should probably become the default once we have a stable network. - if (!config_.RUN_STANDALONE) + if (!config_->RUN_STANDALONE) m_networkOPs->needNetworkLedger (); startGenesisLedger (); @@ -862,14 +862,14 @@ public: // // Set up UNL. // - if (!config_.RUN_STANDALONE) + if (!config_->RUN_STANDALONE) getUNL ().nodeBootstrap (); - mValidations->tune (config_.getSize (siValidationsSize), config_.getSize (siValidationsAge)); - m_nodeStore->tune (config_.getSize (siNodeCacheSize), config_.getSize (siNodeCacheAge)); - m_ledgerMaster->tune (config_.getSize (siLedgerSize), config_.getSize (siLedgerAge)); - family().treecache().setTargetSize (config_.getSize (siTreeCacheSize)); - family().treecache().setTargetAge (config_.getSize (siTreeCacheAge)); + mValidations->tune (config_->getSize (siValidationsSize), config_->getSize (siValidationsAge)); + m_nodeStore->tune (config_->getSize (siNodeCacheSize), config_->getSize (siNodeCacheAge)); + m_ledgerMaster->tune (config_->getSize (siLedgerSize), config_->getSize (siLedgerAge)); + family().treecache().setTargetSize (config_->getSize (siTreeCacheSize)); + family().treecache().setTargetAge (config_->getSize (siTreeCacheAge)); //---------------------------------------------------------------------- // @@ -882,15 +882,15 @@ public: // move the instantiation inside a conditional: // // if (!config_.RUN_STANDALONE) - m_overlay = make_Overlay (*this, setup_Overlay(config_), *m_jobQueue, + m_overlay = make_Overlay (*this, setup_Overlay(*config_), *m_jobQueue, *serverHandler_, *m_resourceManager, *m_resolver, get_io_service(), - config_); + *config_); add (*m_overlay); // add to PropertyStream - m_overlay->setupValidatorKeyManifests (config_, getWalletDB ()); + m_overlay->setupValidatorKeyManifests (*config_, getWalletDB ()); { - auto setup = setup_ServerHandler(config_, std::cerr); + auto setup = setup_ServerHandler(*config_, std::cerr); setup.makeContexts(); serverHandler_->setup (setup, m_journal); } @@ -901,7 +901,7 @@ public: if (! port.websockets()) continue; auto server = websocket::makeServer ( - {*this, port, *m_resourceManager, getOPs(), m_journal, config_, + {*this, port, *m_resourceManager, getOPs(), m_journal, *config_, *m_collectorManager}); if (!server) { @@ -915,11 +915,11 @@ public: //---------------------------------------------------------------------- // Begin connecting to network. - if (!config_.RUN_STANDALONE) + if (!config_->RUN_STANDALONE) { // Should this message be here, conceptually? In theory this sort // of message, if displayed, should be displayed from PeerFinder. - if (config_.PEER_PRIVATE && config_.IPS.empty ()) + if (config_->PEER_PRIVATE && config_->IPS.empty ()) m_journal.warning << "No outbound peer connections will be made"; // VFALCO NOTE the state timer resets the deadlock detector. @@ -1011,7 +1011,7 @@ public: { - if (!config_.RUN_STANDALONE) + if (!config_->RUN_STANDALONE) { // VFALCO NOTE This seems unnecessary. If we properly refactor the load // manager then the deadlock detector can just always be "armed" @@ -1058,7 +1058,7 @@ public: // VFALCO TODO Move all this into doSweep boost::filesystem::space_info space = - boost::filesystem::space (config_.legacy ("database_path")); + boost::filesystem::space (config_->legacy ("database_path")); // VFALCO TODO Give this magic constant a name and move it into a well documented header // @@ -1090,7 +1090,7 @@ public: cachedSLEs_.expire(); // VFALCO NOTE does the call to sweep() happen on another thread? - m_sweepTimer.setExpiration (config_.getSize (siSweepInterval)); + m_sweepTimer.setExpiration (config_->getSize (siSweepInterval)); } @@ -1111,18 +1111,16 @@ void ApplicationImp::startGenesisLedger () { std::shared_ptr const genesis = std::make_shared( - create_genesis, config_, family()); + create_genesis, *config_, family()); m_ledgerMaster->storeLedger (genesis); auto const next = std::make_shared( open_ledger, *genesis, timeKeeper().closeTime()); next->updateSkipList (); next->setClosed (); - next->setImmutable (); - m_ledgerMaster->storeLedger (next); - + next->setImmutable (*config_); m_networkOPs->setLastCloseTime (next->info().closeTime); - openLedger_.emplace(next, config_, + openLedger_.emplace(next, *config_, cachedSLEs_, deprecatedLogs().journal("OpenLedger")); m_ledgerMaster->switchLCL (next); } @@ -1142,7 +1140,7 @@ ApplicationImp::getLastFullLedger() return ledger; ledger->setClosed (); - ledger->setImmutable(); + ledger->setImmutable(*config_); if (getLedgerMaster ().haveLedger (ledgerSeq)) ledger->setValidated (); @@ -1243,7 +1241,7 @@ bool ApplicationImp::loadOldLedger ( } else { - loadLedger = std::make_shared (seq, closeTime, config_, family()); + loadLedger = std::make_shared (seq, closeTime, *config_, family()); loadLedger->setTotalDrops(totalDrops); for (Json::UInt index = 0; index < ledger.get().size(); ++index) @@ -1276,7 +1274,8 @@ bool ApplicationImp::loadOldLedger ( loadLedger->stateMap().flushDirty (hotACCOUNT_NODE, loadLedger->info().seq); loadLedger->setAccepted (closeTime, - closeTimeResolution, ! closeTimeEstimated); + closeTimeResolution, ! closeTimeEstimated, + *config_); } } } @@ -1375,7 +1374,7 @@ bool ApplicationImp::loadOldLedger ( m_ledgerMaster->switchLCL (loadLedger); m_ledgerMaster->forceValid(loadLedger); m_networkOPs->setLastCloseTime (loadLedger->info().closeTime); - openLedger_.emplace(loadLedger, config_, + openLedger_.emplace(loadLedger, *config_, cachedSLEs_, deprecatedLogs().journal("OpenLedger")); if (replay) @@ -1589,7 +1588,7 @@ void ApplicationImp::addTxnSeqField () void ApplicationImp::updateTables () { - if (config_.section (ConfigSection::nodeDatabase ()).empty ()) + if (config_->section (ConfigSection::nodeDatabase ()).empty ()) { WriteLog (lsFATAL, Application) << "The [node_db] configuration setting has been updated and must be set"; exitWithCode(1); @@ -1606,13 +1605,13 @@ void ApplicationImp::updateTables () exitWithCode(1); } - if (config_.doImport) + if (config_->doImport) { NodeStore::DummyScheduler scheduler; std::unique_ptr source = NodeStore::Manager::instance().make_Database ("NodeStore.import", scheduler, deprecatedLogs().journal("NodeObject"), 0, - config_[ConfigSection::importNodeDatabase ()]); + config_->section(ConfigSection::importNodeDatabase ())); WriteLog (lsWARNING, NodeObject) << "Node import from '" << source->getName () << "' to '" @@ -1635,10 +1634,10 @@ Application::Application () } std::unique_ptr -make_Application (Config const& config, Logs& logs) +make_Application (std::unique_ptr config, Logs& logs) { - return std::make_unique( - config, logs); + return std::make_unique ( + std::move(config), logs); } Application& getApp () diff --git a/src/ripple/app/main/Application.h b/src/ripple/app/main/Application.h index 0a7bccef17..ad49368fc9 100644 --- a/src/ripple/app/main/Application.h +++ b/src/ripple/app/main/Application.h @@ -145,7 +145,7 @@ public: }; std::unique_ptr -make_Application(Config const& config, Logs& logs); +make_Application(std::unique_ptr config, Logs& logs); // DEPRECATED extern Application& getApp (); diff --git a/src/ripple/app/main/LocalCredentials.cpp b/src/ripple/app/main/LocalCredentials.cpp index 75d78741f7..84c7a49024 100644 --- a/src/ripple/app/main/LocalCredentials.cpp +++ b/src/ripple/app/main/LocalCredentials.cpp @@ -49,7 +49,7 @@ void LocalCredentials::start () throw std::runtime_error ("unable to retrieve new node identity."); } - if (!getConfig ().QUIET) + if (!app_.config().QUIET) std::cerr << "NodeIdentity: " << mNodePublicKey.humanNodePublic () << std::endl; app_.getUNL ().start (); @@ -76,10 +76,10 @@ bool LocalCredentials::nodeIdentityLoad () bSuccess = true; } - if (getConfig ().NODE_PUB.isValid () && getConfig ().NODE_PRIV.isValid ()) + if (app_.config().NODE_PUB.isValid () && app_.config().NODE_PRIV.isValid ()) { - mNodePublicKey = getConfig ().NODE_PUB; - mNodePrivateKey = getConfig ().NODE_PRIV; + mNodePublicKey = app_.config().NODE_PUB; + mNodePrivateKey = app_.config().NODE_PRIV; } return bSuccess; @@ -88,7 +88,7 @@ bool LocalCredentials::nodeIdentityLoad () // Create and store a network identity. bool LocalCredentials::nodeIdentityCreate () { - if (!getConfig ().QUIET) + if (!app_.config().QUIET) std::cerr << "NodeIdentity: Creating." << std::endl; // @@ -108,7 +108,7 @@ bool LocalCredentials::nodeIdentityCreate () % naNodePublic.humanNodePublic () % naNodePrivate.humanNodePrivate ()); - if (!getConfig ().QUIET) + if (!app_.config().QUIET) std::cerr << "NodeIdentity: Created." << std::endl; return true; diff --git a/src/ripple/app/main/Main.cpp b/src/ripple/app/main/Main.cpp index 2f87153081..80432a5c93 100644 --- a/src/ripple/app/main/Main.cpp +++ b/src/ripple/app/main/Main.cpp @@ -71,10 +71,12 @@ void setupServer (Application& app) } boost::filesystem::path -getEntropyFile() +getEntropyFile(Config const& config) { - return boost::filesystem::path ( - getConfig().legacy("database_path")) / "random.seed"; + auto const path = config.legacy("database_path"); + if (path.empty ()) + return {}; + return boost::filesystem::path (path) / "random.seed"; } void startServer (Application& app) @@ -82,13 +84,13 @@ void startServer (Application& app) // // Execute start up rpc commands. // - if (getConfig ().RPC_STARTUP.isArray ()) + if (app.config().RPC_STARTUP.isArray ()) { - for (int i = 0; i != getConfig ().RPC_STARTUP.size (); ++i) + for (int i = 0; i != app.config().RPC_STARTUP.size (); ++i) { - Json::Value const& jvCommand = getConfig ().RPC_STARTUP[i]; + Json::Value const& jvCommand = app.config().RPC_STARTUP[i]; - if (!getConfig ().QUIET) + if (!app.config().QUIET) std::cerr << "Startup RPC: " << jvCommand << std::endl; Resource::Charge loadType = Resource::feeReferenceRPC; @@ -99,7 +101,7 @@ void startServer (Application& app) Json::Value jvResult; RPC::doCommand (context, jvResult); - if (!getConfig ().QUIET) + if (!app.config().QUIET) std::cerr << "Result: " << jvResult << std::endl; } } @@ -108,7 +110,9 @@ void startServer (Application& app) app.run (); // Try to write out some entropy to use the next time we start. - stir_entropy (getEntropyFile ().string ()); + auto entropy = getEntropyFile (app.config()); + if (!entropy.empty ()) + stir_entropy (entropy.string ()); } void printHelp (const po::options_description& desc) @@ -169,18 +173,20 @@ setupConfigForUnitTests (Config& config) config.legacy("database_path", "DummyForUnitTests"); } -static int runShutdownTests () +static int runShutdownTests (std::unique_ptr config) { // Shutdown tests can not be part of the normal unit tests in 'runUnitTests' // because it needs to create and destroy an application object. - int const numShutdownIterations = 20; + // FIXME: we only loop once, since the Config object will get destroyed + int const numShutdownIterations = 1; //20; + // Give it enough time to sync and run a bit while synced. std::chrono::seconds const serverUptimePerIteration (4 * 60); for (int i = 0; i < numShutdownIterations; ++i) { std::cerr << "\n\nStarting server. Iteration: " << i << "\n" << std::endl; - std::unique_ptr app (make_Application (getConfig(), deprecatedLogs())); + auto app = make_Application (std::move(config), deprecatedLogs()); auto shutdownApp = [&app](std::chrono::seconds sleepTime, int iteration) { std::this_thread::sleep_for (sleepTime); @@ -196,13 +202,17 @@ static int runShutdownTests () return EXIT_SUCCESS; } -static int runUnitTests (std::string const& pattern, - std::string const& argument) +static int runUnitTests ( + std::unique_ptr config, + std::string const& pattern, + std::string const& argument) { // Config needs to be set up before creating Application - setupConfigForUnitTests (getConfig ()); + setupConfigForUnitTests (*config); + // VFALCO TODO Remove dependence on constructing Application object - std::unique_ptr app (make_Application (getConfig(), deprecatedLogs())); + auto app = make_Application (std::move(config), deprecatedLogs()); + using namespace beast::unit_test; beast::debug_ostream stream; reporter r (stream); @@ -224,7 +234,31 @@ int run (int argc, char** argv) using namespace std; setCallingThreadName ("main"); - int iResult = 0; + + { + // We want to seed the RNG early. We acquire a small amount of + // questionable quality entropy from the current time and our + // environment block which will get stirred into the RNG pool + // along with high-quality entropy from the system. + struct entropy_t + { + std::uint64_t timestamp; + std::size_t tid; + std::uintptr_t ptr[4]; + }; + + auto entropy = std::make_unique (); + + entropy->timestamp = beast::Time::currentTimeMillis (); + entropy->tid = std::hash () (std::this_thread::get_id ()); + entropy->ptr[0] = reinterpret_cast(entropy.get ()); + entropy->ptr[1] = reinterpret_cast(&argc); + entropy->ptr[2] = reinterpret_cast(argv); + entropy->ptr[3] = reinterpret_cast(argv[0]); + + add_entropy (entropy.get (), sizeof (entropy_t)); + } + po::variables_map vm; std::string importText; @@ -237,8 +271,6 @@ int run (int argc, char** argv) importText += "] configuration file section)."; } - // VFALCO TODO Replace boost program options with something from Beast. - // // Set up option parsing. // po::options_description desc ("General Options"); @@ -271,51 +303,27 @@ int run (int argc, char** argv) po::positional_options_description p; p.add ("parameters", -1); + // Parse options, if no error. + try { - // We want to seed the RNG early. We acquire a small amount of - // questionable quality entropy from the current time and our - // environment block which will get stirred into the RNG pool - // along with high-quality entropy from the system. - struct entropy_t - { - std::uint64_t timestamp; - std::size_t tid; - std::uintptr_t ptr[4]; - }; - - auto entropy = std::make_unique (); - - entropy->timestamp = beast::Time::currentTimeMillis (); - entropy->tid = std::hash () (std::this_thread::get_id ()); - entropy->ptr[0] = reinterpret_cast(entropy.get ()); - entropy->ptr[1] = reinterpret_cast(&argc); - entropy->ptr[2] = reinterpret_cast(argv); - entropy->ptr[3] = reinterpret_cast(argv[0]); - - add_entropy (entropy.get (), sizeof (entropy_t)); + po::store (po::command_line_parser (argc, argv) + .options (desc) // Parse options. + .positional (p) // Remainder as --parameters. + .run (), + vm); + po::notify (vm); // Invoke option notify functions. + } + catch (...) + { + std::cerr << "rippled: Incorrect command line syntax." << std::endl; + std::cerr << "Use '--help' for a list of options." << std::endl; + return 1; } - if (!iResult) + if (vm.count ("help")) { - // Parse options, if no error. - try - { - po::store (po::command_line_parser (argc, argv) - .options (desc) // Parse options. - .positional (p) // Remainder as --parameters. - .run (), - vm); - po::notify (vm); // Invoke option notify functions. - } - catch (...) - { - iResult = 1; - } - } - - if (!iResult && vm.count ("help")) - { - iResult = 1; + printHelp (desc); + return 0; } if (vm.count ("version")) @@ -328,31 +336,24 @@ int run (int argc, char** argv) // Use a watchdog process unless we're invoking a stand alone type of mode // if (HaveSustain () - && !iResult && !vm.count ("parameters") && !vm.count ("fg") && !vm.count ("standalone") && !vm.count ("shutdowntest") && !vm.count ("unittest")) { - std::string logMe = DoSustain (getConfig ().getDebugLogFile ().string()); + std::string logMe = DoSustain (); if (!logMe.empty ()) std::cerr << logMe; } if (vm.count ("quiet")) - { deprecatedLogs().severity(beast::Journal::kFatal); - } else if (vm.count ("verbose")) - { deprecatedLogs().severity(beast::Journal::kTrace); - } else - { deprecatedLogs().severity(beast::Journal::kInfo); - } // Run the unit tests if requested. // The unit tests will exit the application with an appropriate return code. @@ -364,136 +365,133 @@ int run (int argc, char** argv) if (vm.count("unittest-arg")) argument = vm["unittest-arg"].as(); - return runUnitTests(vm["unittest"].as(), argument); + return runUnitTests( + std::make_unique (), + vm["unittest"].as(), + argument); } - if (!iResult) + auto config = std::make_unique(); + + auto configFile = vm.count ("conf") ? + vm["conf"].as () : std::string(); + + // config file, quiet flag. + config->setup (configFile, bool (vm.count ("quiet"))); + + if (vm.count ("standalone")) { - auto configFile = vm.count ("conf") ? - vm["conf"].as () : std::string(); - - // config file, quiet flag. - getConfig ().setup (configFile, bool (vm.count ("quiet"))); - - if (vm.count ("standalone")) - { - getConfig ().RUN_STANDALONE = true; - getConfig ().LEDGER_HISTORY = 0; - } - - // Use any previously available entropy to stir the pool - stir_entropy (getEntropyFile ().string ()); + config->RUN_STANDALONE = true; + config->LEDGER_HISTORY = 0; } - if (vm.count ("start")) getConfig ().START_UP = Config::FRESH; + // Use any previously available entropy to stir the pool + auto entropy = getEntropyFile (*config); + if (!entropy.empty ()) + stir_entropy (entropy.string ()); + + if (vm.count ("start")) + config->START_UP = Config::FRESH; - // Handle a one-time import option - // if (vm.count ("import")) - { - getConfig ().doImport = true; - } + config->doImport = true; if (vm.count ("ledger")) { - getConfig ().START_LEDGER = vm["ledger"].as (); + config->START_LEDGER = vm["ledger"].as (); if (vm.count("replay")) - getConfig ().START_UP = Config::REPLAY; + config->START_UP = Config::REPLAY; else - getConfig ().START_UP = Config::LOAD; + config->START_UP = Config::LOAD; } else if (vm.count ("ledgerfile")) { - getConfig ().START_LEDGER = vm["ledgerfile"].as (); - getConfig ().START_UP = Config::LOAD_FILE; + config->START_LEDGER = vm["ledgerfile"].as (); + config->START_UP = Config::LOAD_FILE; } else if (vm.count ("load")) { - getConfig ().START_UP = Config::LOAD; + config->START_UP = Config::LOAD; } else if (vm.count ("net")) { - getConfig ().START_UP = Config::NETWORK; + config->START_UP = Config::NETWORK; - if (getConfig ().VALIDATION_QUORUM < 2) - getConfig ().VALIDATION_QUORUM = 2; + if (config->VALIDATION_QUORUM < 2) + config->VALIDATION_QUORUM = 2; } - if (iResult == 0) + // Override the RPC destination IP address. This must + // happen after the config file is loaded. + if (vm.count ("rpc_ip")) { - // These overrides must happen after the config file is loaded. - - // Override the RPC destination IP address - // - if (vm.count ("rpc_ip")) + try { - try - { - getConfig().rpc_ip = - boost::asio::ip::address_v4::from_string( - vm["rpc_ip"].as()); - } - catch(...) - { - std::cerr << - "Invalid rpc_ip = " << vm["rpc_ip"].as(); - return -1; - } + config->rpc_ip = + boost::asio::ip::address_v4::from_string( + vm["rpc_ip"].as()); } - - // Override the RPC destination port number - // - if (vm.count ("rpc_port")) + catch(...) { - try - { - getConfig().rpc_port = vm["rpc_port"].as(); - } - catch(...) - { - std::cerr << - "Invalid rpc_port = " << vm["rpc_port"].as(); - return -1; - } + std::cerr << "Invalid rpc_ip = " << + vm["rpc_ip"].as() << std::endl; + return -1; } + } - if (vm.count ("quorum")) + // Override the RPC destination port number + // + if (vm.count ("rpc_port")) + { + try { - getConfig ().VALIDATION_QUORUM = vm["quorum"].as (); + config->rpc_port = vm["rpc_port"].as(); - if (getConfig ().VALIDATION_QUORUM < 0) - iResult = 1; + if (*config->rpc_port == 0) + throw std::domain_error (""); + } + catch(...) + { + std::cerr << "Invalid rpc_port = " << + vm["rpc_port"].as() << std::endl; + return -1; + } + } + + if (vm.count ("quorum")) + { + try + { + config->VALIDATION_QUORUM = vm["quorum"].as (); + + if (config->VALIDATION_QUORUM < 0) + throw std::domain_error (""); + } + catch(...) + { + std::cerr << "Invalid quorum = " << + vm["quorum"].as () << std::endl; + return -1; } } if (vm.count ("shutdowntest")) + return runShutdownTests (std::move(config)); + + if (!vm.count ("parameters")) { - return runShutdownTests (); + // No arguments. Run server. + auto app = make_Application (std::move(config), deprecatedLogs()); + setupServer (*app); + startServer (*app); + return 0; } - if (iResult == 0) - { - if (!vm.count ("parameters")) - { - // No arguments. Run server. - std::unique_ptr app (make_Application (getConfig(), deprecatedLogs())); - setupServer (*app); - startServer (*app); - } - else - { - // Have a RPC command. - setCallingThreadName ("rpc"); - std::vector vCmd = vm["parameters"].as > (); - - iResult = RPCCall::fromCommandLine (vCmd); - } - } - - if (1 == iResult && !vm.count ("quiet")) - printHelp (desc); - - return iResult; + // We have an RPC command to process: + setCallingThreadName ("rpc"); + return RPCCall::fromCommandLine ( + *config, + vm["parameters"].as>()); } extern int run (int argc, char** argv); diff --git a/src/ripple/app/misc/FeeVoteImpl.cpp b/src/ripple/app/misc/FeeVoteImpl.cpp index a48bc4aaee..92ba91b75a 100644 --- a/src/ripple/app/misc/FeeVoteImpl.cpp +++ b/src/ripple/app/misc/FeeVoteImpl.cpp @@ -119,7 +119,7 @@ void FeeVoteImpl::doValidation (Ledger::ref lastClosedLedger, STObject& baseValidation) { - if (lastClosedLedger->getBaseFee () != target_.reference_fee) + if (lastClosedLedger->fees().base != target_.reference_fee) { if (journal_.info) journal_.info << "Voting for base fee of " << target_.reference_fee; @@ -127,7 +127,7 @@ FeeVoteImpl::doValidation (Ledger::ref lastClosedLedger, baseValidation.setFieldU64 (sfBaseFee, target_.reference_fee); } - if (lastClosedLedger->getReserve (0) != target_.account_reserve) + if (lastClosedLedger->fees().accountReserve(0) != target_.account_reserve) { if (journal_.info) journal_.info << "Voting for base resrve of " << target_.account_reserve; @@ -135,7 +135,7 @@ FeeVoteImpl::doValidation (Ledger::ref lastClosedLedger, baseValidation.setFieldU32(sfReserveBase, target_.account_reserve); } - if (lastClosedLedger->getReserveInc () != target_.owner_reserve) + if (lastClosedLedger->fees().increment != target_.owner_reserve) { if (journal_.info) journal_.info << "Voting for reserve increment of " << target_.owner_reserve; @@ -154,13 +154,13 @@ FeeVoteImpl::doVoting (Ledger::ref lastClosedLedger, assert ((lastClosedLedger->info().seq % 256) == 0); detail::VotableInteger baseFeeVote ( - lastClosedLedger->getBaseFee (), target_.reference_fee); + lastClosedLedger->fees().base, target_.reference_fee); detail::VotableInteger baseReserveVote ( - lastClosedLedger->getReserve (0), target_.account_reserve); + lastClosedLedger->fees().accountReserve(0).drops(), target_.account_reserve); detail::VotableInteger incReserveVote ( - lastClosedLedger->getReserveInc (), target_.owner_reserve); + lastClosedLedger->fees().increment, target_.owner_reserve); for (auto const& e : set) { @@ -203,9 +203,9 @@ FeeVoteImpl::doVoting (Ledger::ref lastClosedLedger, std::uint32_t const incReserve = incReserveVote.getVotes (); // add transactions to our position - if ((baseFee != lastClosedLedger->getBaseFee ()) || - (baseReserve != lastClosedLedger->getReserve (0)) || - (incReserve != lastClosedLedger->getReserveInc ())) + if ((baseFee != lastClosedLedger->fees().base) || + (baseReserve != lastClosedLedger->fees().accountReserve(0)) || + (incReserve != lastClosedLedger->fees().increment)) { if (journal_.warning) journal_.warning << "We are voting for a fee change: " << baseFee << diff --git a/src/ripple/app/misc/NetworkOPs.cpp b/src/ripple/app/misc/NetworkOPs.cpp index 2801de194f..23b4882e83 100644 --- a/src/ripple/app/misc/NetworkOPs.cpp +++ b/src/ripple/app/misc/NetworkOPs.cpp @@ -129,7 +129,7 @@ public: , m_amendmentBlocked (false) , m_heartbeatTimer (this) , m_clusterTimer (this) - , mConsensus (make_Consensus ()) + , mConsensus (make_Consensus (app_.config())) , m_ledgerMaster (ledgerMaster) , mLastLoadBase (256) , mLastLoadFactor (256) @@ -678,7 +678,7 @@ void NetworkOPsImp::submitTransaction (STTx::pointer iTrans) // Tell the call to checkSign() whether multisign is enabled. if (!passesLocalChecks (*trans, reason) || !trans->checkSign (m_ledgerMaster.getValidatedRules().enabled( - featureMultiSign, getConfig().features))) + featureMultiSign, app_.config().features))) { m_journal.warning << "Submitted transaction " << (reason.empty () ? "has bad signature" : "error: " + reason); @@ -845,7 +845,7 @@ void NetworkOPsImp::apply (std::unique_lock& batchLock) auto const result = ripple::apply(app_, view, *e.transaction->getSTransaction(), flags, app_.getHashRouter().sigVerify(), - getConfig(), j); + app_.config(), j); e.result = result.first; e.applied = result.second; return result.second; @@ -1321,7 +1321,7 @@ bool NetworkOPsImp::beginConsensus (uint256 const& networkClosed) // Create a consensus object to get consensus on this ledger assert (!mLedgerConsensus); - prevLedger->setImmutable (); + prevLedger->setImmutable (app_.config()); mLedgerConsensus = mConsensus->startRound ( app_, @@ -1838,10 +1838,10 @@ Json::Value NetworkOPsImp::getServerInfo (bool human, bool admin) if (admin) { - if (getConfig ().VALIDATION_PUB.isValid ()) + if (app_.config().VALIDATION_PUB.isValid ()) { info[jss::pubkey_validator] = - getConfig ().VALIDATION_PUB.humanNodePublic (); + app_.config().VALIDATION_PUB.humanNodePublic (); } else { @@ -1926,8 +1926,8 @@ Json::Value NetworkOPsImp::getServerInfo (bool human, bool admin) if (lpClosed) { - std::uint64_t baseFee = lpClosed->getBaseFee (); - std::uint64_t baseRef = lpClosed->getReferenceFeeUnits (); + std::uint64_t baseFee = lpClosed->fees().base; + std::uint64_t baseRef = lpClosed->fees().units; Json::Value l (Json::objectValue); l[jss::seq] = Json::UInt (lpClosed->info().seq); l[jss::hash] = to_string (lpClosed->getHash ()); @@ -1935,9 +1935,9 @@ Json::Value NetworkOPsImp::getServerInfo (bool human, bool admin) if (!human) { l[jss::base_fee] = Json::Value::UInt (baseFee); - l[jss::reserve_base] = Json::Value::UInt (lpClosed->getReserve (0)); + l[jss::reserve_base] = Json::Value::UInt (lpClosed->fees().accountReserve(0).drops()); l[jss::reserve_inc] = - Json::Value::UInt (lpClosed->getReserveInc ()); + Json::Value::UInt (lpClosed->fees().increment); l[jss::close_time] = Json::Value::UInt (lpClosed->info().closeTime); } @@ -1947,11 +1947,11 @@ Json::Value NetworkOPsImp::getServerInfo (bool human, bool admin) SYSTEM_CURRENCY_PARTS; l[jss::reserve_base_xrp] = static_cast (Json::UInt ( - lpClosed->getReserve (0) * baseFee / baseRef)) + lpClosed->fees().accountReserve(0).drops() * baseFee / baseRef)) / SYSTEM_CURRENCY_PARTS; l[jss::reserve_inc_xrp] = static_cast (Json::UInt ( - lpClosed->getReserveInc () * baseFee / baseRef)) + lpClosed->fees().increment * baseFee / baseRef)) / SYSTEM_CURRENCY_PARTS; auto const nowOffset = app_.timeKeeper().nowOffset(); @@ -2060,10 +2060,10 @@ void NetworkOPsImp::pubLedger (Ledger::ref lpAccepted) = Json::Value::UInt (lpAccepted->info().closeTime); jvObj[jss::fee_ref] - = Json::UInt (lpAccepted->getReferenceFeeUnits ()); - jvObj[jss::fee_base] = Json::UInt (lpAccepted->getBaseFee ()); - jvObj[jss::reserve_base] = Json::UInt (lpAccepted->getReserve (0)); - jvObj[jss::reserve_inc] = Json::UInt (lpAccepted->getReserveInc ()); + = Json::UInt (lpAccepted->fees().units); + jvObj[jss::fee_base] = Json::UInt (lpAccepted->fees().base); + jvObj[jss::reserve_base] = Json::UInt (lpAccepted->fees().accountReserve(0).drops()); + jvObj[jss::reserve_inc] = Json::UInt (lpAccepted->fees().increment); jvObj[jss::txn_count] = Json::UInt (alpAccepted->getTxnCount ()); @@ -2417,10 +2417,10 @@ bool NetworkOPsImp::subLedger (InfoSub::ref isrListener, Json::Value& jvResult) jvResult[jss::ledger_time] = Json::Value::UInt (lpClosed->info().closeTime); jvResult[jss::fee_ref] - = Json::UInt (lpClosed->getReferenceFeeUnits ()); - jvResult[jss::fee_base] = Json::UInt (lpClosed->getBaseFee ()); - jvResult[jss::reserve_base] = Json::UInt (lpClosed->getReserve (0)); - jvResult[jss::reserve_inc] = Json::UInt (lpClosed->getReserveInc ()); + = Json::UInt (lpClosed->fees().units); + jvResult[jss::fee_base] = Json::UInt (lpClosed->fees().base); + jvResult[jss::reserve_base] = Json::UInt (lpClosed->fees().accountReserve(0).drops()); + jvResult[jss::reserve_inc] = Json::UInt (lpClosed->fees().increment); } if ((mMode >= omSYNCING) && !isNeedNetworkLedger ()) diff --git a/src/ripple/app/misc/SHAMapStoreImp.cpp b/src/ripple/app/misc/SHAMapStoreImp.cpp index 5f7fee77c4..991e7591a3 100644 --- a/src/ripple/app/misc/SHAMapStoreImp.cpp +++ b/src/ripple/app/misc/SHAMapStoreImp.cpp @@ -671,19 +671,28 @@ setup_SHAMapStore (Config const& c) { SHAMapStore::Setup setup; - auto const& sec = c.section (ConfigSection::nodeDatabase ()); - get_if_exists (sec, "online_delete", setup.deleteInterval); + // Get existing settings and add some default values if not specified: + setup.nodeDatabase = c.section (ConfigSection::nodeDatabase ()); + + // These two parameters apply only to RocksDB. We want to give them sensible + // defaults if no values are specified. + if (!setup.nodeDatabase.exists ("cache_mb")) + setup.nodeDatabase.set ("cache_mb", std::to_string (c.getSize (siHashNodeDBCache))); + + if (!setup.nodeDatabase.exists ("filter_bits") && (c.NODE_SIZE >= 2)) + setup.nodeDatabase.set ("filter_bits", "10"); + + get_if_exists (setup.nodeDatabase, "online_delete", setup.deleteInterval); if (setup.deleteInterval) - get_if_exists (sec, "advisory_delete", setup.advisoryDelete); + get_if_exists (setup.nodeDatabase, "advisory_delete", setup.advisoryDelete); setup.ledgerHistory = c.LEDGER_HISTORY; - setup.nodeDatabase = c[ConfigSection::nodeDatabase ()]; setup.databasePath = c.legacy("database_path"); - get_if_exists (sec, "delete_batch", setup.deleteBatch); - get_if_exists (sec, "backOff", setup.backOff); - get_if_exists (sec, "age_threshold", setup.ageThreshold); + get_if_exists (setup.nodeDatabase, "delete_batch", setup.deleteBatch); + get_if_exists (setup.nodeDatabase, "backOff", setup.backOff); + get_if_exists (setup.nodeDatabase, "age_threshold", setup.ageThreshold); return setup; } diff --git a/src/ripple/app/misc/UniqueNodeList.cpp b/src/ripple/app/misc/UniqueNodeList.cpp index 647cbdf76c..254a9578e4 100644 --- a/src/ripple/app/misc/UniqueNodeList.cpp +++ b/src/ripple/app/misc/UniqueNodeList.cpp @@ -365,7 +365,7 @@ private: // --> strValidatorsSrc: source details for display // --> naNodePublic: remote source public key - not valid for local // --> vsWhy: reason for adding validator to SeedDomains or SeedNodes. - int processValidators (std::string const& strSite, std::string const& strValidatorsSrc, RippleAddress const& naNodePublic, ValidatorSource vsWhy, IniFileSections::mapped_type* pmtVecStrValidators); + int processValidators (std::string const& strSite, std::string const& strValidatorsSrc, RippleAddress const& naNodePublic, ValidatorSource vsWhy, IniFileSections::mapped_type const* pmtVecStrValidators); // Process a ripple.txt. void processFile (std::string const& strDomain, RippleAddress const& naNodePublic, IniFileSections secSite); @@ -780,38 +780,40 @@ void UniqueNodeListImp::nodeBootstrap() bool bLoaded = iDomains || iNodes; // Always merge in the file specified in the config. - if (!getConfig ().VALIDATORS_FILE.empty ()) + if (!app_.config().VALIDATORS_FILE.empty ()) { WriteLog (lsINFO, UniqueNodeList) << "Bootstrapping UNL: loading from unl_default."; - bLoaded = nodeLoad (getConfig ().VALIDATORS_FILE); + bLoaded = nodeLoad (app_.config().VALIDATORS_FILE); } // If never loaded anything try the current directory. - if (!bLoaded && getConfig ().VALIDATORS_FILE.empty ()) + if (!bLoaded && app_.config().VALIDATORS_FILE.empty ()) { WriteLog (lsINFO, UniqueNodeList) << boost::str (boost::format ("Bootstrapping UNL: loading from '%s'.") - % getConfig ().VALIDATORS_BASE); + % app_.config().VALIDATORS_BASE); - bLoaded = nodeLoad (getConfig ().VALIDATORS_BASE); + bLoaded = nodeLoad (app_.config().VALIDATORS_BASE); } // Always load from rippled.cfg - if (!getConfig ().validators.empty ()) + if (!app_.config().validators.empty ()) { RippleAddress naInvalid; // Don't want a referrer on added entries. WriteLog (lsINFO, UniqueNodeList) << boost::str (boost::format ("Bootstrapping UNL: loading from '%s'.") - % getConfig ().CONFIG_FILE); + % app_.config().CONFIG_FILE); - if (processValidators ("local", getConfig ().CONFIG_FILE.string (), naInvalid, vsConfig, &getConfig ().validators)) + if (processValidators ("local", + app_.config().CONFIG_FILE.string (), naInvalid, + vsConfig, &(app_.config().validators))) bLoaded = true; } if (!bLoaded) { WriteLog (lsINFO, UniqueNodeList) << boost::str (boost::format ("Bootstrapping UNL: loading from '%s'.") - % getConfig ().VALIDATORS_SITE); + % app_.config().VALIDATORS_SITE); nodeNetwork (); } @@ -879,14 +881,14 @@ bool UniqueNodeListImp::nodeLoad (boost::filesystem::path pConfig) void UniqueNodeListImp::nodeNetwork() { - if (!getConfig ().VALIDATORS_SITE.empty ()) + if (!app_.config().VALIDATORS_SITE.empty ()) { HTTPClient::get ( true, app_.getIOService (), - getConfig ().VALIDATORS_SITE, + app_.config().VALIDATORS_SITE, 443, - getConfig ().VALIDATORS_URI, + app_.config().VALIDATORS_URI, VALIDATORS_FILE_BYTES_MAX, boost::posix_time::seconds (VALIDATORS_FETCH_SECONDS), std::bind (&UniqueNodeListImp::validatorsResponse, this, @@ -1017,7 +1019,7 @@ bool UniqueNodeListImp::miscSave() void UniqueNodeListImp::trustedLoad() { boost::regex rNode ("\\`\\s*(\\S+)[\\s]*(.*)\\'"); - for (auto const& c : getConfig ().CLUSTER_NODES) + for (auto const& c : app_.config().CLUSTER_NODES) { boost::smatch match; @@ -1981,7 +1983,7 @@ void UniqueNodeListImp::processIps (std::string const& strSite, RippleAddress co // --> strValidatorsSrc: source details for display // --> naNodePublic: remote source public key - not valid for local // --> vsWhy: reason for adding validator to SeedDomains or SeedNodes. -int UniqueNodeListImp::processValidators (std::string const& strSite, std::string const& strValidatorsSrc, RippleAddress const& naNodePublic, ValidatorSource vsWhy, IniFileSections::mapped_type* pmtVecStrValidators) +int UniqueNodeListImp::processValidators (std::string const& strSite, std::string const& strValidatorsSrc, RippleAddress const& naNodePublic, ValidatorSource vsWhy, IniFileSections::mapped_type const* pmtVecStrValidators) { std::string strNodePublic = naNodePublic.isValid () ? naNodePublic.humanNodePublic () : strValidatorsSrc; int iValues = 0; @@ -2364,7 +2366,7 @@ bool UniqueNodeListImp::validatorsResponse (const boost::system::error_code& err if (!err) { - nodeProcess ("network", strResponse, getConfig ().VALIDATORS_SITE); + nodeProcess ("network", strResponse, app_.config().VALIDATORS_SITE); } else { @@ -2398,7 +2400,7 @@ void UniqueNodeListImp::nodeProcess (std::string const& strSite, std::string con else { WriteLog (lsWARNING, UniqueNodeList) << boost::str (boost::format ("'%s' missing [" SECTION_VALIDATORS "].") - % getConfig ().VALIDATORS_BASE); + % app_.config().VALIDATORS_BASE); } } diff --git a/src/ripple/app/paths/PathRequest.cpp b/src/ripple/app/paths/PathRequest.cpp index a9ed46db66..553ab530ba 100644 --- a/src/ripple/app/paths/PathRequest.cpp +++ b/src/ripple/app/paths/PathRequest.cpp @@ -591,30 +591,30 @@ Json::Value PathRequest::doUpdate (RippleLineCache::ref cache, bool fast) { // first pass if (loaded || fast) - iLevel = getConfig().PATH_SEARCH_FAST; + iLevel = app_.config().PATH_SEARCH_FAST; else - iLevel = getConfig().PATH_SEARCH; + iLevel = app_.config().PATH_SEARCH; } - else if ((iLevel == getConfig().PATH_SEARCH_FAST) && !fast) + else if ((iLevel == app_.config().PATH_SEARCH_FAST) && !fast) { // leaving fast pathfinding - iLevel = getConfig().PATH_SEARCH; - if (loaded && (iLevel > getConfig().PATH_SEARCH_FAST)) + iLevel = app_.config().PATH_SEARCH; + if (loaded && (iLevel > app_.config().PATH_SEARCH_FAST)) --iLevel; } else if (bLastSuccess) { // decrement, if possible - if (iLevel > getConfig().PATH_SEARCH || - (loaded && (iLevel > getConfig().PATH_SEARCH_FAST))) + if (iLevel > app_.config().PATH_SEARCH || + (loaded && (iLevel > app_.config().PATH_SEARCH_FAST))) --iLevel; } else { // adjust as needed - if (!loaded && (iLevel < getConfig().PATH_SEARCH_MAX)) + if (!loaded && (iLevel < app_.config().PATH_SEARCH_MAX)) ++iLevel; - if (loaded && (iLevel > getConfig().PATH_SEARCH_FAST)) + if (loaded && (iLevel > app_.config().PATH_SEARCH_FAST)) --iLevel; } diff --git a/src/ripple/app/tx/impl/Payment.cpp b/src/ripple/app/tx/impl/Payment.cpp index 0d2f2c8885..5043775d47 100644 --- a/src/ripple/app/tx/impl/Payment.cpp +++ b/src/ripple/app/tx/impl/Payment.cpp @@ -261,7 +261,7 @@ Payment::doApply () } else if (saDstAmount < STAmount (view().fees().accountReserve(0))) { - // getReserve() is the minimum amount that an account can have. + // accountReserve is the minimum amount that an account can have. // Reserve is not scaled by load. j_.trace << "Delay transaction: Destination account does not exist. " << diff --git a/src/ripple/app/tx/impl/Transaction.cpp b/src/ripple/app/tx/impl/Transaction.cpp index f5f5614050..c5dd18c21f 100644 --- a/src/ripple/app/tx/impl/Transaction.cpp +++ b/src/ripple/app/tx/impl/Transaction.cpp @@ -91,7 +91,8 @@ Transaction::pointer Transaction::sharedTransaction ( bool Transaction::checkSign (std::string& reason, SigVerify sigVerify) const { bool const allowMultiSign = mApp.getLedgerMaster(). - getValidatedRules().enabled (featureMultiSign, getConfig().features); + getValidatedRules().enabled (featureMultiSign, + mApp.config().features); if (! mFromPubKey.isValid ()) reason = "Transaction has bad source public key"; diff --git a/src/ripple/basics/BasicConfig.h b/src/ripple/basics/BasicConfig.h index aff78bbbe8..666475891c 100644 --- a/src/ripple/basics/BasicConfig.h +++ b/src/ripple/basics/BasicConfig.h @@ -216,7 +216,7 @@ public: * * @param sectionName Retrieve the contents of this section's * legacy value. - * @returun Contents of the legacy value. + * @return Contents of the legacy value. */ std::string legacy(std::string const& sectionName) const; diff --git a/src/ripple/basics/Sustain.h b/src/ripple/basics/Sustain.h index d3c7c5565a..50710d68ed 100644 --- a/src/ripple/basics/Sustain.h +++ b/src/ripple/basics/Sustain.h @@ -26,13 +26,9 @@ namespace ripple { // "Sustain" is a system for a buddy process that monitors the main process // and relaunches it on a fault. -// -// VFALCO TODO Rename this and put it in a class. -// VFALCO TODO Reimplement cross-platform using beast::Process and its ilk -// bool HaveSustain (); std::string StopSustain (); -std::string DoSustain (std::string const& logFile); +std::string DoSustain (); } // ripple diff --git a/src/ripple/basics/impl/Sustain.cpp b/src/ripple/basics/impl/Sustain.cpp index c0a7e09abf..835f3a62f7 100644 --- a/src/ripple/basics/impl/Sustain.cpp +++ b/src/ripple/basics/impl/Sustain.cpp @@ -70,7 +70,7 @@ std::string StopSustain () return "Terminating monitor"; } -std::string DoSustain (std::string const& logFile) +std::string DoSustain () { pManager = getpid (); signal (SIGINT, stop_manager); @@ -111,8 +111,6 @@ std::string DoSustain (std::string const& logFile) auto pc = std::to_string (pChild); rename ("core", ("core." + pc).c_str ()); - if (!logFile.empty()) // FIXME: logFile hasn't been set yet - rename (logFile.c_str(), (logFile + "." + pc).c_str ()); } } @@ -123,7 +121,7 @@ bool HaveSustain () return false; } -std::string DoSustain (const std::string&) +std::string DoSustain () { return ""; } diff --git a/src/ripple/core/Config.h b/src/ripple/core/Config.h index 1e8657197b..b1e08433f7 100644 --- a/src/ripple/core/Config.h +++ b/src/ripple/core/Config.h @@ -159,18 +159,11 @@ public: */ beast::File getModuleDatabasePath () const; - //-------------------------------------------------------------------------- + bool doImport = false; - bool doImport; + bool QUIET = false; - // - // - //-------------------------------------------------------------------------- -public: - // Configuration parameters - bool QUIET; - - bool ELB_SUPPORT; // Support Amazon ELB + bool ELB_SUPPORT = false; std::string VALIDATORS_SITE; // Where to find validators.txt on the Internet. std::string VALIDATORS_URI; // URI of validators.txt. @@ -188,14 +181,14 @@ public: REPLAY, NETWORK }; - StartUpType START_UP; + StartUpType START_UP = NORMAL; std::string START_LEDGER; // Network parameters - int TRANSACTION_FEE_BASE; // The number of fee units a reference transaction costs + int TRANSACTION_FEE_BASE = 10; // The number of fee units a reference transaction costs /** Operate in stand-alone mode. @@ -206,26 +199,26 @@ public: - If no ledger is loaded, the default ledger with the root account is created. */ - bool RUN_STANDALONE; + bool RUN_STANDALONE = false; // Note: The following parameters do not relate to the UNL or trust at all - std::size_t NETWORK_QUORUM; // Minimum number of nodes to consider the network present - int VALIDATION_QUORUM; // Minimum validations to consider ledger authoritative + std::size_t NETWORK_QUORUM = 0; // Minimum number of nodes to consider the network present + int VALIDATION_QUORUM = 1; // Minimum validations to consider ledger authoritative // Peer networking parameters - bool PEER_PRIVATE; // True to ask peers not to relay current IP. - unsigned int PEERS_MAX; + bool PEER_PRIVATE = false; // True to ask peers not to relay current IP. + unsigned int PEERS_MAX = 0; - int WEBSOCKET_PING_FREQ; + int WEBSOCKET_PING_FREQ = 5 * 60; // RPC parameters Json::Value RPC_STARTUP; // Path searching - int PATH_SEARCH_OLD; - int PATH_SEARCH; - int PATH_SEARCH_FAST; - int PATH_SEARCH_MAX; + int PATH_SEARCH_OLD = 7; + int PATH_SEARCH = 7; + int PATH_SEARCH_FAST = 2; + int PATH_SEARCH_MAX = 10; // Validation RippleAddress VALIDATION_SEED; @@ -238,22 +231,17 @@ public: RippleAddress NODE_PUB; RippleAddress NODE_PRIV; - // Fee schedule (All below values are in fee units) - std::uint64_t FEE_DEFAULT; // Default fee. - std::uint64_t FEE_ACCOUNT_RESERVE; // Amount of units not allowed to send. - std::uint64_t FEE_OWNER_RESERVE; // Amount of units not allowed to send per owner entry. - std::uint64_t FEE_OFFER; // Rate per day. - int FEE_CONTRACT_OPERATION; // fee for each contract operation + std::uint64_t FEE_DEFAULT = 10; + std::uint64_t FEE_ACCOUNT_RESERVE = 200*SYSTEM_CURRENCY_PARTS; + std::uint64_t FEE_OWNER_RESERVE = 50*SYSTEM_CURRENCY_PARTS; + std::uint64_t FEE_OFFER = 10; // Node storage configuration - std::uint32_t LEDGER_HISTORY; - std::uint32_t FETCH_DEPTH; - int NODE_SIZE; + std::uint32_t LEDGER_HISTORY = 256; + std::uint32_t FETCH_DEPTH = 1000000000; + int NODE_SIZE = 0; - // Client behavior - int ACCOUNT_PROBE_MAX; // How far to scan for accounts. - - bool SSL_VERIFY; + bool SSL_VERIFY = true; std::string SSL_VERIFY_FILE; std::string SSL_VERIFY_DIR; @@ -264,7 +252,7 @@ public: std::unordered_set> features; public: - Config (); + Config() = default; int getSize (SizedItemName) const; void setup (std::string const& strConf, bool bQuiet); @@ -277,9 +265,6 @@ public: void loadFromString (std::string const& fileContents); }; -// DEPRECATED -extern Config& getConfig(); - } // ripple #endif diff --git a/src/ripple/core/ConfigSections.h b/src/ripple/core/ConfigSections.h index 726a0081e8..0d1685b67d 100644 --- a/src/ripple/core/ConfigSections.h +++ b/src/ripple/core/ConfigSections.h @@ -32,14 +32,12 @@ struct ConfigSection }; // VFALCO TODO Rename and replace these macros with variables. -#define SECTION_ACCOUNT_PROBE_MAX "account_probe_max" #define SECTION_AMENDMENTS "amendments" #define SECTION_CLUSTER_NODES "cluster_nodes" #define SECTION_DEBUG_LOGFILE "debug_logfile" #define SECTION_ELB_SUPPORT "elb_support" #define SECTION_FEE_DEFAULT "fee_default" #define SECTION_FEE_OFFER "fee_offer" -#define SECTION_FEE_OPERATION "fee_operation" #define SECTION_FEE_ACCOUNT_RESERVE "fee_account_reserve" #define SECTION_FEE_OWNER_RESERVE "fee_owner_reserve" #define SECTION_FETCH_DEPTH "fetch_depth" diff --git a/src/ripple/core/impl/Config.cpp b/src/ripple/core/impl/Config.cpp index 09e5598e32..dae8ac0044 100644 --- a/src/ripple/core/impl/Config.cpp +++ b/src/ripple/core/impl/Config.cpp @@ -44,16 +44,6 @@ namespace ripple { // TODO: Check permissions on config file before using it. // -// Fees are in XRP. -#define DEFAULT_FEE_DEFAULT 10 -#define DEFAULT_FEE_ACCOUNT_RESERVE 200*SYSTEM_CURRENCY_PARTS -#define DEFAULT_FEE_OWNER_RESERVE 50*SYSTEM_CURRENCY_PARTS -#define DEFAULT_FEE_OFFER DEFAULT_FEE_DEFAULT -#define DEFAULT_FEE_OPERATION 1 - -// Fee in fee units -#define DEFAULT_TRANSACTION_FEE_BASE 10 - #define SECTION_DEFAULT_NAME "" IniFileSections @@ -194,49 +184,6 @@ parseAddresses (OutputSequence& out, InputIterator first, InputIterator last, // //------------------------------------------------------------------------------ -Config::Config () -{ - // - // Defaults - // - - WEBSOCKET_PING_FREQ = (5 * 60); - - PEER_PRIVATE = false; - PEERS_MAX = 0; // indicates "use default" - - TRANSACTION_FEE_BASE = DEFAULT_TRANSACTION_FEE_BASE; - - NETWORK_QUORUM = 0; // Don't need to see other nodes - VALIDATION_QUORUM = 1; // Only need one node to vouch - - FEE_ACCOUNT_RESERVE = DEFAULT_FEE_ACCOUNT_RESERVE; - FEE_OWNER_RESERVE = DEFAULT_FEE_OWNER_RESERVE; - FEE_OFFER = DEFAULT_FEE_OFFER; - FEE_DEFAULT = DEFAULT_FEE_DEFAULT; - FEE_CONTRACT_OPERATION = DEFAULT_FEE_OPERATION; - - LEDGER_HISTORY = 256; - FETCH_DEPTH = 1000000000; - - // An explanation of these magical values would be nice. - PATH_SEARCH_OLD = 7; - PATH_SEARCH = 7; - PATH_SEARCH_FAST = 2; - PATH_SEARCH_MAX = 10; - - ACCOUNT_PROBE_MAX = 10; - - VALIDATORS_SITE = ""; - - SSL_VERIFY = true; - - ELB_SUPPORT = false; - RUN_STANDALONE = false; - doImport = false; - START_UP = NORMAL; -} - static std::string getEnvVar (char const* name) @@ -264,7 +211,6 @@ void Config::setup (std::string const& strConf, bool bQuiet) // QUIET = bQuiet; - NODE_SIZE = 0; strDbPath = Helpers::getDatabaseDirName (); strConfFile = strConf.empty () ? Helpers::getConfigFileName () : strConf; @@ -324,7 +270,7 @@ void Config::setup (std::string const& strConf, bool bQuiet) } } - HTTPClient::initializeSSLContext(); + HTTPClient::initializeSSLContext(*this); // Update default values load (); @@ -505,9 +451,6 @@ void Config::loadFromString (std::string const& fileContents) if (getSingleSection (secConfig, SECTION_FEE_DEFAULT, strTemp)) FEE_DEFAULT = beast::lexicalCastThrow (strTemp); - if (getSingleSection (secConfig, SECTION_FEE_OPERATION, strTemp)) - FEE_CONTRACT_OPERATION = beast::lexicalCastThrow (strTemp); - if (getSingleSection (secConfig, SECTION_LEDGER_HISTORY, strTemp)) { boost::to_lower (strTemp); @@ -544,9 +487,6 @@ void Config::loadFromString (std::string const& fileContents) if (getSingleSection (secConfig, SECTION_PATH_SEARCH_MAX, strTemp)) PATH_SEARCH_MAX = beast::lexicalCastThrow (strTemp); - if (getSingleSection (secConfig, SECTION_ACCOUNT_PROBE_MAX, strTemp)) - ACCOUNT_PROBE_MAX = beast::lexicalCastThrow (strTemp); - if (getSingleSection (secConfig, SECTION_VALIDATORS_FILE, strTemp)) { VALIDATORS_FILE = strTemp; @@ -610,7 +550,7 @@ boost::filesystem::path Config::getDebugLogFile () const // Unless an absolute path for the log file is specified, the // path is relative to the config file directory. log_file = boost::filesystem::absolute ( - log_file, getConfig ().CONFIG_DIR); + log_file, CONFIG_DIR); } if (!log_file.empty ()) @@ -636,12 +576,6 @@ boost::filesystem::path Config::getDebugLogFile () const return log_file; } -Config& getConfig () -{ - static Config config; - return config; -} - beast::File Config::getConfigDir () const { beast::String const s (CONFIG_FILE.native().c_str ()); diff --git a/src/ripple/core/tests/LoadFeeTrack.test.cpp b/src/ripple/core/tests/LoadFeeTrack.test.cpp index 9be3c7bad5..5864a73018 100644 --- a/src/ripple/core/tests/LoadFeeTrack.test.cpp +++ b/src/ripple/core/tests/LoadFeeTrack.test.cpp @@ -42,7 +42,6 @@ public: expect (l.scaleFeeBase (d.FEE_ACCOUNT_RESERVE, d.FEE_DEFAULT, d.TRANSACTION_FEE_BASE) == 200 * SYSTEM_CURRENCY_PARTS); expect (l.scaleFeeBase (d.FEE_OWNER_RESERVE, d.FEE_DEFAULT, d.TRANSACTION_FEE_BASE) == 50 * SYSTEM_CURRENCY_PARTS); expect (l.scaleFeeBase (d.FEE_OFFER, d.FEE_DEFAULT, d.TRANSACTION_FEE_BASE) == 10); - expect (l.scaleFeeBase (d.FEE_CONTRACT_OPERATION, d.FEE_DEFAULT, d.TRANSACTION_FEE_BASE) == 1); } }; diff --git a/src/ripple/ledger/tests/SkipList_test.cpp b/src/ripple/ledger/tests/SkipList_test.cpp index de77a3ce39..f921330dd6 100644 --- a/src/ripple/ledger/tests/SkipList_test.cpp +++ b/src/ripple/ledger/tests/SkipList_test.cpp @@ -36,7 +36,7 @@ class SkipList_test : public beast::unit_test::suite std::vector> history; { jtx::Env env(*this); - Config const config; + Config config; auto prev = std::make_shared(create_genesis, config, env.app().family()); history.push_back(prev); diff --git a/src/ripple/ledger/tests/View_test.cpp b/src/ripple/ledger/tests/View_test.cpp index cb268c32c2..5d273cc4d8 100644 --- a/src/ripple/ledger/tests/View_test.cpp +++ b/src/ripple/ledger/tests/View_test.cpp @@ -148,7 +148,7 @@ class View_test { using namespace jtx; Env env(*this); - Config const config; + Config config; std::shared_ptr const genesis = std::make_shared( create_genesis, config, env.app().family()); @@ -412,7 +412,7 @@ class View_test { using namespace jtx; Env env(*this); - Config const config; + Config config; std::shared_ptr const genesis = std::make_shared ( create_genesis, config, env.app().family()); @@ -532,7 +532,7 @@ class View_test // erase the item, apply. { Env env(*this); - Config const config; + Config config; std::shared_ptr const genesis = std::make_shared( create_genesis, config, env.app().family()); diff --git a/src/ripple/net/HTTPClient.h b/src/ripple/net/HTTPClient.h index 8d8a77fbff..f63baef243 100644 --- a/src/ripple/net/HTTPClient.h +++ b/src/ripple/net/HTTPClient.h @@ -20,6 +20,7 @@ #ifndef RIPPLE_NET_HTTPCLIENT_H_INCLUDED #define RIPPLE_NET_HTTPCLIENT_H_INCLUDED +#include #include #include #include @@ -36,7 +37,7 @@ public: maxClientHeaderBytes = 32 * 1024 }; - static void initializeSSLContext (); + static void initializeSSLContext (Config const& config); static void get ( bool bSSL, diff --git a/src/ripple/net/RPCCall.h b/src/ripple/net/RPCCall.h index 60cb9470c2..f7e3a1e68c 100644 --- a/src/ripple/net/RPCCall.h +++ b/src/ripple/net/RPCCall.h @@ -20,6 +20,7 @@ #ifndef RIPPLE_NET_RPCCALL_H_INCLUDED #define RIPPLE_NET_RPCCALL_H_INCLUDED +#include #include #include #include @@ -28,29 +29,27 @@ namespace ripple { -// -// This a trusted interface, the user is expected to provide valid input to perform valid requests. -// Error catching and reporting is not a requirement of this command line interface. +// This a trusted interface, the user is expected to provide valid input to +// perform valid requests. Error catching and reporting is not a requirement of +// the command line interface. // // Improvements to be more strict and to provide better diagnostics are welcome. -// -/** Processes Ripple RPC calls. -*/ -class RPCCall -{ -public: +/** Processes Ripple RPC calls. */ +namespace RPCCall { - static int fromCommandLine (const std::vector& vCmd); +int fromCommandLine ( + Config const& config, + const std::vector& vCmd); - static void fromNetwork ( - boost::asio::io_service& io_service, - std::string const& strIp, const int iPort, - std::string const& strUsername, std::string const& strPassword, - std::string const& strPath, std::string const& strMethod, - Json::Value const& jvParams, const bool bSSL, - std::function callbackFuncP = std::function ()); -}; +void fromNetwork ( + boost::asio::io_service& io_service, + std::string const& strIp, const int iPort, + std::string const& strUsername, std::string const& strPassword, + std::string const& strPath, std::string const& strMethod, + Json::Value const& jvParams, const bool bSSL, bool quiet, + std::function callbackFuncP = std::function ()); +} } // ripple diff --git a/src/ripple/net/RPCSub.h b/src/ripple/net/RPCSub.h index b2102bd285..3418ef7183 100644 --- a/src/ripple/net/RPCSub.h +++ b/src/ripple/net/RPCSub.h @@ -31,15 +31,6 @@ namespace ripple { class RPCSub : public InfoSub { public: - using pointer = std::shared_ptr ; - using ref = pointer const&; - - // VFALCO Why is the io_service needed? - static pointer New (InfoSub::Source& source, - boost::asio::io_service& io_service, JobQueue& jobQueue, - std::string const& strUrl, std::string const& strUsername, - std::string const& strPassword); - virtual void setUsername (std::string const& strUsername) = 0; virtual void setPassword (std::string const& strPassword) = 0; @@ -47,6 +38,12 @@ protected: explicit RPCSub (InfoSub::Source& source); }; +// VFALCO Why is the io_service needed? +std::shared_ptr make_RPCSub ( + InfoSub::Source& source, boost::asio::io_service& io_service, + JobQueue& jobQueue, std::string const& strUrl, + std::string const& strUsername, std::string const& strPassword); + } // ripple #endif diff --git a/src/ripple/net/impl/HTTPClient.cpp b/src/ripple/net/impl/HTTPClient.cpp index b9a4b26e05..120da4b8e1 100644 --- a/src/ripple/net/impl/HTTPClient.cpp +++ b/src/ripple/net/impl/HTTPClient.cpp @@ -20,7 +20,6 @@ #include #include #include -#include #include #include #include @@ -40,27 +39,28 @@ namespace ripple { class HTTPClientSSLContext { public: - HTTPClientSSLContext () + HTTPClientSSLContext (Config const& config) : m_context (boost::asio::ssl::context::sslv23) + , verify_ (config.SSL_VERIFY) { boost::system::error_code ec; - if (getConfig().SSL_VERIFY_FILE.empty ()) + if (config.SSL_VERIFY_FILE.empty ()) { m_context.set_default_verify_paths (ec); - if (ec && getConfig().SSL_VERIFY_DIR.empty ()) + if (ec && config.SSL_VERIFY_DIR.empty ()) throw std::runtime_error (boost::str ( boost::format ("Failed to set_default_verify_paths: %s") % ec.message ())); } else { - m_context.load_verify_file (getConfig().SSL_VERIFY_FILE); + m_context.load_verify_file (config.SSL_VERIFY_FILE); } - if (! getConfig().SSL_VERIFY_DIR.empty ()) + if (! config.SSL_VERIFY_DIR.empty ()) { - m_context.add_verify_path (getConfig().SSL_VERIFY_DIR, ec); + m_context.add_verify_path (config.SSL_VERIFY_DIR, ec); if (ec) throw std::runtime_error (boost::str ( @@ -73,15 +73,21 @@ public: return m_context; } + bool sslVerify() const + { + return verify_; + } + private: boost::asio::ssl::context m_context; + bool verify_; }; boost::optional httpClientSSLContext; -void HTTPClient::initializeSSLContext () +void HTTPClient::initializeSSLContext (Config const& config) { - httpClientSSLContext.emplace (); + httpClientSSLContext.emplace (config); } //------------------------------------------------------------------------------ @@ -101,7 +107,7 @@ public: , mResponseMax (responseMax) , mDeadline (io_service) { - if (!getConfig ().SSL_VERIFY) + if (!httpClientSSLContext->sslVerify()) mSocket.SSLSocket ().set_verify_mode (boost::asio::ssl::verify_none); } @@ -290,7 +296,7 @@ public: { WriteLog (lsTRACE, HTTPClient) << "Connected."; - if (getConfig ().SSL_VERIFY) + if (httpClientSSLContext->sslVerify ()) { mShutdown = mSocket.verify (mDeqSites[0]); diff --git a/src/ripple/net/impl/RPCCall.cpp b/src/ripple/net/impl/RPCCall.cpp index 4de2b05e6e..451bbebde8 100644 --- a/src/ripple/net/impl/RPCCall.cpp +++ b/src/ripple/net/impl/RPCCall.cpp @@ -1069,9 +1069,15 @@ struct RPCCallImp }; //------------------------------------------------------------------------------ +namespace RPCCall { -int RPCCall::fromCommandLine (const std::vector& vCmd) +int fromCommandLine ( + Config const& config, + const std::vector& vCmd) { + if (vCmd.empty ()) + return 1; // 1 = print usage. + Json::Value jvOutput; int nRet = 0; Json::Value jvRequest (Json::objectValue); @@ -1081,8 +1087,6 @@ int RPCCall::fromCommandLine (const std::vector& vCmd) RPCParser rpParser; Json::Value jvRpcParams (Json::arrayValue); - if (vCmd.empty ()) return 1; // 1 = print usage. - for (int i = 1; i != vCmd.size (); i++) jvRpcParams.append (vCmd[i]); @@ -1106,7 +1110,7 @@ int RPCCall::fromCommandLine (const std::vector& vCmd) try { std::stringstream ss; - setup = setup_ServerHandler(getConfig(), ss); + setup = setup_ServerHandler(config, ss); } catch(...) { @@ -1114,10 +1118,10 @@ int RPCCall::fromCommandLine (const std::vector& vCmd) // line client works without a config file } - if (getConfig().rpc_ip) - setup.client.ip = getConfig().rpc_ip->to_string(); - if (getConfig().rpc_port) - setup.client.port = *getConfig().rpc_port; + if (config.rpc_ip) + setup.client.ip = config.rpc_ip->to_string(); + if (config.rpc_port) + setup.client.port = *config.rpc_port; Json::Value jvParams (Json::arrayValue); @@ -1142,6 +1146,7 @@ int RPCCall::fromCommandLine (const std::vector& vCmd) ? jvRequest["method"].asString () : vCmd[0], jvParams, // Parsed, execute. setup.client.secure != 0, // Use SSL + config.QUIET, std::bind (RPCCallImp::callRPCHandler, &jvOutput, std::placeholders::_1)); isService.run(); // This blocks until there is no more outstanding async calls. @@ -1204,16 +1209,16 @@ int RPCCall::fromCommandLine (const std::vector& vCmd) //------------------------------------------------------------------------------ -void RPCCall::fromNetwork ( +void fromNetwork ( boost::asio::io_service& io_service, std::string const& strIp, const int iPort, std::string const& strUsername, std::string const& strPassword, std::string const& strPath, std::string const& strMethod, - Json::Value const& jvParams, const bool bSSL, + Json::Value const& jvParams, const bool bSSL, const bool quiet, std::function callbackFuncP) { // Connect to localhost - if (!getConfig ().QUIET) + if (!quiet) { std::cerr << (bSSL ? "Securely connecting to " : "Connecting to ") << strIp << ":" << iPort << std::endl; @@ -1249,4 +1254,6 @@ void RPCCall::fromNetwork ( std::placeholders::_3)); } +} + } // ripple diff --git a/src/ripple/net/impl/RPCSub.cpp b/src/ripple/net/impl/RPCSub.cpp index f3e959ff39..105e4c481b 100644 --- a/src/ripple/net/impl/RPCSub.cpp +++ b/src/ripple/net/impl/RPCSub.cpp @@ -164,7 +164,8 @@ private: mUsername, mPassword, mPath, "event", jvEvent, - mSSL); + mSSL, + true); } catch (const std::exception& e) { @@ -176,7 +177,6 @@ private: } private: -// VFALCO TODO replace this macro with a language constant enum { eventQueueMax = 32 @@ -207,12 +207,12 @@ RPCSub::RPCSub (InfoSub::Source& source) { } -RPCSub::pointer RPCSub::New (InfoSub::Source& source, - boost::asio::io_service& io_service, JobQueue& jobQueue, - std::string const& strUrl, std::string const& strUsername, - std::string const& strPassword) +std::shared_ptr make_RPCSub ( + InfoSub::Source& source, boost::asio::io_service& io_service, + JobQueue& jobQueue, std::string const& strUrl, + std::string const& strUsername, std::string const& strPassword) { - return std::make_shared (std::ref (source), + return std::make_shared (std::ref (source), std::ref (io_service), std::ref (jobQueue), strUrl, strUsername, strPassword); } diff --git a/src/ripple/nodestore/backend/RocksDBFactory.cpp b/src/ripple/nodestore/backend/RocksDBFactory.cpp index 77f022be49..46654cd3e8 100644 --- a/src/ripple/nodestore/backend/RocksDBFactory.cpp +++ b/src/ripple/nodestore/backend/RocksDBFactory.cpp @@ -115,24 +115,11 @@ public: options.create_if_missing = true; options.env = env; - if (!keyValues.exists ("cache_mb")) - { - table_options.block_cache = rocksdb::NewLRUCache (getConfig ().getSize (siHashNodeDBCache) * 1024 * 1024); - } - else - { + if (keyValues.exists ("cache_mb")) table_options.block_cache = rocksdb::NewLRUCache (get(keyValues, "cache_mb") * 1024L * 1024L); - } - if (!keyValues.exists ("filter_bits")) - { - if (getConfig ().NODE_SIZE >= 2) - table_options.filter_policy.reset (rocksdb::NewBloomFilterPolicy (10)); - } - else if (auto const v = get(keyValues, "filter_bits")) - { + if (auto const v = get(keyValues, "filter_bits")) table_options.filter_policy.reset (rocksdb::NewBloomFilterPolicy (v)); - } get_if_exists (keyValues, "open_files", options.max_open_files); diff --git a/src/ripple/overlay/impl/OverlayImpl.cpp b/src/ripple/overlay/impl/OverlayImpl.cpp index 052077f1b4..bd65c8afc7 100644 --- a/src/ripple/overlay/impl/OverlayImpl.cpp +++ b/src/ripple/overlay/impl/OverlayImpl.cpp @@ -486,21 +486,21 @@ OverlayImpl::onPrepare() { PeerFinder::Config config; - if (getConfig ().PEERS_MAX != 0) - config.maxPeers = getConfig ().PEERS_MAX; + if (app_.config().PEERS_MAX != 0) + config.maxPeers = app_.config().PEERS_MAX; config.outPeers = config.calcOutPeers(); auto const port = serverHandler_.setup().overlay.port; - config.peerPrivate = getConfig().PEER_PRIVATE; + config.peerPrivate = app_.config().PEER_PRIVATE; config.wantIncoming = (! config.peerPrivate) && (port != 0); // if it's a private peer or we are running as standalone // automatic connections would defeat the purpose. config.autoConnect = - !getConfig().RUN_STANDALONE && - !getConfig().PEER_PRIVATE; + !app_.config().RUN_STANDALONE && + !app_.config().PEER_PRIVATE; config.listeningPort = port; config.features = ""; @@ -509,7 +509,7 @@ OverlayImpl::onPrepare() m_peerFinder->setConfig (config); - auto bootstrapIps (getConfig ().IPS); + auto bootstrapIps (app_.config().IPS); // If no IPs are specified, use the Ripple Labs round robin // pool to get some servers to insert into the boot cache. @@ -539,9 +539,9 @@ OverlayImpl::onPrepare() }); // Add the ips_fixed from the rippled.cfg file - if (! getConfig ().RUN_STANDALONE && !getConfig ().IPS_FIXED.empty ()) + if (! app_.config().RUN_STANDALONE && !app_.config().IPS_FIXED.empty ()) { - m_resolver.resolve (getConfig ().IPS_FIXED, + m_resolver.resolve (app_.config().IPS_FIXED, [this]( std::string const& name, std::vector const& addresses) diff --git a/src/ripple/overlay/impl/PeerImp.cpp b/src/ripple/overlay/impl/PeerImp.cpp index b0a4b5ade0..b59980f2ff 100644 --- a/src/ripple/overlay/impl/PeerImp.cpp +++ b/src/ripple/overlay/impl/PeerImp.cpp @@ -1051,7 +1051,7 @@ PeerImp::onMessage (std::shared_ptr const& m) flags |= SF_TRUSTED; } - if (! getConfig().VALIDATION_PRIV.isSet()) + if (! app_.config().VALIDATION_PRIV.isSet()) { // For now, be paranoid and have each validator // check each transaction, regardless of source @@ -1208,7 +1208,7 @@ PeerImp::onMessage (std::shared_ptr const& m) RippleAddress signerPublic = RippleAddress::createNodePublic ( strCopy (set.nodepubkey ())); - if (signerPublic == getConfig ().VALIDATION_PUB) + if (signerPublic == app_.config().VALIDATION_PUB) { p_journal_.trace << "Proposal: self"; return; diff --git a/src/ripple/rpc/handlers/Connect.cpp b/src/ripple/rpc/handlers/Connect.cpp index e4af68916a..dc05a7b1ab 100644 --- a/src/ripple/rpc/handlers/Connect.cpp +++ b/src/ripple/rpc/handlers/Connect.cpp @@ -38,7 +38,7 @@ namespace ripple { Json::Value doConnect (RPC::Context& context) { auto lock = beast::make_lock(context.app.getMasterMutex()); - if (getConfig ().RUN_STANDALONE) + if (context.app.config().RUN_STANDALONE) return "cannot connect in standalone mode"; if (!context.params.isMember (jss::ip)) diff --git a/src/ripple/rpc/handlers/LedgerAccept.cpp b/src/ripple/rpc/handlers/LedgerAccept.cpp index 9ded7eda88..6d4bb4c186 100644 --- a/src/ripple/rpc/handlers/LedgerAccept.cpp +++ b/src/ripple/rpc/handlers/LedgerAccept.cpp @@ -36,7 +36,7 @@ Json::Value doLedgerAccept (RPC::Context& context) auto lock = beast::make_lock(context.app.getMasterMutex()); Json::Value jvResult; - if (!getConfig ().RUN_STANDALONE) + if (!context.app.config().RUN_STANDALONE) { jvResult[jss::error] = "notStandAlone"; } diff --git a/src/ripple/rpc/handlers/RipplePathFind.cpp b/src/ripple/rpc/handlers/RipplePathFind.cpp index 9e24e71a17..ae41e554d3 100644 --- a/src/ripple/rpc/handlers/RipplePathFind.cpp +++ b/src/ripple/rpc/handlers/RipplePathFind.cpp @@ -83,7 +83,7 @@ Json::Value doRipplePathFind (RPC::Context& context) Json::Value jvResult; if (true || // TODO MPORTILLA temp fix to disable broken websocket coroutines - getConfig().RUN_STANDALONE || + context.app.config().RUN_STANDALONE || context.params.isMember(jss::ledger) || context.params.isMember(jss::ledger_index) || context.params.isMember(jss::ledger_hash)) @@ -205,7 +205,7 @@ Json::Value doRipplePathFind (RPC::Context& context) jvResult[jss::destination_currencies] = jvDestCur; jvResult[jss::destination_account] = context.app.accountIDCache().toBase58(raDst); - int level = getConfig().PATH_SEARCH_OLD; + int level = context.app.config().PATH_SEARCH_OLD; if ((context.app.config().PATH_SEARCH_MAX > level) && !context.app.getFeeTrack().isLoadedLocal()) { diff --git a/src/ripple/rpc/handlers/SignFor.cpp b/src/ripple/rpc/handlers/SignFor.cpp index 046e43a840..655d170db8 100755 --- a/src/ripple/rpc/handlers/SignFor.cpp +++ b/src/ripple/rpc/handlers/SignFor.cpp @@ -36,7 +36,7 @@ Json::Value doSignFor (RPC::Context& context) { // Bail if multisign is not enabled. if (! context.app.getLedgerMaster().getValidatedRules(). - enabled (featureMultiSign, getConfig().features)) + enabled (featureMultiSign, context.app.config().features)) { RPC::inject_error (rpcNOT_ENABLED, context.params); return context.params; diff --git a/src/ripple/rpc/handlers/SubmitMultiSigned.cpp b/src/ripple/rpc/handlers/SubmitMultiSigned.cpp index 1d75abe8ab..3430ffe36e 100644 --- a/src/ripple/rpc/handlers/SubmitMultiSigned.cpp +++ b/src/ripple/rpc/handlers/SubmitMultiSigned.cpp @@ -35,7 +35,7 @@ Json::Value doSubmitMultiSigned (RPC::Context& context) { // Bail if multisign is not enabled. if (! context.app.getLedgerMaster().getValidatedRules(). - enabled (featureMultiSign, getConfig().features)) + enabled (featureMultiSign, context.app.config().features)) { RPC::inject_error (rpcNOT_ENABLED, context.params); return context.params; diff --git a/src/ripple/rpc/handlers/Subscribe.cpp b/src/ripple/rpc/handlers/Subscribe.cpp index 553e4109de..248287f8d7 100644 --- a/src/ripple/rpc/handlers/Subscribe.cpp +++ b/src/ripple/rpc/handlers/Subscribe.cpp @@ -74,7 +74,7 @@ Json::Value doSubscribe (RPC::Context& context) WriteLog (lsDEBUG, RPCHandler) << "doSubscribe: building: " << strUrl; - RPCSub::pointer rspSub = RPCSub::New (context.app.getOPs (), + auto rspSub = make_RPCSub (context.app.getOPs (), context.app.getIOService (), context.app.getJobQueue (), strUrl, strUsername, strPassword); ispSub = context.netOps.addRpcSub ( @@ -85,11 +85,17 @@ Json::Value doSubscribe (RPC::Context& context) WriteLog (lsTRACE, RPCHandler) << "doSubscribe: reusing: " << strUrl; - if (context.params.isMember (jss::username)) - dynamic_cast (&*ispSub)->setUsername (strUsername); + if (auto rpcSub = std::dynamic_pointer_cast (ispSub)) + { + // Why do we need to check isMember against jss::username and + // jss::password here instead of just setting the username and + // the password? What about url_username and url_password? + if (context.params.isMember (jss::username)) + rpcSub->setUsername (strUsername); - if (context.params.isMember (jss::password)) - dynamic_cast (&*ispSub)->setPassword (strPassword); + if (context.params.isMember (jss::password)) + rpcSub->setPassword (strPassword); + } } } else diff --git a/src/ripple/rpc/handlers/UnlLoad.cpp b/src/ripple/rpc/handlers/UnlLoad.cpp index 8d1091873f..6ba0dd39d7 100644 --- a/src/ripple/rpc/handlers/UnlLoad.cpp +++ b/src/ripple/rpc/handlers/UnlLoad.cpp @@ -33,8 +33,8 @@ Json::Value doUnlLoad (RPC::Context& context) { auto lock = beast::make_lock(context.app.getMasterMutex()); - if (getConfig ().VALIDATORS_FILE.empty () - || !context.app.getUNL ().nodeLoad (getConfig ().VALIDATORS_FILE)) + if (context.app.config().VALIDATORS_FILE.empty () + || !context.app.getUNL ().nodeLoad (context.app.config().VALIDATORS_FILE)) { return rpcError (rpcLOAD_FAILED); } diff --git a/src/ripple/rpc/handlers/ValidationSeed.cpp b/src/ripple/rpc/handlers/ValidationSeed.cpp index 67b9a25916..406ea0dbbf 100644 --- a/src/ripple/rpc/handlers/ValidationSeed.cpp +++ b/src/ripple/rpc/handlers/ValidationSeed.cpp @@ -34,39 +34,45 @@ namespace ripple { // } Json::Value doValidationSeed (RPC::Context& context) { - auto lock = beast::make_lock(context.app.getMasterMutex()); - Json::Value obj (Json::objectValue); + // TODO: This feature is temporarily disabled since we + // cannot modify the config object. We should consider + // whether we want the ability to change the validator + // keys at runtime. + return rpcError (rpcNOT_IMPL); - if (!context.params.isMember (jss::secret)) - { - std::cerr << "Unset validation seed." << std::endl; + // auto lock = beast::make_lock(context.app.getMasterMutex()); + // Json::Value obj (Json::objectValue); - getConfig ().VALIDATION_SEED.clear (); - getConfig ().VALIDATION_PUB.clear (); - getConfig ().VALIDATION_PRIV.clear (); - } - else if (!getConfig ().VALIDATION_SEED.setSeedGeneric ( - context.params[jss::secret].asString ())) - { - getConfig ().VALIDATION_PUB.clear (); - getConfig ().VALIDATION_PRIV.clear (); + // if (!context.params.isMember (jss::secret)) + // { + // std::cerr << "Unset validation seed." << std::endl; - return rpcError (rpcBAD_SEED); - } - else - { - auto& seed = getConfig ().VALIDATION_SEED; - auto& pub = getConfig ().VALIDATION_PUB; + // context.app.config().VALIDATION_SEED.clear (); + // context.app.config().VALIDATION_PUB.clear (); + // context.app.config().VALIDATION_PRIV.clear (); + // } + // else if (!context.app.config().VALIDATION_SEED.setSeedGeneric ( + // context.params[jss::secret].asString ())) + // { + // context.app.config().VALIDATION_PUB.clear (); + // context.app.config().VALIDATION_PRIV.clear (); - pub = RippleAddress::createNodePublic (seed); - getConfig ().VALIDATION_PRIV = RippleAddress::createNodePrivate (seed); + // return rpcError (rpcBAD_SEED); + // } + // else + // { + // auto& seed = context.app.config().VALIDATION_SEED; + // auto& pub = context.app.config().VALIDATION_PUB; - obj[jss::validation_public_key] = pub.humanNodePublic (); - obj[jss::validation_seed] = seed.humanSeed (); - obj[jss::validation_key] = seed.humanSeed1751 (); - } + // pub = RippleAddress::createNodePublic (seed); + // context.app.config().VALIDATION_PRIV = RippleAddress::createNodePrivate (seed); - return obj; + // obj[jss::validation_public_key] = pub.humanNodePublic (); + // obj[jss::validation_seed] = seed.humanSeed (); + // obj[jss::validation_key] = seed.humanSeed1751 (); + // } + + // return obj; } } // ripple diff --git a/src/ripple/rpc/impl/LookupLedger.cpp b/src/ripple/rpc/impl/LookupLedger.cpp index 9099764d2c..679a2a0cd3 100644 --- a/src/ripple/rpc/impl/LookupLedger.cpp +++ b/src/ripple/rpc/impl/LookupLedger.cpp @@ -33,9 +33,9 @@ namespace RPC { namespace { -bool isValidatedOld (LedgerMaster& ledgerMaster) +bool isValidatedOld (LedgerMaster& ledgerMaster, bool standalone) { - if (getConfig ().RUN_STANDALONE) + if (standalone) return false; return ledgerMaster.getValidatedLedgerAge () > @@ -93,7 +93,7 @@ Status ledgerFromRequest (T& ledger, Context& context) return {rpcLGR_NOT_FOUND, "ledgerNotFound"}; if (ledger->info().seq > ledgerMaster.getValidLedgerIndex() && - isValidatedOld(ledgerMaster)) + isValidatedOld(ledgerMaster, context.app.config().RUN_STANDALONE)) { ledger.reset(); return {rpcNO_NETWORK, "InsufficientNetworkMode"}; @@ -101,7 +101,7 @@ Status ledgerFromRequest (T& ledger, Context& context) } else { - if (isValidatedOld (ledgerMaster)) + if (isValidatedOld (ledgerMaster, context.app.config().RUN_STANDALONE)) return {rpcNO_NETWORK, "InsufficientNetworkMode"}; auto const index = indexValue.asString (); diff --git a/src/ripple/rpc/impl/RPCHandler.cpp b/src/ripple/rpc/impl/RPCHandler.cpp index 949a05a520..3b0dc8693d 100644 --- a/src/ripple/rpc/impl/RPCHandler.cpp +++ b/src/ripple/rpc/impl/RPCHandler.cpp @@ -150,7 +150,7 @@ error_code_i fillHandler (Context& context, return rpcNO_NETWORK; } - if (! getConfig ().RUN_STANDALONE && + if (!context.app.config().RUN_STANDALONE && handler->condition_ & NEEDS_CURRENT_LEDGER) { if (context.ledgerMaster.getValidatedLedgerAge () > diff --git a/src/ripple/rpc/impl/TransactionSign.cpp b/src/ripple/rpc/impl/TransactionSign.cpp index 072dbd20e6..69156b4fe0 100644 --- a/src/ripple/rpc/impl/TransactionSign.cpp +++ b/src/ripple/rpc/impl/TransactionSign.cpp @@ -200,7 +200,7 @@ static Json::Value checkPayment( *dstAccountID, sendMax.issue(), amount, - getConfig().PATH_SEARCH_OLD, + app.config().PATH_SEARCH_OLD, 4, // iMaxPaths {}, fullLiquidityPath, @@ -239,6 +239,7 @@ checkTxJsonFields ( Role const role, bool const verify, int validatedLedgerAge, + Config const& config, LoadFeeTrack const& feeTrack) { std::pair ret; @@ -273,7 +274,7 @@ checkTxJsonFields ( } // Check for current ledger. - if (verify && !getConfig ().RUN_STANDALONE && + if (verify && !config.RUN_STANDALONE && (validatedLedgerAge > Tuning::maxValidatedLedgerAge)) { ret.first = rpcError (rpcNO_CURRENT); @@ -352,7 +353,8 @@ transactionPreProcessImpl ( // Check tx_json fields, but don't add any. auto txJsonResult = checkTxJsonFields ( - tx_json, role, verify, validatedLedgerAge, app.getFeeTrack()); + tx_json, role, verify, validatedLedgerAge, + app.config(), app.getFeeTrack()); if (RPC::contains_error (txJsonResult.first)) return std::move (txJsonResult.first); @@ -384,6 +386,7 @@ transactionPreProcessImpl ( params, role, signingArgs.editFields(), + app.config(), app.getFeeTrack(), ledger); @@ -594,6 +597,7 @@ Json::Value checkFee ( Json::Value& request, Role const role, bool doAutoFill, + Config const& config, LoadFeeTrack const& feeTrack, std::shared_ptr& ledger) { @@ -619,7 +623,7 @@ Json::Value checkFee ( } // Default fee in fee units. - std::uint64_t const feeDefault = getConfig().TRANSACTION_FEE_BASE; + std::uint64_t const feeDefault = config.TRANSACTION_FEE_BASE; // Administrative endpoints are exempt from local fees. std::uint64_t const fee = @@ -874,7 +878,8 @@ Json::Value transactionSubmitMultiSigned ( Json::Value& tx_json (jvRequest ["tx_json"]); auto const txJsonResult = checkTxJsonFields ( - tx_json, role, true, validatedLedgerAge, app.getFeeTrack()); + tx_json, role, true, validatedLedgerAge, + app.config(), app.getFeeTrack()); if (RPC::contains_error (txJsonResult.first)) return std::move (txJsonResult.first); @@ -897,7 +902,7 @@ Json::Value transactionSubmitMultiSigned ( { Json::Value err = checkFee ( - jvRequest, role, false, app.getFeeTrack(), ledger); + jvRequest, role, false, app.config(), app.getFeeTrack(), ledger); if (RPC::contains_error(err)) return std::move (err); diff --git a/src/ripple/rpc/impl/TransactionSign.h b/src/ripple/rpc/impl/TransactionSign.h index 9ffae811a2..ec38bb573a 100644 --- a/src/ripple/rpc/impl/TransactionSign.h +++ b/src/ripple/rpc/impl/TransactionSign.h @@ -56,6 +56,7 @@ Json::Value checkFee ( Json::Value& request, Role const role, bool doAutoFill, + Config const& config, LoadFeeTrack const& feeTrack, std::shared_ptr& ledger); diff --git a/src/ripple/rpc/tests/JSONRPC.test.cpp b/src/ripple/rpc/tests/JSONRPC.test.cpp index 327a9ea25b..a2a8b0a319 100644 --- a/src/ripple/rpc/tests/JSONRPC.test.cpp +++ b/src/ripple/rpc/tests/JSONRPC.test.cpp @@ -1397,9 +1397,9 @@ public: void testAutoFillFees () { test::jtx::Env env(*this); - Config const config; std::shared_ptr ledger = - std::make_shared(create_genesis, config, env.app().family()); + std::make_shared(create_genesis, + env.app().config(), env.app().family()); LoadFeeTrack const feeTrack; { @@ -1407,7 +1407,8 @@ public: Json::Reader ().parse ( "{ \"fee_mult_max\" : 1, \"tx_json\" : { } } ", req); Json::Value result = - checkFee (req, Role::ADMIN, true, feeTrack, ledger); + checkFee (req, Role::ADMIN, true, + env.app().config(), feeTrack, ledger); expect (! RPC::contains_error (result), "Legal checkFee"); } @@ -1417,7 +1418,8 @@ public: Json::Reader ().parse ( "{ \"fee_mult_max\" : 0, \"tx_json\" : { } } ", req); Json::Value result = - checkFee (req, Role::ADMIN, true, feeTrack, ledger); + checkFee (req, Role::ADMIN, true, + env.app().config(), feeTrack, ledger); expect (RPC::contains_error (result), "Invalid checkFee"); } diff --git a/src/ripple/server/impl/JSONRPCUtil.cpp b/src/ripple/server/impl/JSONRPCUtil.cpp index b2fabc0846..2ed356c4ce 100644 --- a/src/ripple/server/impl/JSONRPCUtil.cpp +++ b/src/ripple/server/impl/JSONRPCUtil.cpp @@ -101,7 +101,7 @@ void HTTPReply ( "Content-Length: "); // VFALCO TODO Determine if/when this header should be added - //if (getConfig ().RPC_ALLOW_REMOTE) + //if (context.app.config().RPC_ALLOW_REMOTE) // output ("Access-Control-Allow-Origin: *\r\n"); output (std::to_string(content.size () + 2)); diff --git a/src/ripple/test/jtx/Env.h b/src/ripple/test/jtx/Env.h index 4f62c15f1d..c1a38fb774 100644 --- a/src/ripple/test/jtx/Env.h +++ b/src/ripple/test/jtx/Env.h @@ -127,7 +127,6 @@ public: beast::Journal const journal; /** Configuration used. */ - // VFALCO NOTE Some code still calls getConfig() Config const config; /** The master account. */ diff --git a/src/ripple/test/jtx/impl/Env.cpp b/src/ripple/test/jtx/impl/Env.cpp index 4477cb4840..e190427d98 100644 --- a/src/ripple/test/jtx/impl/Env.cpp +++ b/src/ripple/test/jtx/impl/Env.cpp @@ -53,6 +53,7 @@ namespace jtx { // VFALCO Could wrap the log in a Journal here Env::Env (beast::unit_test::suite& test_) : test(test_) + , config() , master("master", generateKeyPair( KeyType::secp256k1, generateSeed("masterpassphrase"))) @@ -105,7 +106,7 @@ Env::close(NetClock::time_point const& closeTime) next->setAccepted ( std::chrono::duration_cast ( closeTime.time_since_epoch ()).count (), - ledgerPossibleTimeResolutions[0], false); + ledgerPossibleTimeResolutions[0], false, app().config()); OrderedTxs locals({}); openLedger.accept(app(), next->rules(), next, locals, false, retries, applyFlags(), *router); diff --git a/src/ripple/websocket/Connection.h b/src/ripple/websocket/Connection.h index 2480a58de9..da311f3977 100644 --- a/src/ripple/websocket/Connection.h +++ b/src/ripple/websocket/Connection.h @@ -119,6 +119,8 @@ private: handler_type& m_handler; weak_connection_ptr m_connection; + + int pingFreq_; }; template @@ -141,7 +143,10 @@ ConnectionImpl ::ConnectionImpl ( , m_pingTimer (io_service) , m_handler (handler) , m_connection (cpConnection) + , pingFreq_ (app.config ().WEBSOCKET_PING_FREQ) { + // VFALCO Disabled since it might cause hangs + pingFreq_ = 0; } template diff --git a/src/ripple/websocket/WebSocket02.cpp b/src/ripple/websocket/WebSocket02.cpp index d91f91bcad..1b0d200609 100644 --- a/src/ripple/websocket/WebSocket02.cpp +++ b/src/ripple/websocket/WebSocket02.cpp @@ -73,16 +73,13 @@ boost::asio::io_service::strand& WebSocket02::getStrand (Connection& con) template <> void ConnectionImpl ::setPingTimer () { - auto freq = getConfig ().WEBSOCKET_PING_FREQ; - // VFALCO Disabled since it might cause hangs - freq = 0; - if (freq <= 0) + if (pingFreq_ <= 0) return; connection_ptr ptr = m_connection.lock (); - if (ptr) { - this->m_pingTimer.expires_from_now (boost::posix_time::seconds (freq)); + this->m_pingTimer.expires_from_now ( + boost::posix_time::seconds (pingFreq_)); this->m_pingTimer.async_wait ( ptr->get_strand ().wrap ( diff --git a/src/ripple/websocket/WebSocket04.cpp b/src/ripple/websocket/WebSocket04.cpp index fa1fde5d9d..2c961b20f0 100644 --- a/src/ripple/websocket/WebSocket04.cpp +++ b/src/ripple/websocket/WebSocket04.cpp @@ -115,14 +115,11 @@ EndpointPtr04 WebSocket04::makeEndpoint (HandlerPtr&& handler) template <> void ConnectionImpl ::setPingTimer () { - auto freq = getConfig ().WEBSOCKET_PING_FREQ; - // VFALCO Disabled since it might cause hangs - freq = 0; - if (freq <= 0) + if (pingFreq_ <= 0) return; if (auto con = m_connection.lock ()) { - auto t = boost::posix_time::seconds (freq); + auto t = boost::posix_time::seconds (pingFreq_); auto ms = t.total_milliseconds(); con->set_timer ( ms,