xrpld
Loading...
Searching...
No Matches
LedgerMaster.h
1#pragma once
2
3#include <xrpld/app/ledger/AbstractFetchPackContainer.h>
4#include <xrpld/app/ledger/InboundLedger.h>
5#include <xrpld/app/ledger/LedgerHistory.h>
6#include <xrpld/app/ledger/LedgerHolder.h>
7#include <xrpld/app/ledger/LedgerReplay.h>
8#include <xrpld/app/main/Application.h>
9#include <xrpld/core/TimeKeeper.h>
10
11#include <xrpl/basics/Blob.h>
12#include <xrpl/basics/RangeSet.h>
13#include <xrpl/basics/UptimeClock.h>
14#include <xrpl/basics/base_uint.h>
15#include <xrpl/basics/chrono.h>
16#include <xrpl/beast/insight/Collector.h>
17#include <xrpl/beast/insight/Gauge.h>
18#include <xrpl/beast/insight/Hook.h>
19#include <xrpl/beast/utility/Journal.h>
20#include <xrpl/json/json_value.h>
21#include <xrpl/ledger/CanonicalTXSet.h>
22#include <xrpl/ledger/Ledger.h>
23#include <xrpl/ledger/ReadView.h>
24#include <xrpl/protocol/Protocol.h>
25#include <xrpl/protocol/RippleLedgerHash.h>
26#include <xrpl/protocol/Rules.h>
27
28#include <xrpl.pb.h>
29
30#include <atomic>
31#include <chrono>
32#include <cstddef>
33#include <cstdint>
34#include <memory>
35#include <mutex>
36#include <optional>
37#include <string>
38#include <utility>
39#include <vector>
40
41namespace xrpl {
42
43class Peer;
44class Transaction;
45
122{
123public:
133 explicit LedgerMaster(
134 Application& app,
136 beast::insight::Collector::Ptr const& collector,
137 beast::Journal journal);
138
143 ~LedgerMaster() override = default;
144
150
156
166 bool
167 isCompatible(ReadView const&, beast::Journal::Stream, char const* reason);
168
177 peekMutex();
178
186
194 {
195 return closedLedger_.get();
196 }
197
206
213 Rules
215
225
233
241
249 bool
250 isCaughtUp(std::string& reason);
251
261
270 bool
272
285 void
286 setFullLedger(std::shared_ptr<Ledger const> const& ledger, bool isSynchronous, bool isCurrent);
287
299 bool
301
309 void
310 switchLCL(std::shared_ptr<Ledger const> const& lastClosed);
311
319 void
320 failedSave(std::uint32_t seq, UInt256 const& hash);
321
326 getCompleteLedgers() const;
327
337
344 void
346
360
367 UInt256
369
380
399 std::uint32_t index,
400 std::shared_ptr<ReadView const> const& referenceLedger,
401 InboundLedger::Reason reason);
402
413
420 getLedgerByHash(UInt256 const& hash);
421
428 void
430
437 getCloseTimeBySeq(LedgerIndex ledgerIndex);
438
448 getCloseTimeByHash(LedgerHash const& ledgerHash, LedgerIndex ledgerIndex);
449
455 void
457
465 void
466 fixMismatch(ReadView const& ledger);
467
473 bool
474 haveLedger(std::uint32_t seq) const;
475
481 void
483
495 bool
496 isValidated(ReadView const& ledger);
497
511 bool
513
523 bool
525
529 void
530 sweep();
531
535 float
537
547 void
549
558 void
559 checkAccept(UInt256 const& hash, std::uint32_t seq);
560
574 void
576 std::shared_ptr<Ledger const> const& ledger,
577 UInt256 const& consensusHash,
578 json::Value consensus);
579
586 void
588
594 void
595 tryAdvance();
596
602 bool
604
609 bool
611
618 bool
620
629 bool
630 fixIndex(LedgerIndex ledgerIndex, LedgerHash const& ledgerHash);
631
638 void
640
646 void
648
649 // ledger replay
650
656 void
658
664
665 // Fetch Packs
666
674 void
675 gotFetchPack(bool progress, std::uint32_t seq);
676
683 void
684 addFetchPack(UInt256 const& hash, std::shared_ptr<Blob> data);
685
695 getFetchPack(UInt256 const& hash) override;
696
708 void
710 std::weak_ptr<Peer> const& wPeer,
712 UInt256 haveLedgerHash,
714
719 getFetchPackCacheSize() const;
720
724 bool
726 {
727 return !validLedger_.empty();
728 }
729
736 minSqlSeq();
737
748 txnIdFromIndex(uint32_t ledgerSeq, uint32_t txnIndex);
749
750private:
758 void
760
767 void
769
778 void
780
787 void
789
800
808
821 void
823 std::uint32_t missing,
824 bool& progress,
827
838 void
840
852
860 void
861 updatePaths();
862
873 bool
875
880
885
896
901
906
911
916
921
926
931
937
942
948
954
958 bool advanceThread_{false};
959
963 bool advanceWork_{false};
964
970
976
981
986
991
996
1002
1007
1013
1017 bool const standalone_;
1018
1023
1028
1033
1040
1046
1052
1057
1058private:
1063 struct Stats
1064 {
1071 template <class Handler>
1072 Stats(Handler const& handler, beast::insight::Collector::Ptr const& collector)
1073 : hook(collector->makeHook(handler))
1074 , validatedLedgerAge(collector->makeGauge("LedgerMaster", "Validated_Ledger_Age"))
1075 , publishedLedgerAge(collector->makeGauge("LedgerMaster", "Published_Ledger_Age"))
1076 {
1077 }
1078
1083
1089
1094 };
1095
1100
1101private:
1106 void
1108 {
1109 std::scoped_lock const lock(mutex_);
1110 stats_.validatedLedgerAge.set(getValidatedLedgerAge().count());
1111 stats_.publishedLedgerAge.set(getPublishedLedgerAge().count());
1112 }
1113};
1114
1115} // namespace xrpl
NetClock::time_point time_point
Provide a light-weight way to check active() before string formatting.
Definition Journal.h:199
A generic endpoint for log messages.
Definition Journal.h:44
std::shared_ptr< Collector > Ptr
Definition Collector.h:29
A metric for measuring an integral value.
Definition Gauge.h:21
A reference to a handler for performing polled collection.
Definition Hook.h:14
Represents a JSON value.
Definition json_value.h:117
An interface facilitating retrieval of fetch packs without an application or ledgermaster object.
Holds transactions which were deferred to the next pass of consensus.
Retains historical ledgers.
Hold a ledger in a thread-safe way.
std::optional< LedgerIndex > minSqlSeq()
Returns the minimum ledger sequence in SQL database, if any.
LedgerIndex const maxLedgerDifference_
Try to keep a validator from switching from test to live network without first wiping the database.
std::atomic_flag gotFetchPackThread_
Set while a GotFetchPack job is outstanding, so only one ever is.
std::pair< UInt256, LedgerIndex > lastValidLedger_
Fully validated ledger, whether or not we have the ledger resident.
std::size_t getNeededValidations()
Determines how many validations are needed to fully validate a ledger.
bool isCompatible(ReadView const &, beast::Journal::Stream, char const *reason)
Tests whether a view can belong to the same chain as what we validated.
std::shared_ptr< STTx const > popAcctTransaction(std::shared_ptr< STTx const > const &tx)
Get the next transaction held for a particular account if any.
void setValidLedger(std::shared_ptr< Ledger const > const &l)
Adopts a ledger as the last validated one and tells the rest of the server, including the amendment-s...
void switchLCL(std::shared_ptr< Ledger const > const &lastClosed)
Adopts a ledger as the last closed ledger, then either accepts it directly (standalone) or tests it f...
std::recursive_mutex & peekMutex()
Exposes mutex_.
std::chrono::seconds getValidatedLedgerAge()
Stats stats_
The gauges and the collector hook that samples them.
TimeKeeper::time_point upgradeWarningPrevTime_
Time that the previous upgrade warning was issued.
bool pathFindNewRequest_
A pathfinding request arrived and has not been picked up yet.
std::uint32_t const ledgerFetchSize_
Cap on ledgers acquired in one publication or prefetch pass.
std::atomic< std::uint32_t > pubLedgerClose_
Close time of pubLedger_, in seconds since the network epoch; 0 if none.
LedgerIndex getCurrentLedgerIndex()
bool fixIndex(LedgerIndex ledgerIndex, LedgerHash const &ledgerHash)
Corrects the cached sequence-to-hash mapping for one ledger.
bool getValidatedRange(std::uint32_t &minVal, std::uint32_t &maxVal)
Returns Ledgers we have all the nodes for and are indexed: a contiguous part of getFullValidatedRange...
void applyHeldTransactions()
Apply held transactions to the open ledger This is normally called as we close the ledger.
bool storeLedger(std::shared_ptr< Ledger const > ledger)
Adds a ledger to the history cache.
void gotFetchPack(bool progress, std::uint32_t seq)
Signals that fetch-pack data arrived, so waiting acquires can use it.
beast::Journal journal_
Log sink for this component.
void tryFill(std::shared_ptr< Ledger const > ledger)
Walks back from a ledger through the SQL index, marking each ancestor resident until the chain breaks...
std::shared_ptr< Ledger const > getLedgerBySeq(std::uint32_t index)
Finds a ledger by sequence, preferring the validated chain.
bool haveValidated()
Whether we have ever fully validated a ledger.
void setPubLedger(std::shared_ptr< Ledger const > const &l)
Records how far publication has reached.
bool newPFWork(char const *name, std::unique_lock< std::recursive_mutex > &)
A thread needs to be dispatched to handle pathfinding work of some kind.
void setFullLedger(std::shared_ptr< Ledger const > const &ledger, bool isSynchronous, bool isCurrent)
A new ledger has been accepted as part of the trusted chain: mark it validated and full,...
std::atomic< LedgerIndex > pubLedgerSeq_
Sequence of pubLedger_; 0 if nothing has been published.
void clearPriorLedgers(LedgerIndex seq)
Forgets that we hold any ledger below a sequence, without touching the cached ledgers themselves.
void setBuildingLedger(LedgerIndex index)
Records which ledger consensus is currently building, so validations for it are not chased separately...
std::uint32_t fetchSeq_
Sequence of the last fetch-pack attempt, so the same one is not tried twice in a row.
void consensusBuilt(std::shared_ptr< Ledger const > const &ledger, UInt256 const &consensusHash, json::Value consensus)
Report that the consensus process built a particular ledger.
UInt256 getHashBySeq(std::uint32_t index)
Get a ledger's hash by sequence number using the cache.
bool isCaughtUp(std::string &reason)
Decides whether the node is close enough to the network to serve clients.
std::size_t getFetchPackCacheSize() const
std::vector< std::shared_ptr< Ledger const > > findNewLedgersToPublish(std::unique_lock< std::recursive_mutex > &)
Collects the next run of validated ledgers to publish, acquiring or replaying the ones that are missi...
std::atomic< LedgerIndex > buildingLedgerSeq_
Sequence consensus is building; 0 once it is built.
std::optional< NetClock::time_point > getCloseTimeByHash(LedgerHash const &ledgerHash, LedgerIndex ledgerIndex)
Reads a close time straight out of the serialized header in the node store.
~LedgerMaster() override=default
Destroys the tracker.
void clearLedger(std::uint32_t seq)
Marks a ledger no longer resident.
void clearLedgerCachePrior(LedgerIndex seq)
Drops cached ledgers below a sequence.
TaggedCache< UInt256, Blob > fetchPacks_
Fetch-pack nodes keyed by node hash.
void sweep()
Expires stale entries from the ledger history and fetch-pack caches.
bool newPathRequest()
Notes a new pathfinding request and dispatches a worker if one is due.
std::unique_ptr< LedgerReplay > replayData_
A set of transactions to replay during the next close.
LedgerMaster(Application &app, Stopwatch &stopwatch, beast::insight::Collector::Ptr const &collector, beast::Journal journal)
Constructs the tracker; reads history and fetch limits from the config.
std::optional< UInt256 > txnIdFromIndex(uint32_t ledgerSeq, uint32_t txnIndex)
Iff a txn exists at the specified ledger and offset then return its txnid.
std::atomic< LedgerIndex > validLedgerSeq_
Sequence of validLedger_; 0 if nothing is validated.
std::shared_ptr< Ledger const > getClosedLedger()
The finalized ledger is the last closed/accepted ledger.
std::shared_ptr< Ledger const > getLedgerByHash(UInt256 const &hash)
void setLedgerRangePresent(std::uint32_t minV, std::uint32_t maxV)
Records a closed range of sequences as resident.
std::optional< NetClock::time_point > getCloseTimeBySeq(LedgerIndex ledgerIndex)
std::shared_ptr< Ledger const > getValidatedLedger()
The validated ledger is the last fully validated ledger.
void fetchForHistory(std::uint32_t missing, bool &progress, InboundLedger::Reason reason, std::unique_lock< std::recursive_mutex > &)
Starts acquiring one missing historical ledger.
bool isValidated(ReadView const &ledger)
Tests whether a ledger is on the validated chain, using the skip list when the ledger does not alread...
void fixMismatch(ReadView const &ledger)
Walks back from a ledger, dropping every resident ledger it cannot confirm against that ledger's skip...
LedgerIndex getValidLedgerIndex()
LedgerHolder validLedger_
The highest-sequence ledger we have fully accepted.
CanonicalTXSet heldTransactions_
Transactions deferred to the next open ledger, in canonical order.
bool const standalone_
The server is in standalone mode.
std::shared_ptr< Ledger const > pathLedger_
The last ledger we did pathfinding against.
std::shared_ptr< Ledger const > pubLedger_
The last ledger we have published.
std::shared_ptr< ReadView const > getPublishedLedger()
This is the last ledger we published to clients and can lag the validated ledger.
bool newOrderBookDB()
If the order book is radically updated, we need to reprocess all pathfinding requests.
std::uint32_t const fetchDepth_
How many ledgers before the closed ledger do we allow peers to request?
std::recursive_mutex mutex_
Guards pubLedger_, pathLedger_, lastValidLedger_, the held transactions and the job flags other than ...
void collectMetrics()
Samples both ledger ages into the gauges.
Rules getValidatedRules()
The Rules are in the last fully validated ledger if there is one.
bool advanceWork_
Publish thread has work to do.
LedgerHistory ledgerHistory_
Cache of ledgers by hash and of validated sequence-to-hash mappings.
std::optional< LedgerHash > walkHashBySeq(std::uint32_t index, InboundLedger::Reason reason)
Walk to a ledger's hash using the skip list.
std::chrono::seconds getPublishedLedgerAge()
bool canBeCurrent(std::shared_ptr< Ledger const > const &ledger)
Check the sequence number and parent close time of a ledger against our clock and last validated ledg...
LedgerHolder closedLedger_
The ledger that most recently closed.
bool getFullValidatedRange(std::uint32_t &minVal, std::uint32_t &maxVal)
Returns Ledgers we have all the nodes for: the contiguous resident range ending at the published ledg...
std::optional< LedgerHash > getLedgerHashForHistory(LedgerIndex index, InboundLedger::Reason reason)
Finds the hash of a ledger the history back-fill wants, preferring the last back-filled ledger as the...
void tryAdvance()
Signals that the ledger stream may be able to make progress.
int fillInProgress_
Sequence a tryFill() job is currently walking back from, or 0 when no fill is running.
int pathFindThread_
Pathfinding jobs queued or running.
RangeSet< std::uint32_t > completeLedgers_
Sequences of the ledgers this node believes it holds in full.
void checkAccept(std::shared_ptr< Ledger const > const &ledger)
If the ledger passes canBeCurrent(), is newer than the validated ledger and has a quorum,...
std::optional< Blob > getFetchPack(UInt256 const &hash) override
Consumes one cached fetch-pack node.
std::uint32_t const ledgerHistorySize_
How much history do we want to keep.
std::atomic< std::uint32_t > validLedgerSign_
Sign time of validLedger_, in seconds since the network epoch: the median of its trusted validations,...
void doAdvance(std::unique_lock< std::recursive_mutex > &)
Try to publish ledgers, acquire missing ledgers.
void addHeldTransaction(std::shared_ptr< Transaction > const &trans)
Defers a transaction to the next open ledger.
std::shared_ptr< ReadView const > getCurrentLedger()
The current ledger is the ledger we believe new transactions should go in.
std::recursive_mutex completeLock_
Guards completeLedgers_ only.
std::string getCompleteLedgers() const
void takeReplay(std::unique_ptr< LedgerReplay > replay)
Stores a transaction set to replay when the next ledger closes.
void updatePaths()
Runs one pathfinding pass per new validated ledger or new request, and exits when neither is new,...
std::unique_ptr< LedgerReplay > releaseReplay()
std::size_t missingFromCompleteLedgerRange(LedgerIndex first, LedgerIndex last) const
Counts gaps in a closed sequence interval.
bool advanceThread_
An AdvanceLedger job is queued or running.
bool haveLedger(std::uint32_t seq) const
std::uint32_t getEarliestFetch()
Get the earliest ledger we will let peers fetch.
void makeFetchPack(std::weak_ptr< Peer > const &wPeer, std::shared_ptr< protocol::TMGetObjectByHash > const &request, UInt256 haveLedgerHash, UptimeClock::time_point uptime)
Builds a fetch pack of the ledgers preceding the one a peer says it has, and sends it.
std::shared_ptr< Ledger const > histLedger_
The last ledger we handled fetching history.
void addFetchPack(UInt256 const &hash, std::shared_ptr< Blob > data)
Caches one fetch-pack node received from a peer.
Application & app_
Owning application, the route to every other subsystem.
void failedSave(std::uint32_t seq, UInt256 const &hash)
Marks a ledger no longer resident after its save failed, and starts fetching it again.
Represents a peer connection in the overlay.
A view into a ledger.
Definition ReadView.h:41
Rules controlling protocol behavior.
Definition Rules.h:40
Map/cache combination.
Definition TaggedCache.h:67
std::chrono::time_point< UptimeClock > time_point
Definition UptimeClock.h:24
Use hash_* containers for keys that do not need a cryptographically secure hashing algorithm.
Definition algorithm.h:5
beast::AbstractClock< std::chrono::steady_clock > Stopwatch
A clock for measuring elapsed time.
Definition chrono.h:90
bool isCurrent(ValidationParms const &p, NetClock::time_point now, NetClock::time_point signTime, NetClock::time_point seenTime)
Whether a validation is still current.
std::uint32_t LedgerIndex
A ledger index.
Definition Protocol.h:382
Stopwatch & stopwatch()
Returns an instance of a wall clock.
Definition chrono.h:101
UInt256 LedgerHash
BaseUInt< 256 > UInt256
Definition base_uint.h:580
boost::icl::interval_set< T, std::less, ClosedInterval< T > > RangeSet
A set of closed intervals over the domain T.
Definition RangeSet.h:54
Ledger-age gauges reported to the insight collector.
beast::insight::Hook hook
Keeps the sampling callback registered for as long as Stats lives.
Stats(Handler const &handler, beast::insight::Collector::Ptr const &collector)
Registers the hook and the gauges.
beast::insight::Gauge publishedLedgerAge
Age of the published ledger, in seconds; two weeks when there is none.
beast::insight::Gauge validatedLedgerAge
Age of the validated ledger, in seconds, counted from its sign time; two weeks when there is none.