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