forked from stellar/stellar-core
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathHerderImpl.cpp
2389 lines (2127 loc) · 74.5 KB
/
HerderImpl.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
// Copyright 2014 Stellar Development Foundation and contributors. Licensed
// under the Apache License, Version 2.0. See the COPYING file at the root
// of this distribution or at http://www.apache.org/licenses/LICENSE-2.0
#include "herder/HerderImpl.h"
#include "crypto/Hex.h"
#include "crypto/KeyUtils.h"
#include "crypto/SHA.h"
#include "crypto/SecretKey.h"
#include "herder/HerderPersistence.h"
#include "herder/HerderUtils.h"
#include "herder/LedgerCloseData.h"
#include "herder/QuorumIntersectionChecker.h"
#include "herder/TxSetFrame.h"
#include "herder/TxSetUtils.h"
#include "ledger/LedgerManager.h"
#include "ledger/LedgerTxn.h"
#include "ledger/LedgerTxnEntry.h"
#include "ledger/LedgerTxnHeader.h"
#include "lib/json/json.h"
#include "main/Application.h"
#include "main/Config.h"
#include "main/ErrorMessages.h"
#include "main/PersistentState.h"
#include "overlay/OverlayManager.h"
#include "scp/LocalNode.h"
#include "scp/Slot.h"
#include "transactions/TransactionUtils.h"
#include "util/DebugMetaUtils.h"
#include "util/LogSlowExecution.h"
#include "util/Logging.h"
#include "util/StatusManager.h"
#include "util/Timer.h"
#include "medida/counter.h"
#include "medida/meter.h"
#include "medida/metrics_registry.h"
#include "util/Decoder.h"
#include "util/XDRStream.h"
#include "xdr/Stellar-internal.h"
#include "xdrpp/marshal.h"
#include "xdrpp/types.h"
#include <Tracy.hpp>
#include "util/GlobalChecks.h"
#include <algorithm>
#include <ctime>
#include <fmt/format.h>
using namespace std;
namespace stellar
{
constexpr uint32 const TRANSACTION_QUEUE_TIMEOUT_LEDGERS = 4;
constexpr uint32 const TRANSACTION_QUEUE_BAN_LEDGERS = 10;
constexpr uint32 const TRANSACTION_QUEUE_SIZE_MULTIPLIER = 2;
constexpr uint32 const SOROBAN_TRANSACTION_QUEUE_SIZE_MULTIPLIER = 2;
std::unique_ptr<Herder>
Herder::create(Application& app)
{
return std::make_unique<HerderImpl>(app);
}
HerderImpl::SCPMetrics::SCPMetrics(Application& app)
: mLostSync(app.getMetrics().NewMeter({"scp", "sync", "lost"}, "sync"))
, mEnvelopeEmit(
app.getMetrics().NewMeter({"scp", "envelope", "emit"}, "envelope"))
, mEnvelopeReceive(
app.getMetrics().NewMeter({"scp", "envelope", "receive"}, "envelope"))
, mCumulativeStatements(app.getMetrics().NewCounter(
{"scp", "memory", "cumulative-statements"}))
, mEnvelopeValidSig(app.getMetrics().NewMeter(
{"scp", "envelope", "validsig"}, "envelope"))
, mEnvelopeInvalidSig(app.getMetrics().NewMeter(
{"scp", "envelope", "invalidsig"}, "envelope"))
{
}
HerderImpl::HerderImpl(Application& app)
: mTransactionQueue(app, TRANSACTION_QUEUE_TIMEOUT_LEDGERS,
TRANSACTION_QUEUE_BAN_LEDGERS,
TRANSACTION_QUEUE_SIZE_MULTIPLIER)
, mPendingEnvelopes(app, *this)
, mHerderSCPDriver(app, *this, mUpgrades, mPendingEnvelopes)
, mLastSlotSaved(0)
, mTrackingTimer(app)
, mLastExternalize(app.getClock().now())
, mTriggerTimer(app)
, mOutOfSyncTimer(app)
, mTxSetGarbageCollectTimer(app)
, mApp(app)
, mLedgerManager(app.getLedgerManager())
, mSCPMetrics(app)
, mState(Herder::HERDER_BOOTING_STATE)
{
auto ln = getSCP().getLocalNode();
mPendingEnvelopes.addSCPQuorumSet(ln->getQuorumSetHash(),
ln->getQuorumSet());
}
HerderImpl::~HerderImpl()
{
}
Herder::State
HerderImpl::getState() const
{
return mState;
}
uint32_t
HerderImpl::getMaxClassicTxSize() const
{
#ifdef BUILD_TESTS
if (mMaxClassicTxSize)
{
return *mMaxClassicTxSize;
}
#endif
return MAX_CLASSIC_TX_SIZE_BYTES;
}
uint32_t
HerderImpl::getFlowControlExtraBuffer() const
{
#ifdef BUILD_TESTS
if (mFlowControlExtraBuffer)
{
return *mFlowControlExtraBuffer;
}
#endif
return FLOW_CONTROL_BYTES_EXTRA_BUFFER;
}
void
HerderImpl::setTrackingSCPState(uint64_t index, StellarValue const& value,
bool isTrackingNetwork)
{
mTrackingSCP = ConsensusData{index, value.closeTime};
if (isTrackingNetwork)
{
setState(Herder::HERDER_TRACKING_NETWORK_STATE);
}
else
{
setState(Herder::HERDER_SYNCING_STATE);
}
}
uint32
HerderImpl::trackingConsensusLedgerIndex() const
{
releaseAssert(getState() != Herder::State::HERDER_BOOTING_STATE);
releaseAssert(mTrackingSCP.mConsensusIndex <= UINT32_MAX);
auto lcl = mLedgerManager.getLastClosedLedgerNum();
if (lcl > mTrackingSCP.mConsensusIndex)
{
std::string msg =
"Inconsistent state in Herder: LCL is ahead of tracking";
CLOG_ERROR(Herder, "{}", msg);
CLOG_ERROR(Herder, "{}", REPORT_INTERNAL_BUG);
throw std::runtime_error(msg);
}
return static_cast<uint32>(mTrackingSCP.mConsensusIndex);
}
TimePoint
HerderImpl::trackingConsensusCloseTime() const
{
releaseAssert(getState() != Herder::State::HERDER_BOOTING_STATE);
return mTrackingSCP.mConsensusCloseTime;
}
void
HerderImpl::setState(State st)
{
bool initState = st == HERDER_BOOTING_STATE;
if (initState && (mState == HERDER_TRACKING_NETWORK_STATE ||
mState == HERDER_SYNCING_STATE))
{
throw std::runtime_error(fmt::format(
FMT_STRING("Invalid state transition in Herder: {} -> {}"),
getStateHuman(mState), getStateHuman(st)));
}
mState = st;
}
void
HerderImpl::lostSync()
{
mHerderSCPDriver.stateChanged();
setState(Herder::State::HERDER_SYNCING_STATE);
}
SCP&
HerderImpl::getSCP()
{
return mHerderSCPDriver.getSCP();
}
void
HerderImpl::syncMetrics()
{
int64_t count = getSCP().getCumulativeStatemtCount();
mSCPMetrics.mCumulativeStatements.set_count(count);
TracyPlot("scp.memory.cumulative-statements", count);
}
std::string
HerderImpl::getStateHuman(State st) const
{
static std::array<const char*, HERDER_NUM_STATE> stateStrings = {
"HERDER_BOOTING_STATE", "HERDER_SYNCING_STATE",
"HERDER_TRACKING_NETWORK_STATE"};
return std::string(stateStrings[st]);
}
void
HerderImpl::bootstrap()
{
CLOG_INFO(Herder, "Force joining SCP with local state");
releaseAssert(getSCP().isValidator());
releaseAssert(mApp.getConfig().FORCE_SCP);
mLedgerManager.moveToSynced();
mHerderSCPDriver.bootstrap();
setupTriggerNextLedger();
newSlotExternalized(
true, mLedgerManager.getLastClosedLedgerHeader().header.scpValue);
}
void
HerderImpl::newSlotExternalized(bool synchronous, StellarValue const& value)
{
ZoneScoped;
CLOG_TRACE(Herder, "HerderImpl::newSlotExternalized");
// start timing next externalize from this point
mLastExternalize = mApp.getClock().now();
// In order to update the transaction queue we need to get the
// applied transactions.
updateTransactionQueue(mPendingEnvelopes.getTxSet(value.txSetHash));
// perform cleanups
// Evict slots that are outside of our ledger validity bracket
auto minSlotToRemember = getMinLedgerSeqToRemember();
if (minSlotToRemember > LedgerManager::GENESIS_LEDGER_SEQ)
{
eraseBelow(minSlotToRemember);
}
mPendingEnvelopes.forceRebuildQuorum();
// Process new ready messages for the next slot
safelyProcessSCPQueue(synchronous);
}
void
HerderImpl::shutdown()
{
mTrackingTimer.cancel();
mOutOfSyncTimer.cancel();
mTriggerTimer.cancel();
if (mLastQuorumMapIntersectionState.mRecalculating)
{
// We want to interrupt any calculation-in-progress at shutdown to
// avoid a long pause joining worker threads.
CLOG_DEBUG(Herder,
"Shutdown interrupting quorum transitive closure analysis.");
mLastQuorumMapIntersectionState.mInterruptFlag = true;
}
mTransactionQueue.shutdown();
if (mSorobanTransactionQueue)
{
mSorobanTransactionQueue->shutdown();
}
mTxSetGarbageCollectTimer.cancel();
}
void
HerderImpl::processExternalized(uint64 slotIndex, StellarValue const& value,
bool isLatestSlot)
{
ZoneScoped;
bool validated = getSCP().isSlotFullyValidated(slotIndex);
CLOG_DEBUG(Herder, "HerderSCPDriver::valueExternalized index: {} txSet: {}",
slotIndex, hexAbbrev(value.txSetHash));
if (getSCP().isValidator() && !validated)
{
CLOG_WARNING(Herder,
"Ledger {} ({}) closed and could NOT be fully "
"validated by validator",
slotIndex, hexAbbrev(value.txSetHash));
}
TxSetXDRFrameConstPtr externalizedSet =
mPendingEnvelopes.getTxSet(value.txSetHash);
// save the SCP messages in the database
if (mApp.getConfig().MODE_STORES_HISTORY_MISC)
{
ZoneNamedN(updateSCPHistoryZone, "update SCP history", true);
if (slotIndex != 0)
{
// Save any new SCP messages received about the previous ledger.
// NOTE: This call uses an empty `QuorumTracker::QuorumMap` because
// there is no new quorum map for the previous ledger.
mApp.getHerderPersistence().saveSCPHistory(
static_cast<uint32>(slotIndex - 1),
getSCP().getExternalizingState(slotIndex - 1),
QuorumTracker::QuorumMap());
}
// Store SCP messages received about the current ledger being closed.
mApp.getHerderPersistence().saveSCPHistory(
static_cast<uint32>(slotIndex),
getSCP().getExternalizingState(slotIndex),
mPendingEnvelopes.getCurrentlyTrackedQuorum());
}
// reflect upgrades with the ones included in this SCP round
{
bool updated;
auto newUpgrades = mUpgrades.removeUpgrades(value.upgrades.begin(),
value.upgrades.end(),
value.closeTime, updated);
if (updated)
{
setUpgrades(newUpgrades);
}
}
// tell the LedgerManager that this value got externalized
// LedgerManager will perform the proper action based on its internal
// state: apply, trigger catchup, etc
LedgerCloseData ledgerData(static_cast<uint32_t>(slotIndex),
externalizedSet, value);
// Only dump the most recent externalized tx set. Ledger sequence on a
// written tx set shall only strictly move forward; it may have gaps with
// the emitted debug meta, if the network is ahead of the local node
// (assumption is that if the network is ahead of the local node, state can
// be replayed from the archives)
if (isLatestSlot && mApp.getConfig().METADATA_DEBUG_LEDGERS != 0)
{
writeDebugTxSet(ledgerData);
}
mLedgerManager.valueExternalized(ledgerData);
// Ensure potential upgrades are handled in overlay
maybeHandleUpgrade();
}
void
HerderImpl::writeDebugTxSet(LedgerCloseData const& lcd)
{
ZoneScoped;
// Dump latest externalized tx set. Do as much of error-handling as possible
// to avoid crashing core, since this is used purely for debugging.
auto path =
metautils::getLatestTxSetFilePath(mApp.getConfig().BUCKET_DIR_PATH);
try
{
if (fs::mkpath(path.parent_path().string()))
{
auto timer = LogSlowExecution(
"write debug tx set", LogSlowExecution::Mode::AUTOMATIC_RAII,
"took", std::chrono::milliseconds(100));
// If we got here, then whatever previous tx set is saved has
// already been applied, and debug meta has been emitted. Therefore,
// it's safe to just remove it.
std::filesystem::remove(path);
XDROutputFileStream stream(mApp.getClock().getIOContext(),
/*fsyncOnClose=*/false);
stream.open(path.string());
stream.writeOne(lcd.toXDR());
}
else
{
CLOG_WARNING(Ledger,
"Failed to make directory '{}' for debug tx set",
path.parent_path().string());
}
}
catch (std::runtime_error& e)
{
CLOG_WARNING(Ledger, "Failed to dump debug tx set '{}': {}",
path.string(), e.what());
}
}
void
HerderImpl::valueExternalized(uint64 slotIndex, StellarValue const& value,
bool isLatestSlot)
{
ZoneScoped;
const int DUMP_SCP_TIMEOUT_SECONDS = 20;
if (isLatestSlot)
{
// called both here and at the end (this one is in case of an exception)
trackingHeartBeat();
// dump SCP information if this ledger took a long time
auto gap = std::chrono::duration<double>(mApp.getClock().now() -
mLastExternalize)
.count();
if (gap > DUMP_SCP_TIMEOUT_SECONDS)
{
auto slotInfo = getJsonQuorumInfo(getSCP().getLocalNodeID(), false,
false, slotIndex);
Json::FastWriter fw;
CLOG_WARNING(Herder, "Ledger took {} seconds, SCP information:{}",
gap, fw.write(slotInfo));
}
// trigger will be recreated when the ledger is closed
// we do not want it to trigger while downloading the current set
// and there is no point in taking a position after the round is over
mTriggerTimer.cancel();
// This call may cause LedgerManager to close ledger and trigger next
// ledger
processExternalized(slotIndex, value, isLatestSlot);
// Perform cleanups, and maybe process SCP queue
newSlotExternalized(false, value);
// Check to see if quorums have changed and we need to reanalyze.
checkAndMaybeReanalyzeQuorumMap();
// heart beat *after* doing all the work (ensures that we do not include
// the overhead of externalization in the way we track SCP)
trackingHeartBeat();
}
else
{
// This call may trigger application of buffered ledgers and in some
// cases a ledger trigger
processExternalized(slotIndex, value, isLatestSlot);
}
}
void
HerderImpl::outOfSyncRecovery()
{
ZoneScoped;
if (isTracking())
{
CLOG_WARNING(Herder,
"HerderImpl::outOfSyncRecovery called when tracking");
return;
}
// see if we can shed some data as to speed up recovery
uint32_t maxSlotsAhead = Herder::LEDGER_VALIDITY_BRACKET;
uint32 purgeSlot = 0;
getSCP().processSlotsDescendingFrom(
std::numeric_limits<uint64>::max(), [&](uint64 seq) {
if (getSCP().gotVBlocking(seq))
{
if (--maxSlotsAhead == 0)
{
purgeSlot = static_cast<uint32>(seq);
}
}
return maxSlotsAhead != 0;
});
if (purgeSlot)
{
CLOG_INFO(Herder, "Purging slots older than {}", purgeSlot);
eraseBelow(purgeSlot);
}
auto const& lcl = mLedgerManager.getLastClosedLedgerHeader().header;
for (auto const& e : getSCP().getLatestMessagesSend(lcl.ledgerSeq + 1))
{
broadcast(e);
}
getMoreSCPState();
}
void
HerderImpl::broadcast(SCPEnvelope const& e)
{
ZoneScoped;
if (!mApp.getConfig().MANUAL_CLOSE)
{
StellarMessage m;
m.type(SCP_MESSAGE);
m.envelope() = e;
CLOG_DEBUG(Herder, "broadcast s:{} i:{}", e.statement.pledges.type(),
e.statement.slotIndex);
mSCPMetrics.mEnvelopeEmit.Mark();
mApp.getOverlayManager().broadcastMessage(m);
}
}
void
HerderImpl::startOutOfSyncTimer()
{
if (mApp.getConfig().MANUAL_CLOSE && mApp.getConfig().RUN_STANDALONE)
{
return;
}
mOutOfSyncTimer.expires_from_now(Herder::OUT_OF_SYNC_RECOVERY_TIMER);
mOutOfSyncTimer.async_wait(
[&]() {
outOfSyncRecovery();
startOutOfSyncTimer();
},
&VirtualTimer::onFailureNoop);
}
void
HerderImpl::emitEnvelope(SCPEnvelope const& envelope)
{
ZoneScoped;
uint64 slotIndex = envelope.statement.slotIndex;
CLOG_DEBUG(Herder, "emitEnvelope s:{} i:{} a:{}",
envelope.statement.pledges.type(), slotIndex,
mApp.getStateHuman());
persistSCPState(slotIndex);
broadcast(envelope);
}
TransactionQueue::AddResult
HerderImpl::recvTransaction(TransactionFrameBasePtr tx, bool submittedFromSelf)
{
ZoneScoped;
TransactionQueue::AddResult result;
// Allow txs of the same kind to reach the tx queue in case it can be
// replaced by fee
bool hasSoroban =
mSorobanTransactionQueue &&
mSorobanTransactionQueue->sourceAccountPending(tx->getSourceID()) &&
!tx->isSoroban();
bool hasClassic =
mTransactionQueue.sourceAccountPending(tx->getSourceID()) &&
tx->isSoroban();
if (hasSoroban || hasClassic)
{
CLOG_DEBUG(Herder,
"recv transaction {} for {} rejected due to 1 tx per source "
"account per ledger limit",
hexAbbrev(tx->getFullHash()),
KeyUtils::toShortString(tx->getSourceID()));
result = TransactionQueue::AddResult::ADD_STATUS_TRY_AGAIN_LATER;
}
else if (!tx->isSoroban())
{
result = mTransactionQueue.tryAdd(tx, submittedFromSelf);
}
else if (mSorobanTransactionQueue)
{
result = mSorobanTransactionQueue->tryAdd(tx, submittedFromSelf);
}
else
{
// Received Soroban transaction before protocol 20; since this
// transaction isn't supported yet, return ERROR
result = TransactionQueue::AddResult::ADD_STATUS_ERROR;
}
if (result == TransactionQueue::AddResult::ADD_STATUS_PENDING)
{
CLOG_TRACE(Herder, "recv transaction {} for {}",
hexAbbrev(tx->getFullHash()),
KeyUtils::toShortString(tx->getSourceID()));
}
return result;
}
bool
HerderImpl::checkCloseTime(SCPEnvelope const& envelope, bool enforceRecent)
{
ZoneScoped;
using std::placeholders::_1;
auto const& st = envelope.statement;
uint64_t ctCutoff = 0;
if (enforceRecent)
{
auto now = VirtualClock::to_time_t(mApp.getClock().system_now());
if (now >= mApp.getConfig().MAXIMUM_LEDGER_CLOSETIME_DRIFT)
{
ctCutoff = now - mApp.getConfig().MAXIMUM_LEDGER_CLOSETIME_DRIFT;
}
}
auto envLedgerIndex = envelope.statement.slotIndex;
auto& scpD = getHerderSCPDriver();
auto const& lcl = mLedgerManager.getLastClosedLedgerHeader().header;
auto lastCloseIndex = lcl.ledgerSeq;
auto lastCloseTime = lcl.scpValue.closeTime;
// see if we can get a better estimate of lastCloseTime for validating this
// statement using consensus data:
// update lastCloseIndex/lastCloseTime to be the highest possible but still
// be less than envLedgerIndex
if (getState() != HERDER_BOOTING_STATE)
{
auto trackingIndex = trackingConsensusLedgerIndex();
if (envLedgerIndex >= trackingIndex && trackingIndex > lastCloseIndex)
{
lastCloseIndex = static_cast<uint32>(trackingIndex);
lastCloseTime = trackingConsensusCloseTime();
}
}
StellarValue sv;
// performs the most conservative check:
// returns true if one of the values is valid
auto checkCTHelper = [&](std::vector<Value> const& values) {
return std::any_of(values.begin(), values.end(), [&](Value const& e) {
auto r = scpD.toStellarValue(e, sv);
// sv must be after cutoff
r = r && sv.closeTime >= ctCutoff;
if (r)
{
// statement received after the fact, only keep externalized
// value
r = (lastCloseIndex == envLedgerIndex &&
lastCloseTime == sv.closeTime);
// for older messages, just ensure that they occurred before
r = r || (lastCloseIndex > envLedgerIndex &&
lastCloseTime > sv.closeTime);
// for future message, perform the same validity check than
// within SCP
r = r || scpD.checkCloseTime(envLedgerIndex, lastCloseTime, sv);
}
return r;
});
};
bool b;
switch (st.pledges.type())
{
case SCP_ST_NOMINATE:
b = checkCTHelper(st.pledges.nominate().accepted) ||
checkCTHelper(st.pledges.nominate().votes);
break;
case SCP_ST_PREPARE:
{
auto& prep = st.pledges.prepare();
b = checkCTHelper({prep.ballot.value});
if (!b && prep.prepared)
{
b = checkCTHelper({prep.prepared->value});
}
if (!b && prep.preparedPrime)
{
b = checkCTHelper({prep.preparedPrime->value});
}
}
break;
case SCP_ST_CONFIRM:
b = checkCTHelper({st.pledges.confirm().ballot.value});
break;
case SCP_ST_EXTERNALIZE:
b = checkCTHelper({st.pledges.externalize().commit.value});
break;
default:
abort();
}
if (!b)
{
CLOG_TRACE(Herder, "Invalid close time processing {}",
getSCP().envToStr(st));
}
return b;
}
uint32_t
HerderImpl::getMinLedgerSeqToRemember() const
{
auto maxSlotsToRemember = mApp.getConfig().MAX_SLOTS_TO_REMEMBER;
auto currSlot = trackingConsensusLedgerIndex();
if (currSlot > maxSlotsToRemember)
{
return (currSlot - maxSlotsToRemember + 1);
}
else
{
return LedgerManager::GENESIS_LEDGER_SEQ;
}
}
Herder::EnvelopeStatus
HerderImpl::recvSCPEnvelope(SCPEnvelope const& envelope)
{
ZoneScoped;
if (mApp.getConfig().MANUAL_CLOSE)
{
return Herder::ENVELOPE_STATUS_DISCARDED;
}
mSCPMetrics.mEnvelopeReceive.Mark();
// **** first perform checks that do NOT require signature verification
// this allows to fast fail messages that we'd throw away anyways
uint32_t minLedgerSeq = getMinLedgerSeqToRemember();
uint32_t maxLedgerSeq = std::numeric_limits<uint32>::max();
if (!checkCloseTime(envelope, false))
{
// if the envelope contains an invalid close time, don't bother
// processing it as we're not going to forward it anyways and it's
// going to just sit in our SCP state not contributing anything useful.
CLOG_TRACE(
Herder,
"skipping invalid close time (incompatible with current state)");
std::string txt("DISCARDED - incompatible close time");
ZoneText(txt.c_str(), txt.size());
return Herder::ENVELOPE_STATUS_DISCARDED;
}
auto checkpoint = getMostRecentCheckpointSeq();
auto index = envelope.statement.slotIndex;
if (isTracking())
{
// when tracking, we can filter messages based on the information we got
// from consensus for the max ledger
// note that this filtering will cause a node on startup
// to potentially drop messages outside of the bracket
// causing it to discard CONSENSUS_STUCK_TIMEOUT_SECONDS worth of
// ledger closing
maxLedgerSeq = nextConsensusLedgerIndex() + LEDGER_VALIDITY_BRACKET;
}
// Allow message with a drift larger than MAXIMUM_LEDGER_CLOSETIME_DRIFT if
// it is a checkpoint message
else if (!checkCloseTime(envelope, trackingConsensusLedgerIndex() <=
LedgerManager::GENESIS_LEDGER_SEQ) &&
index != checkpoint)
{
// if we've never been in sync, we can be more aggressive in how we
// filter messages: we can ignore messages that are unlikely to be
// the latest messages from the network
CLOG_TRACE(Herder, "recvSCPEnvelope: skipping invalid close time "
"(check MAXIMUM_LEDGER_CLOSETIME_DRIFT)");
std::string txt("DISCARDED - invalid close time");
ZoneText(txt.c_str(), txt.size());
return Herder::ENVELOPE_STATUS_DISCARDED;
}
// If envelopes are out of our validity brackets, or if envelope does not
// contain the checkpoint for early catchup, we just ignore them.
if ((index > maxLedgerSeq || index < minLedgerSeq) && index != checkpoint)
{
CLOG_TRACE(Herder, "Ignoring SCPEnvelope outside of range: {}( {},{})",
envelope.statement.slotIndex, minLedgerSeq, maxLedgerSeq);
std::string txt("DISCARDED - out of range");
ZoneText(txt.c_str(), txt.size());
return Herder::ENVELOPE_STATUS_DISCARDED;
}
// **** from this point, we have to check signatures
if (!verifyEnvelope(envelope))
{
std::string txt("DISCARDED - bad envelope");
ZoneText(txt.c_str(), txt.size());
CLOG_TRACE(Herder, "Received bad envelope, discarding");
return Herder::ENVELOPE_STATUS_DISCARDED;
}
if (envelope.statement.nodeID == getSCP().getLocalNode()->getNodeID())
{
CLOG_TRACE(Herder, "recvSCPEnvelope: skipping own message");
std::string txt("SKIPPED_SELF");
ZoneText(txt.c_str(), txt.size());
return Herder::ENVELOPE_STATUS_SKIPPED_SELF;
}
auto status = mPendingEnvelopes.recvSCPEnvelope(envelope);
if (status == Herder::ENVELOPE_STATUS_READY)
{
std::string txt("READY");
ZoneText(txt.c_str(), txt.size());
CLOG_DEBUG(Herder, "recvSCPEnvelope (ready) from: {} s:{} i:{} a:{}",
mApp.getConfig().toShortString(envelope.statement.nodeID),
envelope.statement.pledges.type(),
envelope.statement.slotIndex, mApp.getStateHuman());
processSCPQueue();
}
else
{
if (status == Herder::ENVELOPE_STATUS_FETCHING)
{
std::string txt("FETCHING");
ZoneText(txt.c_str(), txt.size());
}
else if (status == Herder::ENVELOPE_STATUS_PROCESSED)
{
std::string txt("PROCESSED");
ZoneText(txt.c_str(), txt.size());
}
CLOG_TRACE(Herder, "recvSCPEnvelope ({}) from: {} s:{} i:{} a:{}",
static_cast<int>(status),
mApp.getConfig().toShortString(envelope.statement.nodeID),
envelope.statement.pledges.type(),
envelope.statement.slotIndex, mApp.getStateHuman());
}
return status;
}
#ifdef BUILD_TESTS
Herder::EnvelopeStatus
HerderImpl::recvSCPEnvelope(SCPEnvelope const& envelope,
const SCPQuorumSet& qset,
TxSetXDRFrameConstPtr txset)
{
ZoneScoped;
mPendingEnvelopes.addTxSet(txset->getContentsHash(),
envelope.statement.slotIndex, txset);
mPendingEnvelopes.addSCPQuorumSet(xdrSha256(qset), qset);
return recvSCPEnvelope(envelope);
}
Herder::EnvelopeStatus
HerderImpl::recvSCPEnvelope(SCPEnvelope const& envelope,
const SCPQuorumSet& qset,
StellarMessage const& txset)
{
auto txSetFrame =
txset.type() == TX_SET
? TxSetXDRFrame::makeFromWire(txset.txSet())
: TxSetXDRFrame::makeFromWire(txset.generalizedTxSet());
return recvSCPEnvelope(envelope, qset, txSetFrame);
}
void
HerderImpl::externalizeValue(TxSetXDRFrameConstPtr txSet, uint32_t ledgerSeq,
uint64_t closeTime,
xdr::xvector<UpgradeType, 6> const& upgrades,
std::optional<SecretKey> skToSignValue)
{
getPendingEnvelopes().putTxSet(txSet->getContentsHash(), ledgerSeq, txSet);
auto sk = skToSignValue ? *skToSignValue : mApp.getConfig().NODE_SEED;
StellarValue sv =
makeStellarValue(txSet->getContentsHash(), closeTime, upgrades, sk);
getHerderSCPDriver().valueExternalized(ledgerSeq, xdr::xdr_to_opaque(sv));
}
bool
HerderImpl::sourceAccountPending(AccountID const& accountID) const
{
bool accPending = mTransactionQueue.sourceAccountPending(accountID);
if (mSorobanTransactionQueue)
{
accPending = accPending ||
mSorobanTransactionQueue->sourceAccountPending(accountID);
}
return accPending;
}
#endif
void
HerderImpl::sendSCPStateToPeer(uint32 ledgerSeq, Peer::pointer peer)
{
ZoneScoped;
bool log = true;
auto maxSlots = Herder::LEDGER_VALIDITY_BRACKET;
auto sendSlot = [weakPeer = std::weak_ptr<Peer>(peer)](SCPEnvelope const& e,
bool log) {
// If in the process of shutting down, exit early
auto peerPtr = weakPeer.lock();
if (!peerPtr)
{
return false;
}
StellarMessage m;
m.type(SCP_MESSAGE);
m.envelope() = e;
auto mPtr = std::make_shared<StellarMessage const>(m);
peerPtr->sendMessage(mPtr, log);
return true;
};
bool delayCheckpoint = false;
auto checkpoint = getMostRecentCheckpointSeq();
auto consensusIndex = trackingConsensusLedgerIndex();
auto firstSequentialLedgerSeq =
consensusIndex > mApp.getConfig().MAX_SLOTS_TO_REMEMBER
? consensusIndex - mApp.getConfig().MAX_SLOTS_TO_REMEMBER
: LedgerManager::GENESIS_LEDGER_SEQ;
// If there is a gap between the latest completed checkpoint and the next
// saved message, we should delay sending the checkpoint ledger. Send all
// other messages first, then send checkpoint messages after node that is
// catching up knows network state. We need to do this because checkpoint
// message are almost always outside MAXIMUM_LEDGER_CLOSETIME_DRIFT.
// Checkpoint ledgers are special cased to be allowed to be outside this
// range, but to determine if a message is a checkpoint message, the node
// needs the correct trackingConsensusLedgerIndex. We send the checkpoint
// message after a delay so that the recieving node has time to process the
// initially sent messages and establish trackingConsensusLedgerIndex
if (checkpoint < firstSequentialLedgerSeq)
{
delayCheckpoint = true;
}
// Send MAX_SLOTS_TO_SEND slots
getSCP().processSlotsAscendingFrom(ledgerSeq, [&](uint64 seq) {
// Skip checkpoint ledger if we should delay
if (seq == checkpoint && delayCheckpoint)
{
return true;
}
bool slotHadData = false;
getSCP().processCurrentState(
seq,
[&](SCPEnvelope const& e) {
slotHadData = true;
auto ret = sendSlot(e, log);
log = false;
return ret;
},
false);
if (slotHadData)
{
--maxSlots;
}
return maxSlots != 0;
});
// Out of sync node needs to recieve latest messages to determine network
// state before recieving checkpoint message. Delay sending checkpoint
// ledger to achieve this
if (delayCheckpoint)
{
peer->startExecutionDelayedTimer(
Herder::SEND_LATEST_CHECKPOINT_DELAY,
[checkpoint, this, sendSlot]() {
getSCP().processCurrentState(
checkpoint,
[&](SCPEnvelope const& e) { return sendSlot(e, true); },
false);
},
&VirtualTimer::onFailureNoop);
}
}
void
HerderImpl::processSCPQueue()
{
ZoneScoped;
if (isTracking())
{
std::string txt("tracking");
ZoneText(txt.c_str(), txt.size());
processSCPQueueUpToIndex(nextConsensusLedgerIndex());
}
else
{
std::string txt("not tracking");
ZoneText(txt.c_str(), txt.size());
// we don't know which ledger we're in
// try to consume the messages from the queue
// starting from the smallest slot
for (auto& slot : mPendingEnvelopes.readySlots())
{
processSCPQueueUpToIndex(slot);
if (isTracking())
{
// one of the slots externalized
// we go back to regular flow
break;
}
}