20 #include <ripple/app/consensus/RCLConsensus.h>
21 #include <ripple/app/consensus/RCLValidations.h>
22 #include <ripple/app/ledger/BuildLedger.h>
23 #include <ripple/app/ledger/InboundLedgers.h>
24 #include <ripple/app/ledger/InboundTransactions.h>
25 #include <ripple/app/ledger/Ledger.h>
26 #include <ripple/app/ledger/LedgerMaster.h>
27 #include <ripple/app/ledger/LocalTxs.h>
28 #include <ripple/app/ledger/OpenLedger.h>
29 #include <ripple/app/misc/AmendmentTable.h>
30 #include <ripple/app/misc/HashRouter.h>
31 #include <ripple/app/misc/LoadFeeTrack.h>
32 #include <ripple/app/misc/NegativeUNLVote.h>
33 #include <ripple/app/misc/NetworkOPs.h>
34 #include <ripple/app/misc/TxQ.h>
35 #include <ripple/app/misc/ValidatorKeys.h>
36 #include <ripple/app/misc/ValidatorList.h>
37 #include <ripple/basics/random.h>
38 #include <ripple/beast/core/LexicalCast.h>
39 #include <ripple/consensus/LedgerTiming.h>
40 #include <ripple/nodestore/DatabaseShard.h>
41 #include <ripple/overlay/Overlay.h>
42 #include <ripple/overlay/predicates.h>
43 #include <ripple/protocol/BuildInfo.h>
44 #include <ripple/protocol/Feature.h>
45 #include <ripple/protocol/digest.h>
69 , consensus_(clock, adaptor_, journal)
84 , feeVote_(
std::move(feeVote))
87 , inboundTransactions_{inboundTransactions}
89 , nodeID_{validatorKeys.nodeID}
90 , valPublic_{validatorKeys.publicKey}
91 , valSecret_{validatorKeys.secretKey}
92 , valCookie_{rand_int<std::uint64_t>(
95 , nUnlVote_(nodeID_,
j_)
97 assert(valCookie_ != 0);
99 JLOG(
j_.
info()) <<
"Consensus engine started"
101 <<
", Cookie: " << valCookie_ <<
")";
104 boost::optional<RCLCxLedger>
108 auto built = ledgerMaster_.getLedgerByHash(hash);
111 if (acquiringLedger_ != hash)
114 JLOG(
j_.
warn()) <<
"Need consensus ledger " << hash;
117 acquiringLedger_ = hash;
119 app_.getJobQueue().addJob(
121 "getConsensusLedger",
122 [
id = hash, &app = app_](
Job&) {
123 app.getInboundLedgers().acquire(
130 assert(!built->open() && built->isImmutable());
131 assert(built->info().hash == hash);
134 inboundTransactions_.newRound(built->info().seq);
142 protocol::TMProposeSet prop;
146 prop.set_proposeseq(
proposal.proposeSeq());
147 prop.set_closetime(
proposal.closeTime().time_since_epoch().count());
149 prop.set_currenttxhash(
151 prop.set_previousledger(
155 prop.set_nodepubkey(pk.data(), pk.size());
158 prop.set_signature(sig.data(), sig.size());
167 if (app_.getHashRouter().shouldRelay(tx.
id()))
169 JLOG(
j_.
debug()) <<
"Relaying disputed tx " << tx.
id();
171 protocol::TMTransaction msg;
172 msg.set_rawtransaction(slice.data(), slice.size());
173 msg.set_status(protocol::tsNEW);
174 msg.set_receivetimestamp(
175 app_.timeKeeper().now().time_since_epoch().count());
177 std::make_shared<Message>(msg, protocol::mtTRANSACTION)));
181 JLOG(
j_.
debug()) <<
"Not relaying disputed tx " << tx.
id();
187 JLOG(
j_.
trace()) <<
"We propose: "
192 protocol::TMProposeSet prop;
194 prop.set_currenttxhash(
196 prop.set_previousledger(
198 prop.set_proposeseq(
proposal.proposeSeq());
199 prop.set_closetime(
proposal.closeTime().time_since_epoch().count());
201 prop.set_nodepubkey(valPublic_.data(), valPublic_.size());
206 proposal.closeTime().time_since_epoch().count(),
210 auto sig =
signDigest(valPublic_, valSecret_, signingHash);
212 prop.set_signature(sig.data(), sig.size());
222 app_.getHashRouter().addSuppression(suppression);
224 app_.overlay().broadcast(prop);
230 inboundTransactions_.giveSet(txns.
id(), txns.
map_,
false);
233 boost::optional<RCLTxSet>
236 if (
auto txns = inboundTransactions_.getSet(setId,
true))
246 return !app_.openLedger().empty();
252 return app_.getValidations().numTrustedForLedger(h);
274 ledgerMaster_.getValidLedgerIndex());
276 if (netLgr != ledgerID)
279 app_.getOPs().consensusViewChange();
296 notify(protocol::neCLOSING_LEDGER, ledger, !wrongLCL);
298 auto const& prevLedger = ledger.ledger_;
300 ledgerMaster_.applyHeldTransactions();
302 ledgerMaster_.setBuildingLedger(prevLedger->info().seq + 1);
304 auto initialLedger = app_.openLedger().current();
308 initialSet->setUnbacked();
311 for (
auto const& tx : initialLedger->txs)
313 JLOG(
j_.
trace()) <<
"Adding open ledger TX "
314 << tx.first->getTransactionID();
319 SHAMapItem(tx.first->getTransactionID(), std::move(s)));
323 if (app_.config().standalone() || (
proposing && !wrongLCL))
325 if (prevLedger->isFlagLedger())
329 auto validations = app_.validators().negativeUNLFilter(
330 app_.getValidations().getTrustedForLedger(
331 prevLedger->info().parentHash));
332 if (validations.size() >= app_.validators().quorum())
334 feeVote_->doVoting(prevLedger, validations, initialSet);
335 app_.getAmendmentTable().doVoting(
336 prevLedger, validations, initialSet);
340 prevLedger->isVotingLedger() &&
348 app_.validators().getTrustedMasterKeys(),
349 app_.getValidations(),
355 initialSet = initialSet->snapShot(
false);
359 LedgerIndex const seq = prevLedger->info().seq + 1;
362 initialSet->visitLeaves(
367 censorshipDetector_.propose(std::move(proposed));
371 auto const setHash = initialSet->getHash().as_uint256();
374 std::move(initialSet),
376 initialLedger->info().parentHash,
380 app_.timeKeeper().closeTime(),
399 std::move(consensusJson));
411 app_.getJobQueue().addJob(
414 [=, cj = std::move(consensusJson)](
auto&)
mutable {
427 this->app_.getOPs().endConsensus();
443 bool closeTimeCorrect;
454 using namespace std::chrono_literals;
455 consensusCloseTime = prevLedger.
closeTime() + 1s;
456 closeTimeCorrect =
false;
462 consensusCloseTime, closeResolution, prevLedger.
closeTime());
463 closeTimeCorrect =
true;
467 <<
" val=" << (validating_ ?
"yes" :
"no")
468 <<
" corLCL=" << (haveCorrectLCL ?
"yes" :
"no")
469 <<
" fail=" << (consensusFail ?
"yes" :
"no");
470 JLOG(
j_.
debug()) <<
"Report: Prev = " << prevLedger.
id() <<
":"
482 JLOG(
j_.
debug()) <<
"Building canonical tx set: " << retriableTxs.key();
484 for (
auto const& item : *result.
txns.map_)
489 std::make_shared<STTx const>(
SerialIter{item.slice()}));
490 JLOG(
j_.
debug()) <<
" Tx: " << item.key();
494 failed.
insert(item.key());
495 JLOG(
j_.
warn()) <<
" Tx: " << item.key() <<
" throws!";
499 auto built = buildLCL(
508 auto const newLCLHash = built.id();
509 JLOG(
j_.
debug()) <<
"Built ledger #" << built.seq() <<
": " << newLCLHash;
512 notify(protocol::neACCEPTED_LEDGER, built, haveCorrectLCL);
521 result.
txns.map_->visitLeaves(
527 for (
auto const& r : retriableTxs)
528 failed.
insert(r.first.getTXID());
530 censorshipDetector_.check(
533 j = app_.journal(
"CensorshipDetector"),
535 if (failed.count(id))
538 auto const wait = curr - seq;
540 if (wait && (wait % censorshipWarnInternal == 0))
542 std::ostringstream ss;
543 ss <<
"Potential Censorship: Eligible tx " << id
544 <<
", which we are tracking since ledger " << seq
545 <<
" has not been included as of ledger " << curr <<
".";
547 JLOG(j.warn()) << ss.str();
555 validating_ = ledgerMaster_.isCompatible(
556 *built.ledger_,
j_.
warn(),
"Not validating");
558 if (validating_ && !consensusFail &&
559 app_.getValidations().canValidateSeq(built.seq()))
561 validate(built, result.txns, proposing);
562 JLOG(
j_.
info()) <<
"CNF Val " << newLCLHash;
565 JLOG(
j_.
info()) <<
"CNF buildLCL " << newLCLHash;
568 ledgerMaster_.consensusBuilt(
569 built.ledger_, result.txns.id(), std::move(consensusJson));
584 bool anyDisputes =
false;
585 for (
auto const& [_, dispute] : result.disputes)
588 if (!dispute.getOurVote())
594 <<
"Test applying disputed transaction that did"
595 <<
" not get in " << dispute.tx().id();
598 auto txn = std::make_shared<STTx const>(sit);
605 retriableTxs.insert(txn);
612 <<
"Failed to apply transaction we voted NO on";
622 auto const lastVal = ledgerMaster_.getValidatedLedger();
623 boost::optional<Rules> rules;
625 rules.emplace(*lastVal, app_.config().features);
627 rules.emplace(app_.config().features);
628 app_.openLedger().accept(
632 localTxs_.getTxSet(),
639 return app_.getTxQ().accept(app_, view);
644 app_.getOPs().reportFeeChange();
649 ledgerMaster_.switchLCL(built.ledger_);
652 assert(ledgerMaster_.getClosedLedger()->info().hash == built.id());
653 assert(app_.openLedger().current()->info().parentHash == built.id());
664 auto closeTime = rawCloseTimes.self;
666 JLOG(
j_.
info()) <<
"We closed at "
667 << closeTime.time_since_epoch().count();
669 usec64_t closeTotal =
670 std::chrono::duration_cast<usec64_t>(closeTime.time_since_epoch());
673 for (
auto const& [t, v] : rawCloseTimes.peers)
679 std::chrono::duration_cast<usec64_t>(t.time_since_epoch()) * v;
682 closeTotal += usec64_t(closeCount / 2);
683 closeTotal /= closeCount;
688 auto offset = time_point{closeTotal} -
689 std::chrono::time_point_cast<duration>(closeTime);
690 JLOG(
j_.
info()) <<
"Our close offset is estimated at " << offset.count()
691 <<
" (" << closeCount <<
")";
693 app_.timeKeeper().adjustCloseTime(offset);
699 protocol::NodeEvent ne,
703 protocol::TMStatusChange s;
706 s.set_newevent(protocol::neLOST_SYNC);
710 s.set_ledgerseq(ledger.
seq());
711 s.set_networktime(app_.timeKeeper().now().time_since_epoch().count());
712 s.set_ledgerhashprevious(
719 if (!ledgerMaster_.getFullValidatedRange(uMin, uMax))
727 uMin =
std::max(uMin, ledgerMaster_.getEarliestFetch());
729 s.set_firstseq(uMin);
731 app_.overlay().foreach(
732 send_always(std::make_shared<Message>(s, protocol::mtSTATUS_CHANGE)));
733 JLOG(
j_.
trace()) <<
"send status change to peer";
741 bool closeTimeCorrect,
747 if (
auto const replayData = ledgerMaster_.releaseReplay())
749 assert(replayData->parent()->info().hash == previousLedger.
id());
764 using namespace std::chrono_literals;
765 app_.getTxQ().processClosedLedger(app_, *built, roundTime > 5s);
768 if (ledgerMaster_.storeLedger(built))
769 JLOG(
j_.
debug()) <<
"Consensus built ledger we already had";
770 else if (app_.getInboundLedgers().find(built->info().hash))
771 JLOG(
j_.
debug()) <<
"Consensus built ledger we were acquiring";
773 JLOG(
j_.
debug()) <<
"Consensus built new ledger";
783 using namespace std::chrono_literals;
785 auto validationTime = app_.timeKeeper().closeTime();
786 if (validationTime <= lastValidationTime_)
787 validationTime = lastValidationTime_ + 1s;
788 lastValidationTime_ = validationTime;
790 auto v = std::make_shared<STValidation>(
809 if (auto const vl = ledgerMaster_.getValidatedLedger())
810 v.setFieldH256(sfValidatedHash, vl->info().hash);
812 v.setFieldU64(sfCookie, valCookie_);
815 if (ledger.ledger_->isVotingLedger())
817 sfServerVersion, BuildInfo::getEncodedVersion());
822 auto const& ft = app_.getFeeTrack();
823 auto const fee = std::max(ft.getLocalFee(), ft.getClusterFee());
824 if (fee > ft.getLoadBase())
825 v.setFieldU32(sfLoadFee, fee);
830 if (ledger.
ledger_->isVotingLedger())
833 feeVote_->doValidation(ledger.ledger_->fees(), v);
838 auto const amendments = app_.getAmendmentTable().doValidation(
839 getEnabledAmendments(*ledger.ledger_));
841 if (!amendments.empty())
843 sfAmendments, STVector256(sfAmendments, amendments));
848 app_.getHashRouter().addSuppression(
855 protocol::TMValidation val;
857 app_.overlay().broadcast(val);
860 app_.getOPs().pubValidation(v);
866 JLOG(
j_.
info()) <<
"Consensus mode change before=" <<
to_string(before)
874 censorshipDetector_.reset();
902 JLOG(
j_.
error()) <<
"During consensus timerEntry: " << mn.
what();
918 JLOG(
j_.
error()) <<
"During consensus gotTxSet: " << mn.
what();
928 boost::optional<std::chrono::milliseconds> consensusDelay)
940 return consensus_.peerProposal(now, newProposal);
950 validating_ = valPublic_.size() != 0 &&
951 prevLgr.
seq() >= app_.getMaxDisallowedLedger() &&
952 !app_.getOPs().isAmendmentBlocked();
956 if (validating_ && !app_.config().standalone() && app_.validators().count())
958 auto const when = app_.validators().expires();
960 if (!when || *when < app_.timeKeeper().now())
962 JLOG(
j_.
error()) <<
"Voluntarily bowing out of consensus process "
963 "because of an expired validator list.";
972 JLOG(
j_.
info()) <<
"Entering consensus process, validating, synced="
973 << (synced ?
"yes" :
"no");
978 JLOG(
j_.
info()) <<
"Entering consensus process, watching, synced="
979 << (synced ?
"yes" :
"no");
983 inboundTransactions_.newRound(prevLgr.
seq());
988 nUnlVote_.newValidators(prevLgr.
seq() + 1, nowTrusted);
991 return validating_ && synced;
997 return ledgerMaster_.haveValidated();
1003 return ledgerMaster_.getValidLedgerIndex();
1009 return app_.validators().getQuorumKeys();
1017 return app_.getValidations().laggards(seq, trustedKeys);
1023 return !valPublic_.empty();
1029 if (!positions && app_.getOPs().isFull())