forked from XRPLF/rippled
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathConsensus.h
1443 lines (1193 loc) · 42.7 KB
/
Consensus.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//------------------------------------------------------------------------------
/*
This file is part of rippled: https://github.com/ripple/rippled
Copyright (c) 2012-2017 Ripple Labs Inc.
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
//==============================================================================
#ifndef RIPPLE_CONSENSUS_CONSENSUS_H_INCLUDED
#define RIPPLE_CONSENSUS_CONSENSUS_H_INCLUDED
#include <ripple/basics/Log.h>
#include <ripple/basics/chrono.h>
#include <ripple/beast/utility/Journal.h>
#include <ripple/consensus/ConsensusProposal.h>
#include <ripple/consensus/DisputedTx.h>
#include <ripple/consensus/ConsensusTypes.h>
#include <ripple/json/json_writer.h>
namespace ripple {
/** Generic implementation of consensus algorithm.
Achieves consensus on the next ledger.
Two things need consensus:
1. The set of transactions included in the ledger.
2. The close time for the ledger.
The basic flow:
1. A call to `startRound` places the node in the `Open` phase. In this
phase, the node is waiting for transactions to include in its open
ledger.
2. Successive calls to `timerEntry` check if the node can close the ledger.
Once the node `Close`s the open ledger, it transitions to the
`Establish` phase. In this phase, the node shares/receives peer
proposals on which transactions should be accepted in the closed ledger.
3. During a subsequent call to `timerEntry`, the node determines it has
reached consensus with its peers on which transactions to include. It
transitions to the `Accept` phase. In this phase, the node works on
applying the transactions to the prior ledger to generate a new closed
ledger. Once the new ledger is completed, the node shares the validated
ledger with the network, does some book-keeping, then makes a call to
`startRound` to start the cycle again.
This class uses a generic interface to allow adapting Consensus for specific
applications. The Adaptor template implements a set of helper functions that
plug the consensus algorithm into a specific application. It also identifies
the types that play important roles in Consensus (transactions, ledgers, ...).
The code stubs below outline the interface and type requirements. The traits
types must be copy constructible and assignable.
@warning The generic implementation is not thread safe and the public methods
are not intended to be run concurrently. When in a concurrent environment,
the application is responsible for ensuring thread-safety. Simply locking
whenever touching the Consensus instance is one option.
@code
// A single transaction
struct Tx
{
// Unique identifier of transaction
using ID = ...;
ID id() const;
};
// A set of transactions
struct TxSet
{
// Unique ID of TxSet (not of Tx)
using ID = ...;
// Type of individual transaction comprising the TxSet
using Tx = Tx;
bool exists(Tx::ID const &) const;
// Return value should have semantics like Tx const *
Tx const * find(Tx::ID const &) const ;
ID const & id() const;
// Return set of transactions that are not common to this set or other
// boolean indicates which set it was in
std::map<Tx::ID, bool> compare(TxSet const & other) const;
// A mutable view of transactions
struct MutableTxSet
{
MutableTxSet(TxSet const &);
bool insert(Tx const &);
bool erase(Tx::ID const &);
};
// Construct from a mutable view.
TxSet(MutableTxSet const &);
// Alternatively, if the TxSet is itself mutable
// just alias MutableTxSet = TxSet
};
// Agreed upon state that consensus transactions will modify
struct Ledger
{
using ID = ...;
// Unique identifier of ledgerr
ID const id() const;
auto seq() const;
auto closeTimeResolution() const;
auto closeAgree() const;
auto closeTime() const;
auto parentCloseTime() const;
Json::Value getJson() const;
};
// Wraps a peer's ConsensusProposal
struct PeerPosition
{
ConsensusProposal<
std::uint32_t, //NodeID,
typename Ledger::ID,
typename TxSet::ID> const &
proposal() const;
};
class Adaptor
{
public:
//-----------------------------------------------------------------------
// Define consensus types
using Ledger_t = Ledger;
using NodeID_t = std::uint32_t;
using TxSet_t = TxSet;
using PeerPosition_t = PeerPosition;
//-----------------------------------------------------------------------
//
// Attempt to acquire a specific ledger.
boost::optional<Ledger> acquireLedger(Ledger::ID const & ledgerID);
// Acquire the transaction set associated with a proposed position.
boost::optional<TxSet> acquireTxSet(TxSet::ID const & setID);
// Whether any transactions are in the open ledger
bool hasOpenTransactions() const;
// Number of proposers that have validated the given ledger
std::size_t proposersValidated(Ledger::ID const & prevLedger) const;
// Number of proposers that have validated a ledger descended from the
// given ledger
std::size_t proposersFinished(Ledger::ID const & prevLedger) const;
// Return the ID of the last closed (and validated) ledger that the
// application thinks consensus should use as the prior ledger.
Ledger::ID getPrevLedger(Ledger::ID const & prevLedgerID,
Ledger const & prevLedger,
Mode mode);
// Called whenever consensus operating mode changes
void onModeChange(ConsensuMode before, ConsensusMode after);
// Called when ledger closes
Result onClose(Ledger const &, Ledger const & prev, Mode mode);
// Called when ledger is accepted by consensus
void onAccept(Result const & result,
RCLCxLedger const & prevLedger,
NetClock::duration closeResolution,
CloseTimes const & rawCloseTimes,
Mode const & mode);
// Called when ledger was forcibly accepted by consensus via the simulate
// function.
void onForceAccept(Result const & result,
RCLCxLedger const & prevLedger,
NetClock::duration closeResolution,
CloseTimes const & rawCloseTimes,
Mode const & mode);
// Propose the position to peers.
void propose(ConsensusProposal<...> const & pos);
// Relay a received peer proposal on to other peer's.
void relay(PeerPosition_t const & prop);
// Relay a disputed transaction to peers
void relay(Txn const & tx);
// Share given transaction set with peers
void relay(TxSet const &s);
};
@endcode
@tparam Adaptor Defines types and provides helper functions needed to adapt
Consensus to the larger application.
*/
template <class Adaptor>
class Consensus
{
using Ledger_t = typename Adaptor::Ledger_t;
using TxSet_t = typename Adaptor::TxSet_t;
using NodeID_t = typename Adaptor::NodeID_t;
using Tx_t = typename TxSet_t::Tx;
using PeerPosition_t = typename Adaptor::PeerPosition_t;
using Proposal_t = ConsensusProposal<
NodeID_t,
typename Ledger_t::ID,
typename TxSet_t::ID>;
using Result = ConsensusResult<Adaptor>;
// Helper class to ensure adaptor is notified whenver the ConsensusMode
// changes
class MonitoredMode
{
ConsensusMode mode_;
public:
MonitoredMode(ConsensusMode m) : mode_{m}
{
}
ConsensusMode
get() const
{
return mode_;
}
void
set(ConsensusMode mode, Adaptor& a)
{
a.onModeChange(mode_, mode);
mode_ = mode;
}
};
public:
//! Clock type for measuring time within the consensus code
using clock_type = beast::abstract_clock<std::chrono::steady_clock>;
Consensus(Consensus&&) = default;
/** Constructor.
@param clock The clock used to internally sample consensus progress
@param adaptor The instance of the adaptor class
@param j The journal to log debug output
*/
Consensus(clock_type const& clock, Adaptor & adaptor, beast::Journal j);
/** Kick-off the next round of consensus.
Called by the client code to start each round of consensus.
@param now The network adjusted time
@param prevLedgerID the ID of the last ledger
@param prevLedger The last ledger
@param proposing Whether we want to send proposals to peers this round.
@note @b prevLedgerID is not required to the ID of @b prevLedger since
the ID may be known locally before the contents of the ledger arrive
*/
void
startRound(
NetClock::time_point const& now,
typename Ledger_t::ID const& prevLedgerID,
Ledger_t const& prevLedger,
bool proposing);
/** A peer has proposed a new position, adjust our tracking.
@param now The network adjusted time
@param newProposal The new proposal from a peer
@return Whether we should do delayed relay of this proposal.
*/
bool
peerProposal(
NetClock::time_point const& now,
PeerPosition_t const& newProposal);
/** Call periodically to drive consensus forward.
@param now The network adjusted time
*/
void
timerEntry(NetClock::time_point const& now);
/** Process a transaction set acquired from the network
@param now The network adjusted time
@param txSet the transaction set
*/
void
gotTxSet(NetClock::time_point const& now, TxSet_t const& txSet);
/** Simulate the consensus process without any network traffic.
The end result, is that consensus begins and completes as if everyone
had agreed with whatever we propose.
This function is only called from the rpc "ledger_accept" path with the
server in standalone mode and SHOULD NOT be used during the normal
consensus process.
Simulate will call onForceAccept since clients are manually driving
consensus to the accept phase.
@param now The current network adjusted time.
@param consensusDelay Duration to delay between closing and accepting the
ledger. Uses 100ms if unspecified.
*/
void
simulate(
NetClock::time_point const& now,
boost::optional<std::chrono::milliseconds> consensusDelay);
/** Get the previous ledger ID.
The previous ledger is the last ledger seen by the consensus code and
should correspond to the most recent validated ledger seen by this peer.
@return ID of previous ledger
*/
typename Ledger_t::ID
prevLedgerID() const
{
return prevLedgerID_;
}
/** Get the Json state of the consensus process.
Called by the consensus_info RPC.
@param full True if verbose response desired.
@return The Json state.
*/
Json::Value
getJson(bool full) const;
private:
void
startRoundInternal(
NetClock::time_point const& now,
typename Ledger_t::ID const& prevLedgerID,
Ledger_t const& prevLedger,
ConsensusMode mode);
// Change our view of the previous ledger
void
handleWrongLedger(typename Ledger_t::ID const& lgrId);
/** Check if our previous ledger matches the network's.
If the previous ledger differs, we are no longer in sync with
the network and need to bow out/switch modes.
*/
void
checkLedger();
/** If we radically changed our consensus context for some reason,
we need to replay recent proposals so that they're not lost.
*/
void
playbackProposals();
/** Handle pre-close phase.
In the pre-close phase, the ledger is open as we wait for new
transactions. After enough time has elapsed, we will close the ledger,
switch to the establish phase and start the consensus process.
*/
void
phaseOpen();
/** Handle establish phase.
In the establish phase, the ledger has closed and we work with peers
to reach consensus. Update our position only on the timer, and in this
phase.
If we have consensus, move to the accepted phase.
*/
void
phaseEstablish();
// Close the open ledger and establish initial position.
void
closeLedger();
// Adjust our positions to try to agree with other validators.
void
updateOurPositions();
bool
haveConsensus();
// Create disputes between our position and the provided one.
void
createDisputes(TxSet_t const& o);
// Update our disputes given that this node has adopted a new position.
// Will call createDisputes as needed.
void
updateDisputes(NodeID_t const& node, TxSet_t const& other);
//Revoke our outstanding proposal, if any, and cease proposing
// until this round ends.
void
leaveConsensus();
private:
Adaptor & adaptor_;
ConsensusPhase phase_{ConsensusPhase::accepted};
MonitoredMode mode_{ConsensusMode::observing};
bool firstRound_ = true;
bool haveCloseTimeConsensus_ = false;
clock_type const& clock_;
// How long the consensus convergence has taken, expressed as
// a percentage of the time that we expected it to take.
int convergePercent_{0};
// How long has this round been open
ConsensusTimer openTime_;
NetClock::duration closeResolution_ = ledgerDefaultTimeResolution;
// Time it took for the last consensus round to converge
std::chrono::milliseconds prevRoundTime_ = LEDGER_IDLE_INTERVAL;
//-------------------------------------------------------------------------
// Network time measurements of consensus progress
// The current network adjusted time. This is the network time the
// ledger would close if it closed now
NetClock::time_point now_;
NetClock::time_point prevCloseTime_;
//-------------------------------------------------------------------------
// Non-peer (self) consensus data
// Last validated ledger ID provided to consensus
typename Ledger_t::ID prevLedgerID_;
// Last validated ledger seen by consensus
Ledger_t previousLedger_;
// Transaction Sets, indexed by hash of transaction tree
hash_map<typename TxSet_t::ID, const TxSet_t> acquired_;
boost::optional<Result> result_;
ConsensusCloseTimes rawCloseTimes_;
//-------------------------------------------------------------------------
// Peer related consensus data
// Peer proposed positions for the current round
hash_map<NodeID_t, PeerPosition_t> currPeerPositions_;
// Recently received peer positions, available when transitioning between
// ledgers or roundss
hash_map<NodeID_t, std::deque<PeerPosition_t>> recentPeerPositions_;
// The number of proposers who participated in the last consensus round
std::size_t prevProposers_ = 0;
// nodes that have bowed out of this consensus process
hash_set<NodeID_t> deadNodes_;
// Journal for debugging
beast::Journal j_;
};
template <class Adaptor>
Consensus<Adaptor>::Consensus(
clock_type const& clock,
Adaptor & adaptor,
beast::Journal journal)
: adaptor_(adaptor)
, clock_(clock)
, j_{journal}
{
JLOG(j_.debug()) << "Creating consensus object";
}
template <class Adaptor>
void
Consensus<Adaptor>::startRound(
NetClock::time_point const& now,
typename Ledger_t::ID const& prevLedgerID,
Ledger_t const& prevLedger,
bool proposing)
{
if (firstRound_)
{
// take our initial view of closeTime_ from the seed ledger
prevCloseTime_ = prevLedger.closeTime();
firstRound_ = false;
}
else
{
prevCloseTime_ = rawCloseTimes_.self;
}
startRoundInternal(
now,
prevLedgerID,
prevLedger,
proposing ? ConsensusMode::proposing : ConsensusMode::observing);
}
template <class Adaptor>
void
Consensus<Adaptor>::startRoundInternal(
NetClock::time_point const& now,
typename Ledger_t::ID const& prevLedgerID,
Ledger_t const& prevLedger,
ConsensusMode mode)
{
phase_ = ConsensusPhase::open;
mode_.set(mode, adaptor_);
now_ = now;
prevLedgerID_ = prevLedgerID;
previousLedger_ = prevLedger;
result_.reset();
convergePercent_ = 0;
haveCloseTimeConsensus_ = false;
openTime_.reset(clock_.now());
currPeerPositions_.clear();
acquired_.clear();
rawCloseTimes_.peers.clear();
rawCloseTimes_.self = {};
deadNodes_.clear();
closeResolution_ = getNextLedgerTimeResolution(
previousLedger_.closeTimeResolution(),
previousLedger_.closeAgree(),
previousLedger_.seq() + 1);
if (previousLedger_.id() != prevLedgerID_)
{
handleWrongLedger(prevLedgerID_);
// Unable to acquire the correct ledger
if (mode_.get() == ConsensusMode::wrongLedger)
{
JLOG(j_.info())
<< "Entering consensus with: " << previousLedger_.id();
JLOG(j_.info()) << "Correct LCL is: " << prevLedgerID;
}
}
playbackProposals();
if (currPeerPositions_.size() > (prevProposers_ / 2))
{
// We may be falling behind, don't wait for the timer
// consider closing the ledger immediately
timerEntry(now_);
}
}
template <class Adaptor>
bool
Consensus<Adaptor>::peerProposal(
NetClock::time_point const& now,
PeerPosition_t const& newPeerPos)
{
NodeID_t const & peerID = newPeerPos.proposal().nodeID();
// Always need to store recent positions
{
auto& props = recentPeerPositions_[peerID];
if (props.size() >= 10)
props.pop_front();
props.push_back(newPeerPos);
}
// Nothing to do for now if we are currently working on a ledger
if (phase_ == ConsensusPhase::accepted)
return false;
now_ = now;
Proposal_t const & newPeerProp = newPeerPos.proposal();
if (newPeerProp.prevLedger() != prevLedgerID_)
{
JLOG(j_.debug()) << "Got proposal for " << newPeerProp.prevLedger()
<< " but we are on " << prevLedgerID_;
return false;
}
if (deadNodes_.find(peerID) != deadNodes_.end())
{
using std::to_string;
JLOG(j_.info()) << "Position from dead node: " << to_string(peerID);
return false;
}
{
// update current position
auto peerPosIt = currPeerPositions_.find(peerID);
if (peerPosIt != currPeerPositions_.end())
{
if (newPeerProp.proposeSeq() <=
peerPosIt->second.proposal().proposeSeq())
{
return false;
}
}
if (newPeerProp.isBowOut())
{
using std::to_string;
JLOG(j_.info()) << "Peer bows out: " << to_string(peerID);
if (result_)
{
for (auto& it : result_->disputes)
it.second.unVote(peerID);
}
if (peerPosIt != currPeerPositions_.end())
currPeerPositions_.erase(peerID);
deadNodes_.insert(peerID);
return true;
}
if (peerPosIt != currPeerPositions_.end())
peerPosIt->second = newPeerPos;
else
currPeerPositions_.emplace(peerID, newPeerPos);
}
if (newPeerProp.isInitial())
{
// Record the close time estimate
JLOG(j_.trace()) << "Peer reports close time as "
<< newPeerProp.closeTime().time_since_epoch().count();
++rawCloseTimes_.peers[newPeerProp.closeTime()];
}
JLOG(j_.trace()) << "Processing peer proposal " << newPeerProp.proposeSeq()
<< "/" << newPeerProp.position();
{
auto const ait = acquired_.find(newPeerProp.position());
if (ait == acquired_.end())
{
// acquireTxSet will return the set if it is available, or
// spawn a request for it and return none/nullptr. It will call
// gotTxSet once it arrives
if (auto set = adaptor_.acquireTxSet(newPeerProp.position()))
gotTxSet(now_, *set);
else
JLOG(j_.debug()) << "Don't have tx set for peer";
}
else if (result_)
{
updateDisputes(newPeerProp.nodeID(), ait->second);
}
}
return true;
}
template <class Adaptor>
void
Consensus<Adaptor>::timerEntry(NetClock::time_point const& now)
{
// Nothing to do if we are currently working on a ledger
if (phase_ == ConsensusPhase::accepted)
return;
now_ = now;
// Check we are on the proper ledger (this may change phase_)
checkLedger();
if(phase_ == ConsensusPhase::open)
{
phaseOpen();
}
else if (phase_ == ConsensusPhase::establish)
{
phaseEstablish();
}
}
template <class Adaptor>
void
Consensus<Adaptor>::gotTxSet(
NetClock::time_point const& now,
TxSet_t const& txSet)
{
// Nothing to do if we've finished work on a ledger
if (phase_ == ConsensusPhase::accepted)
return;
now_ = now;
auto id = txSet.id();
// If we've already processed this transaction set since requesting
// it from the network, there is nothing to do now
if (!acquired_.emplace(id, txSet).second)
return;
if (!result_)
{
JLOG(j_.debug()) << "Not creating disputes: no position yet.";
}
else
{
// Our position is added to acquired_ as soon as we create it,
// so this txSet must differ
assert(id != result_->position.position());
bool any = false;
for (auto const& it : currPeerPositions_)
{
if (it.second.proposal().position() == id)
{
updateDisputes(it.first, txSet);
any = true;
}
}
if (!any)
{
JLOG(j_.warn())
<< "By the time we got " << id << " no peers were proposing it";
}
}
}
template <class Adaptor>
void
Consensus<Adaptor>::simulate(
NetClock::time_point const& now,
boost::optional<std::chrono::milliseconds> consensusDelay)
{
JLOG(j_.info()) << "Simulating consensus";
now_ = now;
closeLedger();
result_->roundTime.tick(consensusDelay.value_or(100ms));
result_->proposers = prevProposers_ = currPeerPositions_.size();
prevRoundTime_ = result_->roundTime.read();
phase_ = ConsensusPhase::accepted;
adaptor_.onForceAccept(
*result_,
previousLedger_,
closeResolution_,
rawCloseTimes_,
mode_.get(),
getJson(true));
JLOG(j_.info()) << "Simulation complete";
}
template <class Adaptor>
Json::Value
Consensus<Adaptor>::getJson(bool full) const
{
using std::to_string;
using Int = Json::Value::Int;
Json::Value ret(Json::objectValue);
ret["proposing"] = (mode_.get() == ConsensusMode::proposing);
ret["proposers"] = static_cast<int>(currPeerPositions_.size());
if (mode_.get() != ConsensusMode::wrongLedger)
{
ret["synched"] = true;
ret["ledger_seq"] = previousLedger_.seq() + 1;
ret["close_granularity"] = static_cast<Int>(closeResolution_.count());
}
else
ret["synched"] = false;
ret["phase"] = to_string(phase_);
if (result_ && !result_->disputes.empty() && !full)
ret["disputes"] = static_cast<Int>(result_->disputes.size());
if (result_)
ret["our_position"] = result_->position.getJson();
if (full)
{
if (result_)
ret["current_ms"] =
static_cast<Int>(result_->roundTime.read().count());
ret["converge_percent"] = convergePercent_;
ret["close_resolution"] = static_cast<Int>(closeResolution_.count());
ret["have_time_consensus"] = haveCloseTimeConsensus_;
ret["previous_proposers"] = static_cast<Int>(prevProposers_);
ret["previous_mseconds"] = static_cast<Int>(prevRoundTime_.count());
if (!currPeerPositions_.empty())
{
Json::Value ppj(Json::objectValue);
for (auto const & pp : currPeerPositions_)
{
ppj[to_string(pp.first)] = pp.second.getJson();
}
ret["peer_positions"] = std::move(ppj);
}
if (!acquired_.empty())
{
Json::Value acq(Json::arrayValue);
for (auto const & at : acquired_)
{
acq.append(to_string(at.first));
}
ret["acquired"] = std::move(acq);
}
if (result_ && !result_->disputes.empty())
{
Json::Value dsj(Json::objectValue);
for (auto const & dt : result_->disputes)
{
dsj[to_string(dt.first)] = dt.second.getJson();
}
ret["disputes"] = std::move(dsj);
}
if (!rawCloseTimes_.peers.empty())
{
Json::Value ctj(Json::objectValue);
for (auto const & ct : rawCloseTimes_.peers)
{
ctj[std::to_string(ct.first.time_since_epoch().count())] =
ct.second;
}
ret["close_times"] = std::move(ctj);
}
if (!deadNodes_.empty())
{
Json::Value dnj(Json::arrayValue);
for (auto const& dn : deadNodes_)
{
dnj.append(to_string(dn));
}
ret["dead_nodes"] = std::move(dnj);
}
}
return ret;
}
// Handle a change in the prior ledger during a consensus round
template <class Adaptor>
void
Consensus<Adaptor>::handleWrongLedger(
typename Ledger_t::ID const& lgrId)
{
assert(lgrId != prevLedgerID_ || previousLedger_.id() != lgrId);
if (prevLedgerID_ != lgrId)
{
// first time switching to this ledger
prevLedgerID_ = lgrId;
// Stop proposing because we are out of sync
leaveConsensus();
if (result_)
{
result_->disputes.clear();
result_->compares.clear();
}
currPeerPositions_.clear();
rawCloseTimes_.peers.clear();
deadNodes_.clear();
// Get back in sync, this will also recreate disputes
playbackProposals();
}
if (previousLedger_.id() == prevLedgerID_)
return;
// we need to switch the ledger we're working from
if (auto newLedger = adaptor_.acquireLedger(prevLedgerID_))
{
JLOG(j_.info()) << "Have the consensus ledger " << prevLedgerID_;
startRoundInternal(now_, lgrId, *newLedger, ConsensusMode::switchedLedger);
}
else
{
mode_.set(ConsensusMode::wrongLedger, adaptor_);
}
}
template <class Adaptor>
void
Consensus<Adaptor>::checkLedger()
{
auto netLgr =
adaptor_.getPrevLedger(prevLedgerID_, previousLedger_, mode_.get());
if (netLgr != prevLedgerID_)
{
JLOG(j_.warn()) << "View of consensus changed during "
<< to_string(phase_) << " status=" << to_string(phase_)
<< ", "
<< " mode=" << to_string(mode_.get());
JLOG(j_.warn()) << prevLedgerID_ << " to " << netLgr;
JLOG(j_.warn()) << previousLedger_.getJson();
JLOG(j_.debug())<< "State on consensus change " << getJson(true);
handleWrongLedger(netLgr);
}
else if (previousLedger_.id() != prevLedgerID_)
handleWrongLedger(netLgr);
}
template <class Adaptor>
void
Consensus<Adaptor>::playbackProposals()
{
for (auto const& it : recentPeerPositions_)
{
for (auto const& pos : it.second)
{
if (pos.proposal().prevLedger() == prevLedgerID_)
{
if (peerProposal(now_, pos))
adaptor_.relay(pos);
}
}
}
}
template <class Adaptor>
void
Consensus<Adaptor>::phaseOpen()
{
using namespace std::chrono;
// it is shortly before ledger close time
bool anyTransactions = adaptor_.hasOpenTransactions();
auto proposersClosed = currPeerPositions_.size();
auto proposersValidated = adaptor_.proposersValidated(prevLedgerID_);
openTime_.tick(clock_.now());
// This computes how long since last ledger's close time
milliseconds sinceClose;
{
bool previousCloseCorrect =
(mode_.get() != ConsensusMode::wrongLedger) &&
previousLedger_.closeAgree() &&
(previousLedger_.closeTime() !=
(previousLedger_.parentCloseTime() + 1s));
auto lastCloseTime = previousCloseCorrect
? previousLedger_.closeTime() // use consensus timing
: prevCloseTime_; // use the time we saw internally
if (now_ >= lastCloseTime)
sinceClose = duration_cast<milliseconds>(now_ - lastCloseTime);
else
sinceClose = -duration_cast<milliseconds>(lastCloseTime - now_);
}
auto const idleInterval = std::max<seconds>(
LEDGER_IDLE_INTERVAL,
duration_cast<seconds>(2 * previousLedger_.closeTimeResolution()));
// Decide if we should close the ledger
if (shouldCloseLedger(
anyTransactions,
prevProposers_,
proposersClosed,
proposersValidated,
prevRoundTime_,
sinceClose,