forked from stellar/stellar-core
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHerderSCPDriver.cpp
More file actions
1975 lines (1774 loc) · 61 KB
/
Copy pathHerderSCPDriver.cpp
File metadata and controls
1975 lines (1774 loc) · 61 KB
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 2017 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/HerderSCPDriver.h"
#include "HerderUtils.h"
#include "crypto/Hex.h"
#include "crypto/SHA.h"
#include "crypto/SecretKey.h"
#include "herder/HerderImpl.h"
#include "herder/LedgerCloseData.h"
#include "herder/PendingEnvelopes.h"
#include "ledger/LedgerManager.h"
#include "main/Application.h"
#include "main/ErrorMessages.h"
#include "overlay/OverlayManager.h"
#include "overlay/SurveyManager.h"
#include "scp/SCP.h"
#include "scp/Slot.h"
#include "util/Logging.h"
#include "util/Math.h"
#include "util/MetricsRegistry.h"
#include "util/ProtocolVersion.h"
#include "xdr/Stellar-SCP.h"
#include "xdr/Stellar-ledger-entries.h"
#include "xdr/Stellar-ledger.h"
#include <Tracy.hpp>
#include <algorithm>
#include <cmath>
#include <fmt/format.h>
#include <numeric>
#include <optional>
#include <stdexcept>
#include <xdrpp/marshal.h>
namespace stellar
{
namespace
{
bool
isEmptyTxSetStellarValue(StellarValue const& sv)
{
#ifdef CAP_0083
return sv.ext.v() == STELLAR_VALUE_EMPTY_TX_SET;
#else
return false;
#endif
}
}
uint32_t const TXSETVALID_CACHE_SIZE = 1000;
Hash
HerderSCPDriver::getHashOf(std::vector<xdr::opaque_vec<>> const& vals) const
{
SHA256 hasher;
for (auto const& v : vals)
{
hasher.add(v);
}
return hasher.finish();
}
HerderSCPDriver::SCPMetrics::SCPMetrics(Application& app)
: mEnvelopeSign(
app.getMetrics().NewMeter({"scp", "envelope", "sign"}, "envelope"))
, mValueValid(app.getMetrics().NewMeter({"scp", "value", "valid"}, "value"))
, mValueInvalid(
app.getMetrics().NewMeter({"scp", "value", "invalid"}, "value"))
, mCombinedCandidates(app.getMetrics().NewMeter(
{"scp", "nomination", "combinecandidates"}, "value"))
, mNominateToPrepare(
app.getMetrics().NewTimer({"scp", "timing", "nominated"}))
, mPrepareToExternalize(
app.getMetrics().NewTimer({"scp", "timing", "externalized"}))
, mFirstToSelfExternalizeLag(app.getMetrics().NewTimer(
{"scp", "timing", "first-to-self-externalize-lag"}))
, mSelfToOthersExternalizeLag(app.getMetrics().NewTimer(
{"scp", "timing", "self-to-others-externalize-lag"}))
, mBallotBlockedOnTxSet(app.getMetrics().NewTimer(
{"scp", "timing", "ballot-blocked-on-txset"}))
, mEmptyTxSetExternalized(
app.getMetrics().NewCounter({"scp", "empty-tx-set", "externalized"}))
, mEmptyTxSetValueReplaced(app.getMetrics().NewCounter(
{"scp", "empty-tx-set", "value-replaced"}))
{
}
HerderSCPDriver::HerderSCPDriver(Application& app, HerderImpl& herder,
Upgrades const& upgrades,
PendingEnvelopes& pendingEnvelopes)
: mApp{app}
, mHerder{herder}
, mLedgerManager{mApp.getLedgerManager()}
, mUpgrades{upgrades}
, mPendingEnvelopes{pendingEnvelopes}
, mSCP{*this, mApp.getConfig().NODE_SEED.getPublicKey(),
mApp.getConfig().NODE_IS_VALIDATOR, mApp.getConfig().QUORUM_SET}
, mSCPMetrics{mApp}
, mNominateTimeout{mApp.getMetrics().NewHistogram(
{"scp", "timeout", "nominate"})}
, mPrepareTimeout{mApp.getMetrics().NewHistogram(
{"scp", "timeout", "prepare"})}
, mUniqueValues{mApp.getMetrics().NewHistogram(
{"scp", "slot", "values-referenced"})}
, mLedgerSeqNominating(0)
, mTxSetValidCache(TXSETVALID_CACHE_SIZE)
{
}
HerderSCPDriver::~HerderSCPDriver()
{
}
void
HerderSCPDriver::stateChanged()
{
mApp.syncOwnMetrics();
}
void
HerderSCPDriver::bootstrap()
{
stateChanged();
clearSCPExecutionEvents();
}
// envelope handling
class SCPHerderEnvelopeWrapper : public SCPEnvelopeWrapper
{
HerderImpl& mHerder;
SCPQuorumSetPtr mQSet;
std::vector<TxSetXDRFrameConstPtr> mTxSets;
public:
// Wrap an SCP envelope `e`, using `herder` to fetch the quorum set. This
// function inserts hashes corresponding to missing transaction sets into
// the output parameter `missingTxSets`.
explicit SCPHerderEnvelopeWrapper(SCPEnvelope const& e, HerderImpl& herder,
std::set<Hash>& missingTxSets)
: SCPEnvelopeWrapper(e), mHerder(herder)
{
releaseAssert(missingTxSets.empty());
// attach everything we can to the wrapper
auto qSetH = Slot::getCompanionQuorumSetHashFromStatement(e.statement);
mQSet = mHerder.getQSet(qSetH);
if (!mQSet)
{
throw std::runtime_error(fmt::format(
FMT_STRING("SCPHerderEnvelopeWrapper: Wrapping an unknown "
"qset {} from envelope"),
hexAbbrev(qSetH)));
}
auto txSets = getValidatedTxSetHashes(e);
for (auto const& txSetH : txSets)
{
auto result = mHerder.getTxSet(txSetH);
if (auto* txSet = std::get_if<TxSetXDRFrameConstPtr>(&result))
{
if (*txSet)
{
mTxSets.emplace_back(*txSet);
}
else
{
missingTxSets.insert(txSetH);
}
}
// EmptyTxSet: not missing, nothing to store
}
}
void
addTxSet(TxSetXDRFrameConstPtr txSet) override
{
mTxSets.emplace_back(txSet);
}
};
SCPEnvelopeWrapperPtr
HerderSCPDriver::wrapEnvelope(SCPEnvelope const& envelope)
{
std::set<Hash> missingTxSets;
auto r = std::make_shared<SCPHerderEnvelopeWrapper>(envelope, mHerder,
missingTxSets);
// Register this wrapper for any tx sets that weren't available
// so we can update it later when the tx set arrives
for (auto const& h : missingTxSets)
{
mPendingTxSetEnvelopeWrappers[h].push_back(r);
}
return r;
}
void
HerderSCPDriver::signEnvelope(SCPEnvelope& envelope)
{
ZoneScoped;
mSCPMetrics.mEnvelopeSign.Mark();
mHerder.signEnvelope(mApp.getConfig().NODE_SEED, envelope);
}
void
HerderSCPDriver::emitEnvelope(SCPEnvelope const& envelope)
{
ZoneScoped;
mHerder.emitEnvelope(envelope);
}
bool
HerderSCPDriver::isEnvelopeReady(SCPEnvelope const& env) const
{
if (!mPendingEnvelopes.isQsetFetched(env))
{
// QSet must be available
return false;
}
if (mPendingEnvelopes.areTxSetsFetched(env))
{
// Have all tx sets and the qset. This envelope is ready to be processed
return true;
}
if (!isParallelTxSetDownloadEnabled())
{
// Parallel downloading is disabled, so we need all tx sets
return false;
}
// Beyond this point all checks relate to whether SCP can process `env`
// in parallel with downloading the missing tx sets it references.
auto const type = env.statement.pledges.type();
if (type != SCP_ST_NOMINATE && type != SCP_ST_PREPARE)
{
// Parallel tx set downloading is only allowed for nomination and
// prepare messages.
return false;
}
auto const& lcl = mLedgerManager.getLastClosedLedgerHeader();
if (env.statement.slotIndex != lcl.header.ledgerSeq + 1)
{
// Parallel tx set downloading is only enabled for LCL+1
return false;
}
// Parallel downloading is only enabled when tracking and in sync
return mHerder.isTracking() &&
mApp.getState() == Application::State::APP_SYNCED_STATE;
}
bool
HerderSCPDriver::protocolAllowsEmptyTxSetValues() const
{
auto const& lcl = mLedgerManager.getLastClosedLedgerHeader();
return protocolVersionStartsFrom(lcl.header.ledgerVersion,
EMPTY_TX_SET_PROTOCOL_VERSION);
}
bool
HerderSCPDriver::isParallelTxSetDownloadEnabled() const
{
return mApp.getConfig().EXPERIMENTAL_PARALLEL_TX_SET_DOWNLOAD &&
protocolAllowsEmptyTxSetValues();
}
// value validation
bool
HerderSCPDriver::checkCloseTime(uint64_t slotIndex, uint64_t lastCloseTime,
StellarValue const& b) const
{
// Check closeTime (not too old)
if (b.closeTime <= lastCloseTime)
{
CLOG_TRACE(Herder, "Close time too old for slot {}, got {} vs {}",
slotIndex, b.closeTime, lastCloseTime);
return false;
}
// Check closeTime (not too far in future)
uint64_t timeNow = mApp.timeNow();
if (b.closeTime > timeNow + Herder::MAX_TIME_SLIP_SECONDS.count())
{
CLOG_TRACE(Herder,
"Close time too far in future for slot {}, got {} vs {}",
slotIndex, b.closeTime, timeNow);
return false;
}
return true;
}
SCPDriver::ValidationLevel
HerderSCPDriver::validatePastOrFutureValue(
uint64_t slotIndex, StellarValue const& b,
LedgerHeaderHistoryEntry const& lcl) const
{
ZoneScoped;
releaseAssert(slotIndex != lcl.header.ledgerSeq + 1);
if (slotIndex == lcl.header.ledgerSeq)
{
// previous ledger
if (b.closeTime != lcl.header.scpValue.closeTime)
{
CLOG_TRACE(Herder,
"Got a bad close time for ledger {}, got {} vs {}",
slotIndex, b.closeTime, lcl.header.scpValue.closeTime);
return SCPDriver::kInvalidValue;
}
#ifdef CAP_0083
if (isEmptyTxSetStellarValue(b))
{
if (!protocolAllowsEmptyTxSetValues())
{
return SCPDriver::kInvalidValue;
}
auto const& ov = b.ext.proposedValue();
// We can check previousLedgerHash because the LCL header
// contains the hash of its parent. We cannot check
// previousLedgerVersion because the LCL header only has
// its own version, and a protocol upgrade on the LCL
// could make it differ from its parent's version.
if (ov.previousLedgerHash != lcl.header.previousLedgerHash)
{
CLOG_TRACE(Herder,
"Got a bad previousLedgerHash for empty-tx-set "
"value in ledger {}",
slotIndex);
return SCPDriver::kInvalidValue;
}
}
#endif // CAP_0083
}
else if (slotIndex < lcl.header.ledgerSeq)
{
// basic sanity check on older value
if (b.closeTime >= lcl.header.scpValue.closeTime)
{
CLOG_TRACE(Herder,
"Got a bad close time for ledger {}, got {} vs {}",
slotIndex, b.closeTime, lcl.header.scpValue.closeTime);
return SCPDriver::kInvalidValue;
}
}
else if (!checkCloseTime(slotIndex, lcl.header.scpValue.closeTime, b))
{
// future messages must be valid compared to lastCloseTime
return SCPDriver::kInvalidValue;
}
if (!mHerder.isTracking())
{
// if we're not tracking, there is not much more we can do to
// validate
CLOG_TRACE(Herder, "MaybeValidValue (not tracking) for slot {}",
slotIndex);
return SCPDriver::kMaybeValidNotCurrentValue;
}
// Check slotIndex.
if (mHerder.nextConsensusLedgerIndex() > slotIndex)
{
// we already moved on from this slot
// still send it through for emitting the final messages
CLOG_TRACE(Herder,
"MaybeValidValue (already moved on) for slot {}, at {}",
slotIndex, mHerder.nextConsensusLedgerIndex());
return SCPDriver::kMaybeValidNotCurrentValue;
}
if (mHerder.nextConsensusLedgerIndex() < slotIndex)
{
// this is probably a bug as "tracking" means we're processing
// messages only for smaller slots
CLOG_ERROR(Herder,
"HerderSCPDriver::validateValue i: {} processing a future "
"message while tracking {} ",
slotIndex, mHerder.trackingConsensusLedgerIndex());
return SCPDriver::kInvalidValue;
}
// when tracking, we use the tracked time for last close time
auto lastCloseTime = mHerder.trackingConsensusCloseTime();
if (!checkCloseTime(slotIndex, lastCloseTime, b))
{
return SCPDriver::kInvalidValue;
}
// this is as far as we can go if we don't have the state
CLOG_TRACE(Herder, "Can't validate locally, value may be valid for slot {}",
slotIndex);
return SCPDriver::kMaybeValidNotCurrentValue;
}
SCPDriver::ValidationLevel
HerderSCPDriver::validateValueAgainstLocalState(uint64_t slotIndex,
StellarValue const& b,
bool nomination) const
{
ZoneScoped;
releaseAssert(threadIsMain());
auto const& lcl = mLedgerManager.getLastClosedLedgerHeader();
// We can only fully validate values for LCL+1
// For past and future slots, perform partial validity checks, specifically
// validate close time and network tracking ledger sequence.
bool isCurrentLedger = slotIndex == lcl.header.ledgerSeq + 1;
SCPDriver::ValidationLevel res;
if (isCurrentLedger)
{
// The value is for LCL+1, perform all possible checks
if (!checkCloseTime(slotIndex, lcl.header.scpValue.closeTime, b))
{
return SCPDriver::kInvalidValue;
}
#ifdef CAP_0083
// For empty-tx-set values, validate that the previous ledger context
// matches our LCL. Empty-tx-set values don't have a real tx set to
// validate.
if (isEmptyTxSetStellarValue(b))
{
if (!protocolAllowsEmptyTxSetValues())
{
return SCPDriver::kInvalidValue;
}
if (nomination)
{
// Empty-tx-set values should only appear in balloting, and so
// are considered invalid during nomination.
CLOG_DEBUG(Herder,
"HerderSCPDriver::validateValue i: {} rejecting "
"empty-tx-set value during nomination",
slotIndex);
return SCPDriver::kInvalidValue;
}
auto const& ov = b.ext.proposedValue();
if (ov.previousLedgerHash != lcl.hash ||
ov.previousLedgerVersion != lcl.header.ledgerVersion)
{
CLOG_DEBUG(Herder,
"HerderSCPDriver::validateValue i: {} empty-tx-set "
"value has mismatched previous ledger context",
slotIndex);
return SCPDriver::kInvalidValue;
}
return SCPDriver::kFullyValidatedValue;
}
#endif // CAP_0083
Hash const& txSetHash = b.txSetHash;
// Empty-tx-set values return early above, so this only runs for
// non-empty-tx-set hashes. Extract the TxSetXDRFrameConstPtr.
TxSetXDRFrameConstPtr txSet = std::get<TxSetXDRFrameConstPtr>(
mPendingEnvelopes.getTxSet(txSetHash));
auto closeTimeOffset = b.closeTime - lcl.header.scpValue.closeTime;
if (!txSet)
{
if (isParallelTxSetDownloadEnabled() &&
mPendingEnvelopes.getTxSetWaitingTime(txSetHash).has_value())
{
res = SCPDriver::kStructurallyValidValue;
}
else
{
CLOG_ERROR(Herder, "validateValue i:{} unknown txSet {}",
slotIndex, hexAbbrev(txSetHash));
res = SCPDriver::kInvalidValue;
}
}
else if (!checkAndCacheTxSetValid(*txSet, lcl, closeTimeOffset))
{
CLOG_DEBUG(Herder,
"HerderSCPDriver::validateValue i: {} invalid txSet {}",
slotIndex, hexAbbrev(txSetHash));
res = protocolAllowsEmptyTxSetValues()
? SCPDriver::kStructurallyValidValue
: SCPDriver::kInvalidValue;
}
else
{
CLOG_DEBUG(Herder,
"HerderSCPDriver::validateValue i: {} valid txSet {}",
slotIndex, hexAbbrev(txSetHash));
res = SCPDriver::kFullyValidatedValue;
}
// kMaybeValidNotCurrentValue should never be returned for LCL+1 values,
// as these values should always be fully valid/invalid, or awaiting
// download
releaseAssert(res != SCPDriver::kMaybeValidNotCurrentValue);
}
else
{
res = validatePastOrFutureValue(slotIndex, b, lcl);
// Non-LCL+1 values cannot be fully validated and are not eligible for
// parallel downloading.
releaseAssert(res != SCPDriver::kStructurallyValidValue &&
res != SCPDriver::kFullyValidatedValue);
}
return res;
}
bool
HerderSCPDriver::deserializeAndValidateStellarValue(Value const& value,
StellarValue& sv) const
{
ZoneScoped;
try
{
ZoneNamedN(xdrZone, "XDR deserialize", true);
xdr::xdr_from_opaque(value, sv);
}
catch (...)
{
return false;
}
bool const emptyTxSetsAllowed = protocolAllowsEmptyTxSetValues();
if (sv.ext.v() != STELLAR_VALUE_SIGNED)
{
if (!emptyTxSetsAllowed)
{
// Empty-tx-set values are not allowed, and the value is not a
// signed value, so it is invalid.
return false;
}
if (!isEmptyTxSetStellarValue(sv))
{
// The value is not a signed value or an empty-tx-set value, so it
// is invalid.
return false;
}
}
// Empty-tx-set values must have the empty-tx-set hash, and
// non-explicitly-empty-tx-set values must not have the empty-tx-set hash.
if ((sv.txSetHash == Herder::EMPTY_TX_SET_HASH) !=
isEmptyTxSetStellarValue(sv))
{
return false;
}
{
ZoneNamedN(sigZone, "signature check", true);
if (!mHerder.verifyStellarValueSignature(sv))
{
return false;
}
}
return true;
}
void
HerderSCPDriver::extractValidUpgrades(StellarValue& sv, bool nomination) const
{
LedgerUpgradeType lastUpgradeType = LEDGER_UPGRADE_VERSION;
LedgerUpgradeType thisUpgradeType;
bool first = true;
for (auto it = sv.upgrades.begin(); it != sv.upgrades.end();)
{
if (!mUpgrades.isValid(*it, thisUpgradeType, nomination, mApp))
{
it = sv.upgrades.erase(it);
}
else if (!first && lastUpgradeType >= thisUpgradeType)
{
it = sv.upgrades.erase(it);
}
else
{
lastUpgradeType = thisUpgradeType;
first = false;
it++;
}
}
}
SCPDriver::ValidationLevel
HerderSCPDriver::validateValue(uint64_t slotIndex, Value const& value,
bool nomination) const
{
ZoneScoped;
releaseAssert(threadIsMain());
StellarValue b;
if (!deserializeAndValidateStellarValue(value, b))
{
mSCPMetrics.mValueInvalid.Mark();
return SCPDriver::kInvalidValue;
}
SCPDriver::ValidationLevel res =
validateValueAgainstLocalState(slotIndex, b, nomination);
if (res != SCPDriver::kInvalidValue)
{
auto origSize = b.upgrades.size();
extractValidUpgrades(b, nomination);
if (b.upgrades.size() != origSize)
{
CLOG_TRACE(Herder,
"HerderSCPDriver::validateValue i: {} rejected due to "
"invalid or misordered upgrade steps",
slotIndex);
res = SCPDriver::kInvalidValue;
}
}
if (res)
{
mSCPMetrics.mValueValid.Mark();
}
else
{
mSCPMetrics.mValueInvalid.Mark();
}
return res;
}
ValueWrapperPtr
HerderSCPDriver::extractValidValue(uint64_t slotIndex, Value const& value)
{
ZoneScoped;
StellarValue b;
if (!deserializeAndValidateStellarValue(value, b))
{
return nullptr;
}
ValueWrapperPtr res;
if (validateValueAgainstLocalState(slotIndex, b, true) >=
SCPDriver::kStructurallyValidValue)
{
extractValidUpgrades(b, true);
res = wrapStellarValue(b);
}
return res;
}
// value marshaling
std::string
HerderSCPDriver::toShortString(NodeID const& pk) const
{
return mApp.getConfig().toShortString(pk);
}
std::string
HerderSCPDriver::getValueString(Value const& v) const
{
StellarValue b;
if (v.empty())
{
return "[:empty:]";
}
try
{
xdr::xdr_from_opaque(v, b);
return stellarValueToString(mApp.getConfig(), b);
}
catch (...)
{
return "[:invalid:]";
}
}
#ifdef CAP_0083
Value
HerderSCPDriver::makeEmptyTxSetValueFromValue(Value const& v) const
{
ZoneScoped;
StellarValue proposedValue = toStellarValueOrThrow(v);
releaseAssert(proposedValue.ext.v() == STELLAR_VALUE_SIGNED);
auto const& lcl = mLedgerManager.getLastClosedLedgerHeader();
StellarValue sv;
sv.ext.v(STELLAR_VALUE_EMPTY_TX_SET);
sv.txSetHash = Herder::EMPTY_TX_SET_HASH;
sv.closeTime = proposedValue.closeTime;
sv.upgrades = proposedValue.upgrades;
sv.ext.proposedValue().txSetHash = proposedValue.txSetHash;
sv.ext.proposedValue().previousLedgerHash = lcl.hash;
sv.ext.proposedValue().previousLedgerVersion = lcl.header.ledgerVersion;
sv.ext.proposedValue().lcValueSignature =
proposedValue.ext.lcValueSignature();
return xdr::xdr_to_opaque(sv);
}
#endif
bool
HerderSCPDriver::isEmptyTxSetValue(Value const& v) const
{
ZoneScoped;
StellarValue sv;
bool success = toStellarValue(v, sv);
if (!success)
{
return false;
}
return isEmptyTxSetStellarValue(sv);
}
// timer handling
void
HerderSCPDriver::timerCallbackWrapper(uint64_t slotIndex, int timerID,
std::function<void()> cb)
{
// reschedule timers for future slots when tracking
if (mHerder.isTracking() && mHerder.nextConsensusLedgerIndex() != slotIndex)
{
CLOG_WARNING(
Herder, "Herder rescheduled timer {} for slot {} with next slot {}",
timerID, slotIndex, mHerder.nextConsensusLedgerIndex());
setupTimer(slotIndex, timerID, std::chrono::seconds(1),
std::bind(&HerderSCPDriver::timerCallbackWrapper, this,
slotIndex, timerID, cb));
}
else
{
auto SCPTimingIt = mSCPExecutionTimes.find(slotIndex);
if (SCPTimingIt != mSCPExecutionTimes.end())
{
auto& SCPTiming = SCPTimingIt->second;
if (timerID == Slot::BALLOT_PROTOCOL_TIMER)
{
// Timeout happened in between first prepare and externalize
++SCPTiming.mPrepareTimeoutCount;
}
else
{
if (!SCPTiming.mPrepareStart)
{
// Timeout happened between nominate and first prepare
++SCPTiming.mNominationTimeoutCount;
}
}
}
cb();
}
}
void
HerderSCPDriver::setupTimer(uint64_t slotIndex, int timerID,
std::chrono::milliseconds timeout,
std::function<void()> cb)
{
// don't setup timers for old slots
if (slotIndex <= mApp.getHerder().trackingConsensusLedgerIndex())
{
mSCPTimers.erase(slotIndex);
return;
}
auto& slotTimers = mSCPTimers[slotIndex];
auto it = slotTimers.find(timerID);
if (it == slotTimers.end())
{
it = slotTimers.emplace(timerID, std::make_unique<VirtualTimer>(mApp))
.first;
}
auto& timer = *it->second;
timer.cancel();
if (cb)
{
timer.expires_from_now(timeout);
timer.async_wait(std::bind(&HerderSCPDriver::timerCallbackWrapper, this,
slotIndex, timerID, cb),
&VirtualTimer::onFailureNoop);
}
}
void
HerderSCPDriver::stopTimer(uint64 slotIndex, int timerID)
{
auto timersIt = mSCPTimers.find(slotIndex);
if (timersIt == mSCPTimers.end())
{
return;
}
auto& slotTimers = timersIt->second;
auto it = slotTimers.find(timerID);
if (it != slotTimers.end())
{
auto& timer = *it->second;
timer.cancel();
}
}
static uint32_t const MAX_TIMEOUT_MS = (30 * 60) * 1000;
std::chrono::milliseconds
HerderSCPDriver::computeTimeout(uint32 roundNumber, bool isNomination)
{
releaseAssertOrThrow(roundNumber > 0);
// Before p23, straight linear timeout
// starting at 1 second and capping at MAX_TIMEOUT_MS
uint32_t initialTimeoutMS = 1000;
uint32_t incrementMS = 1000;
auto const& lcl = mLedgerManager.getLastClosedLedgerHeader();
if (protocolVersionStartsFrom(lcl.header.ledgerVersion,
ProtocolVersion::V_23))
{
auto const& networkConfig =
mLedgerManager.getLastClosedSorobanNetworkConfig();
if (isNomination)
{
initialTimeoutMS =
networkConfig.nominationTimeoutInitialMilliseconds();
incrementMS =
networkConfig.nominationTimeoutIncrementMilliseconds();
}
else
{
initialTimeoutMS = networkConfig.ballotTimeoutInitialMilliseconds();
incrementMS = networkConfig.ballotTimeoutIncrementMilliseconds();
}
}
auto timeoutMS = initialTimeoutMS + (roundNumber - 1) * incrementMS;
if (timeoutMS > MAX_TIMEOUT_MS)
{
timeoutMS = MAX_TIMEOUT_MS;
}
return std::chrono::milliseconds(timeoutMS);
}
// returns true if l < r
// lh, rh are the hashes of l,h
static bool
compareTxSets(ApplicableTxSetFrameConstPtr const& l,
ApplicableTxSetFrameConstPtr const& r, Hash const& lh,
Hash const& rh, std::optional<size_t> lEncodedSize,
std::optional<size_t> rEncodedSize, LedgerHeader const& header,
Hash const& s)
{
if (!l && !r)
{
// Do not have either tx set. Compare hashes
return lessThanXored(lh, rh, s);
}
if (!l || !r)
{
// If one exists, choose it
return !l;
}
auto lSize = l->size(header);
auto rSize = r->size(header);
if (lSize != rSize)
{
return lSize < rSize;
}
if (protocolVersionStartsFrom(header.ledgerVersion,
SOROBAN_PROTOCOL_VERSION))
{
auto lBids = l->getTotalInclusionFees();
auto rBids = r->getTotalInclusionFees();
if (lBids != rBids)
{
return lBids < rBids;
}
}
if (protocolVersionStartsFrom(header.ledgerVersion, ProtocolVersion::V_11))
{
auto lFee = l->getTotalFees(header);
auto rFee = r->getTotalFees(header);
if (lFee != rFee)
{
return lFee < rFee;
}
}
if (protocolVersionStartsFrom(header.ledgerVersion,
SOROBAN_PROTOCOL_VERSION))
{
if (lEncodedSize.value() != rEncodedSize.value())
{
// Look for the smallest encoded size.
return lEncodedSize.value() > rEncodedSize.value();
}
}
return lessThanXored(lh, rh, s);
}
ValueWrapperPtr
HerderSCPDriver::combineCandidates(uint64_t slotIndex,
ValueWrapperPtrSet const& candidates)
{
ZoneScoped;
CLOG_DEBUG(Herder, "Combining {} candidates", candidates.size());
mSCPMetrics.mCombinedCandidates.Mark(candidates.size());
std::map<LedgerUpgradeType, LedgerUpgrade> upgrades;
std::set<TransactionFramePtr> aggSet;
releaseAssert(!mLedgerManager.isApplying());
releaseAssert(threadIsMain());
auto const& lcl = mLedgerManager.getLastClosedLedgerHeader();
Hash candidatesHash;
std::vector<StellarValue> candidateValues;
for (auto const& c : candidates)
{
candidateValues.emplace_back();
StellarValue& sv = candidateValues.back();
Value const& val = c->getValue();
uint256 const valHash = sha256(val);
if (!toStellarValue(val, sv))
{
throw std::runtime_error(fmt::format(
"HerderSCPDriver::combineCandidates: cannot parse candidate "
"value with hash {}",
binToHex(valHash)));
}
candidatesHash ^= valHash;
for (auto const& upgrade : sv.upgrades)
{
LedgerUpgrade lupgrade;
try
{
xdr::xdr_from_opaque(upgrade, lupgrade);
}
catch (...)
{
throw std::runtime_error(
fmt::format("HerderSCPDriver::combineCandidates: cannot "
"parse upgrade in candidate with hash {}",
binToHex(valHash)));
}
auto it = upgrades.find(lupgrade.type());
if (it == upgrades.end())
{
upgrades.emplace(std::make_pair(lupgrade.type(), lupgrade));
}
else
{
LedgerUpgrade& clUpgrade = it->second;
switch (lupgrade.type())
{
case LEDGER_UPGRADE_VERSION:
// pick the highest version
clUpgrade.newLedgerVersion() =
std::max(clUpgrade.newLedgerVersion(),
lupgrade.newLedgerVersion());
break;
case LEDGER_UPGRADE_BASE_FEE:
// take the max fee
clUpgrade.newBaseFee() =
std::max(clUpgrade.newBaseFee(), lupgrade.newBaseFee());
break;
case LEDGER_UPGRADE_MAX_TX_SET_SIZE:
// take the max tx set size
clUpgrade.newMaxTxSetSize() =
std::max(clUpgrade.newMaxTxSetSize(),
lupgrade.newMaxTxSetSize());
break;
case LEDGER_UPGRADE_BASE_RESERVE:
// take the max base reserve
clUpgrade.newBaseReserve() = std::max(
clUpgrade.newBaseReserve(), lupgrade.newBaseReserve());
break;
case LEDGER_UPGRADE_FLAGS:
clUpgrade.newFlags() =
std::max(clUpgrade.newFlags(), lupgrade.newFlags());
break;
case LEDGER_UPGRADE_CONFIG:
if (clUpgrade.newConfig().contractID <
lupgrade.newConfig().contractID)