-
Notifications
You must be signed in to change notification settings - Fork 146
Expand file tree
/
Copy pathbcstatetransfer_tests.cpp
More file actions
3014 lines (2744 loc) · 151 KB
/
bcstatetransfer_tests.cpp
File metadata and controls
3014 lines (2744 loc) · 151 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
// Concord
//
// Copyright (c) 2019-2021 VMware, Inc. All Rights Reserved.
//
// This product is licensed to you under the Apache 2.0 license (the "License").
// You may not use this product except in compliance with the Apache 2.0
// License.
//
// This product may include a number of subcomponents with separate copyright
// notices and license terms. Your use of these subcomponents is subject to the
// terms and conditions of the subcomponent's license, as noted in the LICENSE
// file.
// standard library includes
#include <chrono>
#include <thread>
#include <set>
#include <string>
#include <vector>
#include <random>
#include <climits>
#include <optional>
#include <cstring>
#include <algorithm>
// 3rd party includes
#include "gtest/gtest.h"
#include "log/logger.hpp"
#include "SimpleBCStateTransfer.hpp"
#include "BCStateTran.hpp"
#include "test_app_state.hpp"
#include "test_replica.hpp"
#include "DBDataStore.hpp"
#include "direct_kv_db_adapter.h"
#include "storage/memorydb/client.hpp"
#include "storage/direct_kv_key_manipulator.hpp"
#include "ReservedPagesMock.hpp"
#include "EpochManager.hpp"
#include "Messages.hpp"
#include "messages/PrePrepareMsg.hpp"
#include "util/hex_tools.hpp"
#include "RVBManager.hpp"
#include "RangeValidationTree.hpp"
#include "messages/StateTransferMsg.hpp"
#ifdef USE_ROCKSDB
#include "storage/rocksdb/client.hpp"
#include "storage/rocksdb/key_comparator.hpp"
using concord::storage::rocksdb::Client;
using concord::storage::rocksdb::KeyComparator;
#endif
using namespace std;
using namespace bftEngine::bcst;
using namespace concord::util;
using concord::crypto::DigestGenerator;
using concord::crypto::DigestGenerator;
using std::chrono::milliseconds;
using random_bytes_engine = std::independent_bits_engine<std::default_random_engine, CHAR_BIT, unsigned char>;
#define ASSERT_NFF ASSERT_NO_FATAL_FAILURE
#define ASSERT_DEST_UNDER_TEST ASSERT_TRUE(testConfig_.testTarget == TestConfig::TestTarget::DESTINATION)
#define ASSERT_SRC_UNDER_TEST ASSERT_TRUE(testConfig_.testTarget == TestConfig::TestTarget::SOURCE)
#define EMPTY_FUNC \
std::function<void(void)> { \
[]() {} \
}
namespace bftEngine::bcst::impl::test {
using FetchingState = BCStateTran::FetchingState;
/////////////////////////////////////////////////////////
// Config
//
// Target configuration - can be modified in test body before calling initialize()
/////////////////////////////////////////////////////////
Config targetConfig() {
return {
1, // myReplicaId
2, // fVal
0, // cVal
7, // numReplicas
0, // numRoReplicas
false, // pedanticChecks
false, // isReadOnly
1024, // maxChunkSize
24, // maxNumberOfChunksInBatch
1024, // maxBlockSize
256 * 1024 * 1024, // maxPendingDataFromSourceReplica
2048, // maxNumOfReservedPages
4096, // sizeOfReservedPage
600, // gettingMissingBlocksSummaryWindowSize
10, // minPrePrepareMsgsForPrimaryAwareness
24, // fetchRangeSize
6, // RVT_K
300, // refreshTimerMs
2500, // checkpointSummariesRetransmissionTimeoutMs
60000, // maxAcceptableMsgDelayMs
0, // sourceReplicaReplacementTimeoutMs
2000, // fetchRetransmissionTimeoutMs
2, // maxFetchRetransmissions
5, // metricsDumpIntervalSec
5000, // maxTimeSinceLastExecutionInMainWindowMs
2050, // sourceSessionExpiryDurationMs
3, // sourcePerformanceSnapshotFrequencySec
false, // runInSeparateThread
true, // enableReservedPages
true, // enableSourceBlocksPreFetch
true, // enableSourceSelectorPrimaryAwareness
true // enableStoreRvbDataDuringCheckpointing
};
}
/////////////////////////////////////////////////////////
// TestConfig
//
// Test configuration - all configuration that is not part of 'struct Config'.
// Some of the members purely configure the test environment, while some are used to configure the product and are
// part of this struct since we do not run the full replica.
// Can be modified in test body before calling initialize()
/////////////////////////////////////////////////////////
struct TestConfig {
/**
* TestTarget
* SOURCE: testing ST source production code, destination is fake
* DESTINAION: testing ST destination production code, source is fake
*/
enum class TestTarget { SOURCE, DESTINATION };
/**
* Constants
* You may decide a constant is configurable by moving it into the 'Configurable' part
* In some cases you might need to write additional code to support the new configuration value
*/
static constexpr char bcstDbPath[] = "./bcst_db";
static constexpr char fakeBcstDbPath[] = "./fake_bcst_db";
static constexpr size_t numExpectedSourceSelectorMetricCounters = 6;
/**
* Configurable
* A configurable value might be overridden before the actual test starts
* All defaults are inlined
*/
uint64_t maxNumOfRequiredStoredCheckpoints = 3;
uint32_t numberOfRequiredReservedPages = 100;
uint32_t minNumberOfUpdatedReservedPages = 3;
uint32_t maxNumberOfUpdatedReservedPages = 100;
uint32_t checkpointWindowSize = 150;
uint32_t minBlockDataSize = 300;
uint32_t lastReachedConsensusCheckpointNum = 10;
bool productDbDeleteOnStart = true;
bool productDbDeleteOnEnd = true;
bool fakeDbDeleteOnStart = true;
bool fakeDbDeleteOnEnd = true;
TestTarget testTarget = TestTarget::DESTINATION;
string logLevel = "error"; // choose: "trace", "debug", "info", "warn", "error", "fatal"
};
static inline std::ostream& operator<<(std::ostream& os, const TestConfig::TestTarget& c) {
os << ((c == TestConfig::TestTarget::DESTINATION) ? "DESTINATION" : "SOURCE");
return os;
}
static inline std::ostream& operator<<(std::ostream& os, const TestConfig& c) {
os << std::boolalpha
<< KVLOG(c.bcstDbPath,
c.fakeBcstDbPath,
c.maxNumOfRequiredStoredCheckpoints,
c.numberOfRequiredReservedPages,
c.minNumberOfUpdatedReservedPages,
c.maxNumberOfUpdatedReservedPages,
c.checkpointWindowSize,
c.minBlockDataSize,
c.lastReachedConsensusCheckpointNum,
c.productDbDeleteOnStart,
c.productDbDeleteOnEnd,
c.fakeDbDeleteOnStart,
c.fakeDbDeleteOnEnd,
c.testTarget,
c.logLevel);
return os;
}
/////////////////////////////////////////////////////////
// TestUtils
//
// Group of utility functions which can be used by any other class
/////////////////////////////////////////////////////////
class TestUtils {
public:
static void mallocCopy(void* inputBuff, size_t numBytes, char** outputBuff);
static void allocCopyStateTransferMsg(void* inputBuff, size_t numBytes, char** outputBuff);
};
void TestUtils::mallocCopy(void* inputBuff, size_t numBytes, char** outputBuff) {
ASSERT_GT(numBytes, 0);
*outputBuff = static_cast<char*>(std::malloc(numBytes));
ASSERT_TRUE(*outputBuff);
memcpy(*outputBuff, inputBuff, numBytes);
}
void TestUtils::allocCopyStateTransferMsg(void* inputBuff, size_t numBytes, char** outputBuff) {
// We don't allocate real MessageBase::Header, only the body. This is done in order to be sure that the right
// call to deallocate the is done from target code
ASSERT_GT(numBytes, 0);
char* body = static_cast<char*>(std::malloc(numBytes + sizeof(MessageBase::Header)));
ASSERT_TRUE(body);
*outputBuff = body + sizeof(MessageBase::Header);
memcpy(*outputBuff, inputBuff, numBytes);
}
/////////////////////////////////////////////////////////
// TestState
//
// Test initial state is calculated usually as test starts. You shouldn't change a test state directly, you can alter it
// by changing test infra code, product code, or test configuration (for example).
/////////////////////////////////////////////////////////
class TestState {
public:
uint64_t minRequiredBlockId = 0;
uint64_t maxRequiredBlockId = 0;
uint64_t nextRequiredBlock = 0;
uint64_t maxRepliedCheckpointNum = 0;
uint64_t minRepliedCheckpointNum = 0;
uint64_t numBlocksToCollect = 0;
uint64_t lastCheckpointKnownToRequester = 0;
void init(const TestConfig& testConfig, const TestAppState& appState, uint64_t _minRequiredBlockId = 0);
void moveToNextCycle(TestConfig& testConfig,
const TestAppState& appState,
uint64_t _minRequiredBlockId,
uint32_t _lastReachedConsensusCheckpointNum);
};
void TestState::init(const TestConfig& testConfig, const TestAppState& appState, uint64_t _minRequiredBlockId) {
minRequiredBlockId = (_minRequiredBlockId == 0) ? appState.getGenesisBlockNum() + 1 : _minRequiredBlockId;
maxRequiredBlockId = (testConfig.lastReachedConsensusCheckpointNum + 1) * testConfig.checkpointWindowSize;
ASSERT_LE(minRequiredBlockId, maxRequiredBlockId);
maxRepliedCheckpointNum = testConfig.lastReachedConsensusCheckpointNum;
minRepliedCheckpointNum = maxRepliedCheckpointNum - testConfig.maxNumOfRequiredStoredCheckpoints + 1;
lastCheckpointKnownToRequester = std::max(((minRequiredBlockId - 1) / testConfig.checkpointWindowSize), (uint64_t)1);
numBlocksToCollect = maxRequiredBlockId - minRequiredBlockId + 1;
ASSERT_GE(maxRepliedCheckpointNum, minRepliedCheckpointNum);
ASSERT_GT(maxRepliedCheckpointNum, lastCheckpointKnownToRequester);
}
void TestState::moveToNextCycle(TestConfig& testConfig,
const TestAppState& appState,
uint64_t _minRequiredBlockId,
uint32_t _lastReachedConsensusCheckpointNum) {
ASSERT_GT(_lastReachedConsensusCheckpointNum, testConfig.lastReachedConsensusCheckpointNum);
ASSERT_GT(_minRequiredBlockId, maxRequiredBlockId);
testConfig.lastReachedConsensusCheckpointNum = _lastReachedConsensusCheckpointNum;
init(testConfig, appState, _minRequiredBlockId);
}
static inline std::ostream& operator<<(std::ostream& os, const TestState& c) {
os << std::boolalpha
<< KVLOG(c.minRequiredBlockId,
c.maxRequiredBlockId,
c.maxRepliedCheckpointNum,
c.minRepliedCheckpointNum,
c.numBlocksToCollect,
c.lastCheckpointKnownToRequester);
return os;
}
/////////////////////////////////////////////////////////
// Global static helper functions
/////////////////////////////////////////////////////////
static void fillRandomBytes(char* data, size_t bytesToFill) {
using random_bytes_engine = std::independent_bits_engine<std::default_random_engine, CHAR_BIT, unsigned char>;
random_bytes_engine rbe;
std::generate(data, data + bytesToFill, std::ref(rbe));
}
static void assertMsgType(const Msg& msg, uint16_t type) {
auto header = reinterpret_cast<BCStateTranBaseMsg*>(msg.data_.get());
ASSERT_EQ(type, header->type);
}
static void deleteBcStateTransferDbFolder(const string& path) {
string cmd = string("rm -rf ") + string(path);
if (system(cmd.c_str())) {
ASSERT_TRUE(false);
}
}
static DataStore* createDataStore(const string& dbName, const Config& targetConfig) {
#ifdef USE_ROCKSDB
// create a data store
auto* db_key_comparator = new concord::kvbc::v1DirectKeyValue::DBKeyComparator();
concord::storage::IDBClient::ptr dbc(
new concord::storage::rocksdb::Client(string(dbName), make_unique<KeyComparator>(db_key_comparator)));
dbc->init();
return new DBDataStore(dbc,
targetConfig.sizeOfReservedPage,
make_shared<concord::storage::v1DirectKeyValue::STKeyManipulator>(),
targetConfig.enableReservedPages);
#else
concord::storage::IDBClient::ptr dbc2(new concord::storage::memorydb::Client(comparator));
return new InMemoryDataStore(targetConfig.sizeOfReservedPage);
#endif
}
/////////////////////////////////////////////////////////
// DataGenerator
//
// Generates blocks, reserved pages, blocks, digests and
// whatever other data needed for the test to run.
// The data generated is random, but the cryptography applied is valid
/////////////////////////////////////////////////////////
class DataGenerator {
public:
DataGenerator(const Config& targetConfig, const TestConfig& testConfig);
void generateBlocks(TestAppState& appState, uint64_t fromBlockId, uint64_t toBlockId);
void generateCheckpointDescriptors(const TestAppState& appstate,
DataStore* datastore,
uint64_t minRepliedCheckpointNum,
uint64_t maxRepliedCheckpointNum,
RVBManager* rvbm = nullptr);
std::unique_ptr<MessageBase> generatePrePrepareMsg(ReplicaId sender_id);
protected:
void generateReservedPages(DataStore* datastore, uint64_t checkpointNumber);
const Config& targetConfig_;
const TestConfig& testConfig_;
// needed by generatePrePrepareMsg()
bftEngine::test::ReservedPagesMock<EpochManager> fakeReservedPages_;
};
/////////////////////////////////////////////////////////
// BcStTestDelegator
//
// To be able to call into ST non-public function, include this class and use it as an interface
/////////////////////////////////////////////////////////
class BcStTestDelegator {
public:
BcStTestDelegator(const std::unique_ptr<BCStateTran>& stateTransfer) : stateTransfer_(stateTransfer) {}
// State Transfer
static constexpr size_t sizeOfElementOfVirtualBlock = sizeof(BCStateTran::ElementOfVirtualBlock);
static constexpr size_t sizeOfHeaderOfVirtualBlock = sizeof(BCStateTran::HeaderOfVirtualBlock);
static constexpr uint64_t ID_OF_VBLOCK_RES_PAGES = BCStateTran::ID_OF_VBLOCK_RES_PAGES;
void assertBCStateTranMetricKeyVal(const std::string& key, uint64_t val);
uint64_t uniqueMsgSeqNum() { return stateTransfer_->uniqueMsgSeqNum(); }
void handleStateTransferMessage(char* msg,
uint32_t msgLen,
uint16_t senderId,
time_point<steady_clock> incomingEventsQPushTime = steady_clock::now()) {
stateTransfer_->handleStateTransferMessageImpl(msg, msgLen, senderId, incomingEventsQPushTime);
}
uint64_t getNextRequiredBlock() { return stateTransfer_->fetchState_.nextBlockId; }
RVBManager* getRvbManager() { return stateTransfer_->rvbm_.get(); }
size_t getSizeOfRvbDigestInfo() const { return sizeof(RVBManager::RvbDigestInfo); }
SimpleMemoryPool<BCStateTran::BlockIOContext>& getIoPool() const { return stateTransfer_->ioPool_; }
std::deque<BCStateTran::BlockIOContextPtr>& getIoContexts() const { return stateTransfer_->ioContexts_; }
void clearIoContexts() { stateTransfer_->clearIoContexts(); }
RVBId nextRvbBlockId(BlockId blockId) const { return stateTransfer_->rvbm_->nextRvbBlockId(blockId); }
RVBId prevRvbBlockId(BlockId blockId) const { return stateTransfer_->rvbm_->prevRvbBlockId(blockId); }
RangeValidationTree* getRvt() { return stateTransfer_->rvbm_->in_mem_rvt_.get(); }
void createCheckpointOfCurrentState(uint64_t checkpointNum) {
stateTransfer_->createCheckpointOfCurrentState(checkpointNum);
};
void deleteOldCheckpoints(uint64_t checkpointNumber, DataStoreTransaction* txn) {
stateTransfer_->deleteOldCheckpoints(checkpointNumber, txn);
}
std::vector<std::pair<BlockId, Digest>> getPrunedBlocksDigests() {
return stateTransfer_->rvbm_->pruned_blocks_digests_;
}
void fillHeaderOfVirtualBlock(std::unique_ptr<char[]>& rawVBlock,
uint32_t numberOfUpdatedPages,
uint64_t lastCheckpointKnownToRequester);
void fillElementOfVirtualBlock(DataStore* datastore,
char* position,
uint32_t pageId,
uint64_t checkpointNumber,
const Digest& pageDigest,
uint32_t sizeOfReservedPage);
uint32_t getSizeOfVirtualBlock(char* virtualBlock, uint32_t pageSize) {
return stateTransfer_->getSizeOfVirtualBlock(virtualBlock, pageSize);
}
bool checkStructureOfVirtualBlock(char* virtualBlock,
uint32_t virtualBlockSize,
uint32_t pageSize,
logging::Logger& logger) {
return stateTransfer_->checkStructureOfVirtualBlock(virtualBlock, virtualBlockSize, pageSize, logger);
}
const Digest& computeDefaultRvbDataDigest() const { return stateTransfer_->computeDefaultRvbDataDigest(); }
void enableFetchingState(void) {
DataStoreTransaction::Guard g(stateTransfer_->psd_->beginTransaction());
g.txn()->setIsFetchingState(true);
}
void setEraseMetadataFlag() { stateTransfer_->setEraseMetadataFlagImpl(); }
// Source Selector
void assertSourceSelectorMetricKeyVal(const std::string& key, uint64_t val);
SourceSelector& getSourceSelector() { return stateTransfer_->sourceSelector_; }
const std::set<uint16_t>& getPreferredReplicas() { return stateTransfer_->sourceSelector_.preferredReplicas_; }
void validateEqualRVTs(const RangeValidationTree& rvtA, const RangeValidationTree& rvtB) const;
FetchingState getFetchingState() { return stateTransfer_->getFetchingState(); }
bool isSrcSessionOpen() const { return stateTransfer_->sourceSession_.isOpen(); }
uint16_t srcSessionOwnerDestReplicaId() const { return stateTransfer_->sourceSession_.ownerDestReplicaId(); }
private:
const std::unique_ptr<BCStateTran>& stateTransfer_;
};
/////////////////////////////////////////////////////////
// FakeReplicaBase
//
// Base class for a fake replica
/////////////////////////////////////////////////////////
class FakeReplicaBase {
public:
FakeReplicaBase(const Config& targetConfig,
const TestConfig& testConfig,
const TestState& testState,
TestReplica& testedReplicaIf,
const std::shared_ptr<DataGenerator>& dataGen,
std::shared_ptr<BcStTestDelegator>& testAdapter,
BCStateTran* peerStateTransfer);
virtual ~FakeReplicaBase();
const TestAppState& getAppState() const { return appState_; }
// Helper functions
size_t clearSentMessagesByMessageType(uint16_t type) { return filterSentMessagesByMessageType(type, false); }
size_t keepSentMessagesByMessageType(uint16_t type) { return filterSentMessagesByMessageType(type, true); }
private:
size_t filterSentMessagesByMessageType(uint16_t type, bool keep);
protected:
const Config& targetConfig_;
const TestConfig& testConfig_;
const TestState& testState_;
std::shared_ptr<DataStore> datastore_;
TestAppState appState_;
TestReplica& testedReplicaIf_;
unique_ptr<RVBManager> rvbm_;
const std::shared_ptr<DataGenerator> dataGen_;
const std::shared_ptr<BcStTestDelegator> stDelegator_;
BCStateTran* peerStateTransfer_;
};
/////////////////////////////////////////////////////////
// FakeDestination
//
// Fake one or more destination replicas.
// Supposed to work against real ST product source.
/////////////////////////////////////////////////////////Fake a source or multiple sources.
class FakeDestination : public FakeReplicaBase {
public:
FakeDestination(const Config& targetConfig,
const TestConfig& testConfig,
const TestState& testState,
TestReplica& testedReplicaIf,
const std::shared_ptr<DataGenerator>& dataGen,
std::shared_ptr<BcStTestDelegator>& stAdapter,
BCStateTran* srcStateTransfer)
: FakeReplicaBase(targetConfig, testConfig, testState, testedReplicaIf, dataGen, stAdapter, srcStateTransfer) {}
~FakeDestination() {}
void sendAskForCheckpointSummariesMsg(uint64_t minRelevantCheckpointNum, uint16_t senderReplicaId = UINT_LEAST16_MAX);
static constexpr uint16_t kDefaultSenderReplicaId = UINT_LEAST16_MAX;
template <class R, class... Args>
void sendFetchBlocksMsg(uint64_t minBlockId,
uint64_t maxBlockIdInCycle,
// when 0 , (minBlockId + targetConfig_.maxNumberOfChunksInBatch -1) is assigned
uint64_t maxBlockId = 0,
// when 0 , targetConfig_.maxNumberOfChunksInBatch is assigned
size_t numExpectedItemDataMsgsInReply = 0,
// when kDefaultSenderReplicaId , just adding 1 to targetConfig_.myReplicaId
uint16_t senderReplicaId = kDefaultSenderReplicaId,
// when 0, caluclated internally by default logic
uint64_t numexpectedRvbs = 0,
// if non-zero, request RVB digests and validate them
uint64_t rvbGroupId = 0,
// if non-zero - reject is expected and some other arguments are ignored
uint16_t rejectReason = 0,
// These 2 callbcks can be used to perform operations between triggers of onTimer callback
const std::function<R(Args...)>& callBeforeTriggerTimerCb = EMPTY_FUNC,
const std::function<R(Args...)>& callAfterTriggerTimerCb = EMPTY_FUNC);
void sendFetchResPagesMsg(uint64_t lastCheckpointKnownToRequester,
uint64_t requiredCheckpointNum,
uint16_t senderReplicaId = UINT_LEAST16_MAX);
uint64_t getLastMsgSeqNum() { return lastMsgSeqNum_; }
protected:
uint64_t lastMsgSeqNum_;
};
/////////////////////////////////////////////////////////
// FakeSources
//
// Fake a source or multiple sources.
// Supposed to work against real ST product destination.
/////////////////////////////////////////////////////////
class FakeSources : public FakeReplicaBase {
public:
FakeSources(const Config& targetConfig,
const TestConfig& testConfig,
const TestState& testState,
TestReplica& testedReplicaIf,
const std::shared_ptr<DataGenerator>& dataGen,
std::shared_ptr<BcStTestDelegator>& stAdapter,
BCStateTran* peerStateTransfer);
// Source (fake) Replies
void replyAskForCheckpointSummariesMsg(bool generateBlocksAndDescriptors = true);
void replyFetchBlocksMsg();
void replyResPagesMsg(bool& outDoneSending);
void rejectFetchingMsg(uint16_t rejCode, uint64_t reqMsgSeqNum, uint16_t destReplicaId);
void syncBlocks(TestAppState& srcAppState, uint64_t fromBlockId, uint64_t toBlockId);
protected:
std::unique_ptr<char[]> rawVBlock_;
std::optional<FetchResPagesMsg> lastReceivedFetchResPagesMsg_;
};
/////////////////////////////////////////////////////////
// BcStTest
//
// Test fixture for blockchain state transfer tests
/////////////////////////////////////////////////////////
class BcStTest : public ::testing::Test {
/**
* We are testing destination or source ST replica.
* To simplify code, and to avoid having another hierarchy of production dest/source "replicas" which wrap ST
* module in test, we include in this fixture 2 types of members:
* 1) Test infrastructure-related members
* 2) State Transfer building blocks, which represent an ST replica in test, with ST being tested.
*/
protected:
// Infra - Initializers and finalizers
void SetUp() override{};
void TearDown() override;
void initialize();
// Infra configuration and initialization
Config targetConfig_ = targetConfig();
TestConfig testConfig_;
TestState testState_;
// Infra Fake replicas
std::unique_ptr<FakeSources> fakeSrcReplica_;
std::unique_ptr<FakeDestination> fakeDstReplica_;
// Infra services
std::shared_ptr<DataGenerator> dataGen_;
std::shared_ptr<BcStTestDelegator> stDelegator_;
private:
// Infra initialize helpers
void printConfiguration();
bool initialized_ = false;
protected:
// Infra member functions
void compareAppStateblocks(uint64_t minBlockId, uint64_t maxBlockId) const;
// Target/Product - backup replica, during checkpointing
void bkpPrune(uint64_t maxBlockIdToDelete);
// Target/Product ST - destination API & assertions
void dstStartRunningAndCollecting(FetchingState expectedState = FetchingState::NotFetching);
void dstStartCollecting();
void dstAssertAskForCheckpointSummariesSent(uint64_t checkpoint_num);
void dstAssertFetchBlocksMsgSent();
void dstAssertFetchResPagesMsgSent();
void dstReportMultiplePrePrepareMessagesReceived(size_t numberOfPreprepareMessages, uint16_t senderId);
// Target/Product ST - source API & assertions// This should be the same as TestConfig
void srcAssertCheckpointSummariesSent(uint64_t minRepliedCheckpointNum, uint64_t maxRepliedCheckpointNum);
void srcAssertItemDataMsgBatchSentWithBlocks(uint64_t minExpectedBlockId, uint64_t maxExpectedBlockId);
void srcAssertItemDataMsgBatchSentWithResPages(uint32_t expectedChunksSent, uint64_t requiredCheckpointNum);
// Target/Product ST - common (as source/destination) API & assertions
void cmnStartRunning(FetchingState expectedState = FetchingState::NotFetching);
// Target/Product ST - Source Selector
using MetricKeyValPairs = std::map<std::string, uint64_t>;
void validateSourceSelectorMetricCounters(const MetricKeyValPairs& metricCounters);
enum class TRejectFlag { True, False };
enum class TSkipReplyFlag { True, False };
template <class R, class... Args>
void getMissingblocksStage(const std::function<R(Args...)>& callAtStart = EMPTY_FUNC,
const std::function<R(Args...)>& callAtEnd = EMPTY_FUNC,
TSkipReplyFlag skipReply = TSkipReplyFlag::False,
size_t numberOfSkips = 1,
TRejectFlag reject = TRejectFlag::False,
list<uint16_t> rejectionReasons = list<uint16_t>(),
size_t sleepDurationAfterReplyMilli = 20);
void getReservedPagesStage(TSkipReplyFlag skipReply = TSkipReplyFlag::False,
TRejectFlag reject = TRejectFlag::False,
uint16_t rejectionReason = 0,
size_t sleepDurationAfterReplyMilli = 20);
void dstValidateCycleEnd(size_t timeToSleepAfterreportCompletedMilli = 10);
void dstRestart(bool productDbDeleteOnEnd, FetchingState expectedState);
public: // why public? quick workaround to allow binding on derived class
void dstRestartWithIterations(std::set<size_t>& execOnIterations, FetchingState expectedState);
protected:
// These members are used to construct stateTransfer_
TestAppState appState_;
DataStore* datastore_;
TestReplica testedReplicaIf_;
std::unique_ptr<BCStateTran> stateTransfer_;
}; // class BcStTest
/////////////////////////////////////////////////////////
// DataGenerator - definition
/////////////////////////////////////////////////////////
DataGenerator::DataGenerator(const Config& targetConfig, const TestConfig& testConfig)
: targetConfig_(targetConfig), testConfig_(testConfig) {
bftEngine::ReservedPagesClientBase::setReservedPages(&fakeReservedPages_);
}
/**
* toBlockId is assumed to be a checkpoint block, we also assume
* generatedBlocks_ is empty
*/
void DataGenerator::generateBlocks(TestAppState& appState, uint64_t fromBlockId, uint64_t toBlockId) {
std::unique_ptr<char[]> buff = std::make_unique<char[]>(Block::getMaxTotalBlockSize());
ConcordAssertLE(fromBlockId, toBlockId);
ConcordAssertGT(fromBlockId, appState.getGenesisBlockNum());
auto maxBlockDataSize = Block::calcMaxDataSize();
std::shared_ptr<Block> prevBlk;
for (size_t i = fromBlockId; i <= toBlockId; ++i) {
if (appState.hasBlock(i)) continue;
uint32_t dataSize = static_cast<uint32_t>(rand()) % (maxBlockDataSize - testConfig_.minBlockDataSize + 1) +
testConfig_.minBlockDataSize;
ConcordAssertLE(dataSize, maxBlockDataSize);
fillRandomBytes(buff.get(), dataSize);
std::shared_ptr<Block> blk;
StateTransferDigest digestPrev{1};
if ((i == fromBlockId) && (!appState.hasBlock(i - 1))) {
blk.reset(Block::createFromData(dataSize, buff.get(), i, digestPrev), Block::BlockDeleter());
} else {
if (!prevBlk) {
prevBlk = appState.peekBlock(i - 1);
ASSERT_TRUE(prevBlk);
}
computeBlockDigest(
prevBlk->blockId, reinterpret_cast<const char*>(prevBlk.get()), prevBlk->totalBlockSize, &digestPrev);
blk.reset(Block::createFromData(dataSize, buff.get(), i, digestPrev), Block::BlockDeleter());
}
// we assume that last parameter is ignored
ASSERT_TRUE(appState.putBlock(i, reinterpret_cast<const char*>(blk.get()), blk->totalBlockSize, false));
prevBlk = blk;
}
}
void DataGenerator::generateCheckpointDescriptors(const TestAppState& appState,
DataStore* datastore,
uint64_t minRepliedCheckpointNum,
uint64_t maxRepliedCheckpointNum,
RVBManager* rvbm) {
ASSERT_LE(minRepliedCheckpointNum, maxRepliedCheckpointNum);
ASSERT_TRUE(rvbm);
// Compute digest of last block
uint64_t lastBlockId = (maxRepliedCheckpointNum + 1) * testConfig_.checkpointWindowSize;
auto lastBlk = appState.peekBlock(lastBlockId);
ASSERT_TRUE(lastBlk);
StateTransferDigest lastBlockDigest;
computeBlockDigest(
lastBlockId, reinterpret_cast<const char*>(lastBlk.get()), lastBlk->totalBlockSize, &lastBlockDigest);
for (uint64_t i = minRepliedCheckpointNum; i <= maxRepliedCheckpointNum; ++i) {
// for now, we do not support (expect) setting into an already set descriptor
ASSERT_FALSE(datastore->hasCheckpointDesc(i));
DataStore::CheckpointDesc desc;
desc.checkpointNum = i;
desc.maxBlockId = (i + 1) * testConfig_.checkpointWindowSize;
auto digestBytes = desc.digestOfMaxBlockId.getForUpdate();
if (i == maxRepliedCheckpointNum)
memcpy(digestBytes, &lastBlockDigest, sizeof(lastBlockDigest));
else {
auto blk = appState.peekBlock(desc.maxBlockId + 1);
ASSERT_TRUE(blk);
memcpy(digestBytes, &blk->digestPrev, sizeof(blk->digestPrev));
}
ASSERT_NFF(generateReservedPages(datastore, i));
DataStore::ResPagesDescriptor* resPagesDesc = datastore->getResPagesDescriptor(i);
Digest digestOfResPagesDescriptor;
BCStateTran::computeDigestOfPagesDescriptor(resPagesDesc, digestOfResPagesDescriptor);
datastore->free(resPagesDesc);
desc.digestOfResPagesDescriptor = digestOfResPagesDescriptor;
rvbm->updateRvbDataDuringCheckpoint(desc);
datastore->setCheckpointDesc(i, desc);
}
datastore->setFirstStoredCheckpoint(minRepliedCheckpointNum);
datastore->setLastStoredCheckpoint(maxRepliedCheckpointNum);
}
void DataGenerator::generateReservedPages(DataStore* datastore, uint64_t checkpointNumber) {
uint32_t idx = 0;
std::unique_ptr<char[]> buffer(new char[targetConfig_.sizeOfReservedPage]);
for (uint32_t pageId{0}; pageId < testConfig_.maxNumberOfUpdatedReservedPages; ++pageId) {
ConcordAssertLT(idx, testConfig_.maxNumberOfUpdatedReservedPages);
Digest pageDigest;
fillRandomBytes(buffer.get(), targetConfig_.sizeOfReservedPage);
BCStateTran::computeDigestOfPage(
pageId, checkpointNumber, buffer.get(), targetConfig_.sizeOfReservedPage, pageDigest);
ASSERT_TRUE(!pageDigest.isZero());
datastore->setResPage(pageId, checkpointNumber, pageDigest, buffer.get());
idx++;
}
}
std::unique_ptr<MessageBase> DataGenerator::generatePrePrepareMsg(ReplicaId sender_id) {
static constexpr ViewNum view_num_ = 1u;
static constexpr SeqNum seq_num_ = 2u;
static constexpr CommitPath commit_path_ = CommitPath::OPTIMISTIC_FAST;
return make_unique<PrePrepareMsg>(sender_id, view_num_, seq_num_, commit_path_, 0);
}
/////////////////////////////////////////////////////////
// BcStTestDelegator - definition
/////////////////////////////////////////////////////////
void BcStTestDelegator::fillHeaderOfVirtualBlock(std::unique_ptr<char[]>& rawVBlock,
uint32_t numberOfUpdatedPages,
uint64_t lastCheckpointKnownToRequester) {
BCStateTran::HeaderOfVirtualBlock* header = reinterpret_cast<BCStateTran::HeaderOfVirtualBlock*>(rawVBlock.get());
header->lastCheckpointKnownToRequester = lastCheckpointKnownToRequester;
header->numberOfUpdatedPages = numberOfUpdatedPages;
}
void BcStTestDelegator::fillElementOfVirtualBlock(DataStore* datastore,
char* position,
uint32_t pageId,
uint64_t checkpointNumber,
const Digest& pageDigest,
uint32_t sizeOfReservedPage) {
BCStateTran::ElementOfVirtualBlock* currElement = reinterpret_cast<BCStateTran::ElementOfVirtualBlock*>(position);
currElement->pageId = pageId;
currElement->checkpointNumber = checkpointNumber;
currElement->pageDigest = pageDigest;
ASSERT_TRUE(!currElement->pageDigest.isZero());
datastore->getResPage(pageId, checkpointNumber, nullptr, currElement->page, sizeOfReservedPage);
ASSERT_TRUE(!pageDigest.isZero());
}
// Not all metrics are here, you may add more as needed
void BcStTestDelegator::assertBCStateTranMetricKeyVal(const std::string& key, uint64_t val) {
auto& stMetrics_ = stateTransfer_->metrics_;
if (key == "src_overall_batches_sent") {
ASSERT_EQ(stMetrics_.src_overall_batches_sent_.Get().Get(), val);
} else if (key == "src_overall_prefetched_batches_sent") {
ASSERT_EQ(stMetrics_.src_overall_prefetched_batches_sent_.Get().Get(), val);
} else if (key == "src_overall_on_spot_batches_sent") {
ASSERT_EQ(stMetrics_.src_overall_on_spot_batches_sent_.Get().Get(), val);
} else if (key == "src_num_io_contexts_dropped") {
ASSERT_EQ(stMetrics_.src_num_io_contexts_dropped_.Get().Get(), val);
} else if (key == "src_num_io_contexts_invoked") {
ASSERT_EQ(stMetrics_.src_num_io_contexts_invoked_.Get().Get(), val);
} else if (key == "src_num_io_contexts_consumed") {
ASSERT_EQ(stMetrics_.src_num_io_contexts_consumed_.Get().Get(), val);
} else if (key == "received_reject_fetching_msg") {
ASSERT_EQ(stMetrics_.received_reject_fetching_msg_.Get().Get(), val);
} else {
FAIL() << "Unexpected key!";
}
}
// Not all metrics are here, you may add more as needed
void BcStTestDelegator::assertSourceSelectorMetricKeyVal(const std::string& key, uint64_t val) {
auto& ssMetrics_ = stateTransfer_->sourceSelector_.metrics_;
if (key == "total_replacements") {
ASSERT_EQ(ssMetrics_.total_replacements_.Get().Get(), val);
} else if (key == "replacement_due_to_no_source") {
ASSERT_EQ(ssMetrics_.replacement_due_to_no_source_.Get().Get(), val);
} else if (key == "replacement_due_to_bad_data") {
ASSERT_EQ(ssMetrics_.replacement_due_to_bad_data_.Get().Get(), val);
} else if (key == "replacement_due_to_retransmission_timeout") {
ASSERT_EQ(ssMetrics_.replacement_due_to_retransmission_timeout_.Get().Get(), val);
} else if (key == "replacement_due_to_periodic_change") {
ASSERT_EQ(ssMetrics_.replacement_due_to_periodic_change_.Get().Get(), val);
} else if (key == "replacement_due_to_source_same_as_primary") {
ASSERT_EQ(ssMetrics_.replacement_due_to_source_same_as_primary_.Get().Get(), val);
} else {
FAIL() << "Unexpected key!";
}
}
void BcStTestDelegator::validateEqualRVTs(const RangeValidationTree& rvtA, const RangeValidationTree& rvtB) const {
ASSERT_EQ(rvtA.getRootCurrentValueStr(), rvtB.getRootCurrentValueStr());
ASSERT_EQ(rvtA.totalNodes(), rvtB.totalNodes());
ASSERT_EQ(rvtA.totalLevels(), rvtB.totalLevels());
ASSERT_EQ(rvtA.getMinRvbId(), rvtB.getMinRvbId());
ASSERT_EQ(rvtA.getMaxRvbId(), rvtB.getMaxRvbId());
ASSERT_EQ(rvtA.rightmost_rvt_node_.size(), rvtB.rightmost_rvt_node_.size());
ASSERT_EQ(rvtA.leftmost_rvt_node_.size(), rvtB.leftmost_rvt_node_.size());
ASSERT_EQ(rvtA.leftmost_rvt_node_.size(), RangeValidationTree::NodeInfo::kMaxLevels);
ASSERT_EQ(rvtA.rightmost_rvt_node_.size(), RangeValidationTree::NodeInfo::kMaxLevels);
const auto& rmA = rvtA.rightmost_rvt_node_;
const auto& rmB = rvtB.rightmost_rvt_node_;
const auto& lmA = rvtA.leftmost_rvt_node_;
const auto& lmB = rvtB.leftmost_rvt_node_;
for (size_t i{}; i < RangeValidationTree::NodeInfo::kMaxLevels; ++i) {
if (rmA[i]) {
ASSERT_EQ(rmA[i]->info_.id(), rmB[i]->info_.id());
} else {
ASSERT_EQ(rmA[i], rmB[i]);
}
if (lmA[i]) {
ASSERT_EQ(lmA[i]->info_.id(), lmB[i]->info_.id());
} else {
ASSERT_EQ(lmA[i], lmB[i]);
}
}
ASSERT_EQ(rvtA.max_rvb_index_, rvtB.max_rvb_index_);
ASSERT_EQ(rvtA.min_rvb_index_, rvtB.min_rvb_index_);
if (rvtA.root_ && (rvtA.root_ == rvtB.root_)) {
ASSERT_EQ(rvtA.root_->numChildren(), rvtB.root_->numChildren());
ASSERT_EQ(rvtA.root_->parent_id_, rvtB.root_->parent_id_);
ASSERT_EQ(rvtA.root_->insertion_counter_, rvtB.root_->insertion_counter_);
}
}
/////////////////////////////////////////////////////////
// FakeReplicaBase - definition
/////////////////////////////////////////////////////////
FakeReplicaBase::FakeReplicaBase(const Config& targetConfig,
const TestConfig& testConfig,
const TestState& testState,
TestReplica& testedReplicaIf,
const std::shared_ptr<DataGenerator>& dataGen,
std::shared_ptr<BcStTestDelegator>& stAdapter,
BCStateTran* peerStateTransfer)
: targetConfig_(targetConfig),
testConfig_(testConfig),
testState_(testState),
testedReplicaIf_(testedReplicaIf),
dataGen_(dataGen),
stDelegator_(stAdapter),
peerStateTransfer_(peerStateTransfer) {
if (testConfig_.fakeDbDeleteOnStart) deleteBcStateTransferDbFolder(testConfig_.fakeBcstDbPath);
datastore_.reset(createDataStore(testConfig_.fakeBcstDbPath, targetConfig_));
datastore_->setNumberOfReservedPages(testConfig_.numberOfRequiredReservedPages);
rvbm_ = std::make_unique<RVBManager>(targetConfig, &appState_, datastore_);
}
FakeReplicaBase::~FakeReplicaBase() {
if (testConfig_.fakeDbDeleteOnEnd) deleteBcStateTransferDbFolder(testConfig_.fakeBcstDbPath);
}
/**
* keep is true: keep only messages with msg->type == type
* keep is false: keep all message with msg->type != type
* return number of messages deleted
*/
size_t FakeReplicaBase::filterSentMessagesByMessageType(uint16_t type, bool keep) {
auto& sent_messages_ = testedReplicaIf_.sent_messages_;
size_t n{0};
for (auto it = sent_messages_.begin(); it != sent_messages_.end();) {
auto header = reinterpret_cast<BCStateTranBaseMsg*>((*it).data_.get());
// This block can be much shorter. For better readability, keep it like that
if (keep) {
if (header->type != type) {
it = sent_messages_.erase(it);
++n;
continue;
}
} else { // keep == false
if (header->type == type) {
it = sent_messages_.erase(it);
++n;
continue;
}
}
++it;
} // for
return n;
}
/////////////////////////////////////////////////////////
// FakeDestination - definition
/////////////////////////////////////////////////////////
void FakeDestination::sendAskForCheckpointSummariesMsg(uint64_t minRelevantCheckpointNum, uint16_t senderReplicaId) {
ASSERT_SRC_UNDER_TEST;
AskForCheckpointSummariesMsg askForCheckpointSummariesMsg;
lastMsgSeqNum_ = stDelegator_->uniqueMsgSeqNum();
askForCheckpointSummariesMsg.msgSeqNum = lastMsgSeqNum_;
askForCheckpointSummariesMsg.minRelevantCheckpointNum = minRelevantCheckpointNum;
char* askForCheckpointSummariesMsgBuff{nullptr};
ASSERT_NFF(TestUtils::allocCopyStateTransferMsg(reinterpret_cast<char*>(&askForCheckpointSummariesMsg),
sizeof(AskForCheckpointSummariesMsg),
&askForCheckpointSummariesMsgBuff));
senderReplicaId = (senderReplicaId == UINT_LEAST16_MAX)
? ((targetConfig_.myReplicaId + 1) % targetConfig_.numReplicas)
: senderReplicaId;
stDelegator_->handleStateTransferMessage(
askForCheckpointSummariesMsgBuff, sizeof(AskForCheckpointSummariesMsg), senderReplicaId);
}
template <class R, class... Args>
void FakeDestination::sendFetchBlocksMsg(uint64_t minBlockId,
uint64_t maxBlockIdInCycle,
uint64_t maxBlockId,
size_t numExpectedItemDataMsgsInReply,
uint16_t senderReplicaId,
uint64_t numexpectedRvbs,
uint64_t rvbGroupId,
uint16_t rejectReason,
const std::function<R(Args...)>& callBeforeTriggerTimerCb,
const std::function<R(Args...)>& callAfterTriggerTimerCb) {
ASSERT_SRC_UNDER_TEST;
if (maxBlockId == 0) {
maxBlockId = minBlockId + targetConfig_.maxNumberOfChunksInBatch - 1;
}
if (numExpectedItemDataMsgsInReply == 0) {
numExpectedItemDataMsgsInReply = targetConfig_.maxNumberOfChunksInBatch;
}
// Remove this line if we would like to make negative tests
ASSERT_GE(maxBlockId, minBlockId);
ASSERT_GE(maxBlockIdInCycle, maxBlockId);
FetchBlocksMsg fetchBlocksMsg;
lastMsgSeqNum_ = stDelegator_->uniqueMsgSeqNum();
// Simplify things compare to a real destination - ask for a batch of a size up to maxNumberOfChunksInBatch, without
// referring to fetchRangeSize
fetchBlocksMsg.msgSeqNum = lastMsgSeqNum_;
fetchBlocksMsg.minBlockId = minBlockId;
fetchBlocksMsg.maxBlockId = maxBlockId;
fetchBlocksMsg.maxBlockIdInCycle = maxBlockIdInCycle;
fetchBlocksMsg.lastKnownChunkInLastRequiredBlock = 0; // for now, chunking is not supported
fetchBlocksMsg.rvbGroupId = rvbGroupId;
ASSERT_NE(senderReplicaId, targetConfig_.myReplicaId);
senderReplicaId = (senderReplicaId == kDefaultSenderReplicaId)
? ((targetConfig_.myReplicaId + 1) % targetConfig_.numReplicas)
: senderReplicaId;
char* fetchBlocksMsgBuff{nullptr};
ASSERT_NFF(TestUtils::allocCopyStateTransferMsg(
reinterpret_cast<char*>(&fetchBlocksMsg), sizeof(FetchBlocksMsg), &fetchBlocksMsgBuff));
stDelegator_->handleStateTransferMessage(fetchBlocksMsgBuff, sizeof(FetchBlocksMsg), senderReplicaId);
do {
const auto [isTriggered, duration] = testedReplicaIf_.popOneShotTimerDurationMilli();
if (!isTriggered) {
break;
}
this_thread::sleep_for(chrono::milliseconds(duration));
if (callBeforeTriggerTimerCb) {
callBeforeTriggerTimerCb();
}
peerStateTransfer_->onTimer();
if (callAfterTriggerTimerCb) {
callAfterTriggerTimerCb();
}
} while (true);
ASSERT_EQ(testedReplicaIf_.sent_messages_.size(), (rejectReason == 0) ? numExpectedItemDataMsgsInReply : 1);
if (rejectReason != 0) {
ASSERT_EQ(FetchingState::NotFetching, stDelegator_->getFetchingState());
const auto& msg = testedReplicaIf_.sent_messages_.front();
ASSERT_NFF(assertMsgType(msg, MsgType::RejectFetching));
auto* rejectFetchingMsg = reinterpret_cast<RejectFetchingMsg*>(msg.data_.get());
ASSERT_EQ(rejectFetchingMsg->rejectionCode, rejectReason);
testedReplicaIf_.sent_messages_.clear();
} else if (rvbGroupId > 0) {
// As of now, we support a single RVB group within the collection range
// A batch is sent, we expect the 1st item data message to include partial left RVB Group. Lets validate it.
// TODO: assert for the above supported assumption
const auto& msg = testedReplicaIf_.sent_messages_.front();
auto itemDataMsg = reinterpret_cast<ItemDataMsg*>(msg.data_.get());
ASSERT_GT(itemDataMsg->rvbDigestsSize, 0);
const auto sizeOfRvbDigestInfo = stDelegator_->getSizeOfRvbDigestInfo();
ASSERT_EQ(itemDataMsg->rvbDigestsSize % sizeOfRvbDigestInfo, 0);
auto startRvbId = stDelegator_->nextRvbBlockId(minBlockId);
if (startRvbId == 0) {
startRvbId = targetConfig_.fetchRangeSize;
}
const auto endRvbId = stDelegator_->prevRvbBlockId(maxBlockIdInCycle);
ASSERT_GE(endRvbId, startRvbId);
// numexpectedRvbs should be in the range [1,RVT_K]. It is too long to calculate to calculate in a Mock.
// If there is no pruning it should be RVT_K
// If given from outside, we test equality, else test for being in the range
ASSERT_EQ(itemDataMsg->rvbDigestsSize % sizeOfRvbDigestInfo, 0);
auto numRvbs = itemDataMsg->rvbDigestsSize / sizeOfRvbDigestInfo;
if (numexpectedRvbs != 0) {
ASSERT_EQ(numexpectedRvbs, numRvbs);