diff --git a/src/beast/beast/hash/hash_append.h b/src/beast/beast/hash/hash_append.h index 6cab78cc7..5cd5c85b1 100644 --- a/src/beast/beast/hash/hash_append.h +++ b/src/beast/beast/hash/hash_append.h @@ -25,6 +25,7 @@ #include #include #include +#include #include #include #include @@ -472,6 +473,24 @@ hash_append (Hasher& h, std::shared_ptr const& p) noexcept hash_append(h, p.get()); } +// chrono + +template +inline +void +hash_append (Hasher& h, std::chrono::duration const& d) noexcept +{ + hash_append(h, d.count()); +} + +template +inline +void +hash_append (Hasher& h, std::chrono::time_point const& tp) noexcept +{ + hash_append(h, tp.time_since_epoch()); +} + // variadic template diff --git a/src/ripple/app/ledger/Consensus.h b/src/ripple/app/ledger/Consensus.h index a54374a30..edf16be62 100644 --- a/src/ripple/app/ledger/Consensus.h +++ b/src/ripple/app/ledger/Consensus.h @@ -59,7 +59,7 @@ public: /** Returns the time (in milliseconds) that the last close took. */ virtual - int + std::chrono::milliseconds getLastCloseDuration () const = 0; /** Called when a new round of consensus is about to begin */ @@ -72,12 +72,12 @@ public: LedgerMaster& ledgerMaster, LedgerHash const &prevLCLHash, Ledger::ref previousLedger, - std::uint32_t closeTime) = 0; + NetClock::time_point closeTime) = 0; /** Specified the network time when the last ledger closed */ virtual void - setLastCloseTime (std::uint32_t t) = 0; + setLastCloseTime (NetClock::time_point t) = 0; virtual void diff --git a/src/ripple/app/ledger/Ledger.cpp b/src/ripple/app/ledger/Ledger.cpp index d210ef64d..2a9cf92fe 100644 --- a/src/ripple/app/ledger/Ledger.cpp +++ b/src/ripple/app/ledger/Ledger.cpp @@ -198,10 +198,10 @@ Ledger::Ledger (uint256 const& parentHash, uint256 const& transHash, uint256 const& accountHash, std::uint64_t totDrops, - std::uint32_t closeTime, - std::uint32_t parentCloseTime, + NetClock::time_point closeTime, + NetClock::time_point parentCloseTime, int closeFlags, - int closeResolution, + NetClock::duration closeResolution, std::uint32_t ledgerSeq, bool& loaded, Config const& config, @@ -280,14 +280,12 @@ Ledger::Ledger (open_ledger_t, Ledger const& prevLedger, info_.drops = prevLedger.info().drops; info_.closeTimeResolution = prevLedger.info_.closeTimeResolution; info_.parentHash = prevLedger.getHash (); - info_.closeTimeResolution = getNextLedgerTimeResolution ( + info_.closeTimeResolution = getNextLedgerTimeResolution( prevLedger.info_.closeTimeResolution, getCloseAgree(prevLedger.info()), info_.seq); - if (prevLedger.info_.closeTime == 0) + if (prevLedger.info_.closeTime == NetClock::time_point{}) { - info_.closeTime = roundCloseTime ( - closeTime.time_since_epoch().count(), - info_.closeTimeResolution); + info_.closeTime = roundCloseTime(closeTime, info_.closeTimeResolution); } else { @@ -311,7 +309,7 @@ Ledger::Ledger (void const* data, } Ledger::Ledger (std::uint32_t ledgerSeq, - std::uint32_t closeTime, Config const& config, + NetClock::time_point closeTime, Config const& config, Family& family) : mImmutable (false) , txMap_ (std::make_shared ( @@ -368,9 +366,9 @@ void Ledger::updateHash() info_.parentHash, info_.txHash, info_.accountHash, - std::uint32_t(info_.parentCloseTime), - std::uint32_t(info_.closeTime), - std::uint8_t(info_.closeTimeResolution), + std::uint32_t(info_.parentCloseTime.time_since_epoch().count()), + std::uint32_t(info_.closeTime.time_since_epoch().count()), + std::uint8_t(info_.closeTimeResolution.count()), std::uint8_t(info_.closeFlags)); mValidHash = true; } @@ -385,9 +383,9 @@ void Ledger::setRaw (SerialIter& sit, bool hasPrefix, Family& family) info_.parentHash = sit.get256 (); info_.txHash = sit.get256 (); info_.accountHash = sit.get256 (); - info_.parentCloseTime = sit.get32 (); - info_.closeTime = sit.get32 (); - info_.closeTimeResolution = sit.get8 (); + info_.parentCloseTime = NetClock::time_point{NetClock::duration{sit.get32()}}; + info_.closeTime = NetClock::time_point{NetClock::duration{sit.get32()}}; + info_.closeTimeResolution = NetClock::duration{sit.get8()}; info_.closeFlags = sit.get8 (); updateHash (); txMap_ = std::make_shared (SHAMapType::TRANSACTION, info_.txHash, @@ -401,9 +399,10 @@ void Ledger::addRaw (Serializer& s) const ripple::addRaw(info_, s); } -void Ledger::setAccepted ( - std::uint32_t closeTime, int closeResolution, bool correctCloseTime, - Config const& config) +void +Ledger::setAccepted(NetClock::time_point closeTime, + NetClock::duration closeResolution, + bool correctCloseTime, Config const& config) { // Used when we witnessed the consensus. assert (closed()); @@ -477,17 +476,6 @@ bool Ledger::isAcquiringAS (void) const return stateMap_->isSynching (); } -boost::posix_time::ptime Ledger::getCloseTime () const -{ - return ptFromSeconds (info_.closeTime); -} - -void Ledger::setCloseTime (boost::posix_time::ptime ptm) -{ - assert (!mImmutable); - info_.closeTime = iToSeconds (ptm); -} - //------------------------------------------------------------------------------ bool @@ -1096,8 +1084,10 @@ static bool saveValidatedLedger ( *db << boost::str ( addLedger % to_string (ledger->info().hash) % seq % to_string (ledger->info().parentHash) % - to_string (ledger->info().drops) % ledger->info().closeTime % - ledger->info().parentCloseTime % ledger->info().closeTimeResolution % + to_string (ledger->info().drops) % + ledger->info().closeTime.time_since_epoch().count() % + ledger->info().parentCloseTime.time_since_epoch().count() % + ledger->info().closeTimeResolution.count() % ledger->info().closeFlags % to_string (ledger->info().accountHash) % to_string (ledger->info().txHash)); } @@ -1286,15 +1276,17 @@ loadLedgerHelper(std::string const& sqlSuffix, Application& app) if (sTransHash) transHash.SetHexExact (*sTransHash); + using time_point = NetClock::time_point; + using duration = NetClock::duration; bool loaded = false; ledger = std::make_shared(prevHash, transHash, accountHash, totDrops.value_or(0), - closingTime.value_or(0), - prevClosingTime.value_or(0), + time_point{duration{closingTime.value_or(0)}}, + time_point{duration{prevClosingTime.value_or(0)}}, closeFlags.value_or(0), - closeResolution.value_or(0), + duration{closeResolution.value_or(0)}, ledgerSeq, loaded, app.config(), diff --git a/src/ripple/app/ledger/Ledger.h b/src/ripple/app/ledger/Ledger.h index b360e3eb2..822a2ab7b 100644 --- a/src/ripple/app/ledger/Ledger.h +++ b/src/ripple/app/ledger/Ledger.h @@ -103,8 +103,9 @@ public: // Used for ledgers loaded from JSON files Ledger (uint256 const& parentHash, uint256 const& transHash, uint256 const& accountHash, - std::uint64_t totDrops, std::uint32_t closeTime, - std::uint32_t parentCloseTime, int closeFlags, int closeResolution, + std::uint64_t totDrops, NetClock::time_point closeTime, + NetClock::time_point parentCloseTime, int closeFlags, + NetClock::duration closeResolution, std::uint32_t ledgerSeq, bool & loaded, Config const& config, Family& family, beast::Journal j); @@ -127,7 +128,7 @@ public: // used for database ledgers Ledger (std::uint32_t ledgerSeq, - std::uint32_t closeTime, Config const& config, + NetClock::time_point closeTime, Config const& config, Family& family); ~Ledger(); @@ -236,8 +237,8 @@ public: info_.validated = true; } - void setAccepted (std::uint32_t closeTime, - int closeResolution, bool correctCloseTime, + void setAccepted (NetClock::time_point closeTime, + NetClock::duration closeResolution, bool correctCloseTime, Config const& config); void setImmutable (Config const& config); @@ -273,17 +274,6 @@ public: info_.drops = totDrops; } - // close time functions - void setCloseTime (std::uint32_t when) - { - assert (!mImmutable); - info_.closeTime = when; - } - - void setCloseTime (boost::posix_time::ptime); - - boost::posix_time::ptime getCloseTime () const; - SHAMap const& stateMap() const { diff --git a/src/ripple/app/ledger/LedgerMaster.h b/src/ripple/app/ledger/LedgerMaster.h index 7745b3aa1..44c27406b 100644 --- a/src/ripple/app/ledger/LedgerMaster.h +++ b/src/ripple/app/ledger/LedgerMaster.h @@ -43,7 +43,7 @@ class Transaction; struct LedgerReplay { std::map< int, std::shared_ptr > txns_; - std::uint32_t closeTime_; + NetClock::time_point closeTime_; int closeFlags_; Ledger::pointer prevLedger_; }; @@ -93,8 +93,8 @@ public: virtual bool isValidLedger(LedgerInfo const&) = 0; - virtual int getPublishedLedgerAge () = 0; - virtual int getValidatedLedgerAge () = 0; + virtual std::chrono::seconds getPublishedLedgerAge () = 0; + virtual std::chrono::seconds getValidatedLedgerAge () = 0; virtual bool isCaughtUp(std::string& reason) = 0; virtual int getMinValidations () = 0; @@ -137,10 +137,10 @@ public: virtual uint256 getLedgerHash( std::uint32_t desiredSeq, Ledger::ref knownGoodLedger) = 0; - virtual boost::optional getCloseTimeBySeq ( + virtual boost::optional getCloseTimeBySeq ( LedgerIndex ledgerIndex) = 0; - virtual boost::optional getCloseTimeByHash ( + virtual boost::optional getCloseTimeByHash ( LedgerHash const& ledgerHash) = 0; virtual void addHeldTransaction (std::shared_ptr const& trans) = 0; diff --git a/src/ripple/app/ledger/LedgerProposal.cpp b/src/ripple/app/ledger/LedgerProposal.cpp index 24f786a2e..5f12f589a 100644 --- a/src/ripple/app/ledger/LedgerProposal.cpp +++ b/src/ripple/app/ledger/LedgerProposal.cpp @@ -31,7 +31,7 @@ LedgerProposal::LedgerProposal ( uint256 const& pLgr, std::uint32_t seq, uint256 const& tx, - std::uint32_t closeTime, + NetClock::time_point closeTime, RippleAddress const& publicKey, PublicKey const& pk, uint256 const& suppression) @@ -51,7 +51,7 @@ LedgerProposal::LedgerProposal ( RippleAddress const& publicKey, uint256 const& prevLgr, uint256 const& position, - std::uint32_t closeTime) + NetClock::time_point closeTime) : mPreviousLedger (prevLgr) , mCurrentHash (position) , mCloseTime (closeTime) @@ -69,7 +69,7 @@ uint256 LedgerProposal::getSigningHash () const return sha512Half( HashPrefix::proposal, std::uint32_t(mProposeSeq), - std::uint32_t(mCloseTime), + mCloseTime.time_since_epoch().count(), mPreviousLedger, mCurrentHash); } @@ -82,7 +82,7 @@ bool LedgerProposal::checkSign (std::string const& signature) const bool LedgerProposal::changePosition ( uint256 const& newPosition, - std::uint32_t closeTime) + NetClock::time_point closeTime) { if (mProposeSeq == seqLeave) return false; @@ -120,7 +120,7 @@ Json::Value LedgerProposal::getJson () const ret[jss::propose_seq] = mProposeSeq; } - ret[jss::close_time] = mCloseTime; + ret[jss::close_time] = mCloseTime.time_since_epoch().count(); if (mPublicKey.isValid ()) ret[jss::peer_id] = mPublicKey.humanNodePublic (); @@ -132,7 +132,7 @@ uint256 proposalUniqueId ( uint256 const& proposeHash, uint256 const& previousLedger, std::uint32_t proposeSeq, - std::uint32_t closeTime, + NetClock::time_point closeTime, Blob const& pubKey, Blob const& signature) { @@ -141,7 +141,7 @@ uint256 proposalUniqueId ( s.add256 (proposeHash); s.add256 (previousLedger); s.add32 (proposeSeq); - s.add32 (closeTime); + s.add32 (closeTime.time_since_epoch().count()); s.addVL (pubKey); s.addVL (signature); diff --git a/src/ripple/app/ledger/LedgerProposal.h b/src/ripple/app/ledger/LedgerProposal.h index a434b0809..fd48d1c82 100644 --- a/src/ripple/app/ledger/LedgerProposal.h +++ b/src/ripple/app/ledger/LedgerProposal.h @@ -54,7 +54,7 @@ public: uint256 const& prevLgr, std::uint32_t proposeSeq, uint256 const& propose, - std::uint32_t closeTime, + NetClock::time_point closeTime, RippleAddress const& publicKey, PublicKey const& pk, uint256 const& suppress); @@ -65,7 +65,7 @@ public: RippleAddress const& publicKey, uint256 const& prevLedger, uint256 const& position, - std::uint32_t closeTime); + NetClock::time_point closeTime); uint256 getSigningHash () const; bool checkSign (std::string const& signature) const; @@ -90,7 +90,7 @@ public: { return mProposeSeq; } - std::uint32_t getCloseTime () const + NetClock::time_point getCloseTime () const { return mCloseTime; } @@ -116,7 +116,7 @@ public: } bool changePosition ( - uint256 const& newPosition, std::uint32_t newCloseTime); + uint256 const& newPosition, NetClock::time_point newCloseTime); void bowOut (); Json::Value getJson () const; @@ -128,13 +128,14 @@ private: using beast::hash_append; hash_append(h, HashPrefix::proposal); hash_append(h, std::uint32_t(mProposeSeq)); - hash_append(h, std::uint32_t(mCloseTime)); + hash_append(h, mCloseTime); hash_append(h, mPreviousLedger); hash_append(h, mCurrentHash); } uint256 mPreviousLedger, mCurrentHash, mSuppression; - std::uint32_t mCloseTime, mProposeSeq; + NetClock::time_point mCloseTime; + std::uint32_t mProposeSeq; NodeID mPeerID; RippleAddress mPublicKey; @@ -156,7 +157,7 @@ uint256 proposalUniqueId ( uint256 const& proposeHash, uint256 const& previousLedger, std::uint32_t proposeSeq, - std::uint32_t closeTime, + NetClock::time_point closeTime, Blob const& pubKey, Blob const& signature); diff --git a/src/ripple/app/ledger/LedgerTiming.h b/src/ripple/app/ledger/LedgerTiming.h index d8d42effc..40134f754 100644 --- a/src/ripple/app/ledger/LedgerTiming.h +++ b/src/ripple/app/ledger/LedgerTiming.h @@ -20,7 +20,9 @@ #ifndef RIPPLE_APP_LEDGER_LEDGERTIMING_H_INCLUDED #define RIPPLE_APP_LEDGER_LEDGERTIMING_H_INCLUDED +#include #include +#include namespace ripple { @@ -32,8 +34,9 @@ namespace ripple { The time resolution (i.e. the size of the intervals) is adjusted dynamically based on what happened in the last ledger, to try to avoid disagreements. */ -int getNextLedgerTimeResolution ( - int previousResolution, +NetClock::duration +getNextLedgerTimeResolution ( + NetClock::duration previousResolution, bool previousAgree, std::uint32_t ledgerSeq); @@ -42,9 +45,10 @@ int getNextLedgerTimeResolution ( @param closeTime The time to be rouned. @param closeResolution The resolution */ -std::uint32_t roundCloseTime ( - std::uint32_t closeTime, - std::uint32_t closeResolution); +NetClock::time_point +roundCloseTime ( + NetClock::time_point closeTime, + NetClock::duration closeResolution); //------------------------------------------------------------------------------ @@ -52,72 +56,79 @@ std::uint32_t roundCloseTime ( // they should not be changed arbitrarily. // The percentage threshold above which we can declare consensus. -int const minimumConsensusPercentage = 80; +auto constexpr minimumConsensusPercentage = 80; +using namespace std::chrono_literals; // All possible close time resolutions. Values should not be duplicated. -int const ledgerPossibleTimeResolutions[] = { 10, 20, 30, 60, 90, 120 }; +std::chrono::seconds constexpr ledgerPossibleTimeResolutions[] = + { 10s, 20s, 30s, 60s, 90s, 120s }; +#ifndef _MSC_VER // Initial resolution of ledger close time. -int const ledgerDefaultTimeResolution = ledgerPossibleTimeResolutions[2]; +auto constexpr ledgerDefaultTimeResolution = ledgerPossibleTimeResolutions[2]; +#else +// HH Remove this workaround of a VS bug when possible +auto constexpr ledgerDefaultTimeResolution = 30s; +#endif // How often we increase the close time resolution -int const increaseLedgerTimeResolutionEvery = 8; +auto constexpr increaseLedgerTimeResolutionEvery = 8; // How often we decrease the close time resolution -int const decreaseLedgerTimeResolutionEvery = 1; +auto constexpr decreaseLedgerTimeResolutionEvery = 1; // The number of seconds a ledger may remain idle before closing -const int LEDGER_IDLE_INTERVAL = 15; +auto constexpr LEDGER_IDLE_INTERVAL = 15s; // The number of seconds a validation remains current after its ledger's close // time. This is a safety to protect against very old validations and the time // it takes to adjust the close time accuracy window -const int VALIDATION_VALID_WALL = 300; +auto constexpr VALIDATION_VALID_WALL = 5min; // The number of seconds a validation remains current after the time we first // saw it. This provides faster recovery in very rare cases where the number // of validations produced by the network is lower than normal -const int VALIDATION_VALID_LOCAL = 180; +auto constexpr VALIDATION_VALID_LOCAL = 3min; // The number of seconds before a close time that we consider a validation // acceptable. This protects against extreme clock errors -const int VALIDATION_VALID_EARLY = 180; +auto constexpr VALIDATION_VALID_EARLY = 3min; -// The number of milliseconds we wait minimum to ensure participation -const int LEDGER_MIN_CONSENSUS = 2000; +// The number of seconds we wait minimum to ensure participation +auto constexpr LEDGER_MIN_CONSENSUS = 2s; -// Minimum number of milliseconds to wait to ensure others have computed the LCL -const int LEDGER_MIN_CLOSE = 2000; +// Minimum number of seconds to wait to ensure others have computed the LCL +auto constexpr LEDGER_MIN_CLOSE = 2s; // How often we check state or change positions (in milliseconds) -const int LEDGER_GRANULARITY = 1000; +auto constexpr LEDGER_GRANULARITY = 1s; // How long we consider a proposal fresh -const int PROPOSE_FRESHNESS = 20; +auto constexpr PROPOSE_FRESHNESS = 20s; // How often we force generating a new proposal to keep ours fresh -const int PROPOSE_INTERVAL = 12; +auto constexpr PROPOSE_INTERVAL = 12s; // Avalanche tuning // percentage of nodes on our UNL that must vote yes -const int AV_INIT_CONSENSUS_PCT = 50; +auto constexpr AV_INIT_CONSENSUS_PCT = 50; // percentage of previous close time before we advance -const int AV_MID_CONSENSUS_TIME = 50; +auto constexpr AV_MID_CONSENSUS_TIME = 50; // percentage of nodes that most vote yes after advancing -const int AV_MID_CONSENSUS_PCT = 65; +auto constexpr AV_MID_CONSENSUS_PCT = 65; // percentage of previous close time before we advance -const int AV_LATE_CONSENSUS_TIME = 85; +auto constexpr AV_LATE_CONSENSUS_TIME = 85; // percentage of nodes that most vote yes after advancing -const int AV_LATE_CONSENSUS_PCT = 70; +auto constexpr AV_LATE_CONSENSUS_PCT = 70; -const int AV_STUCK_CONSENSUS_TIME = 200; -const int AV_STUCK_CONSENSUS_PCT = 95; +auto constexpr AV_STUCK_CONSENSUS_TIME = 200; +auto constexpr AV_STUCK_CONSENSUS_PCT = 95; -const int AV_CT_CONSENSUS_PCT = 75; +auto constexpr AV_CT_CONSENSUS_PCT = 75; } // ripple diff --git a/src/ripple/app/ledger/impl/ConsensusImp.cpp b/src/ripple/app/ledger/impl/ConsensusImp.cpp index 219e25fe3..b23179669 100644 --- a/src/ripple/app/ledger/impl/ConsensusImp.cpp +++ b/src/ripple/app/ledger/impl/ConsensusImp.cpp @@ -33,9 +33,9 @@ ConsensusImp::ConsensusImp ( , proposing_ (false) , validating_ (false) , lastCloseProposers_ (0) - , lastCloseConvergeTook_ (1000 * LEDGER_IDLE_INTERVAL) - , lastValidationTimestamp_ (0) - , lastCloseTime_ (0) + , lastCloseConvergeTook_ (LEDGER_IDLE_INTERVAL) + , lastValidationTimestamp_ (0s) + , lastCloseTime_ (0s) { } @@ -57,7 +57,7 @@ ConsensusImp::getLastCloseProposers () const return lastCloseProposers_; } -int +std::chrono::milliseconds ConsensusImp::getLastCloseDuration () const { return lastCloseConvergeTook_; @@ -71,7 +71,7 @@ ConsensusImp::startRound ( LedgerMaster& ledgerMaster, LedgerHash const &prevLCLHash, Ledger::ref previousLedger, - std::uint32_t closeTime) + NetClock::time_point closeTime) { return make_LedgerConsensus (app, *this, lastCloseProposers_, lastCloseConvergeTook_, inboundTransactions, localtx, ledgerMaster, @@ -101,7 +101,7 @@ ConsensusImp::setLastValidation (STValidation::ref v) void ConsensusImp::newLCL ( int proposers, - int convergeTime, + std::chrono::milliseconds convergeTime, uint256 const& ledgerHash) { lastCloseProposers_ = proposers; @@ -109,24 +109,24 @@ ConsensusImp::newLCL ( lastCloseHash_ = ledgerHash; } -std::uint32_t -ConsensusImp::validationTimestamp (std::uint32_t vt) +NetClock::time_point +ConsensusImp::validationTimestamp (NetClock::time_point vt) { if (vt <= lastValidationTimestamp_) - vt = lastValidationTimestamp_ + 1; + vt = lastValidationTimestamp_ + 1s; lastValidationTimestamp_ = vt; return vt; } -std::uint32_t +NetClock::time_point ConsensusImp::getLastCloseTime () const { return lastCloseTime_; } void -ConsensusImp::setLastCloseTime (std::uint32_t t) +ConsensusImp::setLastCloseTime (NetClock::time_point t) { lastCloseTime_ = t; } diff --git a/src/ripple/app/ledger/impl/ConsensusImp.h b/src/ripple/app/ledger/impl/ConsensusImp.h index f5c799e91..ddb886b63 100644 --- a/src/ripple/app/ledger/impl/ConsensusImp.h +++ b/src/ripple/app/ledger/impl/ConsensusImp.h @@ -49,7 +49,7 @@ public: int getLastCloseProposers () const override; - int + std::chrono::milliseconds getLastCloseDuration () const override; std::shared_ptr @@ -60,10 +60,10 @@ public: LedgerMaster& ledgerMaster, LedgerHash const &prevLCLHash, Ledger::ref previousLedger, - std::uint32_t closeTime) override; + NetClock::time_point closeTime) override; void - setLastCloseTime (std::uint32_t t) override; + setLastCloseTime (NetClock::time_point t) override; void storeProposal ( @@ -82,13 +82,13 @@ public: void newLCL ( int proposers, - int convergeTime, + std::chrono::milliseconds convergeTime, uint256 const& ledgerHash); - std::uint32_t - validationTimestamp (std::uint32_t vt); + NetClock::time_point + validationTimestamp (NetClock::time_point vt); - std::uint32_t + NetClock::time_point getLastCloseTime () const; void takePosition (int seq, std::shared_ptr const& position); @@ -110,17 +110,17 @@ private: int lastCloseProposers_; // How long the last ledger close took, in milliseconds - int lastCloseConvergeTook_; + std::chrono::milliseconds lastCloseConvergeTook_; // The hash of the last closed ledger uint256 lastCloseHash_; // The timestamp of the last validation we used, in network time. This is // only used for our own validations. - std::uint32_t lastValidationTimestamp_; + NetClock::time_point lastValidationTimestamp_; // The last close time - std::uint32_t lastCloseTime_; + NetClock::time_point lastCloseTime_; // Recent positions taken std::map>> recentPositions_; diff --git a/src/ripple/app/ledger/impl/LedgerConsensusImp.cpp b/src/ripple/app/ledger/impl/LedgerConsensusImp.cpp index 159b168db..03a77f37e 100644 --- a/src/ripple/app/ledger/impl/LedgerConsensusImp.cpp +++ b/src/ripple/app/ledger/impl/LedgerConsensusImp.cpp @@ -70,26 +70,29 @@ namespace ripple { @param openMSeconds time, in milliseconds, waiting to close this ledger @param idleInterval the network's desired idle interval */ -bool shouldCloseLedger ( +static +bool +shouldCloseLedger ( bool anyTransactions, int previousProposers, int proposersClosed, int proposersValidated, - int previousMSeconds, - int currentMSeconds, // Time since last ledger's close time - int openMSeconds, // Time waiting to close this ledger - int idleInterval, + std::chrono::milliseconds previousMSeconds, + std::chrono::milliseconds currentMSeconds, // Time since last ledger's close time + std::chrono::milliseconds openMSeconds, // Time waiting to close this ledger + std::chrono::seconds idleInterval, beast::Journal j) { - if ((previousMSeconds < -1000) || (previousMSeconds > 600000) || - (currentMSeconds > 600000)) + using namespace std::chrono_literals; + if ((previousMSeconds < -1s) || (previousMSeconds > 10min) || + (currentMSeconds > 10min)) { // These are unexpected cases, we just close the ledger JLOG (j.warning) << "shouldCloseLedger Trans=" << (anyTransactions ? "yes" : "no") << " Prop: " << previousProposers << "/" << proposersClosed << - " Secs: " << currentMSeconds << " (last: " << - previousMSeconds << ")"; + " Secs: " << currentMSeconds.count() << " (last: " << + previousMSeconds.count() << ")"; return true; } @@ -103,7 +106,7 @@ bool shouldCloseLedger ( if (!anyTransactions) { // Only close at the end of the idle interval - return currentMSeconds >= (idleInterval * 1000); // normal idle + return currentMSeconds >= idleInterval; // normal idle } // Preserve minimum ledger open time @@ -155,13 +158,15 @@ enum class ConsensusState @param currentAgreeTime how long, in milliseconds, we've been trying to agree */ -ConsensusState checkConsensus ( +static +ConsensusState +checkConsensus ( int previousProposers, int currentProposers, int currentAgree, int currentFinished, - int previousAgreeTime, - int currentAgreeTime, + std::chrono::milliseconds previousAgreeTime, + std::chrono::milliseconds currentAgreeTime, beast::Journal j) { JLOG (j.trace) << @@ -211,13 +216,13 @@ LedgerConsensusImp::LedgerConsensusImp ( Application& app, ConsensusImp& consensus, int previousProposers, - int previousConvergeTime, + std::chrono::milliseconds previousConvergeTime, InboundTransactions& inboundTransactions, LocalTxs& localtx, LedgerMaster& ledgerMaster, LedgerHash const & prevLCLHash, Ledger::ref previousLedger, - std::uint32_t closeTime, + NetClock::time_point closeTime, FeeVote& feeVote) : app_ (app) , consensus_ (consensus) @@ -226,7 +231,7 @@ LedgerConsensusImp::LedgerConsensusImp ( , ledgerMaster_ (ledgerMaster) , m_feeVote (feeVote) , state_ (State::open) - , mCloseTime (closeTime) + , mCloseTime {closeTime} , mPrevLedgerHash (prevLCLHash) , mPreviousLedger (previousLedger) , mValPublic (app_.config().VALIDATION_PUB) @@ -242,9 +247,10 @@ LedgerConsensusImp::LedgerConsensusImp ( { JLOG (j_.debug) << "Creating consensus object"; JLOG (j_.trace) - << "LCL:" << previousLedger->getHash () << ", ct=" << closeTime; + << "LCL:" << previousLedger->getHash () + << ", ct=" << closeTime.time_since_epoch().count(); - assert (mPreviousMSeconds); + assert (mPreviousMSeconds != 0ms); inboundTransactions_.newRound (mPreviousLedger->info().seq); @@ -318,7 +324,7 @@ Json::Value LedgerConsensusImp::getJson (bool full) { ret["synched"] = true; ret["ledger_seq"] = mPreviousLedger->info().seq + 1; - ret["close_granularity"] = mCloseResolution; + ret["close_granularity"] = mCloseResolution.count(); } else ret["synched"] = false; @@ -352,13 +358,13 @@ Json::Value LedgerConsensusImp::getJson (bool full) if (full) { - - ret["current_ms"] = mCurrentMSeconds; + using Int = Json::Value::Int; + ret["current_ms"] = static_cast(mCurrentMSeconds.count()); ret["close_percent"] = mClosePercent; - ret["close_resolution"] = mCloseResolution; + ret["close_resolution"] = mCloseResolution.count(); ret["have_time_consensus"] = mHaveCloseTimeConsensus; ret["previous_proposers"] = mPreviousProposers; - ret["previous_mseconds"] = mPreviousMSeconds; + ret["previous_mseconds"] = static_cast(mPreviousMSeconds.count()); if (!mPeerPositions.empty ()) { @@ -400,8 +406,7 @@ Json::Value LedgerConsensusImp::getJson (bool full) Json::Value ctj (Json::objectValue); for (auto& ct : mCloseTimes) { - ctj[std::to_string(ct.first)] = ct. - second; + ctj[std::to_string(ct.first.time_since_epoch().count())] = ct.second; } ret["close_times"] = ctj; } @@ -697,8 +702,9 @@ void LedgerConsensusImp::timerEntry () if ((state_ != State::finished) && (state_ != State::accepted)) checkLCL (); - mCurrentMSeconds = std::chrono::duration_cast - (std::chrono::steady_clock::now() - mConsensusStartTime).count (); + using namespace std::chrono; + mCurrentMSeconds = duration_cast + (steady_clock::now() - mConsensusStartTime); mClosePercent = mCurrentMSeconds * 100 / mPreviousMSeconds; switch (state_) @@ -747,26 +753,26 @@ void LedgerConsensusImp::statePreClose () (mPrevLedgerHash); // This computes how long since last ledger's close time - int sinceClose; + using namespace std::chrono; + milliseconds sinceClose; { bool previousCloseCorrect = mHaveCorrectLCL && getCloseAgree (mPreviousLedger->info()) && (mPreviousLedger->info().closeTime != - (mPreviousLedger->info().parentCloseTime + 1)); + (mPreviousLedger->info().parentCloseTime + 1s)); auto closeTime = previousCloseCorrect ? mPreviousLedger->info().closeTime // use consensus timing : consensus_.getLastCloseTime(); // use the time we saw - auto now = - app_.timeKeeper().closeTime().time_since_epoch().count(); + auto now = app_.timeKeeper().closeTime(); if (now >= closeTime) - sinceClose = static_cast (1000 * (now - closeTime)); + sinceClose = now - closeTime; else - sinceClose = - static_cast (1000 * (closeTime - now)); + sinceClose = -milliseconds{closeTime - now}; } - auto const idleInterval = std::max (LEDGER_IDLE_INTERVAL, + auto const idleInterval = std::max(LEDGER_IDLE_INTERVAL, 2 * mPreviousLedger->info().closeTimeResolution); // Decide if we should close the ledger @@ -934,8 +940,8 @@ bool LedgerConsensusImp::peerPosition (LedgerProposal::ref newPosition) // Record the close time estimate JLOG (j_.trace) << "Peer reports close time as " - << newPosition->getCloseTime (); - ++mCloseTimes[newPosition->getCloseTime ()]; + << newPosition->getCloseTime().time_since_epoch().count(); + ++mCloseTimes[newPosition->getCloseTime()]; } JLOG (j_.trace) << "Processing peer proposal " @@ -964,7 +970,7 @@ void LedgerConsensusImp::simulate () { JLOG (j_.info) << "Simulating consensus"; closeLedger (); - mCurrentMSeconds = 100; + mCurrentMSeconds = 100ms; beginAccept (true); endConsensus (); JLOG (j_.info) << "Simulation complete"; @@ -985,7 +991,7 @@ void LedgerConsensusImp::accept (std::shared_ptr set) consensusStatus = getJson (true); } - auto closeTime = mOurPosition->getCloseTime (); + auto closeTime = mOurPosition->getCloseTime(); bool closeTimeCorrect; auto replay = ledgerMaster_.releaseReplay(); @@ -995,10 +1001,10 @@ void LedgerConsensusImp::accept (std::shared_ptr set) closeTime = replay->closeTime_; closeTimeCorrect = ((replay->closeFlags_ & sLCF_NoConsensusTime) == 0); } - else if (closeTime == 0) + else if (closeTime == NetClock::time_point{}) { // We agreed to disagree on the close time - closeTime = mPreviousLedger->info().closeTime + 1; + closeTime = mPreviousLedger->info().closeTime + 1s; closeTimeCorrect = false; } else @@ -1018,7 +1024,8 @@ void LedgerConsensusImp::accept (std::shared_ptr set) << ":" << mPreviousLedger->info().seq; JLOG (j_.debug) << "Report: TxSt = " << set->getHash () - << ", close " << closeTime << (closeTimeCorrect ? "" : "X"); + << ", close " << closeTime.time_since_epoch().count() + << (closeTimeCorrect ? "" : "X"); // Put transactions into a deterministic, but unpredictable, order CanonicalTXSet retriableTxs (set->getHash ().as_uint256()); @@ -1052,7 +1059,7 @@ void LedgerConsensusImp::accept (std::shared_ptr set) } // Update fee computations. app_.getTxQ().processValidatedLedger(app_, accum, - mCurrentMSeconds > 5000); + mCurrentMSeconds > 5s); accum.apply(*newLCL); } @@ -1074,7 +1081,8 @@ void LedgerConsensusImp::accept (std::shared_ptr set) } // Accept ledger - newLCL->setAccepted (closeTime, mCloseResolution, closeTimeCorrect, app_.config()); + newLCL->setAccepted(closeTime, mCloseResolution, + closeTimeCorrect, app_.config()); // And stash the ledger in the ledger master if (ledgerMaster_.storeLedger (newLCL)) @@ -1106,8 +1114,7 @@ void LedgerConsensusImp::accept (std::shared_ptr set) { // Build validation auto v = std::make_shared (newLCLHash, - consensus_.validationTimestamp ( - app_.timeKeeper().now().time_since_epoch().count()), + consensus_.validationTimestamp(app_.timeKeeper().now()), mValPublic, mProposing); v->setFieldU32 (sfLedgerSequence, newLCL->info().seq); addLoad(v); // Our network load @@ -1219,32 +1226,33 @@ void LedgerConsensusImp::accept (std::shared_ptr set) // see how close our close time is to other node's // close time reports, and update our clock. JLOG (j_.info) - << "We closed at " << mCloseTime; - std::uint64_t closeTotal = mCloseTime; + << "We closed at " << mCloseTime.time_since_epoch().count(); + using usec64_t = std::chrono::duration; + usec64_t closeTotal = mCloseTime.time_since_epoch(); int closeCount = 1; - for (auto it = mCloseTimes.begin () - , end = mCloseTimes.end (); it != end; ++it) + for (auto const& p : mCloseTimes) { // FIXME: Use median, not average JLOG (j_.info) - << beast::lexicalCastThrow (it->second) + << beast::lexicalCastThrow (p.second) << " time votes for " - << beast::lexicalCastThrow (it->first); - closeCount += it->second; - closeTotal += static_cast - (it->first) * static_cast (it->second); + << beast::lexicalCastThrow + (p.first.time_since_epoch().count()); + closeCount += p.second; + closeTotal += usec64_t(p.first.time_since_epoch()) * p.second; } - closeTotal += (closeCount / 2); + closeTotal += usec64_t(closeCount / 2); // for round to nearest closeTotal /= closeCount; - int offset = static_cast (closeTotal) - - static_cast (mCloseTime); + using duration = std::chrono::duration; + using time_point = std::chrono::time_point; + auto offset = time_point{closeTotal} - + std::chrono::time_point_cast(mCloseTime); JLOG (j_.info) << "Our close offset is estimated at " - << offset << " (" << closeCount << ")"; - app_.timeKeeper().adjustCloseTime( - std::chrono::seconds(offset)); + << offset.count() << " (" << closeCount << ")"; + app_.timeKeeper().adjustCloseTime(offset); } } @@ -1374,7 +1382,7 @@ void LedgerConsensusImp::propose () prop.set_previousledger (mOurPosition->getPrevLedger ().begin () , 256 / 8); prop.set_proposeseq (mOurPosition->getProposeSeq ()); - prop.set_closetime (mOurPosition->getCloseTime ()); + prop.set_closetime(mOurPosition->getCloseTime().time_since_epoch().count()); Blob const pubKey = mValPublic.getNodePublic (); prop.set_nodepubkey (&pubKey[0], pubKey.size ()); @@ -1521,14 +1529,15 @@ participantsNeeded (int participants, int percent) return (result == 0) ? 1 : result; } -std::uint32_t LedgerConsensusImp::effectiveCloseTime (std::uint32_t closeTime) +NetClock::time_point +LedgerConsensusImp::effectiveCloseTime(NetClock::time_point closeTime) { - if (closeTime == 0) - return 0; + if (closeTime == NetClock::time_point{}) + return closeTime; - return std::max ( + return std::max( roundCloseTime (closeTime, mCloseResolution), - mPreviousLedger->info().closeTime + 1); + (mPreviousLedger->info().closeTime + 1s)); } void LedgerConsensusImp::updateOurPositions () @@ -1537,15 +1546,15 @@ void LedgerConsensusImp::updateOurPositions () auto peerCutoff = std::chrono::steady_clock::now (); auto ourCutoff - = peerCutoff - std::chrono::seconds (PROPOSE_INTERVAL); - peerCutoff -= std::chrono::seconds (PROPOSE_FRESHNESS); + = peerCutoff - PROPOSE_INTERVAL; + peerCutoff -= PROPOSE_FRESHNESS; bool changes = false; std::shared_ptr ourPosition; // std::vector addedTx, removedTx; // Verify freshness of peer positions and compute close times - std::map closeTimes; + std::map closeTimes; auto it = mPeerPositions.begin (); while (it != mPeerPositions.end ()) @@ -1563,8 +1572,7 @@ void LedgerConsensusImp::updateOurPositions () else { // proposal is still fresh - ++closeTimes[effectiveCloseTime ( - it->second->getCloseTime ())]; + ++closeTimes[effectiveCloseTime(it->second->getCloseTime())]; ++it; } } @@ -1609,22 +1617,21 @@ void LedgerConsensusImp::updateOurPositions () else neededWeight = AV_STUCK_CONSENSUS_PCT; - std::uint32_t closeTime = 0; + NetClock::time_point closeTime = {}; mHaveCloseTimeConsensus = false; if (mPeerPositions.empty ()) { // no other times mHaveCloseTimeConsensus = true; - closeTime = effectiveCloseTime (mOurPosition->getCloseTime ()); + closeTime = effectiveCloseTime(mOurPosition->getCloseTime()); } else { int participants = mPeerPositions.size (); if (mProposing) { - ++closeTimes[ - effectiveCloseTime (mOurPosition->getCloseTime ())]; + ++closeTimes[effectiveCloseTime(mOurPosition->getCloseTime())]; ++participants; } @@ -1644,7 +1651,8 @@ void LedgerConsensusImp::updateOurPositions () { JLOG (j_.debug) << "CCTime: seq " << mPreviousLedger->info().seq + 1 << ": " - << it.first << " has " << it.second << ", " + << it.first.time_since_epoch().count() + << " has " << it.second << ", " << threshVote << " required"; if (it.second >= threshVote) @@ -1661,7 +1669,7 @@ void LedgerConsensusImp::updateOurPositions () CondLog (!mHaveCloseTimeConsensus, lsDEBUG, LedgerConsensus) << "No CT consensus: Proposers:" << mPeerPositions.size () << " Proposing:" << (mProposing ? "yes" : "no") << " Thresh:" - << threshConsensus << " Pos:" << closeTime; + << threshConsensus << " Pos:" << closeTime.time_since_epoch().count(); } // Temporarily send a new proposal if there's any change to our @@ -1669,7 +1677,7 @@ void LedgerConsensusImp::updateOurPositions () // to the full network, this can be relaxed to force a change // only if the rounded close time has changed. if (!changes && - ((closeTime != mOurPosition->getCloseTime ()) + ((closeTime != mOurPosition->getCloseTime()) || mOurPosition->isStale (ourCutoff))) { // close time changed or our position is stale @@ -1683,10 +1691,11 @@ void LedgerConsensusImp::updateOurPositions () { auto newHash = ourPosition->getHash ().as_uint256(); JLOG (j_.info) - << "Position change: CTime " << closeTime + << "Position change: CTime " + << closeTime.time_since_epoch().count() << ", tx " << newHash; - if (mOurPosition->changePosition (newHash, closeTime)) + if (mOurPosition->changePosition(newHash, closeTime)) { if (mProposing) propose (); @@ -1718,8 +1727,8 @@ void LedgerConsensusImp::closeLedger () checkOurValidation (); state_ = State::establish; mConsensusStartTime = std::chrono::steady_clock::now (); - mCloseTime = app_.timeKeeper().closeTime().time_since_epoch().count(); - consensus_.setLastCloseTime (mCloseTime); + mCloseTime = app_.timeKeeper().closeTime(); + consensus_.setLastCloseTime(mCloseTime); statusChange (protocol::neCLOSING_LEDGER, *mPreviousLedger); ledgerMaster_.applyHeldTransactions (); takeInitialPosition (app_.openLedger().current()); @@ -1750,8 +1759,7 @@ void LedgerConsensusImp::checkOurValidation () } auto v = std::make_shared (mPreviousLedger->getHash (), - consensus_.validationTimestamp ( - app_.timeKeeper().now().time_since_epoch().count()), + consensus_.validationTimestamp(app_.timeKeeper().now()), mValPublic, false); addLoad(v); v->setTrusted (); @@ -1778,8 +1786,7 @@ void LedgerConsensusImp::beginAccept (bool synchronous) return; } - consensus_.newLCL ( - mPeerPositions.size (), mCurrentMSeconds, mNewLedgerHash); + consensus_.newLCL(mPeerPositions.size(), mCurrentMSeconds, mNewLedgerHash); if (synchronous) accept (consensusSet); @@ -1809,10 +1816,11 @@ void LedgerConsensusImp::addLoad(STValidation::ref val) //------------------------------------------------------------------------------ std::shared_ptr make_LedgerConsensus (Application& app, ConsensusImp& consensus, int previousProposers, - int previousConvergeTime, InboundTransactions& inboundTransactions, + std::chrono::milliseconds previousConvergeTime, + InboundTransactions& inboundTransactions, LocalTxs& localtx, LedgerMaster& ledgerMaster, LedgerHash const &prevLCLHash, - Ledger::ref previousLedger, std::uint32_t closeTime, FeeVote& feeVote) + Ledger::ref previousLedger, NetClock::time_point closeTime, FeeVote& feeVote) { return std::make_shared (app, consensus, previousProposers, previousConvergeTime, inboundTransactions, localtx, ledgerMaster, diff --git a/src/ripple/app/ledger/impl/LedgerConsensusImp.h b/src/ripple/app/ledger/impl/LedgerConsensusImp.h index 15ea52f35..ff739e01f 100644 --- a/src/ripple/app/ledger/impl/LedgerConsensusImp.h +++ b/src/ripple/app/ledger/impl/LedgerConsensusImp.h @@ -96,13 +96,13 @@ public: Application& app, ConsensusImp& consensus, int previousProposers, - int previousConvergeTime, + std::chrono::milliseconds previousConvergeTime, InboundTransactions& inboundTransactions, LocalTxs& localtx, LedgerMaster& ledgerMaster, LedgerHash const & prevLCLHash, Ledger::ref previousLedger, - std::uint32_t closeTime, + NetClock::time_point closeTime, FeeVote& feeVote); /** @@ -294,7 +294,7 @@ private: void addLoad(STValidation::ref val); /** Convert an advertised close time to an effective close time */ - std::uint32_t effectiveCloseTime (std::uint32_t closeTime); + NetClock::time_point effectiveCloseTime(NetClock::time_point closeTime); private: Application& app_; @@ -305,20 +305,20 @@ private: FeeVote& m_feeVote; State state_; - std::uint32_t mCloseTime; // The wall time this ledger closed + NetClock::time_point mCloseTime; // The wall time this ledger closed uint256 mPrevLedgerHash, mNewLedgerHash, mAcquiringLedger; Ledger::pointer mPreviousLedger; LedgerProposal::pointer mOurPosition; RippleAddress mValPublic, mValPrivate; bool mProposing, mValidating, mHaveCorrectLCL, mConsensusFail; - int mCurrentMSeconds; + std::chrono::milliseconds mCurrentMSeconds; // How long the close has taken, expressed as a percentage of the time that // we expected it to take. int mClosePercent; - int mCloseResolution; + NetClock::duration mCloseResolution; bool mHaveCloseTimeConsensus; @@ -326,7 +326,7 @@ private: int mPreviousProposers; // The time it took for the last consensus process to converge - int mPreviousMSeconds; + std::chrono::milliseconds mPreviousMSeconds; // Convergence tracking, trusted peers indexed by hash of public key hash_map mPeerPositions; @@ -339,7 +339,7 @@ private: hash_set mCompares; // Close time estimates, keep ordered for predictable traverse - std::map mCloseTimes; + std::map mCloseTimes; // nodes that have bowed out of this consensus process hash_set mDeadNodes; @@ -350,10 +350,11 @@ private: std::shared_ptr make_LedgerConsensus (Application& app, ConsensusImp& consensus, int previousProposers, - int previousConvergeTime, InboundTransactions& inboundTransactions, + std::chrono::milliseconds previousConvergeTime, + InboundTransactions& inboundTransactions, LocalTxs& localtx, LedgerMaster& ledgerMaster, LedgerHash const &prevLCLHash, Ledger::ref previousLedger, - std::uint32_t closeTime, FeeVote& feeVote); + NetClock::time_point closeTime, FeeVote& feeVote); } // ripple diff --git a/src/ripple/app/ledger/impl/LedgerMaster.cpp b/src/ripple/app/ledger/impl/LedgerMaster.cpp index ac6e38e60..bccb37723 100644 --- a/src/ripple/app/ledger/impl/LedgerMaster.cpp +++ b/src/ripple/app/ledger/impl/LedgerMaster.cpp @@ -54,6 +54,8 @@ namespace ripple { +using namespace std::chrono_literals; + // 150/256ths of validations of previous ledger #define MIN_VALIDATION_RATIO 150 @@ -61,7 +63,7 @@ namespace ripple { #define MAX_LEDGER_GAP 100 // Don't acquire history if ledger is too old -#define MAX_LEDGER_AGE_ACQUIRE 60 +auto constexpr MAX_LEDGER_AGE_ACQUIRE = 1min; class LedgerMasterImp : public LedgerMaster @@ -224,44 +226,45 @@ public: return true; } - int getPublishedLedgerAge () override + std::chrono::seconds + getPublishedLedgerAge() override { - std::uint32_t pubClose = mPubLedgerClose.load(); - if (!pubClose) + std::chrono::seconds pubClose{mPubLedgerClose.load()}; + if (pubClose == 0s) { JLOG (m_journal.debug) << "No published ledger"; - return 999999; + return weeks{2}; } - // VFALCO int widening? - auto ret = app_.timeKeeper().closeTime().time_since_epoch().count(); - ret -= static_cast (pubClose); - ret = (ret > 0) ? ret : 0; + std::chrono::seconds ret = app_.timeKeeper().closeTime().time_since_epoch(); + ret -= pubClose; + ret = (ret > 0s) ? ret : 0s; - JLOG (m_journal.trace) << "Published ledger age is " << ret; - return static_cast (ret); + JLOG (m_journal.trace) << "Published ledger age is " << ret.count(); + return ret; } - int getValidatedLedgerAge () override + std::chrono::seconds + getValidatedLedgerAge() override { - std::uint32_t valClose = mValidLedgerSign.load(); - if (!valClose) + std::chrono::seconds valClose{mValidLedgerSign.load()}; + if (valClose == 0s) { JLOG (m_journal.debug) << "No validated ledger"; - return 999999; + return weeks{2}; } - auto ret = app_.timeKeeper().closeTime().time_since_epoch().count(); - ret -= static_cast (valClose); - ret = (ret > 0) ? ret : 0; + std::chrono::seconds ret = app_.timeKeeper().closeTime().time_since_epoch(); + ret -= valClose; + ret = (ret > 0s) ? ret : 0s; - JLOG (m_journal.trace) << "Validated ledger age is " << ret; - return static_cast (ret); + JLOG (m_journal.trace) << "Validated ledger age is " << ret.count(); + return ret; } bool isCaughtUp(std::string& reason) override { - if (getPublishedLedgerAge() > 180) + if (getPublishedLedgerAge() > 3min) { reason = "No recently-published ledger"; return false; @@ -283,8 +286,8 @@ public: void setValidLedger(Ledger::ref l) { - std::vector times; - std::uint32_t signTime; + std::vector times; + NetClock::time_point signTime; if (! app_.config().RUN_STANDALONE) times = app_.getValidations().getValidationTimes( l->getHash()); @@ -292,8 +295,9 @@ public: { // Calculate the sample median std::sort (times.begin (), times.end ()); - signTime = (times[times.size() / 2] + - times[(times.size() - 1) / 2]) / 2; + auto const t0 = times[(times.size() - 1) / 2]; + auto const t1 = times[times.size() / 2]; + signTime = t0 + (t1 - t0)/2; } else { @@ -301,7 +305,7 @@ public: } mValidLedger.set (l); - mValidLedgerSign = signTime; + mValidLedgerSign = signTime.time_since_epoch().count(); mValidLedgerSeq = l->info().seq; app_.getOPs().updateLocalTx (l); app_.getSHAMapStore().onLedgerClosed (getValidatedLedger()); @@ -312,7 +316,7 @@ public: void setPubLedger(Ledger::ref l) { mPubLedger = l; - mPubLedgerClose = l->info().closeTime; + mPubLedgerClose = l->info().closeTime.time_since_epoch().count(); mPubLedgerSeq = l->info().seq; } @@ -1211,10 +1215,10 @@ public: if (!standalone_) { // don't pathfind with a ledger that's more than 60 seconds old - auto age = app_.timeKeeper().closeTime().time_since_epoch() - .count(); - age -= static_cast (lastLedger->info().closeTime); - if (age > 60) + using namespace std::chrono; + auto age = time_point_cast(app_.timeKeeper().closeTime()) + - lastLedger->info().closeTime; + if (age > 1min) { JLOG (m_journal.debug) << "Published ledger too old for updating paths"; @@ -1382,14 +1386,14 @@ public: return mCompleteLedgers.toString (); } - boost::optional + boost::optional getCloseTimeBySeq (LedgerIndex ledgerIndex) override { uint256 hash = getHashBySeq (ledgerIndex); return hash.isNonZero() ? getCloseTimeByHash (hash) : boost::none; } - boost::optional + boost::optional getCloseTimeByHash (LedgerHash const& ledgerHash) override { auto node = app_.getNodeStore().fetch (ledgerHash); @@ -1402,7 +1406,7 @@ public: it.skip ( 4+8+32+ // seq drops parentHash 32+32+4); // txHash acctHash parentClose - return it.get32(); + return NetClock::time_point{NetClock::duration{it.get32()}}; } } @@ -1862,7 +1866,7 @@ void LedgerMasterImp::makeFetchPack ( } if (app_.getFeeTrack ().isLoadedLocal () || - (getValidatedLedgerAge() > 40)) + (getValidatedLedgerAge() > 40s)) { m_journal.info << "Too busy to make fetch pack"; return; diff --git a/src/ripple/app/ledger/impl/LedgerTiming.cpp b/src/ripple/app/ledger/impl/LedgerTiming.cpp index 2b5ac2d9a..9e80c846a 100644 --- a/src/ripple/app/ledger/impl/LedgerTiming.cpp +++ b/src/ripple/app/ledger/impl/LedgerTiming.cpp @@ -25,13 +25,15 @@ namespace ripple { -int getNextLedgerTimeResolution ( - int previousResolution, +NetClock::duration +getNextLedgerTimeResolution ( + NetClock::duration previousResolution, bool previousAgree, std::uint32_t ledgerSeq) { assert (ledgerSeq); + using namespace std::chrono; // Find the current resolution: auto iter = std::find (std::begin (ledgerPossibleTimeResolutions), std::end (ledgerPossibleTimeResolutions), previousResolution); @@ -60,14 +62,15 @@ int getNextLedgerTimeResolution ( return previousResolution; } -std::uint32_t roundCloseTime ( - std::uint32_t closeTime, - std::uint32_t closeResolution) +NetClock::time_point +roundCloseTime ( + NetClock::time_point closeTime, + NetClock::duration closeResolution) { - if (closeTime == 0) - return 0; + if (closeTime == NetClock::time_point{}) + return closeTime; closeTime += (closeResolution / 2); - return closeTime - (closeTime % closeResolution); + return closeTime - (closeTime.time_since_epoch() % closeResolution); } } // ripple diff --git a/src/ripple/app/ledger/impl/LedgerToJson.cpp b/src/ripple/app/ledger/impl/LedgerToJson.cpp index 5113ba023..c572685ed 100644 --- a/src/ripple/app/ledger/impl/LedgerToJson.cpp +++ b/src/ripple/app/ledger/impl/LedgerToJson.cpp @@ -68,14 +68,14 @@ void fillJson(Object& json, LedgerInfo const& info, bool bFull) json[jss::close_flags] = info.closeFlags; // Always show fields that contribute to the ledger hash - json[jss::parent_close_time] = info.parentCloseTime; - json[jss::close_time] = info.closeTime; - json[jss::close_time_resolution] = info.closeTimeResolution; + json[jss::parent_close_time] = info.parentCloseTime.time_since_epoch().count(); + json[jss::close_time] = info.closeTime.time_since_epoch().count(); + json[jss::close_time_resolution] = info.closeTimeResolution.count(); - if (auto closeTime = info.closeTime) + if (info.closeTime != NetClock::time_point{}) { json[jss::close_time_human] = boost::posix_time::to_simple_string ( - ptFromSeconds (closeTime)); + ptFromSeconds (info.closeTime.time_since_epoch().count())); if (! getCloseAgree(info)) json[jss::close_time_estimated] = true; } diff --git a/src/ripple/app/main/Application.cpp b/src/ripple/app/main/Application.cpp index d0c937bf3..b2ae62055 100644 --- a/src/ripple/app/main/Application.cpp +++ b/src/ripple/app/main/Application.cpp @@ -1221,8 +1221,9 @@ bool ApplicationImp::loadOldLedger ( std::uint32_t seq = 1; - auto closeTime = timeKeeper().closeTime().time_since_epoch().count(); - std::uint32_t closeTimeResolution = 30; + auto closeTime = timeKeeper().closeTime(); + using namespace std::chrono_literals; + auto closeTimeResolution = 30s; bool closeTimeEstimated = false; std::uint64_t totalDrops = 0; @@ -1234,12 +1235,14 @@ bool ApplicationImp::loadOldLedger ( } if (ledger.get().isMember ("close_time")) { - closeTime = ledger.get()["close_time"].asUInt(); + using tp = NetClock::time_point; + using d = tp::duration; + closeTime = tp{d{ledger.get()["close_time"].asUInt()}}; } if (ledger.get().isMember ("close_time_resolution")) { - closeTimeResolution = - ledger.get()["close_time_resolution"].asUInt(); + closeTimeResolution = std::chrono::seconds{ + ledger.get()["close_time_resolution"].asUInt()}; } if (ledger.get().isMember ("close_time_estimated")) { diff --git a/src/ripple/app/misc/AmendmentTable.h b/src/ripple/app/misc/AmendmentTable.h index cb20bf7af..bba0840a5 100644 --- a/src/ripple/app/misc/AmendmentTable.h +++ b/src/ripple/app/misc/AmendmentTable.h @@ -30,11 +30,11 @@ namespace ripple { class AmendmentSet { public: - std::uint32_t mCloseTime; + NetClock::time_point mCloseTime; int mTrustedValidations; // number of trusted validations hash_map mVotes; // yes votes by amendment - AmendmentSet (std::uint32_t ct) : mCloseTime (ct), mTrustedValidations (0) + AmendmentSet (NetClock::time_point ct) : mCloseTime (ct), mTrustedValidations (0) { ; } @@ -227,7 +227,7 @@ public: // inject pseudo-transactions virtual std::map doVoting ( - std::uint32_t closeTime, + NetClock::time_point closeTime, enabledAmendments_t const& enabledAmendments, majorityAmendments_t const& majorityAmendments, ValidationSet const& valSet) = 0; diff --git a/src/ripple/app/misc/AmendmentTableImpl.cpp b/src/ripple/app/misc/AmendmentTableImpl.cpp index 5097bf1e0..72f079d2c 100644 --- a/src/ripple/app/misc/AmendmentTableImpl.cpp +++ b/src/ripple/app/misc/AmendmentTableImpl.cpp @@ -100,7 +100,7 @@ public: doValidation (enabledAmendments_t const& enabledAmendments) override; - std::map doVoting (std::uint32_t closeTime, + std::map doVoting (NetClock::time_point closeTime, enabledAmendments_t const& enabledAmendments, majorityAmendments_t const& majorityAmendments, ValidationSet const& validations) override; @@ -402,7 +402,7 @@ AmendmentTableImpl::doValidation ( std::map AmendmentTableImpl::doVoting ( - std::uint32_t closeTime, + NetClock::time_point closeTime, enabledAmendments_t const& enabledAmendments, majorityAmendments_t const& majorityAmendments, ValidationSet const& valSet) @@ -450,7 +450,7 @@ AmendmentTableImpl::doVoting ( { bool const hasValMajority = amendmentSet.count (entry.first) >= threshold; - std::uint32_t majorityTime = 0; + NetClock::time_point majorityTime = {}; auto const it = majorityAmendments.find (entry.first); if (it != majorityAmendments.end ()) majorityTime = it->second; @@ -460,18 +460,19 @@ AmendmentTableImpl::doVoting ( { // Already enabled, nothing to do } - else if (hasValMajority && (majorityTime == 0) && (! entry.second.mVetoed)) + else if (hasValMajority && (majorityTime == NetClock::time_point{}) + && (! entry.second.mVetoed)) { // Ledger says no majority, validators say yes actions[entry.first] = tfGotMajority; } - else if (! hasValMajority && (majorityTime != 0)) + else if (! hasValMajority && (majorityTime != NetClock::time_point{})) { // Ledger says majority, validators say no actions[entry.first] = tfLostMajority; } - else if ((majorityTime != 0) && - ((majorityTime + m_majorityTime.count()) <= closeTime) && + else if ((majorityTime != NetClock::time_point{}) && + ((majorityTime + m_majorityTime) <= closeTime) && ! entry.second.mVetoed) { // Ledger says majority held diff --git a/src/ripple/app/misc/NetworkOPs.cpp b/src/ripple/app/misc/NetworkOPs.cpp index 3be7ef8ea..10d17701a 100644 --- a/src/ripple/app/misc/NetworkOPs.cpp +++ b/src/ripple/app/misc/NetworkOPs.cpp @@ -340,9 +340,9 @@ public: } void setAmendmentBlocked () override; void consensusViewChange () override; - void setLastCloseTime (std::uint32_t t) override + void setLastCloseTime (NetClock::time_point t) override { - mConsensus->setLastCloseTime (t); + mConsensus->setLastCloseTime(t); } Json::Value getConsensusInfo () override; Json::Value getServerInfo (bool human, bool admin) override; @@ -597,7 +597,7 @@ void NetworkOPsImp::setStateTimer () void NetworkOPsImp::setHeartbeatTimer () { - m_heartbeatTimer.setExpiration (LEDGER_GRANULARITY / 1000.0); + m_heartbeatTimer.setExpiration (LEDGER_GRANULARITY); } void NetworkOPsImp::setClusterTimer () @@ -674,10 +674,10 @@ void NetworkOPsImp::processClusterTimer () bool const update = app_.cluster().update( app_.getLocalCredentials().getNodePublic(), "", - (m_ledgerMaster.getValidatedLedgerAge() <= 240) + (m_ledgerMaster.getValidatedLedgerAge() <= 4min) ? app_.getFeeTrack().getLocalFee() : 0, - app_.timeKeeper().now().time_since_epoch().count()); + app_.timeKeeper().now()); if (!update) { @@ -691,7 +691,7 @@ void NetworkOPsImp::processClusterTimer () { protocol::TMClusterNode& n = *cluster.add_clusternodes(); n.set_publickey(node.identity().humanNodePublic()); - n.set_reporttime(node.getReportTime()); + n.set_reporttime(node.getReportTime().time_since_epoch().count()); n.set_nodeload(node.getLoadFee()); if (!node.name().empty()) n.set_nodename(node.name()); @@ -1184,7 +1184,7 @@ void NetworkOPsImp::tryStartConsensus () // Note: Do not go to omFULL if we don't have the previous ledger // check if the ledger is bad enough to go to omCONNECTED -- TODO auto current = m_ledgerMaster.getCurrentLedger(); - if (app_.timeKeeper().now().time_since_epoch().count() < + if (app_.timeKeeper().now() < (current->info().parentCloseTime + 2* current->info().closeTimeResolution)) { setMode (omFULL); @@ -1661,12 +1661,12 @@ void NetworkOPsImp::setMode (OperatingMode om) { if (om == omCONNECTED) { - if (app_.getLedgerMaster ().getValidatedLedgerAge () < 60) + if (app_.getLedgerMaster ().getValidatedLedgerAge () < 1min) om = omSYNCING; } else if (om == omSYNCING) { - if (app_.getLedgerMaster ().getValidatedLedgerAge () >= 60) + if (app_.getLedgerMaster ().getValidatedLedgerAge () >= 1min) om = omCONNECTED; } @@ -2015,13 +2015,14 @@ Json::Value NetworkOPsImp::getServerInfo (bool human, bool admin) if (human) { - lastClose[jss::converge_time_s] = static_cast ( - mConsensus->getLastCloseDuration()) / 1000.0; + lastClose[jss::converge_time_s] = + std::chrono::duration{ + mConsensus->getLastCloseDuration()}.count(); } else { lastClose[jss::converge_time] = - Json::Int (mConsensus->getLastCloseDuration()); + Json::Int (mConsensus->getLastCloseDuration().count()); } info[jss::last_close] = lastClose; @@ -2083,7 +2084,7 @@ Json::Value NetworkOPsImp::getServerInfo (bool human, bool admin) l[jss::reserve_inc] = Json::Value::UInt (lpClosed->fees().increment); l[jss::close_time] = - Json::Value::UInt (lpClosed->info().closeTime); + Json::Value::UInt (lpClosed->info().closeTime.time_since_epoch().count()); } else { @@ -2106,14 +2107,13 @@ Json::Value NetworkOPsImp::getServerInfo (bool human, bool admin) if (std::abs (closeOffset.count()) >= 60) l[jss::close_time_offset] = closeOffset.count(); - std::uint32_t lCloseTime = lpClosed->info().closeTime; - std::uint32_t closeTime = - app_.timeKeeper().closeTime().time_since_epoch().count(); + auto lCloseTime = lpClosed->info().closeTime; + auto closeTime = app_.timeKeeper().closeTime(); if (lCloseTime <= closeTime) { - std::uint32_t age = closeTime - lCloseTime; - if (age < 1000000) - l[jss::age] = Json::UInt (age); + auto age = closeTime - lCloseTime; + if (age < 1000000s) + l[jss::age] = Json::UInt (age.count()); else l[jss::age] = 0; } @@ -2204,7 +2204,7 @@ void NetworkOPsImp::pubLedger (Ledger::ref lpAccepted) jvObj[jss::ledger_index] = lpAccepted->info().seq; jvObj[jss::ledger_hash] = to_string (lpAccepted->getHash ()); jvObj[jss::ledger_time] - = Json::Value::UInt (lpAccepted->info().closeTime); + = Json::Value::UInt (lpAccepted->info().closeTime.time_since_epoch().count()); jvObj[jss::fee_ref] = Json::UInt (lpAccepted->fees().units); @@ -2273,7 +2273,8 @@ Json::Value NetworkOPsImp::transJson( { jvObj[jss::ledger_index] = lpCurrent->info().seq; jvObj[jss::ledger_hash] = to_string (lpCurrent->info().hash); - jvObj[jss::transaction][jss::date] = lpCurrent->info().closeTime; + jvObj[jss::transaction][jss::date] = + lpCurrent->info().closeTime.time_since_epoch().count(); jvObj[jss::validated] = true; // WRITEME: Put the account next seq here @@ -2562,7 +2563,7 @@ bool NetworkOPsImp::subLedger (InfoSub::ref isrListener, Json::Value& jvResult) jvResult[jss::ledger_index] = lpClosed->info().seq; jvResult[jss::ledger_hash] = to_string (lpClosed->getHash ()); jvResult[jss::ledger_time] - = Json::Value::UInt (lpClosed->info().closeTime); + = Json::Value::UInt(lpClosed->info().closeTime.time_since_epoch().count()); jvResult[jss::fee_ref] = Json::UInt (lpClosed->fees().units); jvResult[jss::fee_base] = Json::UInt (lpClosed->fees().base); diff --git a/src/ripple/app/misc/NetworkOPs.h b/src/ripple/app/misc/NetworkOPs.h index f56bf8d2c..66ca27963 100644 --- a/src/ripple/app/misc/NetworkOPs.h +++ b/src/ripple/app/misc/NetworkOPs.h @@ -176,7 +176,7 @@ public: virtual void consensusViewChange () = 0; // FIXME(NIKB): Remove the need for this function - virtual void setLastCloseTime (std::uint32_t t) = 0; + virtual void setLastCloseTime (NetClock::time_point t) = 0; virtual Json::Value getConsensusInfo () = 0; virtual Json::Value getServerInfo (bool human, bool admin) = 0; diff --git a/src/ripple/app/misc/SHAMapStoreImp.cpp b/src/ripple/app/misc/SHAMapStoreImp.cpp index 50b26fd54..929b6ba68 100644 --- a/src/ripple/app/misc/SHAMapStoreImp.cpp +++ b/src/ripple/app/misc/SHAMapStoreImp.cpp @@ -619,11 +619,12 @@ SHAMapStoreImp::health() NetworkOPs::OperatingMode mode = netOPs_->getOperatingMode(); - std::int32_t age = ledgerMaster_->getValidatedLedgerAge(); - if (mode != NetworkOPs::omFULL || age >= setup_.ageThreshold) + auto age = ledgerMaster_->getValidatedLedgerAge(); + if (mode != NetworkOPs::omFULL || age.count() >= setup_.ageThreshold) { - journal_.warning << "Not deleting. state: " << mode << " age " << age - << " age threshold " << setup_.ageThreshold; + journal_.warning << "Not deleting. state: " << mode + << " age " << age.count() + << " age threshold " << setup_.ageThreshold; healthy_ = false; } diff --git a/src/ripple/app/misc/Validations.cpp b/src/ripple/app/misc/Validations.cpp index b9c6f0605..4fc15566a 100644 --- a/src/ripple/app/misc/Validations.cpp +++ b/src/ripple/app/misc/Validations.cpp @@ -94,8 +94,11 @@ private: if (!val->isTrusted ()) { - JLOG (j_.debug) << "Node " << signer.humanNodePublic () << " not in UNL st=" << val->getSignTime () << - ", hash=" << val->getLedgerHash () << ", shash=" << val->getSigningHash () << " src=" << source; + JLOG (j_.debug) << "Node " << signer.humanNodePublic () + << " not in UNL st=" + << val->getSignTime().time_since_epoch().count() + << ", hash=" << val->getLedgerHash () + << ", shash=" << val->getSigningHash () << " src=" << source; } auto hash = val->getLedgerHash (); @@ -174,15 +177,14 @@ private: // that avoids any chance of overflowing or underflowing // the signing time. - auto const now = - app_.timeKeeper().now().time_since_epoch().count(); + auto const now = app_.timeKeeper().now(); auto const signTime = val->getSignTime(); return (signTime > (now - VALIDATION_VALID_EARLY)) && (signTime < (now + VALIDATION_VALID_WALL)) && - ((val->getSeenTime() == 0) || + ((val->getSeenTime() == NetClock::time_point{}) || (val->getSeenTime() < (now + VALIDATION_VALID_LOCAL))); } @@ -403,10 +405,10 @@ private: return ret; } - std::vector + std::vector getValidationTimes (uint256 const& hash) override { - std::vector times; + std::vector times; ScopedLockType sl (mLock); if (auto j = findSet (hash)) for (auto& it : *j) @@ -482,7 +484,8 @@ private: *db << boost::str ( insVal % to_string (it->getLedgerHash ()) % it->getSignerPublic ().humanNodePublic () % - it->getSignTime () % sqlEscape (s.peekData ())); + it->getSignTime().time_since_epoch().count() % + sqlEscape (s.peekData ())); } tr.commit (); diff --git a/src/ripple/app/misc/Validations.h b/src/ripple/app/misc/Validations.h index 1f25a7d63..075e606b7 100644 --- a/src/ripple/app/misc/Validations.h +++ b/src/ripple/app/misc/Validations.h @@ -70,7 +70,7 @@ public: LedgerIndex cutoffBefore) = 0; /** Return the times of all validations for a particular ledger hash. */ - virtual std::vector getValidationTimes ( + virtual std::vector getValidationTimes ( uint256 const& ledger) = 0; virtual std::list diff --git a/src/ripple/app/misc/impl/Transaction.cpp b/src/ripple/app/misc/impl/Transaction.cpp index 629bf6d34..db3c2bbee 100644 --- a/src/ripple/app/misc/impl/Transaction.cpp +++ b/src/ripple/app/misc/impl/Transaction.cpp @@ -159,7 +159,7 @@ Json::Value Transaction::getJson (int options, bool binary) const auto ct = mApp.getLedgerMaster(). getCloseTimeBySeq (mInLedger); if (ct) - ret[jss::date] = *ct; + ret[jss::date] = ct->time_since_epoch().count(); } } diff --git a/src/ripple/app/paths/cursor/AdvanceNode.cpp b/src/ripple/app/paths/cursor/AdvanceNode.cpp index 6c7554ef2..73ae96155 100644 --- a/src/ripple/app/paths/cursor/AdvanceNode.cpp +++ b/src/ripple/app/paths/cursor/AdvanceNode.cpp @@ -212,7 +212,7 @@ TER PathCursor::advanceNode (bool const bReverse) const if (node().sleOffer->isFieldPresent (sfExpiration) && (node().sleOffer->getFieldU32 (sfExpiration) <= - view().parentCloseTime())) + view().parentCloseTime().time_since_epoch().count())) { // Offer is expired. JLOG (j_.trace) diff --git a/src/ripple/app/tests/AmendmentTable.test.cpp b/src/ripple/app/tests/AmendmentTable.test.cpp index 0ac338807..bab601a1f 100644 --- a/src/ripple/app/tests/AmendmentTable.test.cpp +++ b/src/ripple/app/tests/AmendmentTable.test.cpp @@ -388,15 +388,15 @@ public: return ret; } - static std::uint32_t weekTime (int w) + static NetClock::time_point weekTime (weeks w) { - return w * (7*24*60*60); + return NetClock::time_point{w}; } // Execute a pretend consensus round for a flag ledger void doRound ( AmendmentTable& table - , int week + , weeks week , std::vector const& validators , std::vector > const& votes , std::vector & ourVotes @@ -414,7 +414,7 @@ public: // enabled: In/out enabled amendments // majority: In/our majority amendments (and when they got a majority) - std::uint32_t const roundTime = weekTime (week); + auto const roundTime = weekTime (week); // Build validations ValidationSet validations; @@ -501,7 +501,7 @@ public: enabledAmendments_t enabled; majorityAmendments_t majority; - doRound (*table, 1, + doRound (*table, weeks{1}, validators, votes, ourVotes, @@ -513,7 +513,7 @@ public: votes.emplace_back (testAmendment, 256); - doRound (*table, 2, + doRound (*table, weeks{2}, validators, votes, ourVotes, @@ -522,11 +522,11 @@ public: expect (ourVotes.empty(), "Voted on unknown because others did"); expect (enabled.empty(), "Enabled amendment for no reason"); - majority[testAmendment] = weekTime(1); + majority[testAmendment] = weekTime(weeks{1}); // Note that the simulation code assumes others behave as we do, // so the amendment won't get enabled - doRound (*table, 5, + doRound (*table, weeks{5}, validators, votes, ourVotes, @@ -554,7 +554,7 @@ public: enabledAmendments_t enabled; majorityAmendments_t majority; - doRound (*table, 1, + doRound (*table, weeks{1}, validators, votes, ourVotes, @@ -566,7 +566,7 @@ public: votes.emplace_back (testAmendment, 256); - doRound (*table, 2, + doRound (*table, weeks{2}, validators, votes, ourVotes, @@ -575,9 +575,9 @@ public: expect (ourVotes.empty(), "Voted on vetoed amendment because others did"); expect (enabled.empty(), "Enabled amendment for no reason"); - majority[testAmendment] = weekTime(1); + majority[testAmendment] = weekTime(weeks{1}); - doRound (*table, 5, + doRound (*table, weeks{5}, validators, votes, ourVotes, @@ -604,7 +604,7 @@ public: majorityAmendments_t majority; // Week 1: We should vote for all known amendments not enabled - doRound (*table, 1, + doRound (*table, weeks{1}, validators, votes, ourVotes, @@ -620,7 +620,7 @@ public: votes.emplace_back (i.id(), 256); // Week 2: We should recognize a majority - doRound (*table, 2, + doRound (*table, weeks{2}, validators, votes, ourVotes, @@ -629,10 +629,10 @@ public: expect (ourVotes.size() == amendmentNames.size(), "Did not vote"); expect (enabled.empty(), "Enabled amendment for no reason"); for (auto const& i : amendmentNames) - expect (majority[i.id()] == weekTime(2), "majority not detected"); + expect (majority[i.id()] == weekTime(weeks{2}), "majority not detected"); // Week 5: We should enable the amendment - doRound (*table, 5, + doRound (*table, weeks{5}, validators, votes, ourVotes, @@ -641,7 +641,7 @@ public: expect (enabled.size() == amendmentNames.size(), "Did not enable"); // Week 6: We should remove it from our votes and from having a majority - doRound (*table, 6, + doRound (*table, weeks{6}, validators, votes, ourVotes, @@ -676,7 +676,7 @@ public: if ((i > 0) && (i < 17)) votes.emplace_back (testAmendment, i * 16); - doRound (*table, i, + doRound (*table, weeks{i}, validators, votes, ourVotes, enabled, majority); if (i < 14) @@ -737,7 +737,7 @@ public: votes.emplace_back (testAmendment, 250); - doRound (*table, 1, + doRound (*table, weeks{1}, validators, votes, ourVotes, enabled, majority); expect (enabled.empty(), "Enabled for no reason"); @@ -752,7 +752,7 @@ public: // Gradually reduce support votes.emplace_back (testAmendment, 256 - i * 8); - doRound (*table, i + 1, + doRound (*table, weeks{i + 1}, validators, votes, ourVotes, enabled, majority); if (i < 6) diff --git a/src/ripple/app/tests/Offer.test.cpp b/src/ripple/app/tests/Offer.test.cpp index b0ba1bbb5..72d6f4ac6 100644 --- a/src/ripple/app/tests/Offer.test.cpp +++ b/src/ripple/app/tests/Offer.test.cpp @@ -125,6 +125,7 @@ public: { // Regression test for tiny payments using namespace jtx; + using namespace std::chrono_literals; auto const alice = Account ("alice"); auto const bob = Account ("bob"); auto const carol = Account ("carol"); @@ -148,10 +149,10 @@ public: auto const switchoverTime = STAmountCalcSwitchovers::enableUnderflowFixCloseTime (); - for (auto timeDelta : {-10, 10}){ - auto const closeTime = switchoverTime + timeDelta; + for (auto timeDelta : {-10s, 10s}){ + NetClock::time_point const closeTime = switchoverTime + timeDelta; STAmountCalcSwitchovers switchover (closeTime); - env.close (NetClock::time_point (std::chrono::seconds (closeTime))); + env.close (closeTime); // Will fail without the underflow fix auto expectedResult = switchover.enableUnderflowFix () ? tesSUCCESS : tecPATH_PARTIAL; diff --git a/src/ripple/app/tx/impl/CancelTicket.cpp b/src/ripple/app/tx/impl/CancelTicket.cpp index 9da1f87da..84844b5d7 100644 --- a/src/ripple/app/tx/impl/CancelTicket.cpp +++ b/src/ripple/app/tx/impl/CancelTicket.cpp @@ -65,7 +65,9 @@ CancelTicket::doApply () // And finally, anyone can remove an expired ticket if (!authorized && sleTicket->isFieldPresent (sfExpiration)) { - std::uint32_t const expiration = sleTicket->getFieldU32 (sfExpiration); + using tp = NetClock::time_point; + using d = tp::duration; + auto const expiration = tp{d{sleTicket->getFieldU32(sfExpiration)}}; if (view().parentCloseTime() >= expiration) authorized = true; diff --git a/src/ripple/app/tx/impl/Change.cpp b/src/ripple/app/tx/impl/Change.cpp index c1f28c948..5b50c3cd6 100644 --- a/src/ripple/app/tx/impl/Change.cpp +++ b/src/ripple/app/tx/impl/Change.cpp @@ -166,7 +166,7 @@ Change::applyAmendment() auto& entry = newMajorities.back (); entry.emplace_back (STHash256 (sfAmendment, amendment)); entry.emplace_back (STUInt32 (sfCloseTime, - view().parentCloseTime())); + view().parentCloseTime().time_since_epoch().count())); } else if (!lostMajority) { diff --git a/src/ripple/app/tx/impl/CreateOffer.cpp b/src/ripple/app/tx/impl/CreateOffer.cpp index 55ea77419..b5bdbe84a 100644 --- a/src/ripple/app/tx/impl/CreateOffer.cpp +++ b/src/ripple/app/tx/impl/CreateOffer.cpp @@ -177,13 +177,15 @@ CreateOffer::preclaim(PreclaimContext const& ctx) return temBAD_SEQUENCE; } + using d = NetClock::duration; + using tp = NetClock::time_point; auto const expiration = ctx.tx[~sfExpiration]; // Expiration is defined in terms of the close time of the parent ledger, // because we definitively know the time that it closed but we do not // know the closing time of the ledger that is under construction. if (expiration && - (ctx.view.parentCloseTime() >= *expiration)) + (ctx.view.parentCloseTime() >= tp{d{*expiration}})) { // Note that this will get checked again in applyGuts, // but it saves us a call to checkAcceptAsset and @@ -317,7 +319,7 @@ CreateOffer::bridged_cross ( Taker& taker, ApplyView& view, ApplyView& view_cancel, - Clock::time_point const when) + NetClock::time_point const when) { auto const& taker_amount = taker.original_offer (); @@ -479,7 +481,7 @@ CreateOffer::direct_cross ( Taker& taker, ApplyView& view, ApplyView& view_cancel, - Clock::time_point const when) + NetClock::time_point const when) { OfferStream offers ( view, view_cancel, @@ -589,8 +591,7 @@ CreateOffer::cross ( ApplyView& cancel_view, Amounts const& taker_amount) { - Clock::time_point const when = - ctx_.view().parentCloseTime(); + NetClock::time_point const when{ctx_.view().parentCloseTime()}; beast::WrappedSink takerSink (j_, "Taker "); @@ -690,12 +691,14 @@ CreateOffer::applyGuts (ApplyView& view, ApplyView& view_cancel) } auto const expiration = ctx_.tx[~sfExpiration]; + using d = NetClock::duration; + using tp = NetClock::time_point; // Expiration is defined in terms of the close time of the parent ledger, // because we definitively know the time that it closed but we do not // know the closing time of the ledger that is under construction. if (expiration && - (ctx_.view().parentCloseTime() >= *expiration)) + (ctx_.view().parentCloseTime() >= tp{d{*expiration}})) { // If the offer has expired, the transaction has successfully // done nothing, so short circuit from here. diff --git a/src/ripple/app/tx/impl/CreateOffer.h b/src/ripple/app/tx/impl/CreateOffer.h index dbc212438..dc205a38d 100644 --- a/src/ripple/app/tx/impl/CreateOffer.h +++ b/src/ripple/app/tx/impl/CreateOffer.h @@ -24,9 +24,10 @@ #include #include #include -#include +#include #include #include +#include #include #include #include @@ -85,14 +86,14 @@ private: Taker& taker, ApplyView& view, ApplyView& view_cancel, - Clock::time_point const when); + NetClock::time_point const when); std::pair direct_cross ( Taker& taker, ApplyView& view, ApplyView& view_cancel, - Clock::time_point const when); + NetClock::time_point const when); // Step through the stream for as long as possible, skipping any offers // that are from the taker or which cross the taker's threshold. diff --git a/src/ripple/app/tx/impl/CreateTicket.cpp b/src/ripple/app/tx/impl/CreateTicket.cpp index b7bf72a2c..271cc2947 100644 --- a/src/ripple/app/tx/impl/CreateTicket.cpp +++ b/src/ripple/app/tx/impl/CreateTicket.cpp @@ -66,11 +66,11 @@ CreateTicket::doApply () return tecINSUFFICIENT_RESERVE; } - std::uint32_t expiration (0); + NetClock::time_point expiration{}; if (ctx_.tx.isFieldPresent (sfExpiration)) { - expiration = ctx_.tx.getFieldU32 (sfExpiration); + expiration = NetClock::time_point(NetClock::duration(ctx_.tx[sfExpiration])); if (view().parentCloseTime() >= expiration) return tesSUCCESS; @@ -80,8 +80,8 @@ CreateTicket::doApply () getTicketIndex (account_, ctx_.tx.getSequence ())); sleTicket->setAccountID (sfAccount, account_); sleTicket->setFieldU32 (sfSequence, ctx_.tx.getSequence ()); - if (expiration != 0) - sleTicket->setFieldU32 (sfExpiration, expiration); + if (expiration != NetClock::time_point{}) + sleTicket->setFieldU32 (sfExpiration, expiration.time_since_epoch().count()); view().insert (sleTicket); if (ctx_.tx.isFieldPresent (sfTarget)) diff --git a/src/ripple/app/tx/impl/OfferStream.cpp b/src/ripple/app/tx/impl/OfferStream.cpp index 7d8715f73..91e4e2a99 100644 --- a/src/ripple/app/tx/impl/OfferStream.cpp +++ b/src/ripple/app/tx/impl/OfferStream.cpp @@ -24,7 +24,7 @@ namespace ripple { OfferStream::OfferStream (ApplyView& view, ApplyView& cancelView, - Book const& book, Clock::time_point when, + Book const& book, NetClock::time_point when, StepCounter& counter, beast::Journal journal) : j_ (journal) , view_ (view) @@ -104,8 +104,10 @@ OfferStream::step (Logs& l) } // Remove if expired + using d = NetClock::duration; + using tp = NetClock::time_point; if (entry->isFieldPresent (sfExpiration) && - entry->getFieldU32 (sfExpiration) <= expire_) + tp{d{(*entry)[sfExpiration]}} <= expire_) { JLOG(j_.trace) << "Removing expired offer " << entry->getIndex(); diff --git a/src/ripple/app/tx/impl/OfferStream.h b/src/ripple/app/tx/impl/OfferStream.h index 955b7f767..dbfe058eb 100644 --- a/src/ripple/app/tx/impl/OfferStream.h +++ b/src/ripple/app/tx/impl/OfferStream.h @@ -22,6 +22,7 @@ #include #include +#include #include #include #include @@ -81,7 +82,7 @@ private: ApplyView& view_; ApplyView& cancelView_; Book book_; - Clock::time_point const expire_; + NetClock::time_point const expire_; BookTip tip_; Offer offer_; StepCounter& counter_; @@ -91,7 +92,7 @@ private: public: OfferStream (ApplyView& view, ApplyView& cancelView, - Book const& book, Clock::time_point when, + Book const& book, NetClock::time_point when, StepCounter& counter, beast::Journal journal); /** Returns the offer at the tip of the order book. diff --git a/src/ripple/app/tx/impl/SusPay.cpp b/src/ripple/app/tx/impl/SusPay.cpp index 94131db96..9c54b4eb1 100644 --- a/src/ripple/app/tx/impl/SusPay.cpp +++ b/src/ripple/app/tx/impl/SusPay.cpp @@ -164,9 +164,8 @@ SusPayCreate::doApply() // canceled, or finished without proof, within a // reasonable period of time for the first release. using namespace std::chrono; - auto const maxExpire = - ctx_.view().info().parentCloseTime + - seconds{days(7)}.count(); + auto const maxExpire = (ctx_.view().info().parentCloseTime + + weeks{1}).time_since_epoch().count(); if (ctx_.tx[~sfDigest]) { if (! ctx_.tx[~sfCancelAfter] || @@ -315,14 +314,14 @@ SusPayFinish::doApply() // Too soon? if ((*slep)[~sfFinishAfter] && - ctx_.view().info().parentCloseTime <= + ctx_.view().info().parentCloseTime.time_since_epoch().count() <= (*slep)[sfFinishAfter]) return tecNO_PERMISSION; // Too late? if ((*slep)[~sfCancelAfter] && (*slep)[sfCancelAfter] <= - ctx_.view().info().parentCloseTime) + ctx_.view().info().parentCloseTime.time_since_epoch().count()) return tecNO_PERMISSION; // Same digest? @@ -395,7 +394,7 @@ SusPayCancel::doApply() // Too soon? if (! (*slep)[~sfCancelAfter] || - ctx_.view().info().parentCloseTime <= + ctx_.view().info().parentCloseTime.time_since_epoch().count() <= (*slep)[sfCancelAfter]) return tecNO_PERMISSION; diff --git a/src/ripple/basics/chrono.h b/src/ripple/basics/chrono.h index 763359794..e563a226b 100644 --- a/src/ripple/basics/chrono.h +++ b/src/ripple/basics/chrono.h @@ -42,43 +42,17 @@ using weeks = std::chrono::duration /** Clock for measuring Ripple Network Time. The epoch is January 1, 2000 + epoch_offset = days(10957); // 2000-01-01 */ -// VFALCO TODO Finish the implementation and make -// the network clock instance a member -// of the Application object -// -// epoch_offset = days(10957); // 2000-01-01 -// -class NetClock // : public abstract_clock +class NetClock { public: - // Unfortunately this is signed for legacy reasons - using rep = std::int32_t; + using rep = std::uint32_t; + using period = std::ratio<1>; + using duration = std::chrono::duration; + using time_point = std::chrono::time_point; - using period = std::ratio<1>; - - using duration = - std::chrono::duration; - - using time_point = - std::chrono::time_point< - NetClock, duration>; - - static bool const /* constexpr? */ is_steady = - std::chrono::system_clock::is_steady; - - static - time_point - now() - { - using namespace std; - auto const when = - chrono::system_clock::now(); - return time_point( - chrono::duration_cast( - when.time_since_epoch() - - days(10957))); - } + static bool const is_steady = false; }; /** A manual NetClock for unit tests. */ diff --git a/src/ripple/core/TimeKeeper.h b/src/ripple/core/TimeKeeper.h index 963ac8aa2..841809525 100644 --- a/src/ripple/core/TimeKeeper.h +++ b/src/ripple/core/TimeKeeper.h @@ -79,14 +79,16 @@ public: */ virtual void - adjustCloseTime (duration amount) = 0; + adjustCloseTime (std::chrono::duration amount) = 0; + // This may return a negative value virtual - duration + std::chrono::duration nowOffset() const = 0; + // This may return a negative value virtual - duration + std::chrono::duration closeOffset() const = 0; }; diff --git a/src/ripple/core/impl/TimeKeeper.cpp b/src/ripple/core/impl/TimeKeeper.cpp index bea39f22b..8df5d7955 100644 --- a/src/ripple/core/impl/TimeKeeper.cpp +++ b/src/ripple/core/impl/TimeKeeper.cpp @@ -31,7 +31,7 @@ class TimeKeeperImpl : public TimeKeeper private: beast::Journal j_; std::mutex mutable mutex_; - duration closeOffset_; + std::chrono::duration closeOffset_; std::unique_ptr clock_; // Adjust system_clock::time_point for NetClock epoch @@ -77,7 +77,7 @@ public: void adjustCloseTime( - NetClock::duration amount) override + std::chrono::duration amount) override { using namespace std::chrono; auto const s = amount.count(); @@ -107,15 +107,16 @@ public: } } - duration + std::chrono::duration nowOffset() const override { - std::lock_guard lock(mutex_); - return std::chrono::duration_cast( - clock_->offset()); + using namespace std::chrono; + using namespace std; + lock_guard lock(mutex_); + return duration_cast>(clock_->offset()); } - duration + std::chrono::duration closeOffset() const override { std::lock_guard lock(mutex_); diff --git a/src/ripple/ledger/ReadView.h b/src/ripple/ledger/ReadView.h index be8f277f9..100d0fbea 100644 --- a/src/ripple/ledger/ReadView.h +++ b/src/ripple/ledger/ReadView.h @@ -77,7 +77,7 @@ struct LedgerInfo bool open = true; LedgerIndex seq = 0; - std::uint32_t parentCloseTime = 0; + NetClock::time_point parentCloseTime = {}; // // For closed ledgers @@ -101,13 +101,13 @@ struct LedgerInfo int closeFlags = 0; // the resolution for this ledger close time (2-120 seconds) - int closeTimeResolution = 0; + NetClock::duration closeTimeResolution = {}; // For closed ledgers, the time the ledger // closed. For open ledgers, the time the ledger // will close if there's no transactions. // - std::uint32_t closeTime = 0; + NetClock::time_point closeTime = {}; }; //------------------------------------------------------------------------------ @@ -247,7 +247,7 @@ public: } /** Returns the close time of the previous ledger. */ - std::uint32_t + NetClock::time_point parentCloseTime() const { return info().parentCloseTime; diff --git a/src/ripple/ledger/View.h b/src/ripple/ledger/View.h index 598ac835b..e7502f8c8 100644 --- a/src/ripple/ledger/View.h +++ b/src/ripple/ledger/View.h @@ -135,7 +135,7 @@ enabledAmendments_t getEnabledAmendments (ReadView const& view); // Return a map of amendments that have achieved majority -using majorityAmendments_t = std::map ; +using majorityAmendments_t = std::map ; majorityAmendments_t getMajorityAmendments (ReadView const& view); diff --git a/src/ripple/ledger/impl/View.cpp b/src/ripple/ledger/impl/View.cpp index 9230cd40d..ac6138753 100644 --- a/src/ripple/ledger/impl/View.cpp +++ b/src/ripple/ledger/impl/View.cpp @@ -18,6 +18,7 @@ //============================================================================== #include +#include #include #include #include @@ -51,9 +52,9 @@ void addRaw (LedgerInfo const& info, Serializer& s) s.add256 (info.parentHash); s.add256 (info.txHash); s.add256 (info.accountHash); - s.add32 (info.parentCloseTime); - s.add32 (info.closeTime); - s.add8 (info.closeTimeResolution); + s.add32 (info.parentCloseTime.time_since_epoch().count()); + s.add32 (info.closeTime.time_since_epoch().count()); + s.add8 (info.closeTimeResolution.count()); s.add8 (info.closeFlags); } @@ -486,6 +487,8 @@ getEnabledAmendments (ReadView const& view) majorityAmendments_t getMajorityAmendments (ReadView const& view) { + using tp = NetClock::time_point; + using d = tp::duration; majorityAmendments_t majorities; auto const sleAmendments = view.read(keylet::amendments()); @@ -493,7 +496,8 @@ getMajorityAmendments (ReadView const& view) { auto const& majArray = sleAmendments->getFieldArray (sfMajorities); for (auto const& m : majArray) - majorities[m.getFieldH256 (sfAmendment)] = m.getFieldU32 (sfCloseTime); + majorities[m.getFieldH256 (sfAmendment)] = + tp(d(m.getFieldU32(sfCloseTime))); } return majorities; diff --git a/src/ripple/ledger/tests/View_test.cpp b/src/ripple/ledger/tests/View_test.cpp index 828ce0a74..ac21b06f7 100644 --- a/src/ripple/ledger/tests/View_test.cpp +++ b/src/ripple/ledger/tests/View_test.cpp @@ -342,6 +342,7 @@ class View_test testContext() { using namespace jtx; + using namespace std::chrono; { Env env(*this); wipe(env.openLedger); @@ -349,7 +350,7 @@ class View_test OpenView v0(open.get()); expect(v0.seq() != 98); expect(v0.seq() == open->seq()); - expect(v0.parentCloseTime() != 99); + expect(v0.parentCloseTime() != NetClock::time_point{99s}); expect(v0.parentCloseTime() == open->parentCloseTime()); { diff --git a/src/ripple/overlay/Cluster.h b/src/ripple/overlay/Cluster.h index cede510ba..b83ca8f29 100644 --- a/src/ripple/overlay/Cluster.h +++ b/src/ripple/overlay/Cluster.h @@ -22,6 +22,7 @@ #include #include +#include #include #include #include @@ -96,7 +97,7 @@ public: RippleAddress const& identity, std::string name, std::uint32_t loadFee = 0, - std::uint32_t reportTime = 0); + NetClock::time_point reportTime = NetClock::time_point{}); /** Invokes the callback once for every cluster node. @note You are not allowed to call `update` from diff --git a/src/ripple/overlay/ClusterNode.h b/src/ripple/overlay/ClusterNode.h index cf12c5453..6c47b8ad5 100644 --- a/src/ripple/overlay/ClusterNode.h +++ b/src/ripple/overlay/ClusterNode.h @@ -20,6 +20,7 @@ #ifndef RIPPLE_APP_PEERS_CLUSTERNODESTATUS_H_INCLUDED #define RIPPLE_APP_PEERS_CLUSTERNODESTATUS_H_INCLUDED +#include #include #include #include @@ -35,7 +36,7 @@ public: RippleAddress const& identity, std::string const& name, std::uint32_t fee = 0, - std::uint32_t rtime = 0) + NetClock::time_point rtime = NetClock::time_point{}) : identity_ (identity) , name_(name) , mLoadFee(fee) @@ -52,7 +53,7 @@ public: return mLoadFee; } - std::uint32_t getReportTime() const + NetClock::time_point getReportTime() const { return mReportTime; } @@ -67,7 +68,7 @@ private: RippleAddress identity_; std::string name_; std::uint32_t mLoadFee = 0; - std::uint32_t mReportTime = 0; + NetClock::time_point mReportTime = {}; }; } // ripple diff --git a/src/ripple/overlay/impl/Cluster.cpp b/src/ripple/overlay/impl/Cluster.cpp index 526f8891b..4e80b7fbd 100644 --- a/src/ripple/overlay/impl/Cluster.cpp +++ b/src/ripple/overlay/impl/Cluster.cpp @@ -60,7 +60,7 @@ Cluster::update ( RippleAddress const& identity, std::string name, std::uint32_t loadFee, - std::uint32_t reportTime) + NetClock::time_point reportTime) { std::lock_guard lock(mutex_); diff --git a/src/ripple/overlay/impl/PeerImp.cpp b/src/ripple/overlay/impl/PeerImp.cpp index 5eb72214c..6b2dd63b1 100644 --- a/src/ripple/overlay/impl/PeerImp.cpp +++ b/src/ripple/overlay/impl/PeerImp.cpp @@ -53,6 +53,8 @@ #include #include +using namespace std::chrono_literals; + namespace ripple { PeerImp::PeerImp (Application& app, id_t id, endpoint_type remote_endpoint, @@ -923,7 +925,7 @@ PeerImp::onMessage (std::shared_ptr const& m) RippleAddress::createNodePublic(node.publickey()), name, node.nodeload(), - node.reporttime()); + NetClock::time_point{NetClock::duration{node.reporttime()}}); } int loadSources = m->loadsources().size(); @@ -944,7 +946,7 @@ PeerImp::onMessage (std::shared_ptr const& m) } // Calculate the cluster fee: - auto const thresh = app_.timeKeeper().now().time_since_epoch().count() - 90; + auto const thresh = app_.timeKeeper().now() - 90s; std::uint32_t clusterFee = 0; std::vector fees; @@ -1107,7 +1109,7 @@ PeerImp::onMessage (std::shared_ptr const& m) if (app_.getJobQueue().getJobCount(jtTRANSACTION) > 100) p_journal_.info << "Transaction queue is full"; - else if (app_.getLedgerMaster().getValidatedLedgerAge() > 240) + else if (app_.getLedgerMaster().getValidatedLedgerAge() > 4min) p_journal_.trace << "No new transactions until synchronized"; else { @@ -1242,7 +1244,8 @@ PeerImp::onMessage (std::shared_ptr const& m) memcpy (prevLedger.begin (), set.previousledger ().data (), 32); uint256 suppression = proposalUniqueId ( - proposeHash, prevLedger, set.proposeseq(), set.closetime (), + proposeHash, prevLedger, set.proposeseq(), + NetClock::time_point{NetClock::duration{set.closetime()}}, Blob(set.nodepubkey ().begin (), set.nodepubkey ().end ()), Blob(set.signature ().begin (), set.signature ().end ())); @@ -1282,7 +1285,8 @@ PeerImp::onMessage (std::shared_ptr const& m) "Proposal: " << (isTrusted ? "trusted" : "UNTRUSTED"); auto proposal = std::make_shared ( - prevLedger, set.proposeseq (), proposeHash, set.closetime (), + prevLedger, set.proposeseq (), proposeHash, + NetClock::time_point{NetClock::duration{set.closetime()}}, signerPublic, PublicKey(makeSlice(set.nodepubkey())), suppression); @@ -1361,7 +1365,7 @@ PeerImp::onMessage (std::shared_ptr const& m) } if (m->has_ledgerseq() && - app_.getLedgerMaster().getValidatedLedgerAge() < 120) + app_.getLedgerMaster().getValidatedLedgerAge() < 2min) { checkSanity (m->ledgerseq(), app_.getLedgerMaster().getValidLedgerIndex()); } @@ -1552,8 +1556,7 @@ void PeerImp::onMessage (std::shared_ptr const& m) { error_code ec; - auto const closeTime = - app_.timeKeeper().closeTime().time_since_epoch().count(); + auto const closeTime = app_.timeKeeper().closeTime(); if (m->has_hops() && ! slot_->cluster()) m->set_hops(m->hops() + 1); @@ -1786,7 +1789,7 @@ PeerImp::doFetchPack (const std::shared_ptr& packet // Don't queue fetch pack jobs if we're under load or we already have // some queued. if (app_.getFeeTrack ().isLoadedLocal () || - (app_.getLedgerMaster().getValidatedLedgerAge() > 40) || + (app_.getLedgerMaster().getValidatedLedgerAge() > 40s) || (app_.getJobQueue().getJobCount(jtPACK) > 10)) { p_journal_.info << "Too busy to make fetch pack"; diff --git a/src/ripple/overlay/tests/cluster_test.cpp b/src/ripple/overlay/tests/cluster_test.cpp index 2bc4454f5..b2de18a3f 100644 --- a/src/ripple/overlay/tests/cluster_test.cpp +++ b/src/ripple/overlay/tests/cluster_test.cpp @@ -130,7 +130,7 @@ public: auto const node = randomNode (); std::uint32_t load = 0; - std::uint32_t tick = 0; + NetClock::time_point tick = {}; // Initial update expect (c->update (node, "", load, tick)); @@ -149,7 +149,9 @@ public: } // Updating the name (empty updates to non-empty) - expect (c->update (node, node.humanNodePublic (), load, ++tick)); + using namespace std::chrono_literals; + tick += 1s; + expect (c->update (node, node.humanNodePublic (), load, tick)); { auto member = c->member (node); expect (static_cast(member)); @@ -157,7 +159,8 @@ public: } // Updating the name (non-empty doesn't go to empty) - expect (c->update (node, "", load, ++tick)); + tick += 1s; + expect (c->update (node, "", load, tick)); { auto member = c->member (node); expect (static_cast(member)); @@ -165,7 +168,8 @@ public: } // Updating the name (non-empty updates to new non-empty) - expect (c->update (node, "test", load, ++tick)); + tick += 1s; + expect (c->update (node, "test", load, tick)); { auto member = c->member (node); expect (static_cast(member)); diff --git a/src/ripple/protocol/Protocol.h b/src/ripple/protocol/Protocol.h index b86faed33..799cf75fc 100644 --- a/src/ripple/protocol/Protocol.h +++ b/src/ripple/protocol/Protocol.h @@ -46,17 +46,6 @@ struct Protocol static int const txMaxSizeBytes = 1024 * 1024; // 1048576 }; -/** A clock representing network time. - This measures seconds since the Ripple epoch as seen - by the ledger close clock. -*/ -class Clock // : public abstract_clock -{ -public: - using time_point = std::uint32_t; - using duration = std::chrono::seconds; -}; - /** A ledger index. */ using LedgerIndex = std::uint32_t; diff --git a/src/ripple/protocol/STAmount.h b/src/ripple/protocol/STAmount.h index 3a75bd339..69fd45fca 100644 --- a/src/ripple/protocol/STAmount.h +++ b/src/ripple/protocol/STAmount.h @@ -20,6 +20,7 @@ #ifndef RIPPLE_PROTOCOL_STAMOUNT_H_INCLUDED #define RIPPLE_PROTOCOL_STAMOUNT_H_INCLUDED +#include #include #include #include @@ -384,13 +385,13 @@ class STAmountCalcSwitchovers public: STAmountCalcSwitchovers () = delete; explicit - STAmountCalcSwitchovers (std::uint32_t parentCloseTime); + STAmountCalcSwitchovers (NetClock::time_point parentCloseTime); explicit STAmountCalcSwitchovers (bool enableAll) : enableUnderflowFix_ (enableAll) {} bool enableUnderflowFix () const; // for tests - static std::uint32_t enableUnderflowFixCloseTime (); + static NetClock::time_point enableUnderflowFixCloseTime (); }; // multiply, or divide rounding result in specified direction diff --git a/src/ripple/protocol/STObject.h b/src/ripple/protocol/STObject.h index 6cb3625b8..4913f057a 100644 --- a/src/ripple/protocol/STObject.h +++ b/src/ripple/protocol/STObject.h @@ -20,6 +20,7 @@ #ifndef RIPPLE_PROTOCOL_STOBJECT_H_INCLUDED #define RIPPLE_PROTOCOL_STOBJECT_H_INCLUDED +#include #include #include #include diff --git a/src/ripple/protocol/STValidation.h b/src/ripple/protocol/STValidation.h index 1132208fa..18db8f3d9 100644 --- a/src/ripple/protocol/STValidation.h +++ b/src/ripple/protocol/STValidation.h @@ -49,7 +49,7 @@ public: STValidation (SerialIter & sit, bool checkSignature = true); // Does not sign the validation - STValidation (uint256 const& ledgerHash, std::uint32_t signTime, + STValidation (uint256 const& ledgerHash, NetClock::time_point signTime, const RippleAddress & raPub, bool isFull); STBase* @@ -65,8 +65,8 @@ public: } uint256 getLedgerHash () const; - std::uint32_t getSignTime () const; - std::uint32_t getSeenTime () const; + NetClock::time_point getSignTime () const; + NetClock::time_point getSeenTime () const; std::uint32_t getFlags () const; RippleAddress getSignerPublic () const; NodeID getNodeID () const @@ -86,7 +86,7 @@ public: { mTrusted = true; } - void setSeen (std::uint32_t s) + void setSeen (NetClock::time_point s) { mSeen = s; } @@ -118,7 +118,7 @@ private: uint256 mPreviousHash; NodeID mNodeID; bool mTrusted = false; - std::uint32_t mSeen = 0; + NetClock::time_point mSeen = {}; }; } // ripple diff --git a/src/ripple/protocol/impl/STAmount.cpp b/src/ripple/protocol/impl/STAmount.cpp index 4b623329c..9b7ab2264 100644 --- a/src/ripple/protocol/impl/STAmount.cpp +++ b/src/ripple/protocol/impl/STAmount.cpp @@ -1309,14 +1309,15 @@ mulDivNoThrow(std::uint64_t value, std::uint64_t mul, std::uint64_t div) } } -std::uint32_t +NetClock::time_point STAmountCalcSwitchovers::enableUnderflowFixCloseTime () { - // Mon Dec 28 10:00:00am PST - return 504'640'800; + using namespace std::chrono_literals; + // Mon Dec 28, 2015 10:00:00am PST + return NetClock::time_point{504640800s}; } -STAmountCalcSwitchovers::STAmountCalcSwitchovers (std::uint32_t parentCloseTime) +STAmountCalcSwitchovers::STAmountCalcSwitchovers (NetClock::time_point parentCloseTime) { enableUnderflowFix_ = parentCloseTime > enableUnderflowFixCloseTime(); } diff --git a/src/ripple/protocol/impl/STValidation.cpp b/src/ripple/protocol/impl/STValidation.cpp index a8a2907c0..9e4aec759 100644 --- a/src/ripple/protocol/impl/STValidation.cpp +++ b/src/ripple/protocol/impl/STValidation.cpp @@ -40,14 +40,14 @@ STValidation::STValidation (SerialIter& sit, bool checkSignature) } STValidation::STValidation ( - uint256 const& ledgerHash, std::uint32_t signTime, + uint256 const& ledgerHash, NetClock::time_point signTime, RippleAddress const& raPub, bool isFull) : STObject (getFormat (), sfValidation) , mSeen (signTime) { // Does not sign setFieldH256 (sfLedgerHash, ledgerHash); - setFieldU32 (sfSigningTime, signTime); + setFieldU32 (sfSigningTime, signTime.time_since_epoch().count()); setFieldVL (sfSigningPubKey, raPub.getNodePublic ()); mNodeID = raPub.getNodeID (); @@ -79,12 +79,13 @@ uint256 STValidation::getLedgerHash () const return getFieldH256 (sfLedgerHash); } -std::uint32_t STValidation::getSignTime () const +NetClock::time_point +STValidation::getSignTime () const { - return getFieldU32 (sfSigningTime); + return NetClock::time_point{NetClock::duration{getFieldU32(sfSigningTime)}}; } -std::uint32_t STValidation::getSeenTime () const +NetClock::time_point STValidation::getSeenTime () const { return mSeen; } diff --git a/src/ripple/rpc/handlers/Peers.cpp b/src/ripple/rpc/handlers/Peers.cpp index 2c5317ff0..8b78dc0f0 100644 --- a/src/ripple/rpc/handlers/Peers.cpp +++ b/src/ripple/rpc/handlers/Peers.cpp @@ -40,7 +40,7 @@ Json::Value doPeers (RPC::Context& context) jvResult[jss::peers] = context.app.overlay ().json (); - auto const now = context.app.timeKeeper().now().time_since_epoch().count(); + auto const now = context.app.timeKeeper().now(); auto const self = context.app.getLocalCredentials().getNodePublic(); Json::Value& cluster = (jvResult[jss::cluster] = Json::objectValue); @@ -60,10 +60,10 @@ Json::Value doPeers (RPC::Context& context) if ((node.getLoadFee() != ref) && (node.getLoadFee() != 0)) json[jss::fee] = static_cast(node.getLoadFee()) / ref; - if (node.getReportTime()) + if (node.getReportTime() != NetClock::time_point{}) json[jss::age] = (node.getReportTime() >= now) ? 0 - : (now - node.getReportTime()); + : (now - node.getReportTime()).count(); }); } diff --git a/src/ripple/rpc/impl/TransactionSign.cpp b/src/ripple/rpc/impl/TransactionSign.cpp index 0ea2272d8..6e5ca9075 100644 --- a/src/ripple/rpc/impl/TransactionSign.cpp +++ b/src/ripple/rpc/impl/TransactionSign.cpp @@ -240,7 +240,7 @@ checkTxJsonFields ( Json::Value const& tx_json, Role const role, bool const verify, - int validatedLedgerAge, + std::chrono::seconds validatedLedgerAge, Config const& config, LoadFeeTrack const& feeTrack) { @@ -333,7 +333,7 @@ transactionPreProcessImpl ( Json::Value& params, Role role, SigningForParams& signingArgs, - int validatedLedgerAge, + std::chrono::seconds validatedLedgerAge, Application& app, std::shared_ptr ledger) { @@ -673,7 +673,7 @@ Json::Value transactionSign ( Json::Value jvRequest, NetworkOPs::FailHard failType, Role role, - int validatedLedgerAge, + std::chrono::seconds validatedLedgerAge, Application& app, std::shared_ptr ledger, ApplyFlags flags) @@ -708,7 +708,7 @@ Json::Value transactionSubmit ( Json::Value jvRequest, NetworkOPs::FailHard failType, Role role, - int validatedLedgerAge, + std::chrono::seconds validatedLedgerAge, Application& app, std::shared_ptr ledger, ProcessTransactionFn const& processTransaction, @@ -834,7 +834,7 @@ Json::Value transactionSignFor ( Json::Value jvRequest, NetworkOPs::FailHard failType, Role role, - int validatedLedgerAge, + std::chrono::seconds validatedLedgerAge, Application& app, std::shared_ptr ledger, ApplyFlags flags) @@ -944,7 +944,7 @@ Json::Value transactionSubmitMultiSigned ( Json::Value jvRequest, NetworkOPs::FailHard failType, Role role, - int validatedLedgerAge, + std::chrono::seconds validatedLedgerAge, Application& app, std::shared_ptr ledger, ProcessTransactionFn const& processTransaction, diff --git a/src/ripple/rpc/impl/TransactionSign.h b/src/ripple/rpc/impl/TransactionSign.h index 95517a772..5615dd10c 100644 --- a/src/ripple/rpc/impl/TransactionSign.h +++ b/src/ripple/rpc/impl/TransactionSign.h @@ -81,7 +81,7 @@ Json::Value transactionSign ( Json::Value params, // Passed by value so it can be modified locally. NetworkOPs::FailHard failType, Role role, - int validatedLedgerAge, + std::chrono::seconds validatedLedgerAge, Application& app, std::shared_ptr ledger, ApplyFlags flags = tapNONE); @@ -91,7 +91,7 @@ Json::Value transactionSubmit ( Json::Value params, // Passed by value so it can be modified locally. NetworkOPs::FailHard failType, Role role, - int validatedLedgerAge, + std::chrono::seconds validatedLedgerAge, Application& app, std::shared_ptr ledger, ProcessTransactionFn const& processTransaction, @@ -102,7 +102,7 @@ Json::Value transactionSignFor ( Json::Value params, // Passed by value so it can be modified locally. NetworkOPs::FailHard failType, Role role, - int validatedLedgerAge, + std::chrono::seconds validatedLedgerAge, Application& app, std::shared_ptr ledger, ApplyFlags flags = tapNONE); @@ -112,7 +112,7 @@ Json::Value transactionSubmitMultiSigned ( Json::Value params, // Passed by value so it can be modified locally. NetworkOPs::FailHard failType, Role role, - int validatedLedgerAge, + std::chrono::seconds validatedLedgerAge, Application& app, std::shared_ptr ledger, ProcessTransactionFn const& processTransaction, diff --git a/src/ripple/rpc/impl/Tuning.h b/src/ripple/rpc/impl/Tuning.h index 0f0bdf3ee..145c8de8f 100644 --- a/src/ripple/rpc/impl/Tuning.h +++ b/src/ripple/rpc/impl/Tuning.h @@ -51,7 +51,8 @@ static int const defaultAutoFillFeeMultiplier = 10; static int const maxPathfindsInProgress = 2; static int const maxPathfindJobCount = 50; static int const maxJobQueueClients = 500; -static int const maxValidatedLedgerAge = 120; +using namespace std::chrono_literals; +auto constexpr maxValidatedLedgerAge = 2min; static int const maxRequestSize = 1000000; /** Maximum number of pages in one response from a binary LedgerData request. */ diff --git a/src/ripple/rpc/impl/Utilities.cpp b/src/ripple/rpc/impl/Utilities.cpp index b2c3cee86..5a80c8e37 100644 --- a/src/ripple/rpc/impl/Utilities.cpp +++ b/src/ripple/rpc/impl/Utilities.cpp @@ -69,9 +69,10 @@ addPaymentDeliveredAmount ( // If the ledger closed long after the DeliveredAmount code was deployed // then its absence indicates that the amount delivered is listed in the // Amount field. DeliveredAmount went live January 24, 2014. + using namespace std::chrono_literals; auto ct = context.ledgerMaster.getCloseTimeBySeq (transaction->getLedger ()); - if (ct && (*ct > 446000000)) + if (ct && (*ct > NetClock::time_point{446000000s})) { // 446000000 is in Feb 2014, well after DeliveredAmount went live meta[jss::delivered_amount] = diff --git a/src/ripple/rpc/tests/JSONRPC.test.cpp b/src/ripple/rpc/tests/JSONRPC.test.cpp index 52d22e236..84ecce65a 100644 --- a/src/ripple/rpc/tests/JSONRPC.test.cpp +++ b/src/ripple/rpc/tests/JSONRPC.test.cpp @@ -1639,6 +1639,7 @@ public: void testTransactionRPC () { + using namespace std::chrono_literals; // Use jtx to set up a ledger so the tests will do the right thing. test::jtx::Account const a {"a"}; // rnUy2SHTrB9DubsPmkJZUXTf5FcNDGrYEA test::jtx::Account const g {"g"}; // rLPwWB1itaUGMV8kbMLLysjGkEpTM2Soy4 @@ -1666,7 +1667,7 @@ public: Json::Value params, NetworkOPs::FailHard failType, Role role, - int validatedLedgerAge, + std::chrono::seconds validatedLedgerAge, Application& app, std::shared_ptr ledger, ApplyFlags flags); @@ -1675,7 +1676,7 @@ public: Json::Value params, NetworkOPs::FailHard failType, Role role, - int validatedLedgerAge, + std::chrono::seconds validatedLedgerAge, Application& app, std::shared_ptr ledger, ProcessTransactionFn const& processTransaction, @@ -1717,7 +1718,7 @@ public: req, NetworkOPs::FailHard::yes, testRole, - 1, + 1s, env.app(), ledger, tapENABLE_TESTING); @@ -1730,7 +1731,7 @@ public: req, NetworkOPs::FailHard::yes, testRole, - 1, + 1s, env.app(), ledger, processTxn, diff --git a/src/ripple/test/jtx/impl/Env.cpp b/src/ripple/test/jtx/impl/Env.cpp index a62f9b10b..d5a92f02f 100644 --- a/src/ripple/test/jtx/impl/Env.cpp +++ b/src/ripple/test/jtx/impl/Env.cpp @@ -134,10 +134,8 @@ Env::close(NetClock::time_point const& closeTime, } // To ensure that the close time is exact and not rounded, we don't // claim to have reached consensus on what it should be. - next->setAccepted ( - std::chrono::duration_cast ( - closeTime.time_since_epoch ()).count (), - ledgerPossibleTimeResolutions[0], false, app().config()); + next->setAccepted(closeTime, ledgerPossibleTimeResolutions[0], + false, app().config()); OrderedTxs locals({}); openLedger.accept(app(), next->rules(), next, locals, false, retries, applyFlags(), "", f);