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