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();
184 auto const slice = tx.
tx_->slice();
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, prevLedger->seq() - 1));
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(
373 seq](boost::intrusive_ptr<SHAMapItem const>
const& item) {
377 censorshipDetector_.propose(std::move(proposed));
381 auto const setHash = initialSet->getHash().as_uint256();
384 std::move(initialSet),
386 initialLedger->info().parentHash,
390 app_.timeKeeper().closeTime(),
391 validatorKeys_.nodeID}};
409 std::move(consensusJson));
421 app_.getJobQueue().addJob(
424 [=,
this, cj = std::move(consensusJson)]()
mutable {
437 this->app_.getOPs().endConsensus();
453 bool closeTimeCorrect;
464 using namespace std::chrono_literals;
465 consensusCloseTime = prevLedger.
closeTime() + 1s;
466 closeTimeCorrect =
false;
472 consensusCloseTime, closeResolution, prevLedger.
closeTime());
473 closeTimeCorrect =
true;
477 <<
" val=" << (validating_ ?
"yes" :
"no")
478 <<
" corLCL=" << (haveCorrectLCL ?
"yes" :
"no")
479 <<
" fail=" << (consensusFail ?
"yes" :
"no");
480 JLOG(
j_.
debug()) <<
"Report: Prev = " << prevLedger.
id() <<
":"
492 JLOG(
j_.
debug()) <<
"Building canonical tx set: " << retriableTxs.key();
494 for (
auto const& item : *result.
txns.map_)
499 std::make_shared<STTx const>(
SerialIter{item.slice()}));
500 JLOG(
j_.
debug()) <<
" Tx: " << item.key();
504 failed.
insert(item.key());
506 <<
" Tx: " << item.key() <<
" throws: " << ex.
what();
510 auto built = buildLCL(
519 auto const newLCLHash = built.id();
520 JLOG(
j_.
debug()) <<
"Built ledger #" << built.seq() <<
": " << newLCLHash;
523 notify(protocol::neACCEPTED_LEDGER, built, haveCorrectLCL);
532 result.
txns.map_->visitLeaves(
533 [&
accepted](boost::intrusive_ptr<SHAMapItem const>
const& item) {
538 for (
auto const& r : retriableTxs)
539 failed.
insert(r.first.getTXID());
541 censorshipDetector_.check(
544 j = app_.journal(
"CensorshipDetector"),
546 if (failed.count(id))
549 auto const wait = curr - seq;
551 if (wait && (wait % censorshipWarnInternal == 0))
553 std::ostringstream ss;
554 ss <<
"Potential Censorship: Eligible tx " << id
555 <<
", which we are tracking since ledger " << seq
556 <<
" has not been included as of ledger " << curr <<
".";
558 JLOG(j.warn()) << ss.str();
566 validating_ = ledgerMaster_.isCompatible(
567 *built.ledger_,
j_.
warn(),
"Not validating");
569 if (validating_ && !consensusFail &&
570 app_.getValidations().canValidateSeq(built.seq()))
572 validate(built, result.txns, proposing);
573 JLOG(
j_.
info()) <<
"CNF Val " << newLCLHash;
576 JLOG(
j_.
info()) <<
"CNF buildLCL " << newLCLHash;
579 ledgerMaster_.consensusBuilt(
580 built.ledger_, result.txns.id(), std::move(consensusJson));
595 bool anyDisputes =
false;
596 for (
auto const& [_, dispute] : result.disputes)
599 if (!dispute.getOurVote())
605 <<
"Test applying disputed transaction that did"
606 <<
" not get in " << dispute.tx().id();
609 auto txn = std::make_shared<STTx const>(sit);
616 retriableTxs.insert(txn);
622 JLOG(
j_.
debug()) <<
"Failed to apply transaction we voted "
634 auto const lastVal = ledgerMaster_.getValidatedLedger();
639 rules.
emplace(app_.config().features);
640 app_.openLedger().accept(
644 localTxs_.getTxSet(),
651 return app_.getTxQ().accept(app_, view);
656 app_.getOPs().reportFeeChange();
661 ledgerMaster_.switchLCL(built.ledger_);
664 assert(ledgerMaster_.getClosedLedger()->info().hash == built.id());
665 assert(app_.openLedger().current()->info().parentHash == built.id());
676 auto closeTime = rawCloseTimes.self;
678 JLOG(
j_.
info()) <<
"We closed at "
679 << closeTime.time_since_epoch().count();
681 usec64_t closeTotal =
682 std::chrono::duration_cast<usec64_t>(closeTime.time_since_epoch());
685 for (
auto const& [t, v] : rawCloseTimes.peers)
691 std::chrono::duration_cast<usec64_t>(t.time_since_epoch()) * v;
694 closeTotal += usec64_t(closeCount / 2);
695 closeTotal /= closeCount;
700 auto offset = time_point{closeTotal} -
701 std::chrono::time_point_cast<duration>(closeTime);
702 JLOG(
j_.
info()) <<
"Our close offset is estimated at " << offset.count()
703 <<
" (" << closeCount <<
")";
705 app_.timeKeeper().adjustCloseTime(offset);
711 protocol::NodeEvent ne,
715 protocol::TMStatusChange s;
718 s.set_newevent(protocol::neLOST_SYNC);
722 s.set_ledgerseq(ledger.
seq());
723 s.set_networktime(app_.timeKeeper().now().time_since_epoch().count());
724 s.set_ledgerhashprevious(
731 if (!ledgerMaster_.getFullValidatedRange(uMin, uMax))
739 uMin =
std::max(uMin, ledgerMaster_.getEarliestFetch());
741 s.set_firstseq(uMin);
743 app_.overlay().foreach(
744 send_always(std::make_shared<Message>(s, protocol::mtSTATUS_CHANGE)));
745 JLOG(
j_.
trace()) <<
"send status change to peer";
753 bool closeTimeCorrect,
759 if (
auto const replayData = ledgerMaster_.releaseReplay())
761 assert(replayData->parent()->info().hash == previousLedger.
id());
776 using namespace std::chrono_literals;
777 app_.getTxQ().processClosedLedger(app_, *built, roundTime > 5s);
780 if (ledgerMaster_.storeLedger(built))
781 JLOG(
j_.
debug()) <<
"Consensus built ledger we already had";
782 else if (app_.getInboundLedgers().find(built->info().hash))
783 JLOG(
j_.
debug()) <<
"Consensus built ledger we were acquiring";
785 JLOG(
j_.
debug()) <<
"Consensus built new ledger";
795 using namespace std::chrono_literals;
797 auto validationTime = app_.timeKeeper().closeTime();
798 if (validationTime <= lastValidationTime_)
799 validationTime = lastValidationTime_ + 1s;
800 lastValidationTime_ = validationTime;
802 auto v = std::make_shared<STValidation>(
804 validatorKeys_.publicKey,
805 validatorKeys_.secretKey,
806 validatorKeys_.nodeID,
808 v.setFieldH256(sfLedgerHash, ledger.id());
809 v.setFieldH256(sfConsensusHash, txns.id());
811 v.setFieldU32(sfLedgerSequence, ledger.seq());
814 v.setFlag(vfFullValidation);
816 if (ledger.ledger_->rules().enabled(featureHardenedValidations))
821 if (auto const vl = ledgerMaster_.getValidatedLedger())
822 v.setFieldH256(sfValidatedHash, vl->info().hash);
824 v.setFieldU64(sfCookie, valCookie_);
827 if (ledger.ledger_->isVotingLedger())
829 sfServerVersion, BuildInfo::getEncodedVersion());
834 auto const& ft = app_.getFeeTrack();
835 auto const fee = std::max(ft.getLocalFee(), ft.getClusterFee());
836 if (fee > ft.getLoadBase())
837 v.setFieldU32(sfLoadFee, fee);
842 if (ledger.
ledger_->isVotingLedger())
845 feeVote_->doValidation(
846 ledger.ledger_->fees(), ledger.ledger_->rules(), v);
851 auto const amendments = app_.getAmendmentTable().doValidation(
852 getEnabledAmendments(*ledger.ledger_));
854 if (!amendments.empty())
856 sfAmendments, STVector256(sfAmendments, amendments));
860 auto const serialized = v->getSerialized();
868 protocol::TMValidation val;
869 val.set_validation(serialized.data(), serialized.size());
870 app_.overlay().broadcast(val);
873 app_.getOPs().pubValidation(v);
879 JLOG(
j_.
info()) <<
"Consensus mode change before=" <<
to_string(before)
887 censorshipDetector_.reset();
915 JLOG(
j_.
error()) <<
"During consensus timerEntry: " << mn.
what();
931 JLOG(
j_.
error()) <<
"During consensus gotTxSet: " << mn.
what();
953 return consensus_.peerProposal(now, newProposal);
963 validating_ = validatorKeys_.publicKey.size() != 0 &&
964 prevLgr.
seq() >= app_.getMaxDisallowedLedger() &&
965 !app_.getOPs().isBlocked();
969 if (validating_ && !app_.config().standalone() && app_.validators().count())
971 auto const when = app_.validators().expires();
973 if (!when || *when < app_.timeKeeper().now())
975 JLOG(
j_.
error()) <<
"Voluntarily bowing out of consensus process "
976 "because of an expired validator list.";
985 JLOG(
j_.
info()) <<
"Entering consensus process, validating, synced="
986 << (synced ?
"yes" :
"no");
991 JLOG(
j_.
info()) <<
"Entering consensus process, watching, synced="
992 << (synced ?
"yes" :
"no");
996 inboundTransactions_.newRound(prevLgr.
seq());
1000 !nowTrusted.
empty())
1001 nUnlVote_.newValidators(prevLgr.
seq() + 1, nowTrusted);
1004 return validating_ && synced;
1010 return ledgerMaster_.haveValidated();
1016 return ledgerMaster_.getValidLedgerIndex();
1022 return app_.validators().getQuorumKeys();
1030 return app_.getValidations().laggards(seq, trustedKeys);
1036 return !validatorKeys_.publicKey.empty();
1042 if (!positions && app_.getOPs().isFull())