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)
83 , feeVote_(
std::move(feeVote))
86 , inboundTransactions_{inboundTransactions}
88 , validatorKeys_(validatorKeys)
94 , nUnlVote_(validatorKeys_.nodeID,
j_)
96 assert(valCookie_ != 0);
98 JLOG(
j_.
info()) <<
"Consensus engine started (cookie: " +
101 if (validatorKeys_.nodeID != beast::zero)
105 JLOG(
j_.
info()) <<
"Validator identity: "
108 validatorKeys_.masterPublicKey);
110 if (validatorKeys_.masterPublicKey != validatorKeys_.publicKey)
113 <<
"Validator ephemeral signing key: "
124 auto built = ledgerMaster_.getLedgerByHash(hash);
127 if (acquiringLedger_ != hash)
130 JLOG(
j_.
warn()) <<
"Need consensus ledger " << hash;
133 acquiringLedger_ = hash;
135 app_.getJobQueue().addJob(
136 jtADVANCE,
"getConsensusLedger", [
id = hash, &app = app_]() {
137 app.getInboundLedgers().
acquire(
144 assert(!built->open() && built->isImmutable());
145 assert(built->info().hash == hash);
148 inboundTransactions_.newRound(built->info().seq);
156 protocol::TMProposeSet prop;
160 prop.set_proposeseq(
proposal.proposeSeq());
161 prop.set_closetime(
proposal.closeTime().time_since_epoch().count());
163 prop.set_currenttxhash(
165 prop.set_previousledger(
169 prop.set_nodepubkey(pk.data(), pk.size());
172 prop.set_signature(sig.data(), sig.size());
181 if (app_.getHashRouter().shouldRelay(tx.
id()))
183 JLOG(
j_.
debug()) <<
"Relaying disputed tx " << tx.
id();
185 protocol::TMTransaction msg;
186 msg.set_rawtransaction(slice.data(), slice.size());
187 msg.set_status(protocol::tsNEW);
188 msg.set_receivetimestamp(
189 app_.timeKeeper().now().time_since_epoch().count());
191 app_.overlay().relay(tx.
id(), msg, skip);
195 JLOG(
j_.
debug()) <<
"Not relaying disputed tx " << tx.
id();
201 JLOG(
j_.
trace()) << (
proposal.isBowOut() ?
"We bow out: " :
"We propose: ")
205 protocol::TMProposeSet prop;
207 prop.set_currenttxhash(
209 prop.set_previousledger(
211 prop.set_proposeseq(
proposal.proposeSeq());
212 prop.set_closetime(
proposal.closeTime().time_since_epoch().count());
214 validatorKeys_.publicKey.data(), validatorKeys_.publicKey.size());
217 validatorKeys_.publicKey,
218 validatorKeys_.secretKey,
221 prop.set_signature(sig.data(), sig.size());
228 validatorKeys_.publicKey,
231 app_.getHashRouter().addSuppression(suppression);
233 app_.overlay().broadcast(prop);
239 inboundTransactions_.giveSet(txns.
id(), txns.
map_,
false);
245 if (
auto txns = inboundTransactions_.getSet(setId,
true))
255 return !app_.openLedger().empty();
261 return app_.getValidations().numTrustedForLedger(h);
283 ledgerMaster_.getValidLedgerIndex());
285 if (netLgr != ledgerID)
288 app_.getOPs().consensusViewChange();
305 notify(protocol::neCLOSING_LEDGER, ledger, !wrongLCL);
307 auto const& prevLedger = ledger.ledger_;
309 ledgerMaster_.applyHeldTransactions();
311 ledgerMaster_.setBuildingLedger(prevLedger->info().seq + 1);
313 auto initialLedger = app_.openLedger().current();
317 initialSet->setUnbacked();
320 for (
auto const& tx : initialLedger->txs)
322 JLOG(
j_.
trace()) <<
"Adding open ledger TX "
323 << tx.first->getTransactionID();
332 if (app_.config().standalone() || (
proposing && !wrongLCL))
334 if (prevLedger->isFlagLedger())
338 auto validations = app_.validators().negativeUNLFilter(
339 app_.getValidations().getTrustedForLedger(
340 prevLedger->info().parentHash));
341 if (validations.size() >= app_.validators().quorum())
343 feeVote_->doVoting(prevLedger, validations, initialSet);
344 app_.getAmendmentTable().doVoting(
345 prevLedger, validations, initialSet);
349 prevLedger->isVotingLedger() &&
357 app_.validators().getTrustedMasterKeys(),
358 app_.getValidations(),
364 initialSet = initialSet->snapShot(
false);
368 LedgerIndex const seq = prevLedger->info().seq + 1;
371 initialSet->visitLeaves(
376 censorshipDetector_.propose(std::move(proposed));
380 auto const setHash = initialSet->getHash().as_uint256();
383 std::move(initialSet),
385 initialLedger->info().parentHash,
389 app_.timeKeeper().closeTime(),
390 validatorKeys_.nodeID}};
408 std::move(consensusJson));
420 app_.getJobQueue().addJob(
423 [=,
this, cj = std::move(consensusJson)]()
mutable {
436 this->app_.getOPs().endConsensus();
452 bool closeTimeCorrect;
463 using namespace std::chrono_literals;
464 consensusCloseTime = prevLedger.
closeTime() + 1s;
465 closeTimeCorrect =
false;
471 consensusCloseTime, closeResolution, prevLedger.
closeTime());
472 closeTimeCorrect =
true;
476 <<
" val=" << (validating_ ?
"yes" :
"no")
477 <<
" corLCL=" << (haveCorrectLCL ?
"yes" :
"no")
478 <<
" fail=" << (consensusFail ?
"yes" :
"no");
479 JLOG(
j_.
debug()) <<
"Report: Prev = " << prevLedger.
id() <<
":"
491 JLOG(
j_.
debug()) <<
"Building canonical tx set: " << retriableTxs.key();
493 for (
auto const& item : *result.
txns.map_)
498 std::make_shared<STTx const>(
SerialIter{item.slice()}));
499 JLOG(
j_.
debug()) <<
" Tx: " << item.key();
503 failed.
insert(item.key());
504 JLOG(
j_.
warn()) <<
" Tx: " << item.key() <<
" throws!";
508 auto built = buildLCL(
517 auto const newLCLHash = built.id();
518 JLOG(
j_.
debug()) <<
"Built ledger #" << built.seq() <<
": " << newLCLHash;
521 notify(protocol::neACCEPTED_LEDGER, built, haveCorrectLCL);
530 result.
txns.map_->visitLeaves(
536 for (
auto const& r : retriableTxs)
537 failed.
insert(r.first.getTXID());
539 censorshipDetector_.check(
542 j = app_.journal(
"CensorshipDetector"),
544 if (failed.count(id))
547 auto const wait = curr - seq;
549 if (wait && (wait % censorshipWarnInternal == 0))
551 std::ostringstream ss;
552 ss <<
"Potential Censorship: Eligible tx " << id
553 <<
", which we are tracking since ledger " << seq
554 <<
" has not been included as of ledger " << curr <<
".";
556 JLOG(j.warn()) << ss.str();
564 validating_ = ledgerMaster_.isCompatible(
565 *built.ledger_,
j_.
warn(),
"Not validating");
567 if (validating_ && !consensusFail &&
568 app_.getValidations().canValidateSeq(built.seq()))
570 validate(built, result.txns, proposing);
571 JLOG(
j_.
info()) <<
"CNF Val " << newLCLHash;
574 JLOG(
j_.
info()) <<
"CNF buildLCL " << newLCLHash;
577 ledgerMaster_.consensusBuilt(
578 built.ledger_, result.txns.id(), std::move(consensusJson));
593 bool anyDisputes =
false;
594 for (
auto const& [_, dispute] : result.disputes)
597 if (!dispute.getOurVote())
603 <<
"Test applying disputed transaction that did"
604 <<
" not get in " << dispute.tx().id();
607 auto txn = std::make_shared<STTx const>(sit);
614 retriableTxs.insert(txn);
621 <<
"Failed to apply transaction we voted NO on";
631 auto const lastVal = ledgerMaster_.getValidatedLedger();
636 rules.
emplace(app_.config().features);
637 app_.openLedger().accept(
641 localTxs_.getTxSet(),
648 return app_.getTxQ().accept(app_, view);
653 app_.getOPs().reportFeeChange();
658 ledgerMaster_.switchLCL(built.ledger_);
661 assert(ledgerMaster_.getClosedLedger()->info().hash == built.id());
662 assert(app_.openLedger().current()->info().parentHash == built.id());
673 auto closeTime = rawCloseTimes.self;
675 JLOG(
j_.
info()) <<
"We closed at "
676 << closeTime.time_since_epoch().count();
678 usec64_t closeTotal =
679 std::chrono::duration_cast<usec64_t>(closeTime.time_since_epoch());
682 for (
auto const& [t, v] : rawCloseTimes.peers)
688 std::chrono::duration_cast<usec64_t>(t.time_since_epoch()) * v;
691 closeTotal += usec64_t(closeCount / 2);
692 closeTotal /= closeCount;
697 auto offset = time_point{closeTotal} -
698 std::chrono::time_point_cast<duration>(closeTime);
699 JLOG(
j_.
info()) <<
"Our close offset is estimated at " << offset.count()
700 <<
" (" << closeCount <<
")";
702 app_.timeKeeper().adjustCloseTime(offset);
708 protocol::NodeEvent ne,
712 protocol::TMStatusChange s;
715 s.set_newevent(protocol::neLOST_SYNC);
719 s.set_ledgerseq(ledger.
seq());
720 s.set_networktime(app_.timeKeeper().now().time_since_epoch().count());
721 s.set_ledgerhashprevious(
728 if (!ledgerMaster_.getFullValidatedRange(uMin, uMax))
736 uMin =
std::max(uMin, ledgerMaster_.getEarliestFetch());
738 s.set_firstseq(uMin);
740 app_.overlay().foreach(
741 send_always(std::make_shared<Message>(s, protocol::mtSTATUS_CHANGE)));
742 JLOG(
j_.
trace()) <<
"send status change to peer";
750 bool closeTimeCorrect,
756 if (
auto const replayData = ledgerMaster_.releaseReplay())
758 assert(replayData->parent()->info().hash == previousLedger.
id());
773 using namespace std::chrono_literals;
774 app_.getTxQ().processClosedLedger(app_, *built, roundTime > 5s);
777 if (ledgerMaster_.storeLedger(built))
778 JLOG(
j_.
debug()) <<
"Consensus built ledger we already had";
779 else if (app_.getInboundLedgers().find(built->info().hash))
780 JLOG(
j_.
debug()) <<
"Consensus built ledger we were acquiring";
782 JLOG(
j_.
debug()) <<
"Consensus built new ledger";
792 using namespace std::chrono_literals;
794 auto validationTime = app_.timeKeeper().closeTime();
795 if (validationTime <= lastValidationTime_)
796 validationTime = lastValidationTime_ + 1s;
797 lastValidationTime_ = validationTime;
799 auto v = std::make_shared<STValidation>(
801 validatorKeys_.publicKey,
802 validatorKeys_.secretKey,
803 validatorKeys_.nodeID,
805 v.setFieldH256(sfLedgerHash, ledger.id());
806 v.setFieldH256(sfConsensusHash, txns.id());
808 v.setFieldU32(sfLedgerSequence, ledger.seq());
811 v.setFlag(vfFullValidation);
813 if (ledger.ledger_->rules().enabled(featureHardenedValidations))
818 if (auto const vl = ledgerMaster_.getValidatedLedger())
819 v.setFieldH256(sfValidatedHash, vl->info().hash);
821 v.setFieldU64(sfCookie, valCookie_);
824 if (ledger.ledger_->isVotingLedger())
826 sfServerVersion, BuildInfo::getEncodedVersion());
831 auto const& ft = app_.getFeeTrack();
832 auto const fee = std::max(ft.getLocalFee(), ft.getClusterFee());
833 if (fee > ft.getLoadBase())
834 v.setFieldU32(sfLoadFee, fee);
839 if (ledger.
ledger_->isVotingLedger())
842 feeVote_->doValidation(ledger.ledger_->fees(), v);
847 auto const amendments = app_.getAmendmentTable().doValidation(
848 getEnabledAmendments(*ledger.ledger_));
850 if (!amendments.empty())
852 sfAmendments, STVector256(sfAmendments, amendments));
856 auto const serialized = v->getSerialized();
864 protocol::TMValidation val;
865 val.set_validation(serialized.data(), serialized.size());
866 app_.overlay().broadcast(val);
869 app_.getOPs().pubValidation(v);
875 JLOG(
j_.
info()) <<
"Consensus mode change before=" <<
to_string(before)
883 censorshipDetector_.reset();
911 JLOG(
j_.
error()) <<
"During consensus timerEntry: " << mn.
what();
927 JLOG(
j_.
error()) <<
"During consensus gotTxSet: " << mn.
what();
949 return consensus_.peerProposal(now, newProposal);
959 validating_ = validatorKeys_.publicKey.size() != 0 &&
960 prevLgr.
seq() >= app_.getMaxDisallowedLedger() &&
961 !app_.getOPs().isBlocked();
965 if (validating_ && !app_.config().standalone() && app_.validators().count())
967 auto const when = app_.validators().expires();
969 if (!when || *when < app_.timeKeeper().now())
971 JLOG(
j_.
error()) <<
"Voluntarily bowing out of consensus process "
972 "because of an expired validator list.";
981 JLOG(
j_.
info()) <<
"Entering consensus process, validating, synced="
982 << (synced ?
"yes" :
"no");
987 JLOG(
j_.
info()) <<
"Entering consensus process, watching, synced="
988 << (synced ?
"yes" :
"no");
992 inboundTransactions_.newRound(prevLgr.
seq());
997 nUnlVote_.newValidators(prevLgr.
seq() + 1, nowTrusted);
1000 return validating_ && synced;
1006 return ledgerMaster_.haveValidated();
1012 return ledgerMaster_.getValidLedgerIndex();
1018 return app_.validators().getQuorumKeys();
1026 return app_.getValidations().laggards(seq, trustedKeys);
1032 return !validatorKeys_.publicKey.empty();
1038 if (!positions && app_.getOPs().isFull())