xrpld
Loading...
Searching...
No Matches
libxrpl/ledger/Ledger.cpp
1#include <xrpl/ledger/Ledger.h>
2
3#include <xrpl/basics/Log.h>
4#include <xrpl/basics/Slice.h>
5#include <xrpl/basics/UnorderedContainers.h>
6#include <xrpl/basics/base_uint.h>
7#include <xrpl/basics/chrono.h>
8#include <xrpl/basics/contract.h>
9#include <xrpl/beast/utility/Journal.h>
10#include <xrpl/beast/utility/Zero.h>
11#include <xrpl/beast/utility/instrumentation.h>
12#include <xrpl/ledger/LedgerTiming.h>
13#include <xrpl/ledger/ReadView.h>
14#include <xrpl/ledger/entries/FeeSettingsEntry.h>
15#include <xrpl/ledger/entries/NegativeUNLEntry.h>
16#include <xrpl/nodestore/NodeObject.h>
17#include <xrpl/protocol/Feature.h>
18#include <xrpl/protocol/Fees.h>
19#include <xrpl/protocol/Indexes.h>
20#include <xrpl/protocol/KeyType.h>
21#include <xrpl/protocol/Keylet.h>
22#include <xrpl/protocol/LedgerHeader.h>
23#include <xrpl/protocol/Protocol.h>
24#include <xrpl/protocol/PublicKey.h>
25#include <xrpl/protocol/Rules.h>
26#include <xrpl/protocol/SField.h>
27#include <xrpl/protocol/STArray.h>
28#include <xrpl/protocol/STLedgerEntry.h>
29#include <xrpl/protocol/STObject.h>
30#include <xrpl/protocol/STTx.h>
31#include <xrpl/protocol/SecretKey.h>
32#include <xrpl/protocol/Seed.h>
33#include <xrpl/protocol/Serializer.h>
34#include <xrpl/protocol/SystemParameters.h>
35#include <xrpl/shamap/Family.h>
36#include <xrpl/shamap/SHAMap.h>
37#include <xrpl/shamap/SHAMapItem.h>
38#include <xrpl/shamap/SHAMapMissingNode.h>
39#include <xrpl/shamap/SHAMapTreeNode.h>
40
41#include <algorithm>
42#include <cstdint>
43#include <exception>
44#include <memory>
45#include <optional>
46#include <utility>
47#include <vector>
48
49namespace xrpl {
50
52
53//------------------------------------------------------------------------------
54
55class Ledger::SlesIterImpl : public SlesType::IterBase
56{
57private:
59
60public:
61 SlesIterImpl() = delete;
63 operator=(SlesIterImpl const&) = delete;
64
65 SlesIterImpl(SlesIterImpl const&) = default;
66
68 {
69 }
70
71 [[nodiscard]] std::unique_ptr<BaseType>
72 copy() const override
73 {
75 }
76
77 [[nodiscard]] bool
78 equal(BaseType const& impl) const override
79 {
80 if (auto const p = dynamic_cast<SlesIterImpl const*>(&impl))
81 return iter_ == p->iter_;
82 return false;
83 }
84
85 void
86 increment() override
87 {
88 ++iter_;
89 }
90
91 [[nodiscard]] SlesType::value_type
92 dereference() const override
93 {
94 SerialIter sit(iter_->slice());
95 return std::make_shared<SLE const>(sit, iter_->key());
96 }
97};
98
99//------------------------------------------------------------------------------
100
101class Ledger::TxsIterImpl : public TxsType::IterBase
102{
103private:
106
107public:
108 TxsIterImpl() = delete;
110 operator=(TxsIterImpl const&) = delete;
111
112 TxsIterImpl(TxsIterImpl const&) = default;
113
114 TxsIterImpl(bool metadata, SHAMap::ConstIterator iter) : metadata_(metadata), iter_(iter)
115 {
116 }
117
118 [[nodiscard]] std::unique_ptr<BaseType>
119 copy() const override
120 {
121 return std::make_unique<TxsIterImpl>(*this);
122 }
123
124 [[nodiscard]] bool
125 equal(BaseType const& impl) const override
126 {
127 if (auto const p = dynamic_cast<TxsIterImpl const*>(&impl))
128 return iter_ == p->iter_;
129 return false;
130 }
131
132 void
133 increment() override
134 {
135 ++iter_;
136 }
137
138 [[nodiscard]] TxsType::value_type
139 dereference() const override
140 {
141 auto const& item = *iter_;
142 if (metadata_)
144 return {Ledger::deserializeTx(item), nullptr};
145 }
146};
147
148//------------------------------------------------------------------------------
149
152 Rules rules,
153 Fees const& fees,
154 std::vector<UInt256> const& amendments,
155 Family& family)
156 : immutable_(false)
157 , txMap_(SHAMapType::TRANSACTION, family)
158 , stateMap_(SHAMapType::STATE, family)
159 , fees_(fees)
160 , rules_(std::move(rules))
161 , j_(beast::Journal(beast::Journal::getNullSink()))
162{
163 header_.seq = 1;
164 header_.drops = kInitialXrp;
165 header_.closeTimeResolution = kLedgerGenesisTimeResolution;
166
167 static auto const kID =
169 {
170 auto const sle = std::make_shared<SLE>(keylet::account(kID));
171 sle->setFieldU32(sfSequence, 1);
172 sle->setAccountID(sfAccount, kID);
173 sle->setFieldAmount(sfBalance, header_.drops);
174 rawInsert(sle);
175 }
176
177 if (!amendments.empty())
178 {
179 auto const sle = std::make_shared<SLE>(keylet::amendments());
180 sle->setFieldV256(sfAmendments, STVector256{amendments});
181 rawInsert(sle);
182 }
183
184 {
185 auto const sle = std::make_shared<SLE>(keylet::feeSettings());
186 sle->at(sfBaseFeeDrops) = fees.base;
187 sle->at(sfReserveBaseDrops) = fees.reserve;
188 sle->at(sfReserveIncrementDrops) = fees.increment;
189 if (std::ranges::find(amendments, featureSmartEscrow) != amendments.end())
190 {
191 sle->at(sfGasLimit) = fees.gasLimit;
192 sle->at(sfBytecodeSizeLimit) = fees.bytecodeSizeLimit;
193 sle->at(sfGasPrice) = fees.gasPrice;
194 }
195 rawInsert(sle);
196 }
197
199 // Built locally. See Ledger::setImmutable().
200 if (!setImmutable())
201 {
202 // LCOV_EXCL_START
203 logicError("Ledger::Ledger(CreateGenesisT, ...): genesis ledger map is invalid");
204 // LCOV_EXCL_STOP
205 }
206}
207
209 LedgerHeader const& info,
210 bool& loaded,
211 bool acquire,
212 Rules rules,
213 Fees const& fees,
214 Family& family,
216 : immutable_(false)
217 , txMap_(SHAMapType::TRANSACTION, info.txHash, family)
218 , stateMap_(SHAMapType::STATE, info.accountHash, family)
219 , fees_(fees)
220 , rules_(std::move(rules))
221 , header_(info)
222 , j_(j)
223{
224 loaded = true;
225
226 if (header_.txHash.isNonZero() && !txMap_.fetchRoot(SHAMapHash{header_.txHash}, nullptr))
227 {
228 loaded = false;
229 JLOG(j.warn()) << "Don't have transaction root for ledger" << header_.seq;
230 }
231
232 if (header_.accountHash.isNonZero() &&
233 !stateMap_.fetchRoot(SHAMapHash{header_.accountHash}, nullptr))
234 {
235 loaded = false;
236 JLOG(j.warn()) << "Don't have state data root for ledger" << header_.seq;
237 }
238
239 // Loaded locally. See Ledger::setImmutable().
240 if (setMapsImmutable())
241 {
242 immutable_ = true;
243 }
244 else
245 {
246 // LCOV_EXCL_START
247 JLOG(j.error()) << "Invalid map for ledger " << header_.seq;
248 UNREACHABLE("xrpl::Ledger::Ledger(LedgerHeader const&, ...) : map is invalid");
249 // Treat it as a damaged ledger: the code below recomputes the hash and re-acquires.
250 loaded = false;
251 // LCOV_EXCL_STOP
252 }
253
254 if (!setup())
255 loaded = false;
256
257 if (!loaded)
258 {
260 if (acquire)
261 family.missingNodeAcquireByHash(header_.hash, header_.seq);
262 }
263}
264
265// Create a new ledger that follows this one
266Ledger::Ledger(Ledger const& prevLedger, NetClock::time_point closeTime)
267 : immutable_(false)
268 , txMap_(SHAMapType::TRANSACTION, prevLedger.txMap_.family())
269 , stateMap_(prevLedger.stateMap_, true)
270 , fees_(prevLedger.fees_)
271 , rules_(prevLedger.rules_)
272 , j_(beast::Journal(beast::Journal::getNullSink()))
273{
274 header_.seq = prevLedger.header_.seq + 1;
275 header_.parentCloseTime = prevLedger.header_.closeTime;
276 header_.hash = prevLedger.header().hash + UInt256(1);
277 header_.drops = prevLedger.header().drops;
278 header_.closeTimeResolution = prevLedger.header_.closeTimeResolution;
279 header_.parentHash = prevLedger.header().hash;
280 header_.closeTimeResolution = getNextLedgerTimeResolution(
281 prevLedger.header_.closeTimeResolution, getCloseAgree(prevLedger.header()), header_.seq);
282
283 if (prevLedger.header_.closeTime == NetClock::time_point{})
284 {
285 header_.closeTime = roundCloseTime(closeTime, header_.closeTimeResolution);
286 }
287 else
288 {
289 header_.closeTime = prevLedger.header_.closeTime + header_.closeTimeResolution;
290 }
291}
292
294 : immutable_(true)
295 , txMap_(SHAMapType::TRANSACTION, info.txHash, family)
296 , stateMap_(SHAMapType::STATE, info.accountHash, family)
297 , rules_(std::move(rules))
298 , header_(info)
299 , j_(beast::Journal(beast::Journal::getNullSink()))
300{
302}
303
305 std::uint32_t ledgerSeq,
306 NetClock::time_point closeTime,
307 Rules rules,
308 Fees const& fees,
309 Family& family)
310 : immutable_(false)
311 , txMap_(SHAMapType::TRANSACTION, family)
312 , stateMap_(SHAMapType::STATE, family)
313 , fees_(fees)
314 , rules_(std::move(rules))
315 , j_(beast::Journal(beast::Journal::getNullSink()))
316{
317 header_.seq = ledgerSeq;
318 header_.closeTime = closeTime;
319 header_.closeTimeResolution = kLedgerDefaultTimeResolution;
320 setup();
321}
322
323bool
325{
326 // A map found structurally invalid during sync must never be made immutable: isValid() tests
327 // only for Invalid, and an immutable ledger is treated as persistable. Asked before anything is
328 // written, so a refusal leaves the header exactly as it was rather than half relabeled.
329 if (!mapsValid())
330 return false;
331
332 // Read here but written to the header below, once the maps are settled: getHash() can unshare a
333 // dirty tree, so it has to run while the map is still mutable, while a write to the header must
334 // wait until both maps have made it. Skipped once the ledger is immutable, since its maps can
335 // no longer change.
336 bool const deriveMapHashes = !immutable_ && rehash;
337 UInt256 const txHash = deriveMapHashes ? txMap_.getHash().asUInt256() : UInt256{};
338 UInt256 const accountHash = deriveMapHashes ? stateMap_.getHash().asUInt256() : UInt256{};
339
340 // Both were valid at the check above, but a concurrent walk can invalidate one in between (see
341 // SHAMap::state_), so the result is checked. setInvalid() outranks Immutable and can land
342 // after both maps have been settled, so this narrows the window it guards.
343 bool const bothImmutable = setMapsImmutable();
344 SOMETIMES(!bothImmutable, "xrpl::Ledger::setImmutable : map invalidated while going immutable");
345 if (!bothImmutable)
346 return false;
347
348 // Written only now, so losing the race above leaves the header describing what the ledger was
349 // built from rather than a map that has since been abandoned. Forced rather than conditional,
350 // since this is the only place the hash transitions to valid.
351 if (deriveMapHashes)
352 {
353 header_.txHash = txHash;
354 header_.accountHash = accountHash;
355 }
356
357 if (rehash)
359
360 // Set last, so isImmutable() reports only a ledger whose maps are both immutable.
361 immutable_ = true;
362 setup();
363 return true;
364}
365
366bool
368 NetClock::time_point closeTime,
369 NetClock::duration closeResolution,
370 bool correctCloseTime)
371{
372 // Used when we witnessed the consensus.
373 XRPL_ASSERT(!open(), "xrpl::Ledger::setAccepted : valid ledger state");
374
375 header_.closeTime = closeTime;
376 header_.closeTimeResolution = closeResolution;
377 header_.closeFlags = correctCloseTime ? 0 : kSLcfNoConsensusTime;
378 // Built locally. See Ledger::setImmutable().
379 if (!setImmutable())
380 {
381 // LCOV_EXCL_START
382 JLOG(j_.error()) << "Invalid map for accepted ledger " << header_.seq;
383 UNREACHABLE("xrpl::Ledger::setAccepted : map is invalid");
384 return false;
385 // LCOV_EXCL_STOP
386 }
387
388 return true;
389}
390
391bool
393{
394 auto const s = sle.getSerializer();
395 return stateMap_.addItem(SHAMapNodeType::TnAccountState, makeShamapitem(sle.key(), s.slice()));
396}
397
398//------------------------------------------------------------------------------
399
402{
403 SerialIter sit(item.slice());
405}
406
409{
411 SerialIter sit(item.slice());
412 {
413 SerialIter s(sit.getSlice(sit.getVLDataLength()));
415 }
416 {
417 SerialIter s(sit.getSlice(sit.getVLDataLength()));
418 result.second = std::make_shared<STObject const>(s, sfMetadata);
419 }
420 return result;
421}
422
423//------------------------------------------------------------------------------
424
425bool
426Ledger::exists(Keylet const& k) const
427{
428 // VFALCO NOTE Perhaps check the type for debug builds?
429 return stateMap_.hasItem(k.key);
430}
431
432bool
433Ledger::exists(UInt256 const& key) const
434{
435 return stateMap_.hasItem(key);
436}
437
439Ledger::succ(UInt256 const& key, std::optional<UInt256> const& last) const
440{
441 auto const item = stateMap_.upperBound(key);
442 if (item == stateMap_.end())
443 return std::nullopt;
444 if (last && item->key() >= last)
445 return std::nullopt;
446 return item->key();
447}
448
450Ledger::read(Keylet const& k) const
451{
452 if (k.key == beast::kZero)
453 {
454 // LCOV_EXCL_START
455 UNREACHABLE("xrpl::Ledger::read : zero key");
456 return nullptr;
457 // LCOV_EXCL_STOP
458 }
459 auto const& item = stateMap_.peekItem(k.key);
460 if (!item)
461 return nullptr;
462 auto sle = std::make_shared<SLE>(SerialIter{item->slice()}, item->key());
463 if (!k.check(*sle))
464 return nullptr;
465 return sle;
466}
467
468//------------------------------------------------------------------------------
469
470auto
471Ledger::slesBegin() const -> std::unique_ptr<SlesType::IterBase>
472{
474}
475
476auto
477Ledger::slesEnd() const -> std::unique_ptr<SlesType::IterBase>
478{
480}
481
482auto
487
488auto
489Ledger::txsBegin() const -> std::unique_ptr<TxsType::IterBase>
490{
491 return std::make_unique<TxsIterImpl>(!open(), txMap_.begin());
492}
493
494auto
495Ledger::txsEnd() const -> std::unique_ptr<TxsType::IterBase>
496{
497 return std::make_unique<TxsIterImpl>(!open(), txMap_.end());
498}
499
500bool
501Ledger::txExists(UInt256 const& key) const
502{
503 return txMap_.hasItem(key);
504}
505
506auto
507Ledger::txRead(key_type const& key) const -> TxType
508{
509 auto const& item = txMap_.peekItem(key);
510 if (!item)
511 return {};
512 if (!open())
513 {
514 auto result = deserializeTxPlusMeta(*item);
515 return {std::move(result.first), std::move(result.second)};
516 }
517 return {deserializeTx(*item), nullptr};
518}
519
520auto
522{
524 // VFALCO Unfortunately this loads the item
525 // from the NodeStore needlessly.
526 if (!stateMap_.peekItem(key, digest))
527 return std::nullopt;
528 return digest.asUInt256();
529}
530
531//------------------------------------------------------------------------------
532
533void
535{
536 if (!stateMap_.delItem(sle->key()))
537 logicError("Ledger::rawErase: key not found");
538}
539
540void
542{
543 if (!stateMap_.delItem(key))
544 logicError("Ledger::rawErase: key not found");
545}
546
547void
549{
550 Serializer ss;
551 sle->add(ss);
552 if (!stateMap_.addGiveItem(
554 {
555 logicError("Ledger::rawInsert: key already exists");
556 }
557}
558
559void
561{
562 Serializer ss;
563 sle->add(ss);
564 if (!stateMap_.updateGiveItem(
566 {
567 logicError("Ledger::rawReplace: key not found");
568 }
569}
570
571void
573 UInt256 const& key,
575 std::shared_ptr<Serializer const> const& metaData)
576{
577 XRPL_ASSERT(metaData, "xrpl::Ledger::rawTxInsert : non-null metadata input");
578
579 // low-level - just add to table
580 Serializer s(txn->getDataLength() + metaData->getDataLength() + 16);
581 s.addVL(txn->peekData());
582 s.addVL(metaData->peekData());
583 if (!txMap_.addGiveItem(SHAMapNodeType::TnTransactionMd, makeShamapitem(key, s.slice())))
584 logicError("duplicate_tx: " + to_string(key));
585}
586
587bool
589{
590 bool ret = true;
591
592 try
593 {
595 }
596 catch (SHAMapMissingNode const&)
597 {
598 ret = false;
599 }
600 catch (std::exception const& ex)
601 {
602 JLOG(j_.error()) << "Exception in " << __func__ << ": " << ex.what();
603 rethrow();
604 }
605
606 try
607 {
608 if (auto const sle = FeeSettingsEntryR(*this))
609 {
610 bool oldFees = false;
611 bool newFees = false;
612 bool extensionFees = false;
613 {
614 auto const baseFee = sle->at(~sfBaseFee);
615 auto const reserveBase = sle->at(~sfReserveBase);
616 auto const reserveIncrement = sle->at(~sfReserveIncrement);
617 if (baseFee)
618 fees_.base = *baseFee;
619 if (reserveBase)
620 fees_.reserve = *reserveBase;
621 if (reserveIncrement)
622 fees_.increment = *reserveIncrement;
623 oldFees = baseFee || reserveBase || reserveIncrement;
624 }
625 {
626 auto const baseFeeXRP = sle->at(~sfBaseFeeDrops);
627 auto const reserveBaseXRP = sle->at(~sfReserveBaseDrops);
628 auto const reserveIncrementXRP = sle->at(~sfReserveIncrementDrops);
629 auto const assign = [&ret](XRPAmount& dest, std::optional<STAmount> const& src) {
630 if (src)
631 {
632 if (src->native())
633 {
634 dest = src->xrp();
635 }
636 else
637 {
638 ret = false;
639 }
640 }
641 };
642 assign(fees_.base, baseFeeXRP);
643 assign(fees_.reserve, reserveBaseXRP);
644 assign(fees_.increment, reserveIncrementXRP);
645 newFees = baseFeeXRP || reserveBaseXRP || reserveIncrementXRP;
646 }
647 {
648 auto const gasLimit = sle->at(~sfGasLimit);
649 auto const bytecodeSizeLimit = sle->at(~sfBytecodeSizeLimit);
650 auto const gasPrice = sle->at(~sfGasPrice);
651
652 // An absent field resolves to the protocol constant.
653 if (rules_.enabled(featureSmartEscrow))
654 {
655 fees_.gasLimit = gasLimit.value_or(kDefaultGasLimit);
656 fees_.bytecodeSizeLimit = bytecodeSizeLimit.value_or(kDefaultBytecodeSizeLimit);
657 fees_.gasPrice = gasPrice.value_or(kDefaultGasPrice);
658 }
659 extensionFees = gasLimit || bytecodeSizeLimit || gasPrice;
660 }
661 if (oldFees && newFees)
662 {
663 // Should be all of one or the other, but not both
664 ret = false;
665 }
666 if (!rules_.enabled(featureSmartEscrow) && extensionFees)
667 {
668 // Can't populate the extension fees before the amendment is
669 // enabled
670 ret = false;
671 }
672 }
673 }
674 catch (SHAMapMissingNode const&)
675 {
676 ret = false;
677 }
678 catch (std::exception const& ex)
679 {
680 JLOG(j_.error()) << "Exception in " << __func__ << ": " << ex.what();
681 rethrow();
682 }
683
684 return ret;
685}
686
688Ledger::peek(Keylet const& k) const
689{
690 auto const& value = stateMap_.peekItem(k.key);
691 if (!value)
692 return nullptr;
693 auto sle = std::make_shared<SLE>(SerialIter{value->slice()}, value->key());
694 if (!k.check(*sle))
695 return nullptr;
696 return sle;
697}
698
701{
702 HashSet<PublicKey> negUnl;
703 if (auto const sle = NegativeUNLEntryR(*this); sle && sle->isFieldPresent(sfDisabledValidators))
704 {
705 auto const& nUnlData = sle->getFieldArray(sfDisabledValidators);
706 for (auto const& n : nUnlData)
707 {
708 if (n.isFieldPresent(sfPublicKey))
709 {
710 auto const d = n.getFieldVL(sfPublicKey);
711 auto const s = makeSlice(d);
712 if (!publicKeyType(s))
713 {
714 continue;
715 }
716 negUnl.emplace(s);
717 }
718 }
719 }
720
721 return negUnl;
722}
723
726{
727 if (auto const sle = NegativeUNLEntryR(*this); sle && sle->isFieldPresent(sfValidatorToDisable))
728 {
729 auto const d = sle->getFieldVL(sfValidatorToDisable);
730 auto const s = makeSlice(d);
731 if (publicKeyType(s))
732 return PublicKey(s);
733 }
734
735 return std::nullopt;
736}
737
740{
741 if (auto const sle = NegativeUNLEntryR(*this);
742 sle && sle->isFieldPresent(sfValidatorToReEnable))
743 {
744 auto const d = sle->getFieldVL(sfValidatorToReEnable);
745 auto const s = makeSlice(d);
746 if (publicKeyType(s))
747 return PublicKey(s);
748 }
749
750 return std::nullopt;
751}
752
753void
755{
756 auto const sle = peek(keylet::negativeUNL());
757 if (!sle)
758 return;
759
760 bool const hasToDisable = sle->isFieldPresent(sfValidatorToDisable);
761 bool const hasToReEnable = sle->isFieldPresent(sfValidatorToReEnable);
762
763 if (!hasToDisable && !hasToReEnable)
764 return;
765
766 STArray newNUnl;
767 if (sle->isFieldPresent(sfDisabledValidators))
768 {
769 auto const& oldNUnl = sle->getFieldArray(sfDisabledValidators);
770 for (auto const& v : oldNUnl)
771 {
772 if (hasToReEnable && v.isFieldPresent(sfPublicKey) &&
773 v.getFieldVL(sfPublicKey) == sle->getFieldVL(sfValidatorToReEnable))
774 continue;
775 newNUnl.pushBack(v);
776 }
777 }
778
779 if (hasToDisable)
780 {
781 newNUnl.pushBack(STObject::makeInnerObject(sfDisabledValidator));
782 newNUnl.back().setFieldVL(sfPublicKey, sle->getFieldVL(sfValidatorToDisable));
783 newNUnl.back().setFieldU32(sfFirstLedgerSequence, seq());
784 }
785
786 if (!newNUnl.empty())
787 {
788 sle->setFieldArray(sfDisabledValidators, newNUnl);
789 if (hasToReEnable)
790 sle->makeFieldAbsent(sfValidatorToReEnable);
791 if (hasToDisable)
792 sle->makeFieldAbsent(sfValidatorToDisable);
793 rawReplace(sle);
794 }
795 else
796 {
797 rawErase(sle);
798 }
799}
800
801//------------------------------------------------------------------------------
802bool
803Ledger::walkLedger(beast::Journal j, bool parallel) const
804{
805 std::vector<SHAMapMissingNode> missingNodes1;
806 std::vector<SHAMapMissingNode> missingNodes2;
807
808 if (stateMap_.getHash().isZero() && !header_.accountHash.isZero() &&
809 !stateMap_.fetchRoot(SHAMapHash{header_.accountHash}, nullptr))
810 {
811 missingNodes1.emplace_back(SHAMapType::STATE, SHAMapHash{header_.accountHash});
812 }
813 else
814 {
815 if (parallel)
816 {
817 return stateMap_.walkMapParallel(missingNodes1, 32);
818 }
819
820 stateMap_.walkMap(missingNodes1, 32);
821 }
822
823 if (!missingNodes1.empty())
824 {
825 if (auto const stream = j.info())
826 {
827 stream << missingNodes1.size() << " missing account node(s)";
828 stream << "First: " << missingNodes1[0].what();
829 }
830 }
831
832 if (txMap_.getHash().isZero() && header_.txHash.isNonZero() &&
833 !txMap_.fetchRoot(SHAMapHash{header_.txHash}, nullptr))
834 {
836 }
837 else
838 {
839 txMap_.walkMap(missingNodes2, 32);
840 }
841
842 if (!missingNodes2.empty())
843 {
844 if (auto const stream = j.info())
845 {
846 stream << missingNodes2.size() << " missing transaction node(s)";
847 stream << "First: " << missingNodes2[0].what();
848 }
849 }
850 return missingNodes1.empty() && missingNodes2.empty();
851}
852
853bool
855{
856 if (header_.hash.isZero())
857 return false;
858 if (header_.accountHash.isZero())
859 return false;
860 if (header_.accountHash != stateMap_.getHash().asUInt256())
861 return false;
862 if (header_.txHash != txMap_.getHash().asUInt256())
863 return false;
864 return true;
865}
866
867// update the skip list with the information from our previous ledger
868// VFALCO TODO Document this skip list concept
869void
871{
872 if (header_.seq == 0) // genesis ledger has no previous ledger
873 return;
874
875 std::uint32_t const prevIndex = header_.seq - 1;
876
877 // update record of every 256th ledger
878 if ((prevIndex & 0xff) == 0)
879 {
880 auto const k = keylet::skip(prevIndex);
881 auto sle = peek(k);
883
884 bool created = false;
885 if (!sle)
886 {
887 sle = std::make_shared<SLE>(k);
888 created = true;
889 }
890 else
891 {
892 hashes = static_cast<decltype(hashes)>(sle->getFieldV256(sfHashes));
893 created = false;
894 }
895
896 XRPL_ASSERT(
897 hashes.size() <= 256, "xrpl::Ledger::updateSkipList : first maximum hashes size");
898 hashes.push_back(header_.parentHash);
899 sle->setFieldV256(sfHashes, STVector256(hashes));
900 sle->setFieldU32(sfLastLedgerSequence, prevIndex);
901 if (created)
902 {
903 rawInsert(sle);
904 }
905 else
906 {
907 rawReplace(sle);
908 }
909 }
910
911 // update record of past 256 ledger
912 auto const k = keylet::skip();
913 auto sle = peek(k);
915 bool created = false;
916 if (!sle)
917 {
918 sle = std::make_shared<SLE>(k);
919 created = true;
920 }
921 else
922 {
923 hashes = static_cast<decltype(hashes)>(sle->getFieldV256(sfHashes));
924 created = false;
925 }
926 XRPL_ASSERT(hashes.size() <= 256, "xrpl::Ledger::updateSkipList : second maximum hashes size");
927 if (hashes.size() == 256)
928 hashes.erase(hashes.begin());
929 hashes.push_back(header_.parentHash);
930 sle->setFieldV256(sfHashes, STVector256(hashes));
931 sle->setFieldU32(sfLastLedgerSequence, prevIndex);
932 if (created)
933 {
934 rawInsert(sle);
935 }
936 else
937 {
938 rawReplace(sle);
939 }
940}
941
942bool
944{
945 return ::xrpl::isFlagLedger(header_.seq);
946}
947bool
949{
950 return ::xrpl::isVotingLedger(header_.seq + 1);
951}
952
953void
955{
956 stateMap_.unshare();
957 txMap_.unshare();
958}
959
960void
962{
963 stateMap_.invariants();
964 txMap_.invariants();
965}
966
967} // namespace xrpl
T begin(T... args)
A generic endpoint for log messages.
Definition Journal.h:44
Stream error() const
Definition Journal.h:362
Stream info() const
Definition Journal.h:350
virtual void missingNodeAcquireByHash(UInt256 const &refHash, std::uint32_t refNum)=0
Acquire ledger that has a missing node by ledger hash.
SlesIterImpl(SlesIterImpl const &)=default
SlesType::value_type dereference() const override
bool equal(BaseType const &impl) const override
std::unique_ptr< BaseType > copy() const override
SlesIterImpl & operator=(SlesIterImpl const &)=delete
SlesIterImpl(SHAMap::ConstIterator iter)
TxsIterImpl(TxsIterImpl const &)=default
std::unique_ptr< BaseType > copy() const override
bool equal(BaseType const &impl) const override
TxsIterImpl & operator=(TxsIterImpl const &)=delete
TxsType::value_type dereference() const override
TxsIterImpl(bool metadata, SHAMap::ConstIterator iter)
std::unique_ptr< TxsType::IterBase > txsEnd() const override
HashSet< PublicKey > negativeUNL() const
get Negative UNL validators' master public keys
bool txExists(UInt256 const &key) const override
bool isFlagLedger() const
Returns true if the ledger is a flag ledger.
std::optional< DigestType > digest(key_type const &key) const override
Return the digest associated with the key.
std::optional< PublicKey > validatorToDisable() const
get the to be disabled validator's master public key if any
void rawInsert(SLE::Ref sle) override
Unconditionally insert a state item.
void updateNegativeUNL()
update the Negative UNL ledger component.
bool isVotingLedger() const
Returns true if the ledger directly precedes a flag ledger.
std::unique_ptr< SlesType::IterBase > slesBegin() const override
void rawReplace(SLE::Ref sle) override
Unconditionally replace a state item.
bool setImmutable(bool rehash=true)
Mark this ledger as immutable, so it can no longer be modified.
std::unique_ptr< SlesType::IterBase > slesUpperBound(UInt256 const &key) const override
bool open() const override
Returns true if this reflects an open ledger.
static std::pair< std::shared_ptr< STTx const >, std::shared_ptr< STObject const > > deserializeTxPlusMeta(SHAMapItem const &item)
Deserialize a SHAMapItem containing STTx + STObject metadata.
LedgerHeader const & header() const override
Returns information about the ledger.
Ledger(Ledger const &)=delete
static std::shared_ptr< STTx const > deserializeTx(SHAMapItem const &item)
Deserialize a SHAMapItem containing a single STTx.
bool addSLE(SLE const &sle)
bool setAccepted(NetClock::time_point closeTime, NetClock::duration closeResolution, bool correctCloseTime)
Mark this ledger as accepted and attempt to make it immutable.
std::unique_ptr< TxsType::IterBase > txsBegin() const override
std::optional< UInt256 > succ(UInt256 const &key, std::optional< UInt256 > const &last=std::nullopt) const override
std::unique_ptr< SlesType::IterBase > slesEnd() const override
void rawTxInsert(UInt256 const &key, std::shared_ptr< Serializer const > const &txn, std::shared_ptr< Serializer const > const &metaData) override
bool setMapsImmutable()
Make both maps immutable.
Rules const & rules() const override
Returns the tx processing rules.
Fees const & fees() const override
Returns the fees for the base ledger.
bool walkLedger(beast::Journal j, bool parallel=false) const
std::optional< PublicKey > validatorToReEnable() const
get the to be re-enabled validator's master public key if any
TxType txRead(key_type const &key) const override
Read a transaction from the tx map.
SLE::const_pointer read(Keylet const &k) const override
Return the state item associated with a key.
SLE::pointer peek(Keylet const &k) const
bool exists(Keylet const &k) const override
Determine if a state item exists.
void rawErase(SLE::Ref sle) override
Delete an existing state item.
std::chrono::time_point< NetClock > time_point
Definition chrono.h:48
std::chrono::duration< rep, period > duration
Definition chrono.h:47
A public key.
Definition PublicKey.h:53
UInt256 key_type
Definition ReadView.h:45
LedgerIndex seq() const
Returns the sequence number of the base ledger.
Definition ReadView.h:115
Rules controlling protocol behavior.
Definition Rules.h:40
Slice slice() const
Definition SHAMapItem.h:92
bool empty() const
Definition STArray.h:254
void pushBack(STObject const &object)
Definition STArray.h:212
STObject & back()
Definition STArray.h:193
UInt256 const & key() const
Returns the 'key' (or 'index') of this item.
std::shared_ptr< STLedgerEntry > pointer
std::shared_ptr< STLedgerEntry > const & Ref
std::shared_ptr< STLedgerEntry const > const_pointer
void setFieldVL(SField const &field, Blob const &)
Definition STObject.cpp:791
void setFieldU32(SField const &field, std::uint32_t)
Definition STObject.cpp:743
Serializer getSerializer() const
Definition STObject.h:1002
bool isFieldPresent(SField const &field) const
Definition STObject.cpp:464
static STObject makeInnerObject(SField const &name)
Definition STObject.cpp:79
int getVLDataLength()
Reads the length header at the read position and steps past it.
Slice getSlice(std::size_t bytes)
int addVL(Blob const &vector)
Slice slice() const noexcept
Definition Serializer.h:141
T emplace_back(T... args)
T emplace(T... args)
T empty(T... args)
T erase(T... args)
T find(T... args)
T make_shared(T... args)
T make_unique(T... args)
constexpr Zero kZero
Definition Zero.h:30
STL namespace.
Keylet const & skip() noexcept
The index of the "short" skip list.
Definition Indexes.cpp:245
Keylet const & negativeUNL() noexcept
The (fixed) index of the object containing the ledger negativeUNL.
Definition Indexes.cpp:274
Keylet const & feeSettings() noexcept
The (fixed) index of the object containing the ledger fees.
Definition Indexes.cpp:267
Keylet const & amendments() noexcept
The index of the amendment table.
Definition Indexes.cpp:260
Keylet account(AccountID const &id) noexcept
AccountID root.
Definition Indexes.cpp:233
Use hash_* containers for keys that do not need a cryptographically secure hashing algorithm.
Definition algorithm.h:5
constexpr std::uint32_t kDefaultGasLimit
TxType
Transaction type identifiers.
Definition TxFormats.h:45
CreateGenesisT const kCreateGenesis
Rules makeRulesGivenLedger(DigestAwareReadView const &ledger, Rules const &current)
Definition ReadView.cpp:62
Seed generateSeed(std::string const &passPhrase)
Generate a seed deterministically.
Definition Seed.cpp:58
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 getCloseAgree(LedgerHeader const &info)
std::string to_string(BaseUInt< Bits, Tag > const &a)
Definition base_uint.h:658
void logicError(std::string const &how) noexcept
Called when faulty logic causes a broken invariant.
std::optional< KeyType > publicKeyType(Slice const &slice)
Returns the type of public key.
STLedgerEntry SLE
Slice makeSlice(std::array< T, N > const &a)
Definition Slice.h:228
XRPL_NO_SANITIZE_ADDRESS void rethrow()
Rethrow the exception currently being handled.
Definition contract.h:36
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.
void open(soci::session &s, BasicConfig const &config, std::string const &dbName)
Open a soci session.
Definition SociDB.cpp:91
BaseUInt< 256 > UInt256
Definition base_uint.h:581
boost::intrusive_ptr< SHAMapItem > makeShamapitem(UInt256 const &tag, Slice data)
Definition SHAMapItem.h:148
constexpr std::uint32_t kDefaultGasPrice
std::unordered_set< Value, Hash, Pred, Allocator > HashSet
AccountID calcAccountID(PublicKey const &pk)
constexpr std::uint32_t kDefaultBytecodeSizeLimit
constexpr auto kLedgerGenesisTimeResolution
Close time resolution in genesis ledger.
constexpr auto kLedgerDefaultTimeResolution
Initial resolution of ledger close time.
UInt256 calculateLedgerHash(LedgerHeader const &info)
Calculate the hash of a ledger header.
static std::uint32_t const kSLcfNoConsensusTime
FeeSettingsEntry< ReadView > FeeSettingsEntryR
constexpr XRPAmount kInitialXrp
Configure the native currency.
NegativeUNLEntry< ReadView > NegativeUNLEntryR
T push_back(T... args)
T size(T... args)
Reflects the fee settings for a particular ledger.
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:10
Information about the notional ledger backing the view.
NetClock::duration closeTimeResolution
NetClock::time_point closeTime
T what(T... args)