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_(app, std::move(feeVote), ledgerMaster, localTxs, inboundTransactions, validatorKeys, journal)
45 , consensus_(clock, adaptor_, journal)
46 , j_(journal)
47{
48}
49
51 Application& app,
54 LocalTxs& localTxs,
55 InboundTransactions& inboundTransactions,
56 ValidatorKeys const& validatorKeys,
57 beast::Journal journal)
58 : app_(app)
59 , feeVote_(std::move(feeVote))
60 , ledgerMaster_(ledgerMaster)
61 , localTxs_(localTxs)
62 , inboundTransactions_{inboundTransactions}
63 , j_(journal)
64 , validatorKeys_(validatorKeys)
65 , valCookie_(1 + rand_int(crypto_prng(), std::numeric_limits<std::uint64_t>::max() - 1))
66 , nUnlVote_(validatorKeys_.nodeID, j_)
67{
68 XRPL_ASSERT(valCookie_, "xrpl::RCLConsensus::Adaptor::Adaptor : nonzero cookie");
69
70 JLOG(j_.info()) << "Consensus engine started (cookie: " + std::to_string(valCookie_) + ")";
71
72 if (validatorKeys_.nodeID != beast::zero && validatorKeys_.keys)
73 {
75
76 JLOG(j_.info()) << "Validator identity: "
78
79 if (validatorKeys_.keys->masterPublicKey != validatorKeys_.keys->publicKey)
80 {
81 JLOG(j_.debug()) << "Validator ephemeral signing key: "
83 << " (seq: " << std::to_string(validatorKeys_.sequence) << ")";
84 }
85 }
86}
87
90{
91 // we need to switch the ledger we're working from
92 auto built = ledgerMaster_.getLedgerByHash(hash);
93 if (!built)
94 {
95 if (acquiringLedger_ != hash)
96 {
97 // need to start acquiring the correct consensus LCL
98 JLOG(j_.warn()) << "Need consensus ledger " << hash;
99
100 // Tell the ledger acquire system that we need the consensus ledger
101 acquiringLedger_ = hash;
102
103 app_.getJobQueue().addJob(jtADVANCE, "GetConsL1", [id = hash, &app = app_, this]() {
104 JLOG(j_.debug()) << "JOB advanceLedger getConsensusLedger1 started";
105 app.getInboundLedgers().acquireAsync(id, 0, InboundLedger::Reason::CONSENSUS);
106 });
107 }
108 return std::nullopt;
109 }
110
111 XRPL_ASSERT(
112 !built->open() && built->isImmutable(), "xrpl::RCLConsensus::Adaptor::acquireLedger : valid ledger state");
113 XRPL_ASSERT(built->header().hash == hash, "xrpl::RCLConsensus::Adaptor::acquireLedger : ledger hash match");
114
115 // Notify inbound transactions of the new ledger sequence number
116 inboundTransactions_.newRound(built->header().seq);
117
118 return RCLCxLedger(built);
119}
120
121void
123{
124 protocol::TMProposeSet prop;
125
126 auto const& proposal = peerPos.proposal();
127
128 prop.set_proposeseq(proposal.proposeSeq());
129 prop.set_closetime(proposal.closeTime().time_since_epoch().count());
130
131 prop.set_currenttxhash(proposal.position().begin(), proposal.position().size());
132 prop.set_previousledger(proposal.prevLedger().begin(), proposal.position().size());
133
134 auto const pk = peerPos.publicKey().slice();
135 prop.set_nodepubkey(pk.data(), pk.size());
136
137 auto const sig = peerPos.signature();
138 prop.set_signature(sig.data(), sig.size());
139
140 app_.overlay().relay(prop, peerPos.suppressionID(), peerPos.publicKey());
141}
142
143void
145{
146 // If we didn't relay this transaction recently, relay it to all peers
147 if (app_.getHashRouter().shouldRelay(tx.id()))
148 {
149 JLOG(j_.debug()) << "Relaying disputed tx " << tx.id();
150 auto const slice = tx.tx_->slice();
151 protocol::TMTransaction msg;
152 msg.set_rawtransaction(slice.data(), slice.size());
153 msg.set_status(protocol::tsNEW);
154 msg.set_receivetimestamp(app_.timeKeeper().now().time_since_epoch().count());
155 static std::set<Peer::id_t> skip{};
156 app_.overlay().relay(tx.id(), msg, skip);
157 }
158 else
159 {
160 JLOG(j_.debug()) << "Not relaying disputed tx " << tx.id();
161 }
162}
163void
165{
166 JLOG(j_.trace()) << (proposal.isBowOut() ? "We bow out: " : "We propose: ")
167 << xrpl::to_string(proposal.prevLedger()) << " -> " << xrpl::to_string(proposal.position());
168
169 protocol::TMProposeSet prop;
170
171 prop.set_currenttxhash(proposal.position().begin(), proposal.position().size());
172 prop.set_previousledger(proposal.prevLedger().begin(), proposal.prevLedger().size());
173 prop.set_proposeseq(proposal.proposeSeq());
174 prop.set_closetime(proposal.closeTime().time_since_epoch().count());
175
176 if (!validatorKeys_.keys)
177 {
178 JLOG(j_.warn()) << "RCLConsensus::Adaptor::propose: ValidatorKeys "
179 "not set: \n";
180 return;
181 }
182
183 auto const& keys = *validatorKeys_.keys;
184
185 prop.set_nodepubkey(keys.publicKey.data(), keys.publicKey.size());
186
187 auto sig = signDigest(keys.publicKey, keys.secretKey, proposal.signingHash());
188
189 prop.set_signature(sig.data(), sig.size());
190
191 auto const suppression = proposalUniqueId(
192 proposal.position(), proposal.prevLedger(), proposal.proposeSeq(), proposal.closeTime(), keys.publicKey, sig);
193
194 app_.getHashRouter().addSuppression(suppression);
195
196 app_.overlay().broadcast(prop);
197}
198
199void
201{
202 inboundTransactions_.giveSet(txns.id(), txns.map_, false);
203}
204
207{
208 if (auto txns = inboundTransactions_.getSet(setId, true))
209 {
210 return RCLTxSet{std::move(txns)};
211 }
212 return std::nullopt;
213}
214
215bool
217{
218 return !app_.openLedger().empty();
219}
220
223{
224 return app_.getValidations().numTrustedForLedger(h);
225}
226
229{
230 RCLValidations& vals = app_.getValidations();
231 return vals.getNodesAfter(RCLValidatedLedger(ledger.ledger_, vals.adaptor().journal()), h);
232}
233
236{
237 RCLValidations& vals = app_.getValidations();
238 uint256 netLgr = vals.getPreferred(
239 RCLValidatedLedger{ledger.ledger_, vals.adaptor().journal()}, ledgerMaster_.getValidLedgerIndex());
240
241 if (netLgr != ledgerID)
242 {
244 app_.getOPs().consensusViewChange();
245
246 JLOG(j_.debug()) << Json::Compact(app_.getValidations().getJsonTrie());
247 }
248
249 return netLgr;
250}
251
252auto
254 -> Result
255{
256 bool const wrongLCL = mode == ConsensusMode::wrongLedger;
258
259 notify(protocol::neCLOSING_LEDGER, ledger, !wrongLCL);
260
261 auto const& prevLedger = ledger.ledger_;
262
263 ledgerMaster_.applyHeldTransactions();
264 // Tell the ledger master not to acquire the ledger we're probably building
265 ledgerMaster_.setBuildingLedger(prevLedger->header().seq + 1);
266
267 auto initialLedger = app_.openLedger().current();
268
269 auto initialSet = std::make_shared<SHAMap>(SHAMapType::TRANSACTION, app_.getNodeFamily());
270 initialSet->setUnbacked();
271
272 // Build SHAMap containing all transactions in our open ledger
273 for (auto const& tx : initialLedger->txs)
274 {
275 JLOG(j_.trace()) << "Adding open ledger TX " << tx.first->getTransactionID();
276 Serializer s(2048);
277 tx.first->add(s);
278 initialSet->addItem(SHAMapNodeType::tnTRANSACTION_NM, make_shamapitem(tx.first->getTransactionID(), s.slice()));
279 }
280
281 // Add pseudo-transactions to the set
282 if (app_.config().standalone() || (proposing && !wrongLCL))
283 {
284 if (prevLedger->isFlagLedger())
285 {
286 // previous ledger was flag ledger, add fee and amendment
287 // pseudo-transactions
288 auto validations = app_.validators().negativeUNLFilter(
289 app_.getValidations().getTrustedForLedger(prevLedger->header().parentHash, prevLedger->seq() - 1));
290 if (validations.size() >= app_.validators().quorum())
291 {
292 feeVote_->doVoting(prevLedger, validations, initialSet);
293 app_.getAmendmentTable().doVoting(prevLedger, validations, initialSet, j_);
294 }
295 }
296 else if (prevLedger->isVotingLedger())
297 {
298 // previous ledger was a voting ledger,
299 // so the current consensus session is for a flag ledger,
300 // add negative UNL pseudo-transactions
301 nUnlVote_.doVoting(prevLedger, app_.validators().getTrustedMasterKeys(), app_.getValidations(), initialSet);
302 }
303 }
304
305 // Now we need an immutable snapshot
306 initialSet = initialSet->snapShot(false);
307
308 if (!wrongLCL)
309 {
310 LedgerIndex const seq = prevLedger->header().seq + 1;
312
313 initialSet->visitLeaves([&proposed, seq](boost::intrusive_ptr<SHAMapItem const> const& item) {
314 proposed.emplace_back(item->key(), seq);
315 });
316
317 censorshipDetector_.propose(std::move(proposed));
318 }
319
320 // Needed because of the move below.
321 auto const setHash = initialSet->getHash().as_uint256();
322
323 return Result{
324 std::move(initialSet),
326 initialLedger->header().parentHash,
328 setHash,
329 closeTime,
330 app_.timeKeeper().closeTime(),
331 validatorKeys_.nodeID}};
332}
333
334void
336 Result const& result,
337 RCLCxLedger const& prevLedger,
338 NetClock::duration const& closeResolution,
339 ConsensusCloseTimes const& rawCloseTimes,
340 ConsensusMode const& mode,
341 Json::Value&& consensusJson)
342{
343 doAccept(result, prevLedger, closeResolution, rawCloseTimes, mode, std::move(consensusJson));
344}
345
346void
348 Result const& result,
349 RCLCxLedger const& prevLedger,
350 NetClock::duration const& closeResolution,
351 ConsensusCloseTimes const& rawCloseTimes,
352 ConsensusMode const& mode,
353 Json::Value&& consensusJson,
354 bool const validating)
355{
356 app_.getJobQueue().addJob(jtACCEPT, "AcceptLedger", [=, this, cj = std::move(consensusJson)]() mutable {
357 // Note that no lock is held or acquired during this job.
358 // This is because generic Consensus guarantees that once a ledger
359 // is accepted, the consensus results and capture by reference state
360 // will not change until startRound is called (which happens via
361 // endConsensus).
362 RclConsensusLogger clog("onAccept", validating, j_);
363 this->doAccept(result, prevLedger, closeResolution, rawCloseTimes, mode, std::move(cj));
364 this->app_.getOPs().endConsensus(clog.ss());
365 });
366}
367
368void
370 Result const& result,
371 RCLCxLedger const& prevLedger,
372 NetClock::duration closeResolution,
373 ConsensusCloseTimes const& rawCloseTimes,
374 ConsensusMode const& mode,
375 Json::Value&& consensusJson)
376{
377 prevProposers_ = result.proposers;
378 prevRoundTime_ = result.roundTime.read();
379
380 bool closeTimeCorrect;
381
383 bool const haveCorrectLCL = mode != ConsensusMode::wrongLedger;
384 bool const consensusFail = result.state == ConsensusState::MovedOn;
385
386 auto consensusCloseTime = result.position.closeTime();
387
388 if (consensusCloseTime == NetClock::time_point{})
389 {
390 // We agreed to disagree on the close time
391 using namespace std::chrono_literals;
392 consensusCloseTime = prevLedger.closeTime() + 1s;
393 closeTimeCorrect = false;
394 }
395 else
396 {
397 // We agreed on a close time
398 consensusCloseTime = effCloseTime(consensusCloseTime, closeResolution, prevLedger.closeTime());
399 closeTimeCorrect = true;
400 }
401
402 JLOG(j_.debug()) << "Report: Prop=" << (proposing ? "yes" : "no") << " val=" << (validating_ ? "yes" : "no")
403 << " corLCL=" << (haveCorrectLCL ? "yes" : "no") << " fail=" << (consensusFail ? "yes" : "no");
404 JLOG(j_.debug()) << "Report: Prev = " << prevLedger.id() << ":" << prevLedger.seq();
405
406 //--------------------------------------------------------------------------
407 std::set<TxID> failed;
408
409 // We want to put transactions in an unpredictable but deterministic order:
410 // we use the hash of the set.
411 //
412 // FIXME: Use a std::vector and a custom sorter instead of CanonicalTXSet?
413 CanonicalTXSet retriableTxs{result.txns.map_->getHash().as_uint256()};
414
415 JLOG(j_.debug()) << "Building canonical tx set: " << retriableTxs.key();
416
417 for (auto const& item : *result.txns.map_)
418 {
419 try
420 {
421 retriableTxs.insert(std::make_shared<STTx const>(SerialIter{item.slice()}));
422 JLOG(j_.debug()) << " Tx: " << item.key();
423 }
424 catch (std::exception const& ex)
425 {
426 failed.insert(item.key());
427 JLOG(j_.warn()) << " Tx: " << item.key() << " throws: " << ex.what();
428 }
429 }
430
431 auto built = buildLCL(
432 prevLedger,
433 retriableTxs,
434 consensusCloseTime,
435 closeTimeCorrect,
436 closeResolution,
437 result.roundTime.read(),
438 failed);
439
440 auto const newLCLHash = built.id();
441 JLOG(j_.debug()) << "Built ledger #" << built.seq() << ": " << newLCLHash;
442
443 // Tell directly connected peers that we have a new LCL
444 notify(protocol::neACCEPTED_LEDGER, built, haveCorrectLCL);
445
446 // As long as we're in sync with the network, attempt to detect attempts
447 // at censorship of transaction by tracking which ones don't make it in
448 // after a period of time.
449 if (haveCorrectLCL && result.state == ConsensusState::Yes)
450 {
452
453 result.txns.map_->visitLeaves(
454 [&accepted](boost::intrusive_ptr<SHAMapItem const> const& item) { accepted.push_back(item->key()); });
455
456 // Track all the transactions which failed or were marked as retriable
457 for (auto const& r : retriableTxs)
458 failed.insert(r.first.getTXID());
459
460 censorshipDetector_.check(
461 std::move(accepted),
462 [curr = built.seq(), j = app_.journal("CensorshipDetector"), &failed](uint256 const& id, LedgerIndex seq) {
463 if (failed.count(id))
464 return true;
465
466 auto const wait = curr - seq;
467
468 if (wait && (wait % censorshipWarnInternal == 0))
469 {
471 ss << "Potential Censorship: Eligible tx " << id << ", which we are tracking since ledger " << seq
472 << " has not been included as of ledger " << curr << ".";
473
474 JLOG(j.warn()) << ss.str();
475 }
476
477 return false;
478 });
479 }
480
481 if (validating_)
482 validating_ = ledgerMaster_.isCompatible(*built.ledger_, j_.warn(), "Not validating");
483
484 if (validating_ && !consensusFail && app_.getValidations().canValidateSeq(built.seq()))
485 {
486 validate(built, result.txns, proposing);
487 JLOG(j_.info()) << "CNF Val " << newLCLHash;
488 }
489 else
490 JLOG(j_.info()) << "CNF buildLCL " << newLCLHash;
491
492 // See if we can accept a ledger as fully-validated
493 ledgerMaster_.consensusBuilt(built.ledger_, result.txns.id(), std::move(consensusJson));
494
495 //-------------------------------------------------------------------------
496 {
497 // Apply disputed transactions that didn't get in
498 //
499 // The first crack of transactions to get into the new
500 // open ledger goes to transactions proposed by a validator
501 // we trust but not included in the consensus set.
502 //
503 // These are done first because they are the most likely
504 // to receive agreement during consensus. They are also
505 // ordered logically "sooner" than transactions not mentioned
506 // in the previous consensus round.
507 //
508 bool anyDisputes = false;
509 for (auto const& [_, dispute] : result.disputes)
510 {
511 (void)_;
512 if (!dispute.getOurVote())
513 {
514 // we voted NO
515 try
516 {
517 JLOG(j_.debug()) << "Test applying disputed transaction that did"
518 << " not get in " << dispute.tx().id();
519
520 SerialIter sit(dispute.tx().tx_->slice());
521 auto txn = std::make_shared<STTx const>(sit);
522
523 // Disputed pseudo-transactions that were not accepted
524 // can't be successfully applied in the next ledger
525 if (isPseudoTx(*txn))
526 continue;
527
528 retriableTxs.insert(txn);
529
530 anyDisputes = true;
531 }
532 catch (std::exception const& ex)
533 {
534 JLOG(j_.debug()) << "Failed to apply transaction we voted "
535 "NO on. Exception: "
536 << ex.what();
537 }
538 }
539 }
540
541 // Build new open ledger
542 std::unique_lock lock{app_.getMasterMutex(), std::defer_lock};
543 std::unique_lock sl{ledgerMaster_.peekMutex(), std::defer_lock};
544 std::lock(lock, sl);
545
546 auto const lastVal = ledgerMaster_.getValidatedLedger();
548 if (lastVal)
549 rules = makeRulesGivenLedger(*lastVal, app_.config().features);
550 else
551 rules.emplace(app_.config().features);
552 app_.openLedger().accept(
553 app_,
554 *rules,
555 built.ledger_,
556 localTxs_.getTxSet(),
557 anyDisputes,
558 retriableTxs,
559 tapNONE,
560 "consensus",
561 [&](OpenView& view, beast::Journal j) {
562 // Stuff the ledger with transactions from the queue.
563 return app_.getTxQ().accept(app_, view);
564 });
565
566 // Signal a potential fee change to subscribers after the open ledger
567 // is created
568 app_.getOPs().reportFeeChange();
569 }
570
571 //-------------------------------------------------------------------------
572 {
573 ledgerMaster_.switchLCL(built.ledger_);
574
575 // Do these need to exist?
576 XRPL_ASSERT(
577 ledgerMaster_.getClosedLedger()->header().hash == built.id(),
578 "xrpl::RCLConsensus::Adaptor::doAccept : ledger hash match");
579 XRPL_ASSERT(
580 app_.openLedger().current()->header().parentHash == built.id(),
581 "xrpl::RCLConsensus::Adaptor::doAccept : parent hash match");
582 }
583
584 //-------------------------------------------------------------------------
585 // we entered the round with the network,
586 // see how close our close time is to other node's
587 // close time reports, and update our clock.
588 if ((mode == ConsensusMode::proposing || mode == ConsensusMode::observing) && !consensusFail)
589 {
590 auto closeTime = rawCloseTimes.self;
591
592 JLOG(j_.info()) << "We closed at " << closeTime.time_since_epoch().count();
594 usec64_t closeTotal = std::chrono::duration_cast<usec64_t>(closeTime.time_since_epoch());
595 int closeCount = 1;
596
597 for (auto const& [t, v] : rawCloseTimes.peers)
598 {
599 JLOG(j_.info()) << std::to_string(v) << " time votes for " << std::to_string(t.time_since_epoch().count());
600 closeCount += v;
601 closeTotal += std::chrono::duration_cast<usec64_t>(t.time_since_epoch()) * v;
602 }
603
604 closeTotal += usec64_t(closeCount / 2); // for round to nearest
605 closeTotal /= closeCount;
606
607 // Use signed times since we are subtracting
610 auto offset = time_point{closeTotal} - std::chrono::time_point_cast<duration>(closeTime);
611 JLOG(j_.info()) << "Our close offset is estimated at " << offset.count() << " (" << closeCount << ")";
612
613 app_.timeKeeper().adjustCloseTime(offset);
614 }
615}
616
617void
618RCLConsensus::Adaptor::notify(protocol::NodeEvent ne, RCLCxLedger const& ledger, bool haveCorrectLCL)
619{
620 protocol::TMStatusChange s;
621
622 if (!haveCorrectLCL)
623 s.set_newevent(protocol::neLOST_SYNC);
624 else
625 s.set_newevent(ne);
626
627 s.set_ledgerseq(ledger.seq());
628 s.set_networktime(app_.timeKeeper().now().time_since_epoch().count());
629 s.set_ledgerhashprevious(ledger.parentID().begin(), std::decay_t<decltype(ledger.parentID())>::bytes);
630 s.set_ledgerhash(ledger.id().begin(), std::decay_t<decltype(ledger.id())>::bytes);
631
632 std::uint32_t uMin, uMax;
633 if (!ledgerMaster_.getFullValidatedRange(uMin, uMax))
634 {
635 uMin = 0;
636 uMax = 0;
637 }
638 else
639 {
640 // Don't advertise ledgers we're not willing to serve
641 uMin = std::max(uMin, ledgerMaster_.getEarliestFetch());
642 }
643 s.set_firstseq(uMin);
644 s.set_lastseq(uMax);
645 app_.overlay().foreach(send_always(std::make_shared<Message>(s, protocol::mtSTATUS_CHANGE)));
646 JLOG(j_.trace()) << "send status change to peer";
647}
648
651 RCLCxLedger const& previousLedger,
652 CanonicalTXSet& retriableTxs,
653 NetClock::time_point closeTime,
654 bool closeTimeCorrect,
655 NetClock::duration closeResolution,
657 std::set<TxID>& failedTxs)
658{
659 std::shared_ptr<Ledger> built = [&]() {
660 if (auto const replayData = ledgerMaster_.releaseReplay())
661 {
662 XRPL_ASSERT(
663 replayData->parent()->header().hash == previousLedger.id(),
664 "xrpl::RCLConsensus::Adaptor::buildLCL : parent hash match");
665 return buildLedger(*replayData, tapNONE, app_, j_);
666 }
667 return buildLedger(
668 previousLedger.ledger_, closeTime, closeTimeCorrect, closeResolution, app_, retriableTxs, failedTxs, j_);
669 }();
670
671 // Update fee computations based on accepted txs
672 using namespace std::chrono_literals;
673 app_.getTxQ().processClosedLedger(app_, *built, roundTime > 5s);
674
675 // And stash the ledger in the ledger master
676 if (ledgerMaster_.storeLedger(built))
677 JLOG(j_.debug()) << "Consensus built ledger we already had";
678 else if (app_.getInboundLedgers().find(built->header().hash))
679 JLOG(j_.debug()) << "Consensus built ledger we were acquiring";
680 else
681 JLOG(j_.debug()) << "Consensus built new ledger";
682 return RCLCxLedger{std::move(built)};
683}
684
685void
687{
688 using namespace std::chrono_literals;
689
690 auto validationTime = app_.timeKeeper().closeTime();
691 if (validationTime <= lastValidationTime_)
692 validationTime = lastValidationTime_ + 1s;
693 lastValidationTime_ = validationTime;
694
695 if (!validatorKeys_.keys)
696 {
697 JLOG(j_.warn()) << "RCLConsensus::Adaptor::validate: ValidatorKeys "
698 "not set\n";
699 return;
700 }
701
702 auto const& keys = *validatorKeys_.keys;
703
705 lastValidationTime_, keys.publicKey, keys.secretKey, validatorKeys_.nodeID, [&](STValidation& v) {
706 v.setFieldH256(sfLedgerHash, ledger.id());
707 v.setFieldH256(sfConsensusHash, txns.id());
708
709 v.setFieldU32(sfLedgerSequence, ledger.seq());
710
711 if (proposing)
712 v.setFlag(vfFullValidation);
713
714 // Attest to the hash of what we consider to be the last fully
715 // validated ledger. This may be the hash of the ledger we are
716 // validating here, and that's fine.
717 if (auto const vl = ledgerMaster_.getValidatedLedger())
718 v.setFieldH256(sfValidatedHash, vl->header().hash);
719
720 v.setFieldU64(sfCookie, valCookie_);
721
722 // Report our server version every flag ledger:
723 if (ledger.ledger_->isVotingLedger())
724 v.setFieldU64(sfServerVersion, BuildInfo::getEncodedVersion());
725
726 // Report our load
727 {
728 auto const& ft = app_.getFeeTrack();
729 auto const fee = std::max(ft.getLocalFee(), ft.getClusterFee());
730 if (fee > ft.getLoadBase())
731 v.setFieldU32(sfLoadFee, fee);
732 }
733
734 // If the next ledger is a flag ledger, suggest fee changes and
735 // new features:
736 if (ledger.ledger_->isVotingLedger())
737 {
738 // Fees:
739 feeVote_->doValidation(ledger.ledger_->fees(), ledger.ledger_->rules(), v);
740
741 // Amendments
742 // FIXME: pass `v` and have the function insert the array
743 // directly?
744 auto const amendments = app_.getAmendmentTable().doValidation(getEnabledAmendments(*ledger.ledger_));
745
746 if (!amendments.empty())
747 v.setFieldV256(sfAmendments, STVector256(sfAmendments, amendments));
748 }
749 });
750
751 auto const serialized = v->getSerialized();
752
753 // suppress it if we receive it
754 app_.getHashRouter().addSuppression(sha512Half(makeSlice(serialized)));
755
756 handleNewValidation(app_, v, "local");
757
758 // Broadcast to all our peers:
759 protocol::TMValidation val;
760 val.set_validation(serialized.data(), serialized.size());
761 app_.overlay().broadcast(val);
762
763 // Publish to all our subscribers:
764 app_.getOPs().pubValidation(v);
765}
766
767void
769{
770 JLOG(j_.info()) << "Consensus mode change before=" << to_string(before) << ", after=" << to_string(after);
771
772 // If we were proposing but aren't any longer, we need to reset the
773 // censorship tracking to avoid bogus warnings.
774 if ((before == ConsensusMode::proposing || before == ConsensusMode::observing) && before != after)
775 censorshipDetector_.reset();
776
777 mode_ = after;
778}
779
782{
783 Json::Value ret;
784 {
786 ret = consensus_.getJson(full);
787 }
788 ret["validating"] = adaptor_.validating();
789 return ret;
790}
791
792void
794{
795 try
796 {
798 consensus_.timerEntry(now, clog);
799 }
800 catch (SHAMapMissingNode const& mn)
801 {
802 // This should never happen
804 ss << "During consensus timerEntry: " << mn.what();
805 JLOG(j_.error()) << ss.str();
806 CLOG(clog) << ss.str();
807 Rethrow();
808 }
809}
810
811void
813{
814 try
815 {
817 consensus_.gotTxSet(now, txSet);
818 }
819 catch (SHAMapMissingNode const& mn)
820 {
821 // This should never happen
822 JLOG(j_.error()) << "During consensus gotTxSet: " << mn.what();
823 Rethrow();
824 }
825}
826
828
829void
831{
833 consensus_.simulate(now, consensusDelay);
834}
835
836bool
838{
840 return consensus_.peerProposal(now, newProposal);
841}
842
843bool
845{
846 // We have a key, we do not want out of sync validations after a restart
847 // and are not amendment blocked.
848 validating_ = validatorKeys_.keys && prevLgr.seq() >= app_.getMaxDisallowedLedger() && !app_.getOPs().isBlocked();
849
850 // If we are not running in standalone mode and there's a configured UNL,
851 // check to make sure that it's not expired.
852 if (validating_ && !app_.config().standalone() && app_.validators().count())
853 {
854 auto const when = app_.validators().expires();
855
856 if (!when || *when < app_.timeKeeper().now())
857 {
858 JLOG(j_.error()) << "Voluntarily bowing out of consensus process "
859 "because of an expired validator list.";
860 validating_ = false;
861 }
862 }
863
864 bool const synced = app_.getOPs().getOperatingMode() == OperatingMode::FULL;
865
866 if (validating_)
867 {
868 JLOG(j_.info()) << "Entering consensus process, validating, synced=" << (synced ? "yes" : "no");
869 }
870 else
871 {
872 // Otherwise we just want to monitor the validation process.
873 JLOG(j_.info()) << "Entering consensus process, watching, synced=" << (synced ? "yes" : "no");
874 }
875
876 // Notify inbound ledgers that we are starting a new round
877 inboundTransactions_.newRound(prevLgr.seq());
878
879 // Notify NegativeUNLVote that new validators are added
880 if (!nowTrusted.empty())
881 nUnlVote_.newValidators(prevLgr.seq() + 1, nowTrusted);
882
883 // propose only if we're in sync with the network (and validating)
884 return validating_ && synced;
885}
886
887bool
889{
890 return ledgerMaster_.haveValidated();
891}
892
895{
896 return ledgerMaster_.getValidLedgerIndex();
897}
898
901{
902 return app_.validators().getQuorumKeys();
903}
904
907{
908 return app_.getValidations().laggards(seq, trustedKeys);
909}
910
911bool
913{
914 return validatorKeys_.keys.has_value();
915}
916
917void
919{
920 if (!positions && app_.getOPs().isFull())
921 app_.getOPs().setMode(OperatingMode::CONNECTED);
922}
923
924void
926 NetClock::time_point const& now,
927 RCLCxLedger::ID const& prevLgrId,
928 RCLCxLedger const& prevLgr,
929 hash_set<NodeID> const& nowUntrusted,
930 hash_set<NodeID> const& nowTrusted,
932{
934 consensus_.startRound(now, prevLgrId, prevLgr, nowUntrusted, adaptor_.preStartRound(prevLgr, nowTrusted), clog);
935}
936
938{
939 if (!validating && !j.info())
940 return;
943 header_ = "ConsensusLogger ";
944 header_ += label;
945 header_ += ": ";
946}
947
949{
950 if (!ss_)
951 return;
952 auto const duration =
953 std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::steady_clock::now() - start_);
954 std::stringstream outSs;
955 outSs << header_ << "duration " << (duration.count() / 1000) << '.' << std::setw(3) << std::setfill('0')
956 << (duration.count() % 1000) << "s. " << ss_->str();
958}
959
960} // 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:319
Stream debug() const
Definition Journal.h:301
Sink & sink() const
Returns the Sink associated with this Journal.
Definition Journal.h:270
Stream info() const
Definition Journal.h:307
Stream trace() const
Severity stream access functions.
Definition Journal.h:295
Stream warn() const
Definition Journal.h:313
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:167
ID id() const
The unique ID/hash of the transaction set.
Definition RCLCxTx.h:133
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:45
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:113
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:138
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:598
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:92
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:3436
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:214
@ 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:776
@ 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)