rippled
Loading...
Searching...
No Matches
Ledger.cpp
1#include <xrpld/app/ledger/InboundLedgers.h>
2#include <xrpld/app/ledger/Ledger.h>
3#include <xrpld/app/ledger/LedgerToJson.h>
4#include <xrpld/app/ledger/PendingSaves.h>
5#include <xrpld/app/main/Application.h>
6#include <xrpld/consensus/LedgerTiming.h>
7#include <xrpld/core/Config.h>
8
9#include <xrpl/basics/Log.h>
10#include <xrpl/basics/contract.h>
11#include <xrpl/beast/utility/instrumentation.h>
12#include <xrpl/core/HashRouter.h>
13#include <xrpl/core/JobQueue.h>
14#include <xrpl/json/to_string.h>
15#include <xrpl/nodestore/Database.h>
16#include <xrpl/nodestore/detail/DatabaseNodeImp.h>
17#include <xrpl/protocol/Feature.h>
18#include <xrpl/protocol/HashPrefix.h>
19#include <xrpl/protocol/Indexes.h>
20#include <xrpl/protocol/PublicKey.h>
21#include <xrpl/protocol/SecretKey.h>
22#include <xrpl/protocol/digest.h>
23#include <xrpl/protocol/jss.h>
24#include <xrpl/rdb/RelationalDatabase.h>
25
26#include <utility>
27#include <vector>
28
29namespace xrpl {
30
32
35{
36 // VFALCO This has to match addRaw in View.h.
37 return sha512Half(
39 std::uint32_t(info.seq),
41 info.parentHash,
42 info.txHash,
43 info.accountHash,
48}
49
50//------------------------------------------------------------------------------
51
52class Ledger::sles_iter_impl : public sles_type::iter_base
53{
54private:
56
57public:
58 sles_iter_impl() = delete;
60 operator=(sles_iter_impl const&) = delete;
61
62 sles_iter_impl(sles_iter_impl const&) = default;
63
67
69 copy() const override
70 {
72 }
73
74 bool
75 equal(base_type const& impl) const override
76 {
77 if (auto const p = dynamic_cast<sles_iter_impl const*>(&impl))
78 return iter_ == p->iter_;
79 return false;
80 }
81
82 void
83 increment() override
84 {
85 ++iter_;
86 }
87
88 sles_type::value_type
89 dereference() const override
90 {
91 SerialIter sit(iter_->slice());
92 return std::make_shared<SLE const>(sit, iter_->key());
93 }
94};
95
96//------------------------------------------------------------------------------
97
98class Ledger::txs_iter_impl : public txs_type::iter_base
99{
100private:
103
104public:
105 txs_iter_impl() = delete;
107 operator=(txs_iter_impl const&) = delete;
108
109 txs_iter_impl(txs_iter_impl const&) = default;
110
112 : metadata_(metadata), iter_(std::move(iter))
113 {
114 }
115
117 copy() const override
118 {
120 }
121
122 bool
123 equal(base_type const& impl) const override
124 {
125 if (auto const p = dynamic_cast<txs_iter_impl const*>(&impl))
126 return iter_ == p->iter_;
127 return false;
128 }
129
130 void
131 increment() override
132 {
133 ++iter_;
134 }
135
136 txs_type::value_type
137 dereference() const override
138 {
139 auto const& item = *iter_;
140 if (metadata_)
141 return deserializeTxPlusMeta(item);
142 return {deserializeTx(item), nullptr};
143 }
144};
145
146//------------------------------------------------------------------------------
147
150 Config const& config,
151 std::vector<uint256> const& amendments,
152 Family& family)
153 : mImmutable(false)
154 , txMap_(SHAMapType::TRANSACTION, family)
155 , stateMap_(SHAMapType::STATE, family)
156 , rules_{config.features}
157 , j_(beast::Journal(beast::Journal::getNullSink()))
158{
159 header_.seq = 1;
162
163 static auto const id =
165 {
166 auto const sle = std::make_shared<SLE>(keylet::account(id));
167 sle->setFieldU32(sfSequence, 1);
168 sle->setAccountID(sfAccount, id);
169 sle->setFieldAmount(sfBalance, header_.drops);
170 rawInsert(sle);
171 }
172
173 if (!amendments.empty())
174 {
175 auto const sle = std::make_shared<SLE>(keylet::amendments());
176 sle->setFieldV256(sfAmendments, STVector256{amendments});
177 rawInsert(sle);
178 }
179
180 {
182 // Whether featureXRPFees is supported will depend on startup options.
183 if (std::find(amendments.begin(), amendments.end(), featureXRPFees) != amendments.end())
184 {
185 sle->at(sfBaseFeeDrops) = config.FEES.reference_fee;
186 sle->at(sfReserveBaseDrops) = config.FEES.account_reserve;
187 sle->at(sfReserveIncrementDrops) = config.FEES.owner_reserve;
188 }
189 else
190 {
191 if (auto const f = config.FEES.reference_fee.dropsAs<std::uint64_t>())
192 sle->at(sfBaseFee) = *f;
193 if (auto const f = config.FEES.account_reserve.dropsAs<std::uint32_t>())
194 sle->at(sfReserveBase) = *f;
195 if (auto const f = config.FEES.owner_reserve.dropsAs<std::uint32_t>())
196 sle->at(sfReserveIncrement) = *f;
197 sle->at(sfReferenceFeeUnits) = Config::FEE_UNITS_DEPRECATED;
198 }
199 rawInsert(sle);
200 }
201
203 setImmutable();
204}
205
207 LedgerHeader const& info,
208 bool& loaded,
209 bool acquire,
210 Config const& config,
211 Family& family,
213 : mImmutable(true)
214 , txMap_(SHAMapType::TRANSACTION, info.txHash, family)
215 , stateMap_(SHAMapType::STATE, info.accountHash, family)
216 , rules_(config.features)
217 , header_(info)
218 , j_(j)
219{
220 loaded = true;
221
222 if (header_.txHash.isNonZero() && !txMap_.fetchRoot(SHAMapHash{header_.txHash}, nullptr))
223 {
224 loaded = false;
225 JLOG(j.warn()) << "Don't have transaction root for ledger" << header_.seq;
226 }
227
229 !stateMap_.fetchRoot(SHAMapHash{header_.accountHash}, nullptr))
230 {
231 loaded = false;
232 JLOG(j.warn()) << "Don't have state data root for ledger" << header_.seq;
233 }
234
237
238 defaultFees(config);
239 if (!setup())
240 loaded = false;
241
242 if (!loaded)
243 {
245 if (acquire)
247 }
248}
249
250// Create a new ledger that follows this one
251Ledger::Ledger(Ledger const& prevLedger, NetClock::time_point closeTime)
252 : mImmutable(false)
253 , txMap_(SHAMapType::TRANSACTION, prevLedger.txMap_.family())
254 , stateMap_(prevLedger.stateMap_, true)
255 , fees_(prevLedger.fees_)
256 , rules_(prevLedger.rules_)
257 , j_(beast::Journal(beast::Journal::getNullSink()))
258{
259 header_.seq = prevLedger.header_.seq + 1;
261 header_.hash = prevLedger.header().hash + uint256(1);
262 header_.drops = prevLedger.header().drops;
264 header_.parentHash = prevLedger.header().hash;
266 prevLedger.header_.closeTimeResolution, getCloseAgree(prevLedger.header()), header_.seq);
267
268 if (prevLedger.header_.closeTime == NetClock::time_point{})
269 {
271 }
272 else
273 {
275 }
276}
277
278Ledger::Ledger(LedgerHeader const& info, Config const& config, Family& family)
279 : mImmutable(true)
280 , txMap_(SHAMapType::TRANSACTION, info.txHash, family)
281 , stateMap_(SHAMapType::STATE, info.accountHash, family)
282 , rules_{config.features}
283 , header_(info)
284 , j_(beast::Journal(beast::Journal::getNullSink()))
285{
287}
288
290 std::uint32_t ledgerSeq,
291 NetClock::time_point closeTime,
292 Config const& config,
293 Family& family)
294 : mImmutable(false)
295 , txMap_(SHAMapType::TRANSACTION, family)
296 , stateMap_(SHAMapType::STATE, family)
297 , rules_{config.features}
298 , j_(beast::Journal(beast::Journal::getNullSink()))
299{
300 header_.seq = ledgerSeq;
301 header_.closeTime = closeTime;
303 defaultFees(config);
304 setup();
305}
306
307void
309{
310 // Force update, since this is the only
311 // place the hash transitions to valid
312 if (!mImmutable && rehash)
313 {
316 }
317
318 if (rehash)
320
321 mImmutable = true;
324 setup();
325}
326
327void
329 NetClock::time_point closeTime,
330 NetClock::duration closeResolution,
331 bool correctCloseTime)
332{
333 // Used when we witnessed the consensus.
334 XRPL_ASSERT(!open(), "xrpl::Ledger::setAccepted : valid ledger state");
335
336 header_.closeTime = closeTime;
337 header_.closeTimeResolution = closeResolution;
338 header_.closeFlags = correctCloseTime ? 0 : sLCF_NoConsensusTime;
339 setImmutable();
340}
341
342bool
344{
345 auto const s = sle.getSerializer();
346 return stateMap_.addItem(
348}
349
350//------------------------------------------------------------------------------
351
354{
355 SerialIter sit(item.slice());
357}
358
361{
363 SerialIter sit(item.slice());
364 {
365 SerialIter s(sit.getSlice(sit.getVLDataLength()));
367 }
368 {
369 SerialIter s(sit.getSlice(sit.getVLDataLength()));
370 result.second = std::make_shared<STObject const>(s, sfMetadata);
371 }
372 return result;
373}
374
375//------------------------------------------------------------------------------
376
377bool
378Ledger::exists(Keylet const& k) const
379{
380 // VFALCO NOTE Perhaps check the type for debug builds?
381 return stateMap_.hasItem(k.key);
382}
383
384bool
385Ledger::exists(uint256 const& key) const
386{
387 return stateMap_.hasItem(key);
388}
389
391Ledger::succ(uint256 const& key, std::optional<uint256> const& last) const
392{
393 auto item = stateMap_.upper_bound(key);
394 if (item == stateMap_.end())
395 return std::nullopt;
396 if (last && item->key() >= last)
397 return std::nullopt;
398 return item->key();
399}
400
402Ledger::read(Keylet const& k) const
403{
404 if (k.key == beast::zero)
405 {
406 // LCOV_EXCL_START
407 UNREACHABLE("xrpl::Ledger::read : zero key");
408 return nullptr;
409 // LCOV_EXCL_STOP
410 }
411 auto const& item = stateMap_.peekItem(k.key);
412 if (!item)
413 return nullptr;
414 auto sle = std::make_shared<SLE>(SerialIter{item->slice()}, item->key());
415 if (!k.check(*sle))
416 return nullptr;
417 return sle;
418}
419
420//------------------------------------------------------------------------------
421
422auto
423Ledger::slesBegin() const -> std::unique_ptr<sles_type::iter_base>
424{
426}
427
428auto
429Ledger::slesEnd() const -> std::unique_ptr<sles_type::iter_base>
430{
432}
433
434auto
436{
437 return std::make_unique<sles_iter_impl>(stateMap_.upper_bound(key));
438}
439
440auto
441Ledger::txsBegin() const -> std::unique_ptr<txs_type::iter_base>
442{
444}
445
446auto
447Ledger::txsEnd() const -> std::unique_ptr<txs_type::iter_base>
448{
450}
451
452bool
453Ledger::txExists(uint256 const& key) const
454{
455 return txMap_.hasItem(key);
456}
457
458auto
459Ledger::txRead(key_type const& key) const -> tx_type
460{
461 auto const& item = txMap_.peekItem(key);
462 if (!item)
463 return {};
464 if (!open())
465 {
466 auto result = deserializeTxPlusMeta(*item);
467 return {std::move(result.first), std::move(result.second)};
468 }
469 return {deserializeTx(*item), nullptr};
470}
471
472auto
474{
476 // VFALCO Unfortunately this loads the item
477 // from the NodeStore needlessly.
478 if (!stateMap_.peekItem(key, digest))
479 return std::nullopt;
480 return digest.as_uint256();
481}
482
483//------------------------------------------------------------------------------
484
485void
487{
488 if (!stateMap_.delItem(sle->key()))
489 LogicError("Ledger::rawErase: key not found");
490}
491
492void
494{
495 if (!stateMap_.delItem(key))
496 LogicError("Ledger::rawErase: key not found");
497}
498
499void
501{
502 Serializer ss;
503 sle->add(ss);
506 LogicError("Ledger::rawInsert: key already exists");
507}
508
509void
511{
512 Serializer ss;
513 sle->add(ss);
516 LogicError("Ledger::rawReplace: key not found");
517}
518
519void
521 uint256 const& key,
523 std::shared_ptr<Serializer const> const& metaData)
524{
525 XRPL_ASSERT(metaData, "xrpl::Ledger::rawTxInsert : non-null metadata input");
526
527 // low-level - just add to table
528 Serializer s(txn->getDataLength() + metaData->getDataLength() + 16);
529 s.addVL(txn->peekData());
530 s.addVL(metaData->peekData());
532 LogicError("duplicate_tx: " + to_string(key));
533}
534
537 uint256 const& key,
539 std::shared_ptr<Serializer const> const& metaData)
540{
541 XRPL_ASSERT(metaData, "xrpl::Ledger::rawTxInsertWithHash : non-null metadata input");
542
543 // low-level - just add to table
544 Serializer s(txn->getDataLength() + metaData->getDataLength() + 16);
545 s.addVL(txn->peekData());
546 s.addVL(metaData->peekData());
547 auto item = make_shamapitem(key, s.slice());
548 auto hash = sha512Half(HashPrefix::txNode, item->slice(), item->key());
550 LogicError("duplicate_tx: " + to_string(key));
551
552 return hash;
553}
554
555bool
557{
558 bool ret = true;
559
560 try
561 {
563 }
564 catch (SHAMapMissingNode const&)
565 {
566 ret = false;
567 }
568 catch (std::exception const& ex)
569 {
570 JLOG(j_.error()) << "Exception in " << __func__ << ": " << ex.what();
571 Rethrow();
572 }
573
574 try
575 {
576 if (auto const sle = read(keylet::fees()))
577 {
578 bool oldFees = false;
579 bool newFees = false;
580 {
581 auto const baseFee = sle->at(~sfBaseFee);
582 auto const reserveBase = sle->at(~sfReserveBase);
583 auto const reserveIncrement = sle->at(~sfReserveIncrement);
584 if (baseFee)
585 fees_.base = *baseFee;
586 if (reserveBase)
587 fees_.reserve = *reserveBase;
588 if (reserveIncrement)
589 fees_.increment = *reserveIncrement;
590 oldFees = baseFee || reserveBase || reserveIncrement;
591 }
592 {
593 auto const baseFeeXRP = sle->at(~sfBaseFeeDrops);
594 auto const reserveBaseXRP = sle->at(~sfReserveBaseDrops);
595 auto const reserveIncrementXRP = sle->at(~sfReserveIncrementDrops);
596 auto assign = [&ret](XRPAmount& dest, std::optional<STAmount> const& src) {
597 if (src)
598 {
599 if (src->native())
600 dest = src->xrp();
601 else
602 ret = false;
603 }
604 };
605 assign(fees_.base, baseFeeXRP);
606 assign(fees_.reserve, reserveBaseXRP);
607 assign(fees_.increment, reserveIncrementXRP);
608 newFees = baseFeeXRP || reserveBaseXRP || reserveIncrementXRP;
609 }
610 if (oldFees && newFees)
611 // Should be all of one or the other, but not both
612 ret = false;
613 if (!rules_.enabled(featureXRPFees) && newFees)
614 // Can't populate the new fees before the amendment is enabled
615 ret = false;
616 }
617 }
618 catch (SHAMapMissingNode const&)
619 {
620 ret = false;
621 }
622 catch (std::exception const& ex)
623 {
624 JLOG(j_.error()) << "Exception in " << __func__ << ": " << ex.what();
625 Rethrow();
626 }
627
628 return ret;
629}
630
631void
633{
634 XRPL_ASSERT(
635 fees_.base == 0 && fees_.reserve == 0 && fees_.increment == 0,
636 "xrpl::Ledger::defaultFees : zero fees");
637 if (fees_.base == 0)
638 fees_.base = config.FEES.reference_fee;
639 if (fees_.reserve == 0)
641 if (fees_.increment == 0)
643}
644
646Ledger::peek(Keylet const& k) const
647{
648 auto const& value = stateMap_.peekItem(k.key);
649 if (!value)
650 return nullptr;
651 auto sle = std::make_shared<SLE>(SerialIter{value->slice()}, value->key());
652 if (!k.check(*sle))
653 return nullptr;
654 return sle;
655}
656
659{
660 hash_set<PublicKey> negUnl;
661 if (auto sle = read(keylet::negativeUNL()); sle && sle->isFieldPresent(sfDisabledValidators))
662 {
663 auto const& nUnlData = sle->getFieldArray(sfDisabledValidators);
664 for (auto const& n : nUnlData)
665 {
666 if (n.isFieldPresent(sfPublicKey))
667 {
668 auto d = n.getFieldVL(sfPublicKey);
669 auto s = makeSlice(d);
670 if (!publicKeyType(s))
671 {
672 continue;
673 }
674 negUnl.emplace(s);
675 }
676 }
677 }
678
679 return negUnl;
680}
681
684{
685 if (auto sle = read(keylet::negativeUNL()); sle && sle->isFieldPresent(sfValidatorToDisable))
686 {
687 auto d = sle->getFieldVL(sfValidatorToDisable);
688 auto s = makeSlice(d);
689 if (publicKeyType(s))
690 return PublicKey(s);
691 }
692
693 return std::nullopt;
694}
695
698{
699 if (auto sle = read(keylet::negativeUNL()); sle && sle->isFieldPresent(sfValidatorToReEnable))
700 {
701 auto d = sle->getFieldVL(sfValidatorToReEnable);
702 auto s = makeSlice(d);
703 if (publicKeyType(s))
704 return PublicKey(s);
705 }
706
707 return std::nullopt;
708}
709
710void
712{
713 auto sle = peek(keylet::negativeUNL());
714 if (!sle)
715 return;
716
717 bool const hasToDisable = sle->isFieldPresent(sfValidatorToDisable);
718 bool const hasToReEnable = sle->isFieldPresent(sfValidatorToReEnable);
719
720 if (!hasToDisable && !hasToReEnable)
721 return;
722
723 STArray newNUnl;
724 if (sle->isFieldPresent(sfDisabledValidators))
725 {
726 auto const& oldNUnl = sle->getFieldArray(sfDisabledValidators);
727 for (auto v : oldNUnl)
728 {
729 if (hasToReEnable && v.isFieldPresent(sfPublicKey) &&
730 v.getFieldVL(sfPublicKey) == sle->getFieldVL(sfValidatorToReEnable))
731 continue;
732 newNUnl.push_back(v);
733 }
734 }
735
736 if (hasToDisable)
737 {
738 newNUnl.push_back(STObject::makeInnerObject(sfDisabledValidator));
739 newNUnl.back().setFieldVL(sfPublicKey, sle->getFieldVL(sfValidatorToDisable));
740 newNUnl.back().setFieldU32(sfFirstLedgerSequence, seq());
741 }
742
743 if (!newNUnl.empty())
744 {
745 sle->setFieldArray(sfDisabledValidators, newNUnl);
746 if (hasToReEnable)
747 sle->makeFieldAbsent(sfValidatorToReEnable);
748 if (hasToDisable)
749 sle->makeFieldAbsent(sfValidatorToDisable);
750 rawReplace(sle);
751 }
752 else
753 {
754 rawErase(sle);
755 }
756}
757
758//------------------------------------------------------------------------------
759bool
760Ledger::walkLedger(beast::Journal j, bool parallel) const
761{
762 std::vector<SHAMapMissingNode> missingNodes1;
763 std::vector<SHAMapMissingNode> missingNodes2;
764
766 !stateMap_.fetchRoot(SHAMapHash{header_.accountHash}, nullptr))
767 {
769 }
770 else
771 {
772 if (parallel)
773 return stateMap_.walkMapParallel(missingNodes1, 32);
774 else
775 stateMap_.walkMap(missingNodes1, 32);
776 }
777
778 if (!missingNodes1.empty())
779 {
780 if (auto stream = j.info())
781 {
782 stream << missingNodes1.size() << " missing account node(s)";
783 stream << "First: " << missingNodes1[0].what();
784 }
785 }
786
788 !txMap_.fetchRoot(SHAMapHash{header_.txHash}, nullptr))
789 {
791 }
792 else
793 {
794 txMap_.walkMap(missingNodes2, 32);
795 }
796
797 if (!missingNodes2.empty())
798 {
799 if (auto stream = j.info())
800 {
801 stream << missingNodes2.size() << " missing transaction node(s)";
802 stream << "First: " << missingNodes2[0].what();
803 }
804 }
805 return missingNodes1.empty() && missingNodes2.empty();
806}
807
808bool
810{
814 {
815 return true;
816 }
817
818 // LCOV_EXCL_START
819 Json::Value j = getJson({*this, {}});
820
821 j[jss::accountTreeHash] = to_string(header_.accountHash);
822 j[jss::transTreeHash] = to_string(header_.txHash);
823
824 JLOG(ledgerJ.fatal()) << "ledger is not sensible" << j;
825
826 UNREACHABLE("xrpl::Ledger::assertSensible : ledger is not sensible");
827
828 return false;
829 // LCOV_EXCL_STOP
830}
831
832// update the skip list with the information from our previous ledger
833// VFALCO TODO Document this skip list concept
834void
836{
837 if (header_.seq == 0) // genesis ledger has no previous ledger
838 return;
839
840 std::uint32_t prevIndex = header_.seq - 1;
841
842 // update record of every 256th ledger
843 if ((prevIndex & 0xff) == 0)
844 {
845 auto const k = keylet::skip(prevIndex);
846 auto sle = peek(k);
848
849 bool created;
850 if (!sle)
851 {
852 sle = std::make_shared<SLE>(k);
853 created = true;
854 }
855 else
856 {
857 hashes = static_cast<decltype(hashes)>(sle->getFieldV256(sfHashes));
858 created = false;
859 }
860
861 XRPL_ASSERT(
862 hashes.size() <= 256, "xrpl::Ledger::updateSkipList : first maximum hashes size");
864 sle->setFieldV256(sfHashes, STVector256(hashes));
865 sle->setFieldU32(sfLastLedgerSequence, prevIndex);
866 if (created)
867 rawInsert(sle);
868 else
869 rawReplace(sle);
870 }
871
872 // update record of past 256 ledger
873 auto const k = keylet::skip();
874 auto sle = peek(k);
876 bool created;
877 if (!sle)
878 {
879 sle = std::make_shared<SLE>(k);
880 created = true;
881 }
882 else
883 {
884 hashes = static_cast<decltype(hashes)>(sle->getFieldV256(sfHashes));
885 created = false;
886 }
887 XRPL_ASSERT(hashes.size() <= 256, "xrpl::Ledger::updateSkipList : second maximum hashes size");
888 if (hashes.size() == 256)
889 hashes.erase(hashes.begin());
891 sle->setFieldV256(sfHashes, STVector256(hashes));
892 sle->setFieldU32(sfLastLedgerSequence, prevIndex);
893 if (created)
894 rawInsert(sle);
895 else
896 rawReplace(sle);
897}
898
899bool
901{
902 return ::xrpl::isFlagLedger(header_.seq);
903}
904bool
906{
907 return ::xrpl::isVotingLedger(header_.seq + 1);
908}
909
910static bool
912{
913 auto j = app.journal("Ledger");
914 auto seq = ledger->header().seq;
915 if (!app.pendingSaves().startWork(seq))
916 {
917 // The save was completed synchronously
918 JLOG(j.debug()) << "Save aborted";
919 return true;
920 }
921
922 auto& db = app.getRelationalDatabase();
923
924 auto const res = db.saveValidatedLedger(ledger, current);
925
926 // Clients can now trust the database for
927 // information about this ledger sequence.
928 app.pendingSaves().finishWork(seq);
929 return res;
930}
931
935bool
937 Application& app,
938 std::shared_ptr<Ledger const> const& ledger,
939 bool isSynchronous,
940 bool isCurrent)
941{
942 if (!app.getHashRouter().setFlags(ledger->header().hash, HashRouterFlags::SAVED))
943 {
944 // We have tried to save this ledger recently
945 auto stream = app.journal("Ledger").debug();
946 JLOG(stream) << "Double pend save for " << ledger->header().seq;
947
948 if (!isSynchronous || !app.pendingSaves().pending(ledger->header().seq))
949 {
950 // Either we don't need it to be finished
951 // or it is finished
952 return true;
953 }
954 }
955
956 XRPL_ASSERT(ledger->isImmutable(), "xrpl::pendSaveValidated : immutable ledger");
957
958 if (!app.pendingSaves().shouldWork(ledger->header().seq, isSynchronous))
959 {
960 auto stream = app.journal("Ledger").debug();
961 JLOG(stream) << "Pend save with seq in pending saves " << ledger->header().seq;
962
963 return true;
964 }
965
966 // See if we can use the JobQueue.
967 if (!isSynchronous &&
968 app.getJobQueue().addJob(
970 std::to_string(ledger->seq()),
971 [&app, ledger, isCurrent]() { saveValidatedLedger(app, ledger, isCurrent); }))
972 {
973 return true;
974 }
975
976 // The JobQueue won't do the Job. Do the save synchronously.
977 return saveValidatedLedger(app, ledger, isCurrent);
978}
979
980void
982{
984 txMap_.unshare();
985}
986
987void
993//------------------------------------------------------------------------------
994
995/*
996 * Make ledger using info loaded from database.
997 *
998 * @param LedgerHeader: Ledger information.
999 * @param app: Link to the Application.
1000 * @param acquire: Acquire the ledger if not found locally.
1001 * @return Shared pointer to the ledger.
1002 */
1004loadLedgerHelper(LedgerHeader const& info, Application& app, bool acquire)
1005{
1006 bool loaded;
1007 auto ledger = std::make_shared<Ledger>(
1008 info, loaded, acquire, app.config(), app.getNodeFamily(), app.journal("Ledger"));
1009
1010 if (!loaded)
1011 ledger.reset();
1012
1013 return ledger;
1014}
1015
1016static void
1018 std::shared_ptr<Ledger> const& ledger,
1019 Config const& config,
1021{
1022 if (!ledger)
1023 return;
1024
1025 XRPL_ASSERT(
1026 ledger->header().seq < XRP_LEDGER_EARLIEST_FEES || ledger->read(keylet::fees()),
1027 "xrpl::finishLoadByIndexOrHash : valid ledger fees");
1028 ledger->setImmutable();
1029
1030 JLOG(j.trace()) << "Loaded ledger: " << to_string(ledger->header().hash);
1031
1032 ledger->setFull();
1033}
1034
1037{
1039 if (!info)
1040 return {std::shared_ptr<Ledger>(), {}, {}};
1041 return {loadLedgerHelper(*info, app, true), info->seq, info->hash};
1042}
1043
1045loadByIndex(std::uint32_t ledgerIndex, Application& app, bool acquire)
1046{
1049 {
1050 std::shared_ptr<Ledger> ledger = loadLedgerHelper(*info, app, acquire);
1051 finishLoadByIndexOrHash(ledger, app.config(), app.journal("Ledger"));
1052 return ledger;
1053 }
1054 return {};
1055}
1056
1058loadByHash(uint256 const& ledgerHash, Application& app, bool acquire)
1059{
1062 {
1063 std::shared_ptr<Ledger> ledger = loadLedgerHelper(*info, app, acquire);
1064 finishLoadByIndexOrHash(ledger, app.config(), app.journal("Ledger"));
1065 XRPL_ASSERT(
1066 !ledger || ledger->header().hash == ledgerHash,
1067 "xrpl::loadByHash : ledger hash match if loaded");
1068 return ledger;
1069 }
1070 return {};
1071}
1072
1073} // namespace xrpl
T begin(T... args)
Represents a JSON value.
Definition json_value.h:130
A generic endpoint for log messages.
Definition Journal.h:40
Stream fatal() const
Definition Journal.h:325
Stream error() const
Definition Journal.h:319
Stream debug() const
Definition Journal.h:301
Stream info() const
Definition Journal.h:307
Stream trace() const
Severity stream access functions.
Definition Journal.h:295
Stream warn() const
Definition Journal.h:313
virtual Config & config()=0
static constexpr std::uint32_t FEE_UNITS_DEPRECATED
Definition Config.h:142
FeeSetup FEES
Definition Config.h:185
virtual void missingNodeAcquireByHash(uint256 const &refHash, std::uint32_t refNum)=0
Acquire ledger that has a missing node by ledger hash.
bool setFlags(uint256 const &key, HashRouterFlags flags)
Set the flags on a hash.
bool addJob(JobType type, std::string const &name, JobHandler &&jobHandler)
Adds a job to the JobQueue.
Definition JobQueue.h:146
sles_iter_impl(sles_iter_impl const &)=default
void increment() override
Definition Ledger.cpp:83
SHAMap::const_iterator iter_
Definition Ledger.cpp:55
bool equal(base_type const &impl) const override
Definition Ledger.cpp:75
std::unique_ptr< base_type > copy() const override
Definition Ledger.cpp:69
sles_iter_impl & operator=(sles_iter_impl const &)=delete
sles_type::value_type dereference() const override
Definition Ledger.cpp:89
sles_iter_impl(SHAMap::const_iterator iter)
Definition Ledger.cpp:64
bool equal(base_type const &impl) const override
Definition Ledger.cpp:123
SHAMap::const_iterator iter_
Definition Ledger.cpp:102
txs_iter_impl(txs_iter_impl const &)=default
std::unique_ptr< base_type > copy() const override
Definition Ledger.cpp:117
txs_iter_impl(bool metadata, SHAMap::const_iterator iter)
Definition Ledger.cpp:111
void increment() override
Definition Ledger.cpp:131
txs_type::value_type dereference() const override
Definition Ledger.cpp:137
txs_iter_impl & operator=(txs_iter_impl const &)=delete
Holds a ledger.
Definition Ledger.h:60
bool txExists(uint256 const &key) const override
Definition Ledger.cpp:453
std::unique_ptr< txs_type::iter_base > txsEnd() const override
Definition Ledger.cpp:447
Fees fees_
Definition Ledger.h:396
bool isFlagLedger() const
Returns true if the ledger is a flag ledger.
Definition Ledger.cpp:900
std::optional< digest_type > digest(key_type const &key) const override
Return the digest associated with the key.
Definition Ledger.cpp:473
void rawTxInsert(uint256 const &key, std::shared_ptr< Serializer const > const &txn, std::shared_ptr< Serializer const > const &metaData) override
Definition Ledger.cpp:520
std::optional< PublicKey > validatorToDisable() const
get the to be disabled validator's master public key if any
Definition Ledger.cpp:683
uint256 rawTxInsertWithHash(uint256 const &key, std::shared_ptr< Serializer const > const &txn, std::shared_ptr< Serializer const > const &metaData)
Definition Ledger.cpp:536
std::shared_ptr< SLE const > read(Keylet const &k) const override
Return the state item associated with a key.
Definition Ledger.cpp:402
void updateNegativeUNL()
update the Negative UNL ledger component.
Definition Ledger.cpp:711
bool assertSensible(beast::Journal ledgerJ) const
Definition Ledger.cpp:809
bool isVotingLedger() const
Returns true if the ledger directly precedes a flag ledger.
Definition Ledger.cpp:905
std::unique_ptr< sles_type::iter_base > slesBegin() const override
Definition Ledger.cpp:423
Rules rules_
Definition Ledger.h:397
void invariants() const
Definition Ledger.cpp:988
hash_set< PublicKey > negativeUNL() const
get Negative UNL validators' master public keys
Definition Ledger.cpp:658
void rawInsert(std::shared_ptr< SLE > const &sle) override
Unconditionally insert a state item.
Definition Ledger.cpp:500
void rawReplace(std::shared_ptr< SLE > const &sle) override
Unconditionally replace a state item.
Definition Ledger.cpp:510
void setImmutable(bool rehash=true)
Definition Ledger.cpp:308
void updateSkipList()
Definition Ledger.cpp:835
void defaultFees(Config const &config)
Definition Ledger.cpp:632
bool open() const override
Returns true if this reflects an open ledger.
Definition Ledger.h:126
void rawErase(std::shared_ptr< SLE > const &sle) override
Delete an existing state item.
Definition Ledger.cpp:486
LedgerHeader const & header() const override
Returns information about the ledger.
Definition Ledger.h:132
void setAccepted(NetClock::time_point closeTime, NetClock::duration closeResolution, bool correctCloseTime)
Definition Ledger.cpp:328
bool mImmutable
Definition Ledger.h:385
Ledger(Ledger const &)=delete
std::shared_ptr< SLE > peek(Keylet const &k) const
Definition Ledger.cpp:646
LedgerHeader header_
Definition Ledger.h:398
bool addSLE(SLE const &sle)
Definition Ledger.cpp:343
std::unique_ptr< txs_type::iter_base > txsBegin() const override
Definition Ledger.cpp:441
std::unique_ptr< sles_type::iter_base > slesEnd() const override
Definition Ledger.cpp:429
SHAMap stateMap_
Definition Ledger.h:391
std::optional< uint256 > succ(uint256 const &key, std::optional< uint256 > const &last=std::nullopt) const override
Definition Ledger.cpp:391
SHAMap txMap_
Definition Ledger.h:388
beast::Journal j_
Definition Ledger.h:399
bool walkLedger(beast::Journal j, bool parallel=false) const
Definition Ledger.cpp:760
void unshare() const
Definition Ledger.cpp:981
std::unique_ptr< sles_type::iter_base > slesUpperBound(uint256 const &key) const override
Definition Ledger.cpp:435
std::optional< PublicKey > validatorToReEnable() const
get the to be re-enabled validator's master public key if any
Definition Ledger.cpp:697
tx_type txRead(key_type const &key) const override
Read a transaction from the tx map.
Definition Ledger.cpp:459
bool setup()
Definition Ledger.cpp:556
bool exists(Keylet const &k) const override
Determine if a state item exists.
Definition Ledger.cpp:378
void finishWork(LedgerIndex seq)
Finish working on a ledger.
bool shouldWork(LedgerIndex seq, bool isSynchronous)
Check if a ledger should be dispatched.
bool startWork(LedgerIndex seq)
Start working on a ledger.
bool pending(LedgerIndex seq)
Return true if a ledger is in the progress of being saved.
A public key.
Definition PublicKey.h:42
LedgerIndex seq() const
Returns the sequence number of the base ledger.
Definition ReadView.h:97
virtual bool saveValidatedLedger(std::shared_ptr< Ledger const > const &ledger, bool current)=0
saveValidatedLedger Saves a ledger into the database.
virtual std::optional< LedgerHeader > getNewestLedgerInfo()=0
getNewestLedgerInfo Returns the info of the newest saved ledger.
virtual std::optional< LedgerHeader > getLedgerInfoByHash(uint256 const &ledgerHash)=0
getLedgerInfoByHash Returns the info of the ledger with given hash.
virtual std::optional< LedgerHeader > getLedgerInfoByIndex(LedgerIndex ledgerSeq)=0
getLedgerInfoByIndex Returns a ledger by its sequence.
bool enabled(uint256 const &feature) const
Returns true if a feature is enabled.
Definition Rules.cpp:120
uint256 const & as_uint256() const
Definition SHAMapHash.h:24
bool isZero() const
Definition SHAMapHash.h:34
Slice slice() const
Definition SHAMapItem.h:84
bool addItem(SHAMapNodeType type, boost::intrusive_ptr< SHAMapItem const > item)
Definition SHAMap.cpp:792
const_iterator upper_bound(uint256 const &id) const
Find the first item after the given item.
Definition SHAMap.cpp:572
const_iterator end() const
Definition SHAMap.h:698
const_iterator begin() const
Definition SHAMap.h:692
boost::intrusive_ptr< SHAMapItem const > const & peekItem(uint256 const &id) const
Definition SHAMap.cpp:549
int flushDirty(NodeObjectType t)
Flush modified nodes to the nodestore and convert them to shared.
Definition SHAMap.cpp:937
bool walkMapParallel(std::vector< SHAMapMissingNode > &missingNodes, int maxMissing) const
void walkMap(std::vector< SHAMapMissingNode > &missingNodes, int maxMissing) const
bool hasItem(uint256 const &id) const
Does the tree have an item with the given ID?
Definition SHAMap.cpp:640
int unshare()
Convert any modified nodes to shared.
Definition SHAMap.cpp:930
bool updateGiveItem(SHAMapNodeType type, boost::intrusive_ptr< SHAMapItem const > item)
Definition SHAMap.cpp:810
void setImmutable()
Definition SHAMap.h:544
void invariants() const
Definition SHAMap.cpp:1133
bool addGiveItem(SHAMapNodeType type, boost::intrusive_ptr< SHAMapItem const > item)
Definition SHAMap.cpp:723
bool fetchRoot(SHAMapHash const &hash, SHAMapSyncFilter *filter)
Definition SHAMap.cpp:850
SHAMapHash getHash() const
Definition SHAMap.cpp:798
bool delItem(uint256 const &id)
Definition SHAMap.cpp:646
void push_back(STObject const &object)
Definition STArray.h:189
bool empty() const
Definition STArray.h:231
STObject & back()
Definition STArray.h:170
uint256 const & key() const
Returns the 'key' (or 'index') of this item.
void setFieldVL(SField const &field, Blob const &)
Definition STObject.cpp:768
void setFieldU32(SField const &field, std::uint32_t)
Definition STObject.cpp:726
Serializer getSerializer() const
Definition STObject.h:977
static STObject makeInnerObject(SField const &name)
Definition STObject.cpp:74
Slice getSlice(std::size_t bytes)
int addVL(Blob const &vector)
Slice slice() const noexcept
Definition Serializer.h:44
virtual JobQueue & getJobQueue()=0
virtual RelationalDatabase & getRelationalDatabase()=0
virtual PendingSaves & pendingSaves()=0
virtual HashRouter & getHashRouter()=0
virtual Family & getNodeFamily()=0
virtual beast::Journal journal(std::string const &name)=0
constexpr value_type drops() const
Returns the number of drops.
Definition XRPAmount.h:157
std::optional< Dest > dropsAs() const
Definition XRPAmount.h:167
bool isZero() const
Definition base_uint.h:511
bool isNonZero() const
Definition base_uint.h:516
T emplace_back(T... args)
T emplace(T... args)
T empty(T... args)
T erase(T... args)
T find(T... args)
T is_same_v
STL namespace.
Keylet const & skip() noexcept
The index of the "short" skip list.
Definition Indexes.cpp:177
Keylet const & negativeUNL() noexcept
The (fixed) index of the object containing the ledger negativeUNL.
Definition Indexes.cpp:207
Keylet const & amendments() noexcept
The index of the amendment table.
Definition Indexes.cpp:193
Keylet account(AccountID const &id) noexcept
AccountID root.
Definition Indexes.cpp:165
Keylet const & fees() noexcept
The (fixed) index of the object containing the ledger fees.
Definition Indexes.cpp:200
Use hash_* containers for keys that do not need a cryptographically secure hashing algorithm.
Definition algorithm.h:5
static constexpr std::uint32_t XRP_LEDGER_EARLIEST_FEES
The XRP Ledger mainnet's earliest ledger with a FeeSettings object.
std::shared_ptr< Ledger > loadByHash(uint256 const &ledgerHash, Application &app, bool acquire)
Definition Ledger.cpp:1058
std::shared_ptr< Ledger > loadLedgerHelper(LedgerHeader const &info, Application &app, bool acquire)
Definition Ledger.cpp:1004
bool isCurrent(ValidationParms const &p, NetClock::time_point now, NetClock::time_point signTime, NetClock::time_point seenTime)
Whether a validation is still current.
void LogicError(std::string const &how) noexcept
Called when faulty logic causes a broken invariant.
static void finishLoadByIndexOrHash(std::shared_ptr< Ledger > const &ledger, Config const &config, beast::Journal j)
Definition Ledger.cpp:1017
static Hasher::result_type digest(void const *data, std::size_t size) noexcept
Definition tokens.cpp:138
boost::intrusive_ptr< SHAMapItem > make_shamapitem(uint256 const &tag, Slice data)
Definition SHAMapItem.h:139
Json::Value getJson(LedgerFill const &fill)
Return a new Json::Value representing the ledger with given options.
sha512_half_hasher::result_type sha512Half(Args const &... args)
Returns the SHA512-Half of a series of objects.
Definition digest.h:204
std::string to_string(base_uint< Bits, Tag > const &a)
Definition base_uint.h:600
Rules makeRulesGivenLedger(DigestAwareReadView const &ledger, Rules const &current)
Definition ReadView.cpp:50
std::pair< std::shared_ptr< STTx const >, std::shared_ptr< STObject const > > deserializeTxPlusMeta(SHAMapItem const &item)
Deserialize a SHAMapItem containing STTx + STObject metadata.
Definition Ledger.cpp:360
std::tuple< std::shared_ptr< Ledger >, std::uint32_t, uint256 > getLatestLedger(Application &app)
Definition Ledger.cpp:1036
std::shared_ptr< STTx const > deserializeTx(SHAMapItem const &item)
Deserialize a SHAMapItem containing a single STTx.
Definition Ledger.cpp:353
create_genesis_t const create_genesis
Definition Ledger.cpp:31
static bool saveValidatedLedger(Application &app, std::shared_ptr< Ledger const > const &ledger, bool current)
Definition Ledger.cpp:911
auto constexpr ledgerDefaultTimeResolution
Initial resolution of ledger close time.
@ hotACCOUNT_NODE
Definition NodeObject.h:15
Seed generateSeed(std::string const &passPhrase)
Generate a seed deterministically.
Definition Seed.cpp:57
std::chrono::duration< Rep, Period > getNextLedgerTimeResolution(std::chrono::duration< Rep, Period > previousResolution, bool previousAgree, Seq ledgerSeq)
Calculates the close time resolution for the specified ledger.
std::pair< PublicKey, SecretKey > generateKeyPair(KeyType type, Seed const &seed)
Generate a key pair deterministically.
bool pendSaveValidated(Application &app, std::shared_ptr< Ledger const > const &ledger, bool isSynchronous, bool isCurrent)
Save, or arrange to save, a fully-validated ledger Returns false on error.
Definition Ledger.cpp:936
bool getCloseAgree(LedgerHeader const &info)
uint256 calculateLedgerHash(LedgerHeader const &info)
Definition Ledger.cpp:34
@ current
This was a new validation and was added.
std::optional< KeyType > publicKeyType(Slice const &slice)
Returns the type of public key.
base_uint< 256 > uint256
Definition base_uint.h:529
std::shared_ptr< Ledger > loadByIndex(std::uint32_t ledgerIndex, Application &app, bool acquire)
Definition Ledger.cpp:1045
std::chrono::time_point< Clock, Duration > roundCloseTime(std::chrono::time_point< Clock, Duration > closeTime, std::chrono::duration< Rep, Period > closeResolution)
Calculates the close time for a ledger, given a close time resolution.
@ jtPUBLEDGER
Definition Job.h:47
@ jtPUBOLDLEDGER
Definition Job.h:23
@ open
We haven't closed our ledger yet, but others might have.
static std::uint32_t const sLCF_NoConsensusTime
AccountID calcAccountID(PublicKey const &pk)
auto constexpr ledgerGenesisTimeResolution
Close time resolution in genesis ledger.
@ txNode
transaction plus metadata
@ ledgerMaster
ledger master data for signing
constexpr XRPAmount INITIAL_XRP
Configure the native currency.
void Rethrow()
Rethrow the exception currently being handled.
Definition contract.h:28
std::enable_if_t< std::is_same< T, char >::value||std::is_same< T, unsigned char >::value, Slice > makeSlice(std::array< T, N > const &a)
Definition Slice.h:215
T push_back(T... args)
T size(T... args)
XRPAmount reference_fee
The cost of a reference transaction in drops.
Definition Config.h:50
XRPAmount account_reserve
The account reserve requirement in drops.
Definition Config.h:53
XRPAmount owner_reserve
The per-owned item reserve requirement in drops.
Definition Config.h:56
XRPAmount reserve
XRPAmount increment
XRPAmount base
A pair of SHAMap key and LedgerEntryType.
Definition Keylet.h:19
uint256 key
Definition Keylet.h:20
bool check(STLedgerEntry const &) const
Returns true if the SLE matches the type.
Definition Keylet.cpp:9
Information about the notional ledger backing the view.
NetClock::time_point parentCloseTime
NetClock::duration closeTimeResolution
NetClock::time_point closeTime
T time_since_epoch(T... args)
T to_string(T... args)
T what(T... args)