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();
318 SHAMapItem(tx.first->getTransactionID(), std::move(s)),
324 if (app_.config().standalone() || (
proposing && !wrongLCL))
326 if (prevLedger->isFlagLedger())
330 auto validations = app_.validators().negativeUNLFilter(
331 app_.getValidations().getTrustedForLedger(
332 prevLedger->info().parentHash));
333 if (validations.size() >= app_.validators().quorum())
335 feeVote_->doVoting(prevLedger, validations, initialSet);
336 app_.getAmendmentTable().doVoting(
337 prevLedger, validations, initialSet);
341 prevLedger->isVotingLedger() &&
349 app_.validators().getTrustedMasterKeys(),
350 app_.getValidations(),
356 initialSet = initialSet->snapShot(
false);
360 LedgerIndex const seq = prevLedger->info().seq + 1;
363 initialSet->visitLeaves(
368 censorshipDetector_.propose(std::move(proposed));
372 auto const setHash = initialSet->getHash().as_uint256();
375 std::move(initialSet),
377 initialLedger->info().parentHash,
381 app_.timeKeeper().closeTime(),
400 std::move(consensusJson));
412 app_.getJobQueue().addJob(
415 [=, cj = std::move(consensusJson)](
auto&)
mutable {
428 this->app_.getOPs().endConsensus();
444 bool closeTimeCorrect;
455 using namespace std::chrono_literals;
456 consensusCloseTime = prevLedger.
closeTime() + 1s;
457 closeTimeCorrect =
false;
463 consensusCloseTime, closeResolution, prevLedger.
closeTime());
464 closeTimeCorrect =
true;
468 <<
" val=" << (validating_ ?
"yes" :
"no")
469 <<
" corLCL=" << (haveCorrectLCL ?
"yes" :
"no")
470 <<
" fail=" << (consensusFail ?
"yes" :
"no");
471 JLOG(
j_.
debug()) <<
"Report: Prev = " << prevLedger.
id() <<
":"
483 JLOG(
j_.
debug()) <<
"Building canonical tx set: " << retriableTxs.key();
485 for (
auto const& item : *result.
txns.map_)
490 std::make_shared<STTx const>(
SerialIter{item.slice()}));
491 JLOG(
j_.
debug()) <<
" Tx: " << item.key();
495 failed.
insert(item.key());
496 JLOG(
j_.
warn()) <<
" Tx: " << item.key() <<
" throws!";
500 auto built = buildLCL(
509 auto const newLCLHash = built.id();
510 JLOG(
j_.
debug()) <<
"Built ledger #" << built.seq() <<
": " << newLCLHash;
513 notify(protocol::neACCEPTED_LEDGER, built, haveCorrectLCL);
522 result.
txns.map_->visitLeaves(
528 for (
auto const& r : retriableTxs)
529 failed.
insert(r.first.getTXID());
531 censorshipDetector_.check(
534 j = app_.journal(
"CensorshipDetector"),
536 if (failed.count(id))
539 auto const wait = curr - seq;
541 if (wait && (wait % censorshipWarnInternal == 0))
543 std::ostringstream ss;
544 ss <<
"Potential Censorship: Eligible tx " << id
545 <<
", which we are tracking since ledger " << seq
546 <<
" has not been included as of ledger " << curr <<
".";
548 JLOG(j.warn()) << ss.str();
556 validating_ = ledgerMaster_.isCompatible(
557 *built.ledger_,
j_.
warn(),
"Not validating");
559 if (validating_ && !consensusFail &&
560 app_.getValidations().canValidateSeq(built.seq()))
562 validate(built, result.txns, proposing);
563 JLOG(
j_.
info()) <<
"CNF Val " << newLCLHash;
566 JLOG(
j_.
info()) <<
"CNF buildLCL " << newLCLHash;
569 ledgerMaster_.consensusBuilt(
570 built.ledger_, result.txns.id(), std::move(consensusJson));
585 bool anyDisputes =
false;
586 for (
auto const& [_, dispute] : result.disputes)
589 if (!dispute.getOurVote())
595 <<
"Test applying disputed transaction that did"
596 <<
" not get in " << dispute.tx().id();
599 auto txn = std::make_shared<STTx const>(sit);
606 retriableTxs.insert(txn);
613 <<
"Failed to apply transaction we voted NO on";
623 auto const lastVal = ledgerMaster_.getValidatedLedger();
624 boost::optional<Rules> rules;
626 rules.emplace(*lastVal, app_.config().features);
628 rules.emplace(app_.config().features);
629 app_.openLedger().accept(
633 localTxs_.getTxSet(),
640 return app_.getTxQ().accept(app_, view);
645 app_.getOPs().reportFeeChange();
650 ledgerMaster_.switchLCL(built.ledger_);
653 assert(ledgerMaster_.getClosedLedger()->info().hash == built.id());
654 assert(app_.openLedger().current()->info().parentHash == built.id());
665 auto closeTime = rawCloseTimes.self;
667 JLOG(
j_.
info()) <<
"We closed at "
668 << closeTime.time_since_epoch().count();
670 usec64_t closeTotal =
671 std::chrono::duration_cast<usec64_t>(closeTime.time_since_epoch());
674 for (
auto const& [t, v] : rawCloseTimes.peers)
680 std::chrono::duration_cast<usec64_t>(t.time_since_epoch()) * v;
683 closeTotal += usec64_t(closeCount / 2);
684 closeTotal /= closeCount;
689 auto offset = time_point{closeTotal} -
690 std::chrono::time_point_cast<duration>(closeTime);
691 JLOG(
j_.
info()) <<
"Our close offset is estimated at " << offset.count()
692 <<
" (" << closeCount <<
")";
694 app_.timeKeeper().adjustCloseTime(offset);
700 protocol::NodeEvent ne,
704 protocol::TMStatusChange s;
707 s.set_newevent(protocol::neLOST_SYNC);
711 s.set_ledgerseq(ledger.
seq());
712 s.set_networktime(app_.timeKeeper().now().time_since_epoch().count());
713 s.set_ledgerhashprevious(
720 if (!ledgerMaster_.getFullValidatedRange(uMin, uMax))
728 uMin =
std::max(uMin, ledgerMaster_.getEarliestFetch());
730 s.set_firstseq(uMin);
732 app_.overlay().foreach(
733 send_always(std::make_shared<Message>(s, protocol::mtSTATUS_CHANGE)));
734 JLOG(
j_.
trace()) <<
"send status change to peer";
742 bool closeTimeCorrect,
748 if (
auto const replayData = ledgerMaster_.releaseReplay())
750 assert(replayData->parent()->info().hash == previousLedger.
id());
765 using namespace std::chrono_literals;
766 app_.getTxQ().processClosedLedger(app_, *built, roundTime > 5s);
769 if (ledgerMaster_.storeLedger(built))
770 JLOG(
j_.
debug()) <<
"Consensus built ledger we already had";
771 else if (app_.getInboundLedgers().find(built->info().hash))
772 JLOG(
j_.
debug()) <<
"Consensus built ledger we were acquiring";
774 JLOG(
j_.
debug()) <<
"Consensus built new ledger";
784 using namespace std::chrono_literals;
786 auto validationTime = app_.timeKeeper().closeTime();
787 if (validationTime <= lastValidationTime_)
788 validationTime = lastValidationTime_ + 1s;
789 lastValidationTime_ = validationTime;
791 auto v = std::make_shared<STValidation>(
810 if (auto const vl = ledgerMaster_.getValidatedLedger())
811 v.setFieldH256(sfValidatedHash, vl->info().hash);
813 v.setFieldU64(sfCookie, valCookie_);
816 if (ledger.ledger_->isVotingLedger())
818 sfServerVersion, BuildInfo::getEncodedVersion());
823 auto const& ft = app_.getFeeTrack();
824 auto const fee = std::max(ft.getLocalFee(), ft.getClusterFee());
825 if (fee > ft.getLoadBase())
826 v.setFieldU32(sfLoadFee, fee);
831 if (ledger.
ledger_->isVotingLedger())
834 feeVote_->doValidation(ledger.ledger_->fees(), v);
839 auto const amendments = app_.getAmendmentTable().doValidation(
840 getEnabledAmendments(*ledger.ledger_));
842 if (!amendments.empty())
844 sfAmendments, STVector256(sfAmendments, amendments));
849 app_.getHashRouter().addSuppression(
856 protocol::TMValidation val;
858 app_.overlay().broadcast(val);
861 app_.getOPs().pubValidation(v);
867 JLOG(
j_.
info()) <<
"Consensus mode change before=" <<
to_string(before)
875 censorshipDetector_.reset();
903 JLOG(
j_.
error()) <<
"During consensus timerEntry: " << mn.
what();
919 JLOG(
j_.
error()) <<
"During consensus gotTxSet: " << mn.
what();
929 boost::optional<std::chrono::milliseconds> consensusDelay)
941 return consensus_.peerProposal(now, newProposal);
951 validating_ = valPublic_.size() != 0 &&
952 prevLgr.
seq() >= app_.getMaxDisallowedLedger() &&
953 !app_.getOPs().isAmendmentBlocked();
957 if (validating_ && !app_.config().standalone() && app_.validators().count())
959 auto const when = app_.validators().expires();
961 if (!when || *when < app_.timeKeeper().now())
963 JLOG(
j_.
error()) <<
"Voluntarily bowing out of consensus process "
964 "because of an expired validator list.";
973 JLOG(
j_.
info()) <<
"Entering consensus process, validating, synced="
974 << (synced ?
"yes" :
"no");
979 JLOG(
j_.
info()) <<
"Entering consensus process, watching, synced="
980 << (synced ?
"yes" :
"no");
984 inboundTransactions_.newRound(prevLgr.
seq());
989 nUnlVote_.newValidators(prevLgr.
seq() + 1, nowTrusted);
992 return validating_ && synced;
998 return ledgerMaster_.haveValidated();
1004 return ledgerMaster_.getValidLedgerIndex();
1010 return app_.validators().getQuorumKeys();
1018 return app_.getValidations().laggards(seq, trustedKeys);
1024 return !valPublic_.empty();
1030 if (!positions && app_.getOPs().isFull())