-
Notifications
You must be signed in to change notification settings - Fork 1.5k
/
LedgerMaster.cpp
2398 lines (2091 loc) · 71.7 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/app/consensus/RCLValidations.h>
#include <ripple/app/ledger/Ledger.h>
#include <ripple/app/ledger/LedgerMaster.h>
#include <ripple/app/ledger/LedgerReplayer.h>
#include <ripple/app/ledger/OpenLedger.h>
#include <ripple/app/ledger/OrderBookDB.h>
#include <ripple/app/ledger/PendingSaves.h>
#include <ripple/app/main/Application.h>
#include <ripple/app/misc/AmendmentTable.h>
#include <ripple/app/misc/HashRouter.h>
#include <ripple/app/misc/LoadFeeTrack.h>
#include <ripple/app/misc/NetworkOPs.h>
#include <ripple/app/misc/SHAMapStore.h>
#include <ripple/app/misc/Transaction.h>
#include <ripple/app/misc/TxQ.h>
#include <ripple/app/misc/ValidatorList.h>
#include <ripple/app/paths/PathRequests.h>
#include <ripple/app/rdb/backend/PostgresDatabase.h>
#include <ripple/app/tx/apply.h>
#include <ripple/basics/Log.h>
#include <ripple/basics/MathUtilities.h>
#include <ripple/basics/TaggedCache.h>
#include <ripple/basics/UptimeClock.h>
#include <ripple/basics/contract.h>
#include <ripple/basics/safe_cast.h>
#include <ripple/core/DatabaseCon.h>
#include <ripple/core/Pg.h>
#include <ripple/core/TimeKeeper.h>
#include <ripple/nodestore/DatabaseShard.h>
#include <ripple/overlay/Overlay.h>
#include <ripple/overlay/Peer.h>
#include <ripple/protocol/BuildInfo.h>
#include <ripple/protocol/HashPrefix.h>
#include <ripple/protocol/digest.h>
#include <ripple/resource/Fees.h>
#include <algorithm>
#include <cassert>
#include <chrono>
#include <cstdlib>
#include <limits>
#include <memory>
#include <vector>
namespace ripple {
namespace {
//==============================================================================
/**
Automatically unlocks and re-locks a unique_lock object.
This is the reverse of a std::unique_lock object - instead of locking the
mutex for the lifetime of this object, it unlocks it.
Make sure you don't try to unlock mutexes that aren't actually locked!
This is essentially a less-versatile boost::reverse_lock.
e.g. @code
std::mutex mut;
for (;;)
{
std::unique_lock myScopedLock{mut};
// mut is now locked
... do some stuff with it locked ..
while (xyz)
{
... do some stuff with it locked ..
ScopedUnlock unlocker{myScopedLock};
// mut is now unlocked for the remainder of this block,
// and re-locked at the end.
...do some stuff with it unlocked ...
} // mut gets locked here.
} // mut gets unlocked here
@endcode
*/
template <class MutexType>
class ScopedUnlock
{
std::unique_lock<MutexType>& lock_;
public:
/** Creates a ScopedUnlock.
As soon as it is created, this will unlock the unique_lock, and
when the ScopedLock object is deleted, the unique_lock will
be re-locked.
Make sure this object is created and deleted by the same thread,
otherwise there are no guarantees what will happen! Best just to use it
as a local stack object, rather than creating on the heap.
*/
explicit ScopedUnlock(std::unique_lock<MutexType>& lock) : lock_(lock)
{
assert(lock_.owns_lock());
lock_.unlock();
}
ScopedUnlock(ScopedUnlock const&) = delete;
ScopedUnlock&
operator=(ScopedUnlock const&) = delete;
/** Destructor.
The unique_lock will be locked after the destructor is called.
Make sure this object is created and deleted by the same thread,
otherwise there are no guarantees what will happen!
*/
~ScopedUnlock() noexcept(false)
{
lock_.lock();
}
};
} // namespace
// Don't catch up more than 100 ledgers (cannot exceed 256)
static constexpr int MAX_LEDGER_GAP{100};
// Don't acquire history if ledger is too old
static constexpr std::chrono::minutes MAX_LEDGER_AGE_ACQUIRE{1};
// Don't acquire history if write load is too high
static constexpr int MAX_WRITE_LOAD_ACQUIRE{8192};
// Helper function for LedgerMaster::doAdvance()
// Return true if candidateLedger should be fetched from the network.
static bool
shouldAcquire(
std::uint32_t const currentLedger,
std::uint32_t const ledgerHistory,
std::optional<LedgerIndex> const minimumOnline,
std::uint32_t const candidateLedger,
beast::Journal j)
{
bool const ret = [&]() {
// Fetch ledger if it may be the current ledger
if (candidateLedger >= currentLedger)
return true;
// Or if it is within our configured history range:
if (currentLedger - candidateLedger <= ledgerHistory)
return true;
// Or if greater than or equal to a specific minimum ledger.
// Do nothing if the minimum ledger to keep online is unknown.
return minimumOnline.has_value() && candidateLedger >= *minimumOnline;
}();
JLOG(j.trace()) << "Missing ledger " << candidateLedger
<< (ret ? " should" : " should NOT") << " be acquired";
return ret;
}
LedgerMaster::LedgerMaster(
Application& app,
Stopwatch& stopwatch,
beast::insight::Collector::ptr const& collector,
beast::Journal journal)
: app_(app)
, m_journal(journal)
, mLedgerHistory(collector, app)
, standalone_(app_.config().standalone())
, fetch_depth_(
app_.getSHAMapStore().clampFetchDepth(app_.config().FETCH_DEPTH))
, ledger_history_(app_.config().LEDGER_HISTORY)
, ledger_fetch_size_(app_.config().getValueFor(SizedItem::ledgerFetch))
, fetch_packs_(
"FetchPack",
65536,
std::chrono::seconds{45},
stopwatch,
app_.journal("TaggedCache"))
, m_stats(std::bind(&LedgerMaster::collect_metrics, this), collector)
{
}
LedgerIndex
LedgerMaster::getCurrentLedgerIndex()
{
return app_.openLedger().current()->info().seq;
}
LedgerIndex
LedgerMaster::getValidLedgerIndex()
{
return mValidLedgerSeq;
}
bool
LedgerMaster::isCompatible(
ReadView const& view,
beast::Journal::Stream s,
char const* reason)
{
auto validLedger = getValidatedLedger();
if (validLedger && !areCompatible(*validLedger, view, s, reason))
{
return false;
}
{
std::lock_guard sl(m_mutex);
if ((mLastValidLedger.second != 0) &&
!areCompatible(
mLastValidLedger.first,
mLastValidLedger.second,
view,
s,
reason))
{
return false;
}
}
return true;
}
std::chrono::seconds
LedgerMaster::getPublishedLedgerAge()
{
using namespace std::chrono_literals;
std::chrono::seconds pubClose{mPubLedgerClose.load()};
if (pubClose == 0s)
{
JLOG(m_journal.debug()) << "No published ledger";
return weeks{2};
}
std::chrono::seconds ret = app_.timeKeeper().closeTime().time_since_epoch();
ret -= pubClose;
ret = (ret > 0s) ? ret : 0s;
static std::chrono::seconds lastRet = -1s;
if (ret != lastRet)
{
JLOG(m_journal.trace()) << "Published ledger age is " << ret.count();
lastRet = ret;
}
return ret;
}
std::chrono::seconds
LedgerMaster::getValidatedLedgerAge()
{
using namespace std::chrono_literals;
#ifdef RIPPLED_REPORTING
if (app_.config().reporting())
return static_cast<PostgresDatabase*>(&app_.getRelationalDatabase())
->getValidatedLedgerAge();
#endif
std::chrono::seconds valClose{mValidLedgerSign.load()};
if (valClose == 0s)
{
JLOG(m_journal.debug()) << "No validated ledger";
return weeks{2};
}
std::chrono::seconds ret = app_.timeKeeper().closeTime().time_since_epoch();
ret -= valClose;
ret = (ret > 0s) ? ret : 0s;
static std::chrono::seconds lastRet = -1s;
if (ret != lastRet)
{
JLOG(m_journal.trace()) << "Validated ledger age is " << ret.count();
lastRet = ret;
}
return ret;
}
bool
LedgerMaster::isCaughtUp(std::string& reason)
{
using namespace std::chrono_literals;
#ifdef RIPPLED_REPORTING
if (app_.config().reporting())
return static_cast<PostgresDatabase*>(&app_.getRelationalDatabase())
->isCaughtUp(reason);
#endif
if (getPublishedLedgerAge() > 3min)
{
reason = "No recently-published ledger";
return false;
}
std::uint32_t validClose = mValidLedgerSign.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
LedgerMaster::setValidLedger(std::shared_ptr<Ledger const> const& l)
{
std::vector<NetClock::time_point> times;
std::optional<uint256> consensusHash;
if (!standalone_)
{
auto validations = app_.validators().negativeUNLFilter(
app_.getValidations().getTrustedForLedger(
l->info().hash, l->info().seq));
times.reserve(validations.size());
for (auto const& val : validations)
times.push_back(val->getSignTime());
if (!validations.empty())
consensusHash = validations.front()->getConsensusHash();
}
NetClock::time_point signTime;
if (!times.empty() && times.size() >= app_.validators().quorum())
{
// Calculate the sample median
std::sort(times.begin(), times.end());
auto const t0 = times[(times.size() - 1) / 2];
auto const t1 = times[times.size() / 2];
signTime = t0 + (t1 - t0) / 2;
}
else
{
signTime = l->info().closeTime;
}
mValidLedger.set(l);
// In case we're waiting for a valid before proceeding with Consensus.
validCond_.notify_one();
mValidLedgerSign = signTime.time_since_epoch().count();
assert(
mValidLedgerSeq || !app_.getMaxDisallowedLedger() ||
l->info().seq + max_ledger_difference_ > app_.getMaxDisallowedLedger());
(void)max_ledger_difference_;
mValidLedgerSeq = l->info().seq;
app_.getOPs().updateLocalTx(*l);
app_.getSHAMapStore().onLedgerClosed(getValidatedLedger());
mLedgerHistory.validatedLedger(l, consensusHash);
app_.getAmendmentTable().doValidatedLedger(l);
if (!app_.getOPs().isBlocked())
{
if (app_.getAmendmentTable().hasUnsupportedEnabled())
{
JLOG(m_journal.error()) << "One or more unsupported amendments "
"activated: server blocked.";
app_.getOPs().setAmendmentBlocked();
}
else if (!app_.getOPs().isAmendmentWarned() || l->isFlagLedger())
{
// Amendments can lose majority, so re-check periodically (every
// flag ledger), and clear the flag if appropriate. If an unknown
// amendment gains majority log a warning as soon as it's
// discovered, then again every flag ledger until the operator
// upgrades, the amendment loses majority, or the amendment goes
// live and the node gets blocked. Unlike being amendment blocked,
// this message may be logged more than once per session, because
// the node will otherwise function normally, and this gives
// operators an opportunity to see and resolve the warning.
if (auto const first =
app_.getAmendmentTable().firstUnsupportedExpected())
{
JLOG(m_journal.error()) << "One or more unsupported amendments "
"reached majority. Upgrade before "
<< to_string(*first)
<< " to prevent your server from "
"becoming amendment blocked.";
app_.getOPs().setAmendmentWarned();
}
else
app_.getOPs().clearAmendmentWarned();
}
}
}
void
LedgerMaster::setPubLedger(std::shared_ptr<Ledger const> const& l)
{
mPubLedger = l;
mPubLedgerClose = l->info().closeTime.time_since_epoch().count();
mPubLedgerSeq = l->info().seq;
}
void
LedgerMaster::addHeldTransaction(
std::shared_ptr<Transaction> const& transaction)
{
std::lock_guard ml(m_mutex);
mHeldTransactions.insert(transaction->getSTransaction());
}
// Validate a ledger's close time and sequence number if we're considering
// jumping to that ledger. This helps defend against some rare hostile or
// diverged majority scenarios.
bool
LedgerMaster::canBeCurrent(std::shared_ptr<Ledger const> const& ledger)
{
assert(ledger);
// Never jump to a candidate ledger that precedes our
// last validated ledger
auto validLedger = getValidatedLedger();
if (validLedger && (ledger->info().seq < validLedger->info().seq))
{
JLOG(m_journal.trace())
<< "Candidate for current ledger has low seq " << ledger->info().seq
<< " < " << validLedger->info().seq;
return false;
}
// Ensure this ledger's parent close time is within five minutes of
// our current time. If we already have a known fully-valid ledger
// we perform this check. Otherwise, we only do it if we've built a
// few ledgers as our clock can be off when we first start up
auto closeTime = app_.timeKeeper().closeTime();
auto ledgerClose = ledger->info().parentCloseTime;
using namespace std::chrono_literals;
if ((validLedger || (ledger->info().seq > 10)) &&
((std::max(closeTime, ledgerClose) - std::min(closeTime, ledgerClose)) >
5min))
{
JLOG(m_journal.warn())
<< "Candidate for current ledger has close time "
<< to_string(ledgerClose) << " at network time "
<< to_string(closeTime) << " seq " << ledger->info().seq;
return false;
}
if (validLedger)
{
// Sequence number must not be too high. We allow ten ledgers
// for time inaccuracies plus a maximum run rate of one ledger
// every two seconds. The goal is to prevent a malicious ledger
// from increasing our sequence unreasonably high
LedgerIndex maxSeq = validLedger->info().seq + 10;
if (closeTime > validLedger->info().parentCloseTime)
maxSeq += std::chrono::duration_cast<std::chrono::seconds>(
closeTime - validLedger->info().parentCloseTime)
.count() /
2;
if (ledger->info().seq > maxSeq)
{
JLOG(m_journal.warn())
<< "Candidate for current ledger has high seq "
<< ledger->info().seq << " > " << maxSeq;
return false;
}
JLOG(m_journal.trace())
<< "Acceptable seq range: " << validLedger->info().seq
<< " <= " << ledger->info().seq << " <= " << maxSeq;
}
return true;
}
void
LedgerMaster::switchLCL(std::shared_ptr<Ledger const> const& lastClosed)
{
assert(lastClosed);
if (!lastClosed->isImmutable())
LogicError("mutable ledger in switchLCL");
if (lastClosed->open())
LogicError("The new last closed ledger is open!");
{
std::lock_guard ml(m_mutex);
mClosedLedger.set(lastClosed);
}
if (standalone_)
{
setFullLedger(lastClosed, true, false);
tryAdvance();
}
else
{
checkAccept(lastClosed);
}
}
bool
LedgerMaster::fixIndex(LedgerIndex ledgerIndex, LedgerHash const& ledgerHash)
{
return mLedgerHistory.fixIndex(ledgerIndex, ledgerHash);
}
bool
LedgerMaster::storeLedger(std::shared_ptr<Ledger const> ledger)
{
bool validated = ledger->info().validated;
// Returns true if we already had the ledger
return mLedgerHistory.insert(std::move(ledger), validated);
}
/** 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
LedgerMaster::applyHeldTransactions()
{
std::lock_guard sl(m_mutex);
// It can be expensive to modify the open ledger even with no transactions
// to process. Regardless, make sure to reset held transactions with
// the parent.
if (mHeldTransactions.size())
{
app_.openLedger().modify([&](OpenView& view, beast::Journal j) {
bool any = false;
for (auto const& it : mHeldTransactions)
{
ApplyFlags flags = tapNONE;
auto const result =
app_.getTxQ().apply(app_, view, it.second, flags, j);
if (result.second)
any = true;
}
return any;
});
}
// VFALCO NOTE The hash for an open ledger is undefined so we use
// something that is a reasonable substitute.
mHeldTransactions.reset(app_.openLedger().current()->info().parentHash);
}
std::shared_ptr<STTx const>
LedgerMaster::popAcctTransaction(std::shared_ptr<STTx const> const& tx)
{
std::lock_guard sl(m_mutex);
return mHeldTransactions.popAcctTransaction(tx);
}
void
LedgerMaster::setBuildingLedger(LedgerIndex i)
{
mBuildingLedgerSeq.store(i);
}
bool
LedgerMaster::haveLedger(std::uint32_t seq)
{
std::lock_guard sl(mCompleteLock);
return boost::icl::contains(mCompleteLedgers, seq);
}
void
LedgerMaster::clearLedger(std::uint32_t seq)
{
std::lock_guard sl(mCompleteLock);
mCompleteLedgers.erase(seq);
}
// returns Ledgers we have all the nodes for
bool
LedgerMaster::getFullValidatedRange(
std::uint32_t& minVal,
std::uint32_t& maxVal)
{
// Validated ledger is likely not stored in the DB yet so we use the
// published ledger which is.
maxVal = mPubLedgerSeq.load();
if (!maxVal)
return false;
std::optional<std::uint32_t> maybeMin;
{
std::lock_guard sl(mCompleteLock);
maybeMin = prevMissing(mCompleteLedgers, maxVal);
}
if (maybeMin == std::nullopt)
minVal = maxVal;
else
minVal = 1 + *maybeMin;
return true;
}
// Returns Ledgers we have all the nodes for and are indexed
bool
LedgerMaster::getValidatedRange(std::uint32_t& minVal, std::uint32_t& maxVal)
{
if (app_.config().reporting())
{
std::string res = getCompleteLedgers();
try
{
if (res == "empty" || res == "error" || res.empty())
return false;
else if (size_t delim = res.find('-'); delim != std::string::npos)
{
minVal = std::stol(res.substr(0, delim));
maxVal = std::stol(res.substr(delim + 1));
}
else
{
minVal = maxVal = std::stol(res);
}
return true;
}
catch (std::exception const& e)
{
JLOG(m_journal.error()) << "LedgerMaster::getValidatedRange: "
"exception parsing complete ledgers: "
<< e.what();
return false;
}
}
if (!getFullValidatedRange(minVal, maxVal))
return false;
// Remove from the validated range any ledger sequences that may not be
// fully updated in the database yet
auto const pendingSaves = app_.pendingSaves().getSnapshot();
if (!pendingSaves.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 (pendingSaves.count(maxVal) > 0)
--maxVal;
while (pendingSaves.count(minVal) > 0)
++minVal;
// Best effort for remaining exclusions
for (auto v : pendingSaves)
{
if ((v.first >= minVal) && (v.first <= maxVal))
{
if (v.first > ((minVal + maxVal) / 2))
maxVal = v.first - 1;
else
minVal = v.first + 1;
}
}
if (minVal > maxVal)
minVal = maxVal = 0;
}
return true;
}
// Get the earliest ledger we will let peers fetch
std::uint32_t
LedgerMaster::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()->info().seq;
if (e > fetch_depth_)
e -= fetch_depth_;
else
e = 0;
return e;
}
void
LedgerMaster::tryFill(std::shared_ptr<Ledger const> ledger)
{
std::uint32_t seq = ledger->info().seq;
uint256 prevHash = ledger->info().parentHash;
std::map<std::uint32_t, LedgerHashPair> ledgerHashes;
std::uint32_t minHas = seq;
std::uint32_t maxHas = seq;
NodeStore::Database& nodeStore{app_.getNodeStore()};
while (!app_.getJobQueue().isStopping() && seq > 0)
{
{
std::lock_guard ml(m_mutex);
minHas = seq;
--seq;
if (haveLedger(seq))
break;
}
auto it(ledgerHashes.find(seq));
if (it == ledgerHashes.end())
{
if (app_.isStopping())
return;
{
std::lock_guard ml(mCompleteLock);
mCompleteLedgers.insert(range(minHas, maxHas));
}
maxHas = minHas;
ledgerHashes = app_.getRelationalDatabase().getHashesByIndex(
(seq < 500) ? 0 : (seq - 499), seq);
it = ledgerHashes.find(seq);
if (it == ledgerHashes.end())
break;
if (!nodeStore.fetchNodeObject(
ledgerHashes.begin()->second.ledgerHash,
ledgerHashes.begin()->first))
{
// The ledger is not backed by the node store
JLOG(m_journal.warn()) << "SQL DB ledger sequence " << seq
<< " mismatches node store";
break;
}
}
if (it->second.ledgerHash != prevHash)
break;
prevHash = it->second.parentHash;
}
{
std::lock_guard ml(mCompleteLock);
mCompleteLedgers.insert(range(minHas, maxHas));
}
{
std::lock_guard ml(m_mutex);
mFillInProgress = 0;
tryAdvance();
}
}
/** Request a fetch pack to get to the specified ledger
*/
void
LedgerMaster::getFetchPack(LedgerIndex missing, InboundLedger::Reason reason)
{
LedgerIndex const ledgerIndex([&]() {
if (reason == InboundLedger::Reason::SHARD)
{
// Do not acquire a ledger sequence greater
// than the last ledger in the shard
auto const shardStore{app_.getShardStore()};
auto const shardIndex{shardStore->seqToShardIndex(missing)};
return std::min(missing + 1, shardStore->lastLedgerSeq(shardIndex));
}
return missing + 1;
}());
auto const haveHash{getLedgerHashForHistory(ledgerIndex, reason)};
if (!haveHash || haveHash->isZero())
{
if (reason == InboundLedger::Reason::SHARD)
{
auto const shardStore{app_.getShardStore()};
auto const shardIndex{shardStore->seqToShardIndex(missing)};
if (missing < shardStore->lastLedgerSeq(shardIndex))
{
JLOG(m_journal.error())
<< "No hash for fetch pack. "
<< "Missing ledger sequence " << missing
<< " while acquiring shard " << shardIndex;
}
}
else
{
JLOG(m_journal.error())
<< "No hash for fetch pack. Missing Index " << missing;
}
return;
}
// Select target Peer based on highest score. The score is randomized
// but biased in favor of Peers with low latency.
std::shared_ptr<Peer> target;
{
int maxScore = 0;
auto peerList = app_.overlay().getActivePeers();
for (auto const& peer : peerList)
{
if (peer->hasRange(missing, missing + 1))
{
int score = peer->getScore(true);
if (!target || (score > maxScore))
{
target = peer;
maxScore = score;
}
}
}
}
if (target)
{
protocol::TMGetObjectByHash tmBH;
tmBH.set_query(true);
tmBH.set_type(protocol::TMGetObjectByHash::otFETCH_PACK);
tmBH.set_ledgerhash(haveHash->begin(), 32);
auto packet = std::make_shared<Message>(tmBH, protocol::mtGET_OBJECTS);
target->send(packet);
JLOG(m_journal.trace()) << "Requested fetch pack for " << missing;
}
else
JLOG(m_journal.debug()) << "No peer for fetch pack";
}
void
LedgerMaster::fixMismatch(ReadView const& ledger)
{
int invalidate = 0;
std::optional<uint256> hash;
for (std::uint32_t lSeq = ledger.info().seq - 1; lSeq > 0; --lSeq)
{
if (haveLedger(lSeq))
{
try
{
hash = hashOfSeq(ledger, lSeq, m_journal);
}
catch (std::exception const& ex)
{
JLOG(m_journal.warn())
<< "fixMismatch encounters partial ledger. Exception: "
<< ex.what();
clearLedger(lSeq);
return;
}
if (hash)
{
// try to close the seam
auto otherLedger = getLedgerBySeq(lSeq);
if (otherLedger && (otherLedger->info().hash == *hash))
{
// we closed the seam
if (invalidate != 0)
{
JLOG(m_journal.warn())
<< "Match at " << lSeq << ", " << invalidate
<< " prior ledgers invalidated";
}
return;
}
}
clearLedger(lSeq);
++invalidate;
}
}
// all prior ledgers invalidated
if (invalidate != 0)
{
JLOG(m_journal.warn())
<< "All " << invalidate << " prior ledgers invalidated";
}
}
void
LedgerMaster::setFullLedger(
std::shared_ptr<Ledger const> const& ledger,
bool isSynchronous,
bool isCurrent)
{
// A new ledger has been accepted as part of the trusted chain
JLOG(m_journal.debug()) << "Ledger " << ledger->info().seq
<< " accepted :" << ledger->info().hash;
assert(ledger->stateMap().getHash().isNonZero());
ledger->setValidated();
ledger->setFull();
if (isCurrent)
mLedgerHistory.insert(ledger, true);
{
// Check the SQL database's entry for the sequence before this
// ledger, if it's not this ledger's parent, invalidate it
uint256 prevHash =
app_.getRelationalDatabase().getHashByIndex(ledger->info().seq - 1);
if (prevHash.isNonZero() && prevHash != ledger->info().parentHash)
clearLedger(ledger->info().seq - 1);
}
pendSaveValidated(app_, ledger, isSynchronous, isCurrent);
{
std::lock_guard ml(mCompleteLock);
mCompleteLedgers.insert(ledger->info().seq);
}
{
std::lock_guard ml(m_mutex);
if (ledger->info().seq > mValidLedgerSeq)
setValidLedger(ledger);
if (!mPubLedger)
{
setPubLedger(ledger);
app_.getOrderBookDB().setup(ledger);
}
if (ledger->info().seq != 0 && haveLedger(ledger->info().seq - 1))
{
// we think we have the previous ledger, double check
auto prevLedger = getLedgerBySeq(ledger->info().seq - 1);
if (!prevLedger ||
(prevLedger->info().hash != ledger->info().parentHash))
{
JLOG(m_journal.warn())
<< "Acquired ledger invalidates previous ledger: "
<< (prevLedger ? "hashMismatch" : "missingLedger");
fixMismatch(*ledger);
}
}
}
}
void
LedgerMaster::failedSave(std::uint32_t seq, uint256 const& hash)
{
clearLedger(seq);
app_.getInboundLedgers().acquire(hash, seq, InboundLedger::Reason::GENERIC);
}
// Check if the specified ledger can become the new last fully-validated
// ledger.
void
LedgerMaster::checkAccept(uint256 const& hash, std::uint32_t seq)
{
std::size_t valCount = 0;
if (seq != 0)
{
// Ledger is too old
if (seq < mValidLedgerSeq)
return;
auto validations = app_.validators().negativeUNLFilter(
app_.getValidations().getTrustedForLedger(hash, seq));
valCount = validations.size();
if (valCount >= app_.validators().quorum())
{