rippled
Loading...
Searching...
No Matches
RCLConsensus.cpp
1#include <xrpld/app/consensus/RCLConsensus.h>
2#include <xrpld/app/consensus/RCLValidations.h>
3#include <xrpld/app/ledger/BuildLedger.h>
4#include <xrpld/app/ledger/InboundLedgers.h>
5#include <xrpld/app/ledger/InboundTransactions.h>
6#include <xrpld/app/ledger/Ledger.h>
7#include <xrpld/app/ledger/LedgerMaster.h>
8#include <xrpld/app/ledger/LocalTxs.h>
9#include <xrpld/app/ledger/OpenLedger.h>
10#include <xrpld/app/misc/AmendmentTable.h>
11#include <xrpld/app/misc/HashRouter.h>
12#include <xrpld/app/misc/LoadFeeTrack.h>
13#include <xrpld/app/misc/NegativeUNLVote.h>
14#include <xrpld/app/misc/NetworkOPs.h>
15#include <xrpld/app/misc/TxQ.h>
16#include <xrpld/app/misc/ValidatorKeys.h>
17#include <xrpld/app/misc/ValidatorList.h>
18#include <xrpld/consensus/LedgerTiming.h>
19#include <xrpld/overlay/Overlay.h>
20#include <xrpld/overlay/predicates.h>
21
22#include <xrpl/basics/random.h>
23#include <xrpl/beast/core/LexicalCast.h>
24#include <xrpl/beast/utility/instrumentation.h>
25#include <xrpl/protocol/BuildInfo.h>
26#include <xrpl/protocol/Feature.h>
27#include <xrpl/protocol/digest.h>
28
29#include <algorithm>
30#include <iomanip>
31#include <mutex>
32
33namespace xrpl {
34
36 Application& app,
39 LocalTxs& localTxs,
40 InboundTransactions& inboundTransactions,
42 ValidatorKeys const& validatorKeys,
43 beast::Journal journal)
44 : adaptor_(
45 app,
46 std::move(feeVote),
48 localTxs,
49 inboundTransactions,
50 validatorKeys,
51 journal)
52 , consensus_(clock, adaptor_, journal)
53 , j_(journal)
54{
55}
56
58 Application& app,
61 LocalTxs& localTxs,
62 InboundTransactions& inboundTransactions,
63 ValidatorKeys const& validatorKeys,
64 beast::Journal journal)
65 : app_(app)
66 , feeVote_(std::move(feeVote))
67 , ledgerMaster_(ledgerMaster)
68 , localTxs_(localTxs)
69 , inboundTransactions_{inboundTransactions}
70 , j_(journal)
71 , validatorKeys_(validatorKeys)
72 , valCookie_(
73 1 +
76 std::numeric_limits<std::uint64_t>::max() - 1))
77 , nUnlVote_(validatorKeys_.nodeID, j_)
78{
79 XRPL_ASSERT(
80 valCookie_, "xrpl::RCLConsensus::Adaptor::Adaptor : nonzero cookie");
81
82 JLOG(j_.info()) << "Consensus engine started (cookie: " +
84
85 if (validatorKeys_.nodeID != beast::zero && validatorKeys_.keys)
86 {
88
89 JLOG(j_.info()) << "Validator identity: "
90 << toBase58(
92 validatorKeys_.keys->masterPublicKey);
93
94 if (validatorKeys_.keys->masterPublicKey !=
95 validatorKeys_.keys->publicKey)
96 {
97 JLOG(j_.debug())
98 << "Validator ephemeral signing key: "
99 << toBase58(
101 << " (seq: " << std::to_string(validatorKeys_.sequence) << ")";
102 }
103 }
104}
105
108{
109 // we need to switch the ledger we're working from
110 auto built = ledgerMaster_.getLedgerByHash(hash);
111 if (!built)
112 {
113 if (acquiringLedger_ != hash)
114 {
115 // need to start acquiring the correct consensus LCL
116 JLOG(j_.warn()) << "Need consensus ledger " << hash;
117
118 // Tell the ledger acquire system that we need the consensus ledger
119 acquiringLedger_ = hash;
120
121 app_.getJobQueue().addJob(
122 jtADVANCE, "GetConsL1", [id = hash, &app = app_, this]() {
123 JLOG(j_.debug())
124 << "JOB advanceLedger getConsensusLedger1 started";
125 app.getInboundLedgers().acquireAsync(
127 });
128 }
129 return std::nullopt;
130 }
131
132 XRPL_ASSERT(
133 !built->open() && built->isImmutable(),
134 "xrpl::RCLConsensus::Adaptor::acquireLedger : valid ledger state");
135 XRPL_ASSERT(
136 built->header().hash == hash,
137 "xrpl::RCLConsensus::Adaptor::acquireLedger : ledger hash match");
138
139 // Notify inbound transactions of the new ledger sequence number
140 inboundTransactions_.newRound(built->header().seq);
141
142 return RCLCxLedger(built);
143}
144
145void
147{
148 protocol::TMProposeSet prop;
149
150 auto const& proposal = peerPos.proposal();
151
152 prop.set_proposeseq(proposal.proposeSeq());
153 prop.set_closetime(proposal.closeTime().time_since_epoch().count());
154
155 prop.set_currenttxhash(
156 proposal.position().begin(), proposal.position().size());
157 prop.set_previousledger(
158 proposal.prevLedger().begin(), proposal.position().size());
159
160 auto const pk = peerPos.publicKey().slice();
161 prop.set_nodepubkey(pk.data(), pk.size());
162
163 auto const sig = peerPos.signature();
164 prop.set_signature(sig.data(), sig.size());
165
166 app_.overlay().relay(prop, peerPos.suppressionID(), peerPos.publicKey());
167}
168
169void
171{
172 // If we didn't relay this transaction recently, relay it to all peers
173 if (app_.getHashRouter().shouldRelay(tx.id()))
174 {
175 JLOG(j_.debug()) << "Relaying disputed tx " << tx.id();
176 auto const slice = tx.tx_->slice();
177 protocol::TMTransaction msg;
178 msg.set_rawtransaction(slice.data(), slice.size());
179 msg.set_status(protocol::tsNEW);
180 msg.set_receivetimestamp(
181 app_.timeKeeper().now().time_since_epoch().count());
182 static std::set<Peer::id_t> skip{};
183 app_.overlay().relay(tx.id(), msg, skip);
184 }
185 else
186 {
187 JLOG(j_.debug()) << "Not relaying disputed tx " << tx.id();
188 }
189}
190void
192{
193 JLOG(j_.trace()) << (proposal.isBowOut() ? "We bow out: " : "We propose: ")
194 << xrpl::to_string(proposal.prevLedger()) << " -> "
195 << xrpl::to_string(proposal.position());
196
197 protocol::TMProposeSet prop;
198
199 prop.set_currenttxhash(
200 proposal.position().begin(), proposal.position().size());
201 prop.set_previousledger(
202 proposal.prevLedger().begin(), proposal.prevLedger().size());
203 prop.set_proposeseq(proposal.proposeSeq());
204 prop.set_closetime(proposal.closeTime().time_since_epoch().count());
205
206 if (!validatorKeys_.keys)
207 {
208 JLOG(j_.warn()) << "RCLConsensus::Adaptor::propose: ValidatorKeys "
209 "not set: \n";
210 return;
211 }
212
213 auto const& keys = *validatorKeys_.keys;
214
215 prop.set_nodepubkey(keys.publicKey.data(), keys.publicKey.size());
216
217 auto sig =
218 signDigest(keys.publicKey, keys.secretKey, proposal.signingHash());
219
220 prop.set_signature(sig.data(), sig.size());
221
222 auto const suppression = proposalUniqueId(
223 proposal.position(),
224 proposal.prevLedger(),
225 proposal.proposeSeq(),
226 proposal.closeTime(),
227 keys.publicKey,
228 sig);
229
230 app_.getHashRouter().addSuppression(suppression);
231
232 app_.overlay().broadcast(prop);
233}
234
235void
237{
238 inboundTransactions_.giveSet(txns.id(), txns.map_, false);
239}
240
243{
244 if (auto txns = inboundTransactions_.getSet(setId, true))
245 {
246 return RCLTxSet{std::move(txns)};
247 }
248 return std::nullopt;
249}
250
251bool
253{
254 return !app_.openLedger().empty();
255}
256
259{
260 return app_.getValidations().numTrustedForLedger(h);
261}
262
265 RCLCxLedger const& ledger,
266 LedgerHash const& h) const
267{
268 RCLValidations& vals = app_.getValidations();
269 return vals.getNodesAfter(
270 RCLValidatedLedger(ledger.ledger_, vals.adaptor().journal()), h);
271}
272
275 uint256 ledgerID,
276 RCLCxLedger const& ledger,
278{
279 RCLValidations& vals = app_.getValidations();
280 uint256 netLgr = vals.getPreferred(
281 RCLValidatedLedger{ledger.ledger_, vals.adaptor().journal()},
282 ledgerMaster_.getValidLedgerIndex());
283
284 if (netLgr != ledgerID)
285 {
287 app_.getOPs().consensusViewChange();
288
289 JLOG(j_.debug()) << Json::Compact(app_.getValidations().getJsonTrie());
290 }
291
292 return netLgr;
293}
294
295auto
297 RCLCxLedger const& ledger,
298 NetClock::time_point const& closeTime,
300{
301 bool const wrongLCL = mode == ConsensusMode::wrongLedger;
303
304 notify(protocol::neCLOSING_LEDGER, ledger, !wrongLCL);
305
306 auto const& prevLedger = ledger.ledger_;
307
308 ledgerMaster_.applyHeldTransactions();
309 // Tell the ledger master not to acquire the ledger we're probably building
310 ledgerMaster_.setBuildingLedger(prevLedger->header().seq + 1);
311
312 auto initialLedger = app_.openLedger().current();
313
314 auto initialSet =
316 initialSet->setUnbacked();
317
318 // Build SHAMap containing all transactions in our open ledger
319 for (auto const& tx : initialLedger->txs)
320 {
321 JLOG(j_.trace()) << "Adding open ledger TX "
322 << tx.first->getTransactionID();
323 Serializer s(2048);
324 tx.first->add(s);
325 initialSet->addItem(
327 make_shamapitem(tx.first->getTransactionID(), s.slice()));
328 }
329
330 // Add pseudo-transactions to the set
331 if (app_.config().standalone() || (proposing && !wrongLCL))
332 {
333 if (prevLedger->isFlagLedger())
334 {
335 // previous ledger was flag ledger, add fee and amendment
336 // pseudo-transactions
337 auto validations = app_.validators().negativeUNLFilter(
338 app_.getValidations().getTrustedForLedger(
339 prevLedger->header().parentHash, prevLedger->seq() - 1));
340 if (validations.size() >= app_.validators().quorum())
341 {
342 feeVote_->doVoting(prevLedger, validations, initialSet);
343 app_.getAmendmentTable().doVoting(
344 prevLedger, validations, initialSet, j_);
345 }
346 }
347 else if (prevLedger->isVotingLedger())
348 {
349 // previous ledger was a voting ledger,
350 // so the current consensus session is for a flag ledger,
351 // add negative UNL pseudo-transactions
352 nUnlVote_.doVoting(
353 prevLedger,
354 app_.validators().getTrustedMasterKeys(),
355 app_.getValidations(),
356 initialSet);
357 }
358 }
359
360 // Now we need an immutable snapshot
361 initialSet = initialSet->snapShot(false);
362
363 if (!wrongLCL)
364 {
365 LedgerIndex const seq = prevLedger->header().seq + 1;
367
368 initialSet->visitLeaves(
369 [&proposed,
370 seq](boost::intrusive_ptr<SHAMapItem const> const& item) {
371 proposed.emplace_back(item->key(), seq);
372 });
373
374 censorshipDetector_.propose(std::move(proposed));
375 }
376
377 // Needed because of the move below.
378 auto const setHash = initialSet->getHash().as_uint256();
379
380 return Result{
381 std::move(initialSet),
383 initialLedger->header().parentHash,
385 setHash,
386 closeTime,
387 app_.timeKeeper().closeTime(),
388 validatorKeys_.nodeID}};
389}
390
391void
393 Result const& result,
394 RCLCxLedger const& prevLedger,
395 NetClock::duration const& closeResolution,
396 ConsensusCloseTimes const& rawCloseTimes,
397 ConsensusMode const& mode,
398 Json::Value&& consensusJson)
399{
400 doAccept(
401 result,
402 prevLedger,
403 closeResolution,
404 rawCloseTimes,
405 mode,
406 std::move(consensusJson));
407}
408
409void
411 Result const& result,
412 RCLCxLedger const& prevLedger,
413 NetClock::duration const& closeResolution,
414 ConsensusCloseTimes const& rawCloseTimes,
415 ConsensusMode const& mode,
416 Json::Value&& consensusJson,
417 bool const validating)
418{
419 app_.getJobQueue().addJob(
420 jtACCEPT,
421 "AcceptLedger",
422 [=, this, cj = std::move(consensusJson)]() mutable {
423 // Note that no lock is held or acquired during this job.
424 // This is because generic Consensus guarantees that once a ledger
425 // is accepted, the consensus results and capture by reference state
426 // will not change until startRound is called (which happens via
427 // endConsensus).
428 RclConsensusLogger clog("onAccept", validating, j_);
429 this->doAccept(
430 result,
431 prevLedger,
432 closeResolution,
433 rawCloseTimes,
434 mode,
435 std::move(cj));
436 this->app_.getOPs().endConsensus(clog.ss());
437 });
438}
439
440void
442 Result const& result,
443 RCLCxLedger const& prevLedger,
444 NetClock::duration closeResolution,
445 ConsensusCloseTimes const& rawCloseTimes,
446 ConsensusMode const& mode,
447 Json::Value&& consensusJson)
448{
449 prevProposers_ = result.proposers;
450 prevRoundTime_ = result.roundTime.read();
451
452 bool closeTimeCorrect;
453
455 bool const haveCorrectLCL = mode != ConsensusMode::wrongLedger;
456 bool const consensusFail = result.state == ConsensusState::MovedOn;
457
458 auto consensusCloseTime = result.position.closeTime();
459
460 if (consensusCloseTime == NetClock::time_point{})
461 {
462 // We agreed to disagree on the close time
463 using namespace std::chrono_literals;
464 consensusCloseTime = prevLedger.closeTime() + 1s;
465 closeTimeCorrect = false;
466 }
467 else
468 {
469 // We agreed on a close time
470 consensusCloseTime = effCloseTime(
471 consensusCloseTime, closeResolution, prevLedger.closeTime());
472 closeTimeCorrect = true;
473 }
474
475 JLOG(j_.debug()) << "Report: Prop=" << (proposing ? "yes" : "no")
476 << " val=" << (validating_ ? "yes" : "no")
477 << " corLCL=" << (haveCorrectLCL ? "yes" : "no")
478 << " fail=" << (consensusFail ? "yes" : "no");
479 JLOG(j_.debug()) << "Report: Prev = " << prevLedger.id() << ":"
480 << prevLedger.seq();
481
482 //--------------------------------------------------------------------------
483 std::set<TxID> failed;
484
485 // We want to put transactions in an unpredictable but deterministic order:
486 // we use the hash of the set.
487 //
488 // FIXME: Use a std::vector and a custom sorter instead of CanonicalTXSet?
489 CanonicalTXSet retriableTxs{result.txns.map_->getHash().as_uint256()};
490
491 JLOG(j_.debug()) << "Building canonical tx set: " << retriableTxs.key();
492
493 for (auto const& item : *result.txns.map_)
494 {
495 try
496 {
497 retriableTxs.insert(
499 JLOG(j_.debug()) << " Tx: " << item.key();
500 }
501 catch (std::exception const& ex)
502 {
503 failed.insert(item.key());
504 JLOG(j_.warn())
505 << " Tx: " << item.key() << " throws: " << ex.what();
506 }
507 }
508
509 auto built = buildLCL(
510 prevLedger,
511 retriableTxs,
512 consensusCloseTime,
513 closeTimeCorrect,
514 closeResolution,
515 result.roundTime.read(),
516 failed);
517
518 auto const newLCLHash = built.id();
519 JLOG(j_.debug()) << "Built ledger #" << built.seq() << ": " << newLCLHash;
520
521 // Tell directly connected peers that we have a new LCL
522 notify(protocol::neACCEPTED_LEDGER, built, haveCorrectLCL);
523
524 // As long as we're in sync with the network, attempt to detect attempts
525 // at censorship of transaction by tracking which ones don't make it in
526 // after a period of time.
527 if (haveCorrectLCL && result.state == ConsensusState::Yes)
528 {
530
531 result.txns.map_->visitLeaves(
532 [&accepted](boost::intrusive_ptr<SHAMapItem const> const& item) {
533 accepted.push_back(item->key());
534 });
535
536 // Track all the transactions which failed or were marked as retriable
537 for (auto const& r : retriableTxs)
538 failed.insert(r.first.getTXID());
539
540 censorshipDetector_.check(
541 std::move(accepted),
542 [curr = built.seq(),
543 j = app_.journal("CensorshipDetector"),
544 &failed](uint256 const& id, LedgerIndex seq) {
545 if (failed.count(id))
546 return true;
547
548 auto const wait = curr - seq;
549
550 if (wait && (wait % censorshipWarnInternal == 0))
551 {
553 ss << "Potential Censorship: Eligible tx " << id
554 << ", which we are tracking since ledger " << seq
555 << " has not been included as of ledger " << curr << ".";
556
557 JLOG(j.warn()) << ss.str();
558 }
559
560 return false;
561 });
562 }
563
564 if (validating_)
565 validating_ = ledgerMaster_.isCompatible(
566 *built.ledger_, j_.warn(), "Not validating");
567
568 if (validating_ && !consensusFail &&
569 app_.getValidations().canValidateSeq(built.seq()))
570 {
571 validate(built, result.txns, proposing);
572 JLOG(j_.info()) << "CNF Val " << newLCLHash;
573 }
574 else
575 JLOG(j_.info()) << "CNF buildLCL " << newLCLHash;
576
577 // See if we can accept a ledger as fully-validated
578 ledgerMaster_.consensusBuilt(
579 built.ledger_, result.txns.id(), std::move(consensusJson));
580
581 //-------------------------------------------------------------------------
582 {
583 // Apply disputed transactions that didn't get in
584 //
585 // The first crack of transactions to get into the new
586 // open ledger goes to transactions proposed by a validator
587 // we trust but not included in the consensus set.
588 //
589 // These are done first because they are the most likely
590 // to receive agreement during consensus. They are also
591 // ordered logically "sooner" than transactions not mentioned
592 // in the previous consensus round.
593 //
594 bool anyDisputes = false;
595 for (auto const& [_, dispute] : result.disputes)
596 {
597 (void)_;
598 if (!dispute.getOurVote())
599 {
600 // we voted NO
601 try
602 {
603 JLOG(j_.debug())
604 << "Test applying disputed transaction that did"
605 << " not get in " << dispute.tx().id();
606
607 SerialIter sit(dispute.tx().tx_->slice());
608 auto txn = std::make_shared<STTx const>(sit);
609
610 // Disputed pseudo-transactions that were not accepted
611 // can't be successfully applied in the next ledger
612 if (isPseudoTx(*txn))
613 continue;
614
615 retriableTxs.insert(txn);
616
617 anyDisputes = true;
618 }
619 catch (std::exception const& ex)
620 {
621 JLOG(j_.debug()) << "Failed to apply transaction we voted "
622 "NO on. Exception: "
623 << ex.what();
624 }
625 }
626 }
627
628 // Build new open ledger
629 std::unique_lock lock{app_.getMasterMutex(), std::defer_lock};
630 std::unique_lock sl{ledgerMaster_.peekMutex(), std::defer_lock};
631 std::lock(lock, sl);
632
633 auto const lastVal = ledgerMaster_.getValidatedLedger();
635 if (lastVal)
636 rules = makeRulesGivenLedger(*lastVal, app_.config().features);
637 else
638 rules.emplace(app_.config().features);
639 app_.openLedger().accept(
640 app_,
641 *rules,
642 built.ledger_,
643 localTxs_.getTxSet(),
644 anyDisputes,
645 retriableTxs,
646 tapNONE,
647 "consensus",
648 [&](OpenView& view, beast::Journal j) {
649 // Stuff the ledger with transactions from the queue.
650 return app_.getTxQ().accept(app_, view);
651 });
652
653 // Signal a potential fee change to subscribers after the open ledger
654 // is created
655 app_.getOPs().reportFeeChange();
656 }
657
658 //-------------------------------------------------------------------------
659 {
660 ledgerMaster_.switchLCL(built.ledger_);
661
662 // Do these need to exist?
663 XRPL_ASSERT(
664 ledgerMaster_.getClosedLedger()->header().hash == built.id(),
665 "xrpl::RCLConsensus::Adaptor::doAccept : ledger hash match");
666 XRPL_ASSERT(
667 app_.openLedger().current()->header().parentHash == built.id(),
668 "xrpl::RCLConsensus::Adaptor::doAccept : parent hash match");
669 }
670
671 //-------------------------------------------------------------------------
672 // we entered the round with the network,
673 // see how close our close time is to other node's
674 // close time reports, and update our clock.
677 !consensusFail)
678 {
679 auto closeTime = rawCloseTimes.self;
680
681 JLOG(j_.info()) << "We closed at "
682 << closeTime.time_since_epoch().count();
684 usec64_t closeTotal =
685 std::chrono::duration_cast<usec64_t>(closeTime.time_since_epoch());
686 int closeCount = 1;
687
688 for (auto const& [t, v] : rawCloseTimes.peers)
689 {
690 JLOG(j_.info()) << std::to_string(v) << " time votes for "
691 << std::to_string(t.time_since_epoch().count());
692 closeCount += v;
693 closeTotal +=
694 std::chrono::duration_cast<usec64_t>(t.time_since_epoch()) * v;
695 }
696
697 closeTotal += usec64_t(closeCount / 2); // for round to nearest
698 closeTotal /= closeCount;
699
700 // Use signed times since we are subtracting
703 auto offset = time_point{closeTotal} -
704 std::chrono::time_point_cast<duration>(closeTime);
705 JLOG(j_.info()) << "Our close offset is estimated at " << offset.count()
706 << " (" << closeCount << ")";
707
708 app_.timeKeeper().adjustCloseTime(offset);
709 }
710}
711
712void
714 protocol::NodeEvent ne,
715 RCLCxLedger const& ledger,
716 bool haveCorrectLCL)
717{
718 protocol::TMStatusChange s;
719
720 if (!haveCorrectLCL)
721 s.set_newevent(protocol::neLOST_SYNC);
722 else
723 s.set_newevent(ne);
724
725 s.set_ledgerseq(ledger.seq());
726 s.set_networktime(app_.timeKeeper().now().time_since_epoch().count());
727 s.set_ledgerhashprevious(
728 ledger.parentID().begin(),
729 std::decay_t<decltype(ledger.parentID())>::bytes);
730 s.set_ledgerhash(
731 ledger.id().begin(), std::decay_t<decltype(ledger.id())>::bytes);
732
733 std::uint32_t uMin, uMax;
734 if (!ledgerMaster_.getFullValidatedRange(uMin, uMax))
735 {
736 uMin = 0;
737 uMax = 0;
738 }
739 else
740 {
741 // Don't advertise ledgers we're not willing to serve
742 uMin = std::max(uMin, ledgerMaster_.getEarliestFetch());
743 }
744 s.set_firstseq(uMin);
745 s.set_lastseq(uMax);
746 app_.overlay().foreach(
747 send_always(std::make_shared<Message>(s, protocol::mtSTATUS_CHANGE)));
748 JLOG(j_.trace()) << "send status change to peer";
749}
750
753 RCLCxLedger const& previousLedger,
754 CanonicalTXSet& retriableTxs,
755 NetClock::time_point closeTime,
756 bool closeTimeCorrect,
757 NetClock::duration closeResolution,
759 std::set<TxID>& failedTxs)
760{
761 std::shared_ptr<Ledger> built = [&]() {
762 if (auto const replayData = ledgerMaster_.releaseReplay())
763 {
764 XRPL_ASSERT(
765 replayData->parent()->header().hash == previousLedger.id(),
766 "xrpl::RCLConsensus::Adaptor::buildLCL : parent hash match");
767 return buildLedger(*replayData, tapNONE, app_, j_);
768 }
769 return buildLedger(
770 previousLedger.ledger_,
771 closeTime,
772 closeTimeCorrect,
773 closeResolution,
774 app_,
775 retriableTxs,
776 failedTxs,
777 j_);
778 }();
779
780 // Update fee computations based on accepted txs
781 using namespace std::chrono_literals;
782 app_.getTxQ().processClosedLedger(app_, *built, roundTime > 5s);
783
784 // And stash the ledger in the ledger master
785 if (ledgerMaster_.storeLedger(built))
786 JLOG(j_.debug()) << "Consensus built ledger we already had";
787 else if (app_.getInboundLedgers().find(built->header().hash))
788 JLOG(j_.debug()) << "Consensus built ledger we were acquiring";
789 else
790 JLOG(j_.debug()) << "Consensus built new ledger";
791 return RCLCxLedger{std::move(built)};
792}
793
794void
796 RCLCxLedger const& ledger,
797 RCLTxSet const& txns,
798 bool proposing)
799{
800 using namespace std::chrono_literals;
801
802 auto validationTime = app_.timeKeeper().closeTime();
803 if (validationTime <= lastValidationTime_)
804 validationTime = lastValidationTime_ + 1s;
805 lastValidationTime_ = validationTime;
806
807 if (!validatorKeys_.keys)
808 {
809 JLOG(j_.warn()) << "RCLConsensus::Adaptor::validate: ValidatorKeys "
810 "not set\n";
811 return;
812 }
813
814 auto const& keys = *validatorKeys_.keys;
815
817 lastValidationTime_,
818 keys.publicKey,
819 keys.secretKey,
820 validatorKeys_.nodeID,
821 [&](STValidation& v) {
822 v.setFieldH256(sfLedgerHash, ledger.id());
823 v.setFieldH256(sfConsensusHash, txns.id());
824
825 v.setFieldU32(sfLedgerSequence, ledger.seq());
826
827 if (proposing)
828 v.setFlag(vfFullValidation);
829
830 // Attest to the hash of what we consider to be the last fully
831 // validated ledger. This may be the hash of the ledger we are
832 // validating here, and that's fine.
833 if (auto const vl = ledgerMaster_.getValidatedLedger())
834 v.setFieldH256(sfValidatedHash, vl->header().hash);
835
836 v.setFieldU64(sfCookie, valCookie_);
837
838 // Report our server version every flag ledger:
839 if (ledger.ledger_->isVotingLedger())
840 v.setFieldU64(sfServerVersion, BuildInfo::getEncodedVersion());
841
842 // Report our load
843 {
844 auto const& ft = app_.getFeeTrack();
845 auto const fee = std::max(ft.getLocalFee(), ft.getClusterFee());
846 if (fee > ft.getLoadBase())
847 v.setFieldU32(sfLoadFee, fee);
848 }
849
850 // If the next ledger is a flag ledger, suggest fee changes and
851 // new features:
852 if (ledger.ledger_->isVotingLedger())
853 {
854 // Fees:
855 feeVote_->doValidation(
856 ledger.ledger_->fees(), ledger.ledger_->rules(), v);
857
858 // Amendments
859 // FIXME: pass `v` and have the function insert the array
860 // directly?
861 auto const amendments = app_.getAmendmentTable().doValidation(
862 getEnabledAmendments(*ledger.ledger_));
863
864 if (!amendments.empty())
865 v.setFieldV256(
866 sfAmendments, STVector256(sfAmendments, amendments));
867 }
868 });
869
870 auto const serialized = v->getSerialized();
871
872 // suppress it if we receive it
873 app_.getHashRouter().addSuppression(sha512Half(makeSlice(serialized)));
874
875 handleNewValidation(app_, v, "local");
876
877 // Broadcast to all our peers:
878 protocol::TMValidation val;
879 val.set_validation(serialized.data(), serialized.size());
880 app_.overlay().broadcast(val);
881
882 // Publish to all our subscribers:
883 app_.getOPs().pubValidation(v);
884}
885
886void
888{
889 JLOG(j_.info()) << "Consensus mode change before=" << to_string(before)
890 << ", after=" << to_string(after);
891
892 // If we were proposing but aren't any longer, we need to reset the
893 // censorship tracking to avoid bogus warnings.
894 if ((before == ConsensusMode::proposing ||
895 before == ConsensusMode::observing) &&
896 before != after)
897 censorshipDetector_.reset();
898
899 mode_ = after;
900}
901
904{
905 Json::Value ret;
906 {
908 ret = consensus_.getJson(full);
909 }
910 ret["validating"] = adaptor_.validating();
911 return ret;
912}
913
914void
916 NetClock::time_point const& now,
918{
919 try
920 {
922 consensus_.timerEntry(now, clog);
923 }
924 catch (SHAMapMissingNode const& mn)
925 {
926 // This should never happen
928 ss << "During consensus timerEntry: " << mn.what();
929 JLOG(j_.error()) << ss.str();
930 CLOG(clog) << ss.str();
931 Rethrow();
932 }
933}
934
935void
937{
938 try
939 {
941 consensus_.gotTxSet(now, txSet);
942 }
943 catch (SHAMapMissingNode const& mn)
944 {
945 // This should never happen
946 JLOG(j_.error()) << "During consensus gotTxSet: " << mn.what();
947 Rethrow();
948 }
949}
950
952
953void
955 NetClock::time_point const& now,
957{
959 consensus_.simulate(now, consensusDelay);
960}
961
962bool
964 NetClock::time_point const& now,
965 RCLCxPeerPos const& newProposal)
966{
968 return consensus_.peerProposal(now, newProposal);
969}
970
971bool
973 RCLCxLedger const& prevLgr,
974 hash_set<NodeID> const& nowTrusted)
975{
976 // We have a key, we do not want out of sync validations after a restart
977 // and are not amendment blocked.
978 validating_ = validatorKeys_.keys &&
979 prevLgr.seq() >= app_.getMaxDisallowedLedger() &&
980 !app_.getOPs().isBlocked();
981
982 // If we are not running in standalone mode and there's a configured UNL,
983 // check to make sure that it's not expired.
984 if (validating_ && !app_.config().standalone() && app_.validators().count())
985 {
986 auto const when = app_.validators().expires();
987
988 if (!when || *when < app_.timeKeeper().now())
989 {
990 JLOG(j_.error()) << "Voluntarily bowing out of consensus process "
991 "because of an expired validator list.";
992 validating_ = false;
993 }
994 }
995
996 bool const synced = app_.getOPs().getOperatingMode() == OperatingMode::FULL;
997
998 if (validating_)
999 {
1000 JLOG(j_.info()) << "Entering consensus process, validating, synced="
1001 << (synced ? "yes" : "no");
1002 }
1003 else
1004 {
1005 // Otherwise we just want to monitor the validation process.
1006 JLOG(j_.info()) << "Entering consensus process, watching, synced="
1007 << (synced ? "yes" : "no");
1008 }
1009
1010 // Notify inbound ledgers that we are starting a new round
1011 inboundTransactions_.newRound(prevLgr.seq());
1012
1013 // Notify NegativeUNLVote that new validators are added
1014 if (!nowTrusted.empty())
1015 nUnlVote_.newValidators(prevLgr.seq() + 1, nowTrusted);
1016
1017 // propose only if we're in sync with the network (and validating)
1018 return validating_ && synced;
1019}
1020
1021bool
1023{
1024 return ledgerMaster_.haveValidated();
1025}
1026
1029{
1030 return ledgerMaster_.getValidLedgerIndex();
1031}
1032
1035{
1036 return app_.validators().getQuorumKeys();
1037}
1038
1041 Ledger_t::Seq const seq,
1043{
1044 return app_.getValidations().laggards(seq, trustedKeys);
1045}
1046
1047bool
1049{
1050 return validatorKeys_.keys.has_value();
1051}
1052
1053void
1055{
1056 if (!positions && app_.getOPs().isFull())
1057 app_.getOPs().setMode(OperatingMode::CONNECTED);
1058}
1059
1060void
1062 NetClock::time_point const& now,
1063 RCLCxLedger::ID const& prevLgrId,
1064 RCLCxLedger const& prevLgr,
1065 hash_set<NodeID> const& nowUntrusted,
1066 hash_set<NodeID> const& nowTrusted,
1068{
1070 consensus_.startRound(
1071 now,
1072 prevLgrId,
1073 prevLgr,
1074 nowUntrusted,
1075 adaptor_.preStartRound(prevLgr, nowTrusted),
1076 clog);
1077}
1078
1080 char const* label,
1081 bool const validating,
1083 : j_(j)
1084{
1085 if (!validating && !j.info())
1086 return;
1089 header_ = "ConsensusLogger ";
1090 header_ += label;
1091 header_ += ": ";
1092}
1093
1095{
1096 if (!ss_)
1097 return;
1098 auto const duration = std::chrono::duration_cast<std::chrono::milliseconds>(
1100 std::stringstream outSs;
1101 outSs << header_ << "duration " << (duration.count() / 1000) << '.'
1102 << std::setw(3) << std::setfill('0') << (duration.count() % 1000)
1103 << "s. " << ss_->str();
1105}
1106
1107} // namespace xrpl
Decorator for streaming out compact json.
Represents a JSON value.
Definition json_value.h:131
virtual void writeAlways(Severity level, std::string const &text)=0
Bypass filter and write text to the sink at the specified severity.
A generic endpoint for log messages.
Definition Journal.h:41
Stream error() const
Definition Journal.h:327
Stream debug() const
Definition Journal.h:309
Sink & sink() const
Returns the Sink associated with this Journal.
Definition Journal.h:278
Stream info() const
Definition Journal.h:315
Stream trace() const
Severity stream access functions.
Definition Journal.h:303
Stream warn() const
Definition Journal.h:321
Holds transactions which were deferred to the next pass of consensus.
NetClock::time_point const & closeTime() const
The current position on the consensus close time.
std::chrono::milliseconds read() const
Manages the acquisition and lifetime of transaction sets.
Writable ledger view that accumulates state and tx changes.
Definition OpenView.h:46
Slice slice() const noexcept
Definition PublicKey.h:104
Result onClose(RCLCxLedger const &ledger, NetClock::time_point const &closeTime, ConsensusMode mode)
Close the open ledger and return initial consensus position.
bool preStartRound(RCLCxLedger const &prevLedger, hash_set< NodeID > const &nowTrusted)
Called before kicking off a new consensus round.
bool validator() const
Whether I am a validator.
LedgerIndex getValidLedgerIndex() const
Adaptor(Application &app, std::unique_ptr< FeeVote > &&feeVote, LedgerMaster &ledgerMaster, LocalTxs &localTxs, InboundTransactions &inboundTransactions, ValidatorKeys const &validatorKeys, beast::Journal journal)
void updateOperatingMode(std::size_t const positions) const
Update operating mode based on current peer positions.
std::size_t proposersFinished(RCLCxLedger const &ledger, LedgerHash const &h) const
Number of proposers that have validated a ledger descended from requested ledger.
void validate(RCLCxLedger const &ledger, RCLTxSet const &txns, bool proposing)
Validate the given ledger and share with peers as necessary.
void doAccept(Result const &result, RCLCxLedger const &prevLedger, NetClock::duration closeResolution, ConsensusCloseTimes const &rawCloseTimes, ConsensusMode const &mode, Json::Value &&consensusJson)
Accept a new ledger based on the given transactions.
void propose(RCLCxPeerPos::Proposal const &proposal)
Propose the given position to my peers.
RCLCxLedger buildLCL(RCLCxLedger const &previousLedger, CanonicalTXSet &retriableTxs, NetClock::time_point closeTime, bool closeTimeCorrect, NetClock::duration closeResolution, std::chrono::milliseconds roundTime, std::set< TxID > &failedTxs)
Build the new last closed ledger.
std::size_t proposersValidated(LedgerHash const &h) const
Number of proposers that have validated the given ledger.
void notify(protocol::NodeEvent ne, RCLCxLedger const &ledger, bool haveCorrectLCL)
Notify peers of a consensus state change.
void onAccept(Result const &result, RCLCxLedger const &prevLedger, NetClock::duration const &closeResolution, ConsensusCloseTimes const &rawCloseTimes, ConsensusMode const &mode, Json::Value &&consensusJson, bool const validating)
Process the accepted ledger.
std::atomic< ConsensusMode > mode_
std::pair< std::size_t, hash_set< NodeKey_t > > getQuorumKeys() const
std::optional< RCLTxSet > acquireTxSet(RCLTxSet::ID const &setId)
Acquire the transaction set associated with a proposal.
ValidatorKeys const & validatorKeys_
uint256 getPrevLedger(uint256 ledgerID, RCLCxLedger const &ledger, ConsensusMode mode)
Get the ID of the previous ledger/last closed ledger(LCL) on the network.
beast::Journal const j_
std::size_t laggards(Ledger_t::Seq const seq, hash_set< NodeKey_t > &trustedKeys) const
void onForceAccept(Result const &result, RCLCxLedger const &prevLedger, NetClock::duration const &closeResolution, ConsensusCloseTimes const &rawCloseTimes, ConsensusMode const &mode, Json::Value &&consensusJson)
Process the accepted ledger that was a result of simulation/force accept.
std::optional< RCLCxLedger > acquireLedger(LedgerHash const &hash)
Attempt to acquire a specific ledger.
bool hasOpenTransactions() const
Whether the open ledger has any transactions.
RCLCensorshipDetector< TxID, LedgerIndex > censorshipDetector_
void onModeChange(ConsensusMode before, ConsensusMode after)
Notified of change in consensus mode.
std::uint64_t const valCookie_
void share(RCLCxPeerPos const &peerPos)
Share the given proposal with all peers.
Consensus< Adaptor > consensus_
void timerEntry(NetClock::time_point const &now, std::unique_ptr< std::stringstream > const &clog={})
void startRound(NetClock::time_point const &now, RCLCxLedger::ID const &prevLgrId, RCLCxLedger const &prevLgr, hash_set< NodeID > const &nowUntrusted, hash_set< NodeID > const &nowTrusted, std::unique_ptr< std::stringstream > const &clog)
Adjust the set of trusted validators and kick-off the next round of consensus.
bool validating() const
Whether we are validating consensus ledgers.
beast::Journal const j_
bool peerProposal(NetClock::time_point const &now, RCLCxPeerPos const &newProposal)
void simulate(NetClock::time_point const &now, std::optional< std::chrono::milliseconds > consensusDelay)
Json::Value getJson(bool full) const
std::recursive_mutex mutex_
static constexpr unsigned int censorshipWarnInternal
Warn for transactions that haven't been included every so many ledgers.
RCLConsensus(Application &app, std::unique_ptr< FeeVote > &&feeVote, LedgerMaster &ledgerMaster, LocalTxs &localTxs, InboundTransactions &inboundTransactions, Consensus< Adaptor >::clock_type const &clock, ValidatorKeys const &validatorKeys, beast::Journal journal)
Constructor.
ConsensusMode mode() const
void gotTxSet(NetClock::time_point const &now, RCLTxSet const &txSet)
Represents a ledger in RCLConsensus.
Definition RCLCxLedger.h:17
std::shared_ptr< Ledger const > ledger_
The ledger instance.
Seq const & seq() const
Sequence number of the ledger.
Definition RCLCxLedger.h:42
ID const & parentID() const
Unique identifier (hash) of this ledger's parent.
Definition RCLCxLedger.h:56
ID const & id() const
Unique identifier (hash) of this ledger.
Definition RCLCxLedger.h:49
NetClock::time_point closeTime() const
The close time of this ledger.
Definition RCLCxLedger.h:77
A peer's signed, proposed position for use in RCLConsensus.
uint256 const & suppressionID() const
Unique id used by hash router to suppress duplicates.
PublicKey const & publicKey() const
Public key of peer that sent the proposal.
Slice signature() const
Signature of the proposal (not necessarily verified)
Proposal const & proposal() const
Represents a transaction in RCLConsensus.
Definition RCLCxTx.h:14
boost::intrusive_ptr< SHAMapItem const > tx_
The SHAMapItem that represents the transaction.
Definition RCLCxTx.h:35
ID const & id() const
The unique identifier/hash of the transaction.
Definition RCLCxTx.h:29
Represents a set of transactions in RCLConsensus.
Definition RCLCxTx.h:44
std::shared_ptr< SHAMap > map_
The SHAMap representing the transactions.
Definition RCLCxTx.h:169
ID id() const
The unique ID/hash of the transaction set.
Definition RCLCxTx.h:134
Wraps a ledger instance for use in generic Validations LedgerTrie.
beast::Journal journal() const
Collects logging information.
std::unique_ptr< std::stringstream > const & ss()
std::chrono::steady_clock::time_point start_
RclConsensusLogger(char const *label, bool validating, beast::Journal j)
std::unique_ptr< std::stringstream > ss_
Slice slice() const noexcept
Definition Serializer.h:47
std::size_t getNodesAfter(Ledger const &ledger, ID const &ledgerID)
Count the number of current trusted validators working on a ledger after the specified one.
Adaptor const & adaptor() const
Return the adaptor instance.
std::optional< std::pair< Seq, ID > > getPreferred(Ledger const &curr)
Return the sequence number and ID of the preferred working ledger.
Validator keys and manifest as set in configuration file.
std::uint32_t sequence
std::optional< Keys > keys
iterator begin()
Definition base_uint.h:117
T count(T... args)
T emplace_back(T... args)
T emplace(T... args)
T empty(T... args)
T insert(T... args)
T is_same_v
T lock(T... args)
T max(T... args)
STL namespace.
Use hash_* containers for keys that do not need a cryptographically secure hashing algorithm.
Definition algorithm.h:6
std::chrono::time_point< Clock, Duration > effCloseTime(std::chrono::time_point< Clock, Duration > closeTime, std::chrono::duration< Rep, Period > resolution, std::chrono::time_point< Clock, Duration > priorCloseTime)
Calculate the effective ledger close time.
ConsensusMode
Represents how a node currently participates in Consensus.
@ wrongLedger
We have the wrong ledger and are attempting to acquire it.
@ proposing
We are normal participant in consensus and propose our position.
@ observing
We are observing peer positions, but not proposing our position.
csprng_engine & crypto_prng()
The default cryptographically secure PRNG.
boost::intrusive_ptr< SHAMapItem > make_shamapitem(uint256 const &tag, Slice data)
Definition SHAMapItem.h:142
sha512_half_hasher::result_type sha512Half(Args const &... args)
Returns the SHA512-Half of a series of objects.
Definition digest.h:205
std::string to_string(base_uint< Bits, Tag > const &a)
Definition base_uint.h:611
Rules makeRulesGivenLedger(DigestAwareReadView const &ledger, Rules const &current)
Definition ReadView.cpp:50
std::string toBase58(AccountID const &v)
Convert AccountID to base58 checked string.
Definition AccountID.cpp:95
std::enable_if_t< std::is_integral< Integral >::value, Integral > rand_int()
@ MovedOn
The network has consensus without us.
@ Yes
We have consensus along with the network.
@ jtACCEPT
Definition Job.h:53
@ jtADVANCE
Definition Job.h:47
bool after(NetClock::time_point now, std::uint32_t mark)
Has the specified time passed?
Definition View.cpp:3923
std::shared_ptr< Ledger > buildLedger(std::shared_ptr< Ledger const > const &parent, NetClock::time_point closeTime, bool const closeTimeCorrect, NetClock::duration closeResolution, Application &app, CanonicalTXSet &txns, std::set< TxID > &failedTxs, beast::Journal j)
Build a new ledger by applying consensus transactions.
Buffer signDigest(PublicKey const &pk, SecretKey const &sk, uint256 const &digest)
Generate a signature for a message digest.
@ tapNONE
Definition ApplyView.h:12
@ ledgerMaster
ledger master data for signing
@ proposal
proposal for signing
uint256 proposalUniqueId(uint256 const &proposeHash, uint256 const &previousLedger, std::uint32_t proposeSeq, NetClock::time_point closeTime, Slice const &publicKey, Slice const &signature)
Calculate a unique identifier for a signed proposal.
void handleNewValidation(Application &app, std::shared_ptr< STValidation > const &val, std::string const &source, BypassAccept const bypassAccept, std::optional< beast::Journal > j)
Handle a new validation.
void Rethrow()
Rethrow the exception currently being handled.
Definition contract.h:29
std::enable_if_t< std::is_same< T, char >::value||std::is_same< T, unsigned char >::value, Slice > makeSlice(std::array< T, N > const &a)
Definition Slice.h:225
@ CONNECTED
convinced we are talking to the network
@ FULL
we have the ledger and can even validate
bool isPseudoTx(STObject const &tx)
Check whether a transaction is a pseudo-transaction.
Definition STTx.cpp:810
@ accepted
Manifest is valid.
T setfill(T... args)
T setw(T... args)
T str(T... args)
Stores the set of initial close times.
NetClock::time_point self
Our close time estimate.
std::map< NetClock::time_point, int > peers
Close time estimates, keep ordered for predictable traverse.
Encapsulates the result of consensus.
TxSet_t txns
The set of transactions consensus agrees go in the ledger.
hash_map< typename Tx_t::ID, Dispute_t > disputes
Transactions which are under dispute with our peers.
ConsensusTimer roundTime
Proposal_t position
Our proposed position on transactions/close time.
Sends a message to all peers.
Definition predicates.h:13
T to_string(T... args)
T what(T... args)