-
Notifications
You must be signed in to change notification settings - Fork 1.5k
/
Copy pathLedgerMaster.cpp
1486 lines (1247 loc) · 49.1 KB
/
LedgerMaster.cpp
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, 2013 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.
*/
//==============================================================================
#include <ripple/basics/containers/RangeSet.h>
#include <cassert>
namespace ripple {
#define MIN_VALIDATION_RATIO 150 // 150/256ths of validations of previous ledger
#define MAX_LEDGER_GAP 100 // Don't catch up more than 100 ledgers (cannot exceed 256)
SETUP_LOG (LedgerMaster)
class LedgerCleanerLog;
template <> char const* LogPartition::getPartitionName <LedgerCleanerLog> () { return "LedgerCleaner"; }
class LedgerMasterImp
: public LedgerMaster
, public beast::LeakChecked <LedgerMasterImp>
{
public:
typedef std::function <void (Ledger::ref)> callback;
typedef RippleRecursiveMutex LockType;
typedef std::lock_guard <LockType> ScopedLockType;
typedef beast::GenericScopedUnlock <LockType> ScopedUnlockType;
beast::Journal m_journal;
LockType m_mutex;
LedgerHolder mCurrentLedger; // The ledger we are currently processiong
LedgerHolder mClosedLedger; // The ledger that most recently closed
LedgerHolder mValidLedger; // The highest-sequence ledger we have fully accepted
Ledger::pointer mPubLedger; // The last ledger we have published
Ledger::pointer mPathLedger; // The last ledger we did pathfinding against
LedgerHistory mLedgerHistory;
CanonicalTXSet mHeldTransactions;
LockType mCompleteLock;
RangeSet mCompleteLedgers;
std::unique_ptr <LedgerCleaner> mLedgerCleaner;
int mMinValidations; // The minimum validations to publish a ledger
uint256 mLastValidateHash;
std::uint32_t mLastValidateSeq;
std::list<callback> mOnValidate; // Called when a ledger has enough validations
bool mAdvanceThread; // Publish thread is running
bool mAdvanceWork; // Publish thread has work to do
int mFillInProgress;
int mPathFindThread; // Pathfinder jobs dispatched
bool mPathFindNewLedger;
bool mPathFindNewRequest;
std::atomic <std::uint32_t> mPubLedgerClose;
std::atomic <std::uint32_t> mPubLedgerSeq;
std::atomic <std::uint32_t> mValidLedgerClose;
std::atomic <std::uint32_t> mValidLedgerSeq;
std::atomic <std::uint32_t> mBuildingLedgerSeq;
//--------------------------------------------------------------------------
explicit LedgerMasterImp (Stoppable& parent, beast::Journal journal)
: LedgerMaster (parent)
, m_journal (journal)
, mHeldTransactions (uint256 ())
, mLedgerCleaner (LedgerCleaner::New(*this, LogPartition::getJournal<LedgerCleanerLog>()))
, mMinValidations (0)
, mLastValidateSeq (0)
, mAdvanceThread (false)
, mAdvanceWork (false)
, mFillInProgress (0)
, mPathFindThread (0)
, mPathFindNewRequest (false)
, mPubLedgerClose (0)
, mPubLedgerSeq (0)
, mValidLedgerClose (0)
, mValidLedgerSeq (0)
, mBuildingLedgerSeq (0)
{
}
~LedgerMasterImp ()
{
}
LedgerIndex getCurrentLedgerIndex ()
{
return mCurrentLedger.get ()->getLedgerSeq ();
}
LedgerIndex getValidLedgerIndex ()
{
return mValidLedgerSeq;
}
int getPublishedLedgerAge ()
{
std::uint32_t pubClose = mPubLedgerClose.load();
if (!pubClose)
{
WriteLog (lsDEBUG, LedgerMaster) << "No published ledger";
return 999999;
}
std::int64_t ret = getApp().getOPs ().getCloseTimeNC ();
ret -= static_cast<std::int64_t> (pubClose);
ret = (ret > 0) ? ret : 0;
WriteLog (lsTRACE, LedgerMaster) << "Published ledger age is " << ret;
return static_cast<int> (ret);
}
int getValidatedLedgerAge ()
{
std::uint32_t valClose = mValidLedgerClose.load();
if (!valClose)
{
WriteLog (lsDEBUG, LedgerMaster) << "No validated ledger";
return 999999;
}
std::int64_t ret = getApp().getOPs ().getCloseTimeNC ();
ret -= static_cast<std::int64_t> (valClose);
ret = (ret > 0) ? ret : 0;
WriteLog (lsTRACE, LedgerMaster) << "Validated ledger age is " << ret;
return static_cast<int> (ret);
}
bool isCaughtUp(std::string& reason)
{
if (getPublishedLedgerAge() > 180)
{
reason = "No recently-published ledger";
return false;
}
std::uint32_t validClose = mValidLedgerClose.load();
std::uint32_t pubClose = mPubLedgerClose.load();
if (!validClose || !pubClose)
{
reason = "No published ledger";
return false;
}
if (validClose > (pubClose + 90))
{
reason = "Published ledger lags validated ledger";
return false;
}
return true;
}
void setValidLedger(Ledger::ref l)
{
mValidLedger.set (l);
mValidLedgerClose = l->getCloseTimeNC();
mValidLedgerSeq = l->getLedgerSeq();
getApp().getOPs().updateLocalTx (l);
}
void setPubLedger(Ledger::ref l)
{
mPubLedger = l;
mPubLedgerClose = l->getCloseTimeNC();
mPubLedgerSeq = l->getLedgerSeq();
}
void addHeldTransaction (Transaction::ref transaction)
{
// returns true if transaction was added
ScopedLockType ml (m_mutex);
mHeldTransactions.push_back (transaction->getSTransaction ());
}
void pushLedger (Ledger::pointer newLedger)
{
// Caller should already have properly assembled this ledger into "ready-to-close" form --
// all candidate transactions must already be applied
WriteLog (lsINFO, LedgerMaster) << "PushLedger: " << newLedger->getHash ();
{
ScopedLockType ml (m_mutex);
Ledger::pointer closedLedger = mCurrentLedger.getMutable ();
if (closedLedger)
{
closedLedger->setClosed ();
closedLedger->setImmutable ();
mClosedLedger.set (closedLedger);
}
mCurrentLedger.set (newLedger);
}
if (getConfig().RUN_STANDALONE)
{
setFullLedger(newLedger, true, false);
tryAdvance();
}
else
checkAccept(newLedger);
}
void pushLedger (Ledger::pointer newLCL, Ledger::pointer newOL)
{
assert (newLCL->isClosed () && newLCL->isAccepted ());
assert (!newOL->isClosed () && !newOL->isAccepted ());
{
ScopedLockType ml (m_mutex);
mClosedLedger.set (newLCL);
mCurrentLedger.set (newOL);
}
if (getConfig().RUN_STANDALONE)
{
setFullLedger(newLCL, true, false);
tryAdvance();
}
else
{
mLedgerHistory.builtLedger (newLCL);
}
}
void switchLedgers (Ledger::pointer lastClosed, Ledger::pointer current)
{
assert (lastClosed && current);
{
ScopedLockType ml (m_mutex);
lastClosed->setClosed ();
lastClosed->setAccepted ();
mCurrentLedger.set (current);
mClosedLedger.set (lastClosed);
assert (!current->isClosed ());
}
checkAccept (lastClosed);
}
bool fixIndex (LedgerIndex ledgerIndex, LedgerHash const& ledgerHash)
{
return mLedgerHistory.fixIndex (ledgerIndex, ledgerHash);
}
bool storeLedger (Ledger::pointer ledger)
{
// Returns true if we already had the ledger
return mLedgerHistory.addLedger (ledger, false);
}
void forceValid (Ledger::pointer ledger)
{
ledger->setValidated();
setFullLedger(ledger, true, false);
}
/** Apply held transactions to the open ledger
This is normally called as we close the ledger.
The open ledger remains open to handle new transactions
until a new open ledger is built.
*/
void applyHeldTransactions ()
{
ScopedLockType sl (m_mutex);
// Start with a mutable snapshot of the open ledger
TransactionEngine engine (mCurrentLedger.getMutable ());
int recovers = 0;
for (auto const& it : mHeldTransactions)
{
try
{
TransactionEngineParams tepFlags = tapOPEN_LEDGER;
if (getApp().getHashRouter ().addSuppressionFlags (it.first.getTXID (), SF_SIGGOOD))
tepFlags = static_cast<TransactionEngineParams> (tepFlags | tapNO_CHECK_SIGN);
bool didApply;
engine.applyTransaction (*it.second, tepFlags, didApply);
if (didApply)
++recovers;
// If a transaction is recovered but hasn't been relayed,
// it will become disputed in the consensus process, which
// will cause it to be relayed.
}
catch (...)
{
WriteLog (lsWARNING, LedgerMaster) << "Held transaction throws";
}
}
CondLog (recovers != 0, lsINFO, LedgerMaster) << "Recovered " << recovers << " held transactions";
// VFALCO TODO recreate the CanonicalTxSet object instead of resetting it
mHeldTransactions.reset (engine.getLedger()->getHash ());
mCurrentLedger.set (engine.getLedger ());
}
LedgerIndex getBuildingLedger ()
{
// The ledger we are currently building, 0 of none
return mBuildingLedgerSeq.load ();
}
void setBuildingLedger (LedgerIndex i)
{
mBuildingLedgerSeq.store (i);
}
TER doTransaction (SerializedTransaction::ref txn, TransactionEngineParams params, bool& didApply)
{
Ledger::pointer ledger;
TransactionEngine engine;
TER result;
didApply = false;
{
ScopedLockType sl (m_mutex);
ledger = mCurrentLedger.getMutable ();
engine.setLedger (ledger);
result = engine.applyTransaction (*txn, params, didApply);
}
if (didApply)
{
mCurrentLedger.set (ledger);
getApp().getOPs ().pubProposedTransaction (ledger, txn, result);
}
return result;
}
bool haveLedgerRange (std::uint32_t from, std::uint32_t to)
{
ScopedLockType sl (mCompleteLock);
std::uint32_t prevMissing = mCompleteLedgers.prevMissing (to + 1);
return (prevMissing == RangeSet::absent) || (prevMissing < from);
}
bool haveLedger (std::uint32_t seq)
{
ScopedLockType sl (mCompleteLock);
return mCompleteLedgers.hasValue (seq);
}
void clearLedger (std::uint32_t seq)
{
ScopedLockType sl (mCompleteLock);
return mCompleteLedgers.clearValue (seq);
}
// returns Ledgers we have all the nodes for
bool getFullValidatedRange (std::uint32_t& minVal, std::uint32_t& maxVal)
{
maxVal = mPubLedgerSeq.load();
if (!maxVal)
return false;
{
ScopedLockType sl (mCompleteLock);
minVal = mCompleteLedgers.prevMissing (maxVal);
}
if (minVal == RangeSet::absent)
minVal = maxVal;
else
++minVal;
return true;
}
// Returns Ledgers we have all the nodes for and are indexed
bool getValidatedRange (std::uint32_t& minVal, std::uint32_t& maxVal)
{
maxVal = mPubLedgerSeq.load();
if (!maxVal)
return false;
{
ScopedLockType sl (mCompleteLock);
minVal = mCompleteLedgers.prevMissing (maxVal);
}
if (minVal == RangeSet::absent)
minVal = maxVal;
else
++minVal;
// Remove from the validated range any ledger sequences that may not be
// fully updated in the database yet
std::set<std::uint32_t> sPendingSaves = Ledger::getPendingSaves();
if (!sPendingSaves.empty() && ((minVal != 0) || (maxVal != 0)))
{
// Ensure we shrink the tips as much as possible
// If we have 7-9 and 8,9 are invalid, we don't want to see the 8 and shrink to just 9
// because then we'll have nothing when we could have 7.
while (sPendingSaves.count(maxVal) > 0)
--maxVal;
while (sPendingSaves.count(minVal) > 0)
++minVal;
// Best effort for remaining exclusions
for(auto v : sPendingSaves)
{
if ((v >= minVal) && (v <= maxVal))
{
if (v > ((minVal + maxVal) / 2))
maxVal = v - 1;
else
minVal = v + 1;
}
}
if (minVal > maxVal)
minVal = maxVal = 0;
}
return true;
}
// Get the earliest ledger we will let peers fetch
std::uint32_t getEarliestFetch ()
{
// The earliest ledger we will let people fetch is ledger zero,
// unless that creates a larger range than allowed
std::uint32_t e = getClosedLedger()->getLedgerSeq();
if (e > getConfig().FETCH_DEPTH)
e -= getConfig().FETCH_DEPTH;
else
e = 0;
return e;
}
void tryFill (Job& job, Ledger::pointer ledger)
{
std::uint32_t seq = ledger->getLedgerSeq ();
uint256 prevHash = ledger->getParentHash ();
std::map< std::uint32_t, std::pair<uint256, uint256> > ledgerHashes;
std::uint32_t minHas = ledger->getLedgerSeq ();
std::uint32_t maxHas = ledger->getLedgerSeq ();
while (! job.shouldCancel() && seq > 0)
{
{
ScopedLockType ml (m_mutex);
minHas = seq;
--seq;
if (haveLedger (seq))
break;
}
auto it (ledgerHashes.find (seq));
if (it == ledgerHashes.end ())
{
if (getApp().isShutdown ())
return;
{
ScopedLockType ml (mCompleteLock);
mCompleteLedgers.setRange (minHas, maxHas);
}
maxHas = minHas;
ledgerHashes = Ledger::getHashesByIndex ((seq < 500)
? 0
: (seq - 499), seq);
it = ledgerHashes.find (seq);
if (it == ledgerHashes.end ())
break;
}
if (it->second.first != prevHash)
break;
prevHash = it->second.second;
}
{
ScopedLockType ml (mCompleteLock);
mCompleteLedgers.setRange (minHas, maxHas);
}
{
ScopedLockType ml (m_mutex);
mFillInProgress = 0;
tryAdvance();
}
}
/** Request a fetch pack to get the ledger prior to 'nextLedger'
*/
void getFetchPack (Ledger::ref nextLedger)
{
Peer::ptr target;
int count = 0;
Overlay::PeerSequence peerList = getApp().overlay ().getActivePeers ();
for (auto const& peer : peerList)
{
if (peer->hasRange (nextLedger->getLedgerSeq() - 1, nextLedger->getLedgerSeq()))
{
if (count++ == 0)
target = peer;
else if ((rand () % ++count) == 0)
target = peer;
}
}
if (target)
{
protocol::TMGetObjectByHash tmBH;
tmBH.set_query (true);
tmBH.set_type (protocol::TMGetObjectByHash::otFETCH_PACK);
tmBH.set_ledgerhash (nextLedger->getHash().begin (), 32);
Message::pointer packet = std::make_shared<Message> (tmBH, protocol::mtGET_OBJECTS);
target->send (packet);
WriteLog (lsTRACE, LedgerMaster) << "Requested fetch pack for " << nextLedger->getLedgerSeq() - 1;
}
else
WriteLog (lsDEBUG, LedgerMaster) << "No peer for fetch pack";
}
void fixMismatch (Ledger::ref ledger)
{
int invalidate = 0;
uint256 hash;
for (std::uint32_t lSeq = ledger->getLedgerSeq () - 1; lSeq > 0; --lSeq)
if (haveLedger (lSeq))
{
try
{
hash = ledger->getLedgerHash (lSeq);
}
catch (...)
{
WriteLog (lsWARNING, LedgerMaster) <<
"fixMismatch encounters partial ledger";
clearLedger(lSeq);
return;
}
if (hash.isNonZero ())
{
// try to close the seam
Ledger::pointer otherLedger = getLedgerBySeq (lSeq);
if (otherLedger && (otherLedger->getHash () == hash))
{
// we closed the seam
CondLog (invalidate != 0, lsWARNING, LedgerMaster) <<
"Match at " << lSeq << ", " << invalidate <<
" prior ledgers invalidated";
return;
}
}
clearLedger (lSeq);
++invalidate;
}
// all prior ledgers invalidated
CondLog (invalidate != 0, lsWARNING, LedgerMaster) << "All " <<
invalidate << " prior ledgers invalidated";
}
void setFullLedger (Ledger::pointer ledger, bool isSynchronous, bool isCurrent)
{
// A new ledger has been accepted as part of the trusted chain
WriteLog (lsDEBUG, LedgerMaster) << "Ledger " << ledger->getLedgerSeq () << " accepted :" << ledger->getHash ();
assert (ledger->peekAccountStateMap ()->getHash ().isNonZero ());
ledger->setValidated();
mLedgerHistory.addLedger(ledger, true);
ledger->setFull();
ledger->pendSaveValidated (isSynchronous, isCurrent);
{
{
ScopedLockType ml (mCompleteLock);
mCompleteLedgers.setValue (ledger->getLedgerSeq ());
}
ScopedLockType ml (m_mutex);
if (ledger->getLedgerSeq() > mValidLedgerSeq)
setValidLedger(ledger);
if (!mPubLedger)
{
setPubLedger(ledger);
getApp().getOrderBookDB().setup(ledger);
}
if ((ledger->getLedgerSeq () != 0) && haveLedger (ledger->getLedgerSeq () - 1))
{
// we think we have the previous ledger, double check
Ledger::pointer prevLedger = getLedgerBySeq (ledger->getLedgerSeq () - 1);
if (!prevLedger || (prevLedger->getHash () != ledger->getParentHash ()))
{
WriteLog (lsWARNING, LedgerMaster) << "Acquired ledger invalidates previous ledger: " <<
(prevLedger ? "hashMismatch" : "missingLedger");
fixMismatch (ledger);
}
}
}
//--------------------------------------------------------------------------
//
{
if (isCurrent)
getApp ().getValidators ().ledgerClosed (ledger->getHash());
}
//
//--------------------------------------------------------------------------
}
void failedSave(std::uint32_t seq, uint256 const& hash)
{
clearLedger(seq);
getApp().getInboundLedgers().findCreate(hash, seq, InboundLedger::fcGENERIC);
}
// Check if the specified ledger can become the new last fully-validated ledger
void checkAccept (uint256 const& hash, std::uint32_t seq)
{
if (seq != 0)
{
// Ledger is too old
if (seq <= mValidLedgerSeq)
return;
// Ledger could match the ledger we're already building
if (seq == mBuildingLedgerSeq)
return;
}
Ledger::pointer ledger = mLedgerHistory.getLedgerByHash (hash);
if (!ledger)
{
// FIXME: We should really only fetch if the ledger
//has sufficient validations to accept it
InboundLedger::pointer l =
getApp().getInboundLedgers().findCreate(hash, 0, InboundLedger::fcGENERIC);
if (l && l->isComplete() && !l->isFailed())
ledger = l->getLedger();
else
{
WriteLog (lsDEBUG, LedgerMaster) <<
"checkAccept triggers acquire " << to_string (hash);
}
}
if (ledger)
checkAccept (ledger);
}
/**
* Determines how many validations are needed to fully-validated a ledger
*
* @return Number of validations needed
*/
int getNeededValidations ()
{
if (getConfig ().RUN_STANDALONE)
return 0;
int minVal = mMinValidations;
if (mLastValidateHash.isNonZero ())
{
int val = getApp().getValidations ().getTrustedValidationCount (mLastValidateHash);
val *= MIN_VALIDATION_RATIO;
val /= 256;
if (val > minVal)
minVal = val;
}
return minVal;
}
void checkAccept (Ledger::ref ledger)
{
if (ledger->getLedgerSeq() <= mValidLedgerSeq)
return;
// Can we advance the last fully-validated ledger? If so, can we publish?
ScopedLockType ml (m_mutex);
if (ledger->getLedgerSeq() <= mValidLedgerSeq)
return;
int minVal = getNeededValidations();
int tvc = getApp().getValidations().getTrustedValidationCount(ledger->getHash());
if (tvc < minVal) // nothing we can do
{
WriteLog (lsTRACE, LedgerMaster) << "Only " << tvc << " validations for " << ledger->getHash();
return;
}
WriteLog (lsINFO, LedgerMaster) << "Advancing accepted ledger to " << ledger->getLedgerSeq() << " with >= " << minVal << " validations";
mLastValidateHash = ledger->getHash();
mLastValidateSeq = ledger->getLedgerSeq();
ledger->setValidated();
ledger->setFull();
setValidLedger(ledger);
if (!mPubLedger)
{
ledger->pendSaveValidated(true, true);
setPubLedger(ledger);
getApp().getOrderBookDB().setup(ledger);
}
std::uint64_t fee, fee2, ref;
ref = getApp().getFeeTrack().getLoadBase();
int count = getApp().getValidations().getFeeAverage(ledger->getHash(), ref, fee);
int count2 = getApp().getValidations().getFeeAverage(ledger->getParentHash(), ref, fee2);
if ((count + count2) == 0)
getApp().getFeeTrack().setRemoteFee(ref);
else
getApp().getFeeTrack().setRemoteFee(((fee * count) + (fee2 * count2)) / (count + count2));
tryAdvance ();
}
/** Report that the consensus process built a particular ledger */
void consensusBuilt (Ledger::ref ledger) override
{
// Because we just built a ledger, we are no longer building one
setBuildingLedger (0);
// No need to process validations in standalone mode
if (getConfig().RUN_STANDALONE)
return;
if (ledger->getLedgerSeq() <= mValidLedgerSeq)
{
WriteLog (lsINFO, LedgerConsensus)
<< "Consensus built old ledger: "
<< ledger->getLedgerSeq() << " <= " << mValidLedgerSeq;
return;
}
// See if this ledger can be the new fully-validated ledger
checkAccept (ledger);
if (ledger->getLedgerSeq() <= mValidLedgerSeq)
{
WriteLog (lsDEBUG, LedgerConsensus)
<< "Consensus ledger fully validated";
return;
}
// This ledger cannot be the new fully-validated ledger, but
// maybe we saved up validations for some other ledger that can be
auto const val = getApp().getValidations().getCurrentTrustedValidations();
// Track validation counts with sequence numbers
class valSeq
{
public:
valSeq () : valCount_ (0), ledgerSeq_ (0) { ; }
void mergeValidation (LedgerSeq seq)
{
valCount_++;
// If we didn't already know the sequence, now we do
if (ledgerSeq_ == 0)
ledgerSeq_ = seq;
}
int valCount_;
LedgerSeq ledgerSeq_;
};
// Count the number of current, trusted validations
ripple::unordered_map <uint256, valSeq> count;
for (auto const& v : val)
{
valSeq& vs = count[v->getLedgerHash()];
vs.mergeValidation (v->getFieldU32 (sfLedgerSequence));
}
int neededValidations = getNeededValidations ();
LedgerSeq maxSeq = mValidLedgerSeq;
uint256 maxLedger = ledger->getHash();
// Of the ledgers with sufficient validations,
// find the one with the highest sequence
for (auto& v : count)
if (v.second.valCount_ > neededValidations)
{
// If we still don't know the sequence, get it
if (v.second.ledgerSeq_ == 0)
{
Ledger::pointer ledger = getLedgerByHash (v.first);
if (ledger)
v.second.ledgerSeq_ = ledger->getLedgerSeq();
}
if (v.second.ledgerSeq_ > maxSeq)
{
maxSeq = v.second.ledgerSeq_;
maxLedger = v.first;
}
}
if (maxSeq > mValidLedgerSeq)
{
WriteLog (lsDEBUG, LedgerConsensus)
<< "Consensus triggered check of ledger";
checkAccept (maxLedger, maxSeq);
}
}
void advanceThread()
{
ScopedLockType sl (m_mutex);
assert (!mValidLedger.empty () && mAdvanceThread);
WriteLog (lsTRACE, LedgerMaster) << "advanceThread<";
try
{
doAdvance();
}
catch (...)
{
WriteLog (lsFATAL, LedgerMaster) << "doAdvance throws an exception";
}
mAdvanceThread = false;
WriteLog (lsTRACE, LedgerMaster) << "advanceThread>";
}
// Try to publish ledgers, acquire missing ledgers
void doAdvance ()
{
do
{
mAdvanceWork = false; // If there's work to do, we'll make progress
bool progress = false;
std::list<Ledger::pointer> pubLedgers = findNewLedgersToPublish ();
if (pubLedgers.empty())
{
if (!getConfig().RUN_STANDALONE && !getApp().getFeeTrack().isLoadedLocal() &&
(getApp().getJobQueue().getJobCount(jtPUBOLDLEDGER) < 10) &&
(mValidLedgerSeq == mPubLedgerSeq))
{ // We are in sync, so can acquire
std::uint32_t missing;
{
ScopedLockType sl (mCompleteLock);
missing = mCompleteLedgers.prevMissing(mPubLedger->getLedgerSeq());
}
WriteLog (lsTRACE, LedgerMaster) << "tryAdvance discovered missing " << missing;
if ((missing != RangeSet::absent) && (missing > 0) &&
shouldAcquire(mValidLedgerSeq, getConfig().LEDGER_HISTORY, missing) &&
((mFillInProgress == 0) || (missing > mFillInProgress)))
{
WriteLog (lsTRACE, LedgerMaster) << "advanceThread should acquire";
{
ScopedUnlockType sl(m_mutex);
Ledger::pointer nextLedger = mLedgerHistory.getLedgerBySeq(missing + 1);
if (nextLedger)
{
assert (nextLedger->getLedgerSeq() == (missing + 1));
Ledger::pointer ledger = getLedgerByHash(nextLedger->getParentHash());
if (!ledger)
{
if (!getApp().getInboundLedgers().isFailure(nextLedger->getParentHash()))
{
InboundLedger::pointer acq =
getApp().getInboundLedgers().findCreate(nextLedger->getParentHash(),
nextLedger->getLedgerSeq() - 1,
InboundLedger::fcHISTORY);
if (acq->isComplete() && !acq->isFailed())
ledger = acq->getLedger();
else if ((missing > 40000) && getApp().getOPs().shouldFetchPack(missing))
{
WriteLog (lsTRACE, LedgerMaster) << "tryAdvance want fetch pack " << missing;
getFetchPack(nextLedger);
}
else
WriteLog (lsTRACE, LedgerMaster) << "tryAdvance no fetch pack for " << missing;
}
else
WriteLog (lsDEBUG, LedgerMaster) << "tryAdvance found failed acquire";
}
if (ledger)
{
assert(ledger->getLedgerSeq() == missing);
WriteLog (lsTRACE, LedgerMaster) << "tryAdvance acquired " << ledger->getLedgerSeq();
setFullLedger(ledger, false, false);
if ((mFillInProgress == 0) && (Ledger::getHashByIndex(ledger->getLedgerSeq() - 1) == ledger->getParentHash()))
{ // Previous ledger is in DB
ScopedLockType sl(m_mutex);
mFillInProgress = ledger->getLedgerSeq();
getApp().getJobQueue().addJob(jtADVANCE, "tryFill", std::bind (
&LedgerMasterImp::tryFill, this,
std::placeholders::_1, ledger));
}
progress = true;
}
else
{
try
{
for (int i = 0; i < getConfig().getSize(siLedgerFetch); ++i)
{
std::uint32_t seq = missing - i;
uint256 hash = nextLedger->getLedgerHash(seq);
if (hash.isNonZero())
getApp().getInboundLedgers().findCreate(hash,
seq, InboundLedger::fcHISTORY);
}
}
catch (...)
{
WriteLog (lsWARNING, LedgerMaster) << "Threw while prefecthing";
}
}
}
else
{
WriteLog (lsFATAL, LedgerMaster) << "Unable to find ledger following prevMissing " << missing;
WriteLog (lsFATAL, LedgerMaster) << "Pub:" << mPubLedgerSeq << " Val:" << mValidLedgerSeq;
WriteLog (lsFATAL, LedgerMaster) << "Ledgers: " << getApp().getLedgerMaster().getCompleteLedgers();
clearLedger (missing + 1);
progress = true;
}
}
if (mValidLedgerSeq != mPubLedgerSeq)
{
WriteLog (lsDEBUG, LedgerMaster) << "tryAdvance found last valid changed";
progress = true;
}
}
}
else
WriteLog (lsTRACE, LedgerMaster) << "tryAdvance not fetching history";
}
else
{
WriteLog (lsTRACE, LedgerMaster) <<
"tryAdvance found " << pubLedgers.size() <<
" ledgers to publish";
for(auto ledger : pubLedgers)
{
{
ScopedUnlockType sul (m_mutex);