forked from stellar/stellar-core
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSurveyManager.cpp
587 lines (493 loc) · 18.5 KB
/
SurveyManager.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
// Copyright 2019 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 "SurveyManager.h"
#include "herder/Herder.h"
#include "main/Application.h"
#include "main/ErrorMessages.h"
#include "overlay/OverlayManager.h"
#include "util/GlobalChecks.h"
#include "util/Logging.h"
#include "xdrpp/marshal.h"
namespace stellar
{
uint32_t const SurveyManager::SURVEY_THROTTLE_TIMEOUT_MULT(3);
SurveyManager::SurveyManager(Application& app)
: mApp(app)
, mSurveyThrottleTimer(std::make_unique<VirtualTimer>(mApp))
, NUM_LEDGERS_BEFORE_IGNORE(12) // ~60 seconds
, MAX_REQUEST_LIMIT_PER_LEDGER(10)
, mMessageLimiter(app, NUM_LEDGERS_BEFORE_IGNORE,
MAX_REQUEST_LIMIT_PER_LEDGER)
, SURVEY_THROTTLE_TIMEOUT_SEC(
mApp.getConfig().getExpectedLedgerCloseTime() *
SURVEY_THROTTLE_TIMEOUT_MULT)
{
}
bool
SurveyManager::startSurvey(SurveyMessageCommandType type,
std::chrono::seconds surveyDuration)
{
if (mRunningSurveyType)
{
return false;
}
// results are only cleared when we start the NEXT survey so we can query
// the results after the survey closes
mResults.clear();
mBadResponseNodes.clear();
// queued peers are only cleared when we start the NEXT survey so we know
// which peers were in our backlog before we stopped
mPeersToSurvey.clear();
mPeersToSurveyQueue = std::queue<NodeID>();
mRunningSurveyType = std::make_optional<SurveyMessageCommandType>(type);
mCurve25519SecretKey = curve25519RandomSecret();
mCurve25519PublicKey = curve25519DerivePublic(mCurve25519SecretKey);
updateSurveyExpiration(surveyDuration);
// starts timer
topOffRequests(type);
return true;
}
void
SurveyManager::stopSurvey()
{
// do nothing if survey isn't running
if (!mRunningSurveyType)
{
return;
}
mRunningSurveyType.reset();
mSurveyThrottleTimer->cancel();
clearCurve25519Keys(mCurve25519PublicKey, mCurve25519SecretKey);
CLOG_INFO(Overlay, "SurveyResults {}", getJsonResults().toStyledString());
}
void
SurveyManager::addNodeToRunningSurveyBacklog(
SurveyMessageCommandType type, std::chrono::seconds surveyDuration,
NodeID const& nodeToSurvey)
{
if (!mRunningSurveyType || *mRunningSurveyType != type)
{
throw std::runtime_error("addNodeToRunningSurveyBacklog failed");
}
addPeerToBacklog(nodeToSurvey);
updateSurveyExpiration(surveyDuration);
}
void
SurveyManager::relayOrProcessResponse(StellarMessage const& msg,
Peer::pointer peer)
{
releaseAssert(msg.type() == SURVEY_RESPONSE);
auto const& signedResponse = msg.signedSurveyResponseMessage();
auto const& response = signedResponse.response;
auto onSuccessValidation = [&]() -> bool {
return dropPeerIfSigInvalid(response.surveyedPeerID,
signedResponse.responseSignature,
xdr::xdr_to_opaque(response), peer);
};
if (!mMessageLimiter.recordAndValidateResponse(response,
onSuccessValidation))
{
return;
}
// mMessageLimiter filters out duplicates, so here we are guaranteed
// to record the message for the first time
mApp.getOverlayManager().recvFloodedMsg(msg, peer);
if (response.surveyorPeerID == mApp.getConfig().NODE_SEED.getPublicKey())
{
// only process if survey is still running and we haven't seen the
// response
if (mRunningSurveyType && *mRunningSurveyType == response.commandType)
{
try
{
xdr::opaque_vec<> opaqueDecrypted = curve25519Decrypt(
mCurve25519SecretKey, mCurve25519PublicKey,
response.encryptedBody);
SurveyResponseBody body;
xdr::xdr_from_opaque(opaqueDecrypted, body);
processTopologyResponse(response.surveyedPeerID, body);
}
catch (std::exception const& e)
{
CLOG_ERROR(Overlay, "processing survey response failed: {}",
e.what());
mBadResponseNodes.emplace(response.surveyedPeerID);
return;
}
}
}
else
{
// messageLimiter guarantees we only flood the response if we've seen
// the request
broadcast(msg);
}
}
void
SurveyManager::relayOrProcessRequest(StellarMessage const& msg,
Peer::pointer peer)
{
releaseAssert(msg.type() == SURVEY_REQUEST);
SignedSurveyRequestMessage const& signedRequest =
msg.signedSurveyRequestMessage();
SurveyRequestMessage const& request = signedRequest.request;
auto surveyorIsSelf =
request.surveyorPeerID == mApp.getConfig().NODE_SEED.getPublicKey();
if (!surveyorIsSelf)
{
releaseAssert(peer);
// perform all validation checks before signature validation so we don't
// waste time verifying signatures
auto const& surveyorKeys = mApp.getConfig().SURVEYOR_KEYS;
if (surveyorKeys.empty())
{
auto const& quorumMap =
mApp.getHerder().getCurrentlyTrackedQuorum();
if (quorumMap.count(request.surveyorPeerID) == 0)
{
return;
}
}
else
{
if (surveyorKeys.count(request.surveyorPeerID) == 0)
{
return;
}
}
}
auto onSuccessValidation = [&]() -> bool {
auto res = dropPeerIfSigInvalid(request.surveyorPeerID,
signedRequest.requestSignature,
xdr::xdr_to_opaque(request), peer);
if (!res && surveyorIsSelf)
{
CLOG_ERROR(Overlay, "Unexpected invalid survey request: {} ",
REPORT_INTERNAL_BUG);
}
return res;
};
if (!mMessageLimiter.addAndValidateRequest(request, onSuccessValidation))
{
return;
}
if (peer)
{
mApp.getOverlayManager().recvFloodedMsg(msg, peer);
}
if (request.surveyedPeerID == mApp.getConfig().NODE_SEED.getPublicKey())
{
processTopologyRequest(request);
}
else
{
broadcast(msg);
}
}
StellarMessage
SurveyManager::makeSurveyRequest(NodeID const& nodeToSurvey) const
{
StellarMessage newMsg;
newMsg.type(SURVEY_REQUEST);
auto& signedRequest = newMsg.signedSurveyRequestMessage();
auto& request = signedRequest.request;
request.ledgerNum = mApp.getHerder().trackingConsensusLedgerIndex();
request.surveyorPeerID = mApp.getConfig().NODE_SEED.getPublicKey();
request.surveyedPeerID = nodeToSurvey;
request.encryptionKey = mCurve25519PublicKey;
request.commandType = SURVEY_TOPOLOGY;
auto sigBody = xdr::xdr_to_opaque(request);
signedRequest.requestSignature = mApp.getConfig().NODE_SEED.sign(sigBody);
return newMsg;
}
void
SurveyManager::sendTopologyRequest(NodeID const& nodeToSurvey)
{
// Record the request in message limiter and broadcast
relayOrProcessRequest(makeSurveyRequest(nodeToSurvey), nullptr);
}
void
SurveyManager::processTopologyResponse(NodeID const& surveyedPeerID,
SurveyResponseBody const& body)
{
auto& peerResults =
mResults["topology"][KeyUtils::toStrKey(surveyedPeerID)];
auto populatePeerResults = [&](auto const& topologyBody) {
auto& inboundResults = peerResults["inboundPeers"];
auto& outboundResults = peerResults["outboundPeers"];
peerResults["numTotalInboundPeers"] =
topologyBody.totalInboundPeerCount;
peerResults["numTotalOutboundPeers"] =
topologyBody.totalOutboundPeerCount;
recordResults(inboundResults, topologyBody.inboundPeers);
recordResults(outboundResults, topologyBody.outboundPeers);
};
bool extendedSurveyType = body.type() == SURVEY_TOPOLOGY_RESPONSE_V1;
if (extendedSurveyType)
{
auto const& topologyBody = body.topologyResponseBodyV1();
populatePeerResults(topologyBody);
peerResults["maxInboundPeerCount"] = topologyBody.maxInboundPeerCount;
peerResults["maxOutboundPeerCount"] = topologyBody.maxOutboundPeerCount;
}
else
{
auto const& topologyBody = body.topologyResponseBodyV0();
populatePeerResults(topologyBody);
}
}
void
SurveyManager::processTopologyRequest(SurveyRequestMessage const& request) const
{
CLOG_TRACE(Overlay, "Responding to Topology request from {}",
mApp.getConfig().toShortString(request.surveyorPeerID));
StellarMessage newMsg;
newMsg.type(SURVEY_RESPONSE);
auto& signedResponse = newMsg.signedSurveyResponseMessage();
auto& response = signedResponse.response;
response.ledgerNum = request.ledgerNum;
response.surveyorPeerID = request.surveyorPeerID;
response.surveyedPeerID = mApp.getConfig().NODE_SEED.getPublicKey();
response.commandType = SURVEY_TOPOLOGY;
SurveyResponseBody body;
body.type(SURVEY_TOPOLOGY_RESPONSE_V1);
auto& topologyBody = body.topologyResponseBodyV1();
auto const& randomInboundPeers =
mApp.getOverlayManager().getRandomInboundAuthenticatedPeers();
auto const& randomOutboundPeers =
mApp.getOverlayManager().getRandomOutboundAuthenticatedPeers();
populatePeerStats(randomInboundPeers, topologyBody.inboundPeers,
mApp.getClock().now());
populatePeerStats(randomOutboundPeers, topologyBody.outboundPeers,
mApp.getClock().now());
topologyBody.totalInboundPeerCount =
static_cast<uint32_t>(randomInboundPeers.size());
topologyBody.totalOutboundPeerCount =
static_cast<uint32_t>(randomOutboundPeers.size());
topologyBody.maxInboundPeerCount =
mApp.getConfig().MAX_ADDITIONAL_PEER_CONNECTIONS;
topologyBody.maxOutboundPeerCount =
mApp.getConfig().TARGET_PEER_CONNECTIONS;
try
{
response.encryptedBody = curve25519Encrypt<EncryptedBody::max_size()>(
request.encryptionKey, xdr::xdr_to_opaque(body));
}
catch (std::exception const& e)
{
CLOG_ERROR(Overlay, "curve25519Encrypt failed: {}", e.what());
return;
}
auto sigBody = xdr::xdr_to_opaque(response);
signedResponse.responseSignature = mApp.getConfig().NODE_SEED.sign(sigBody);
broadcast(newMsg);
}
void
SurveyManager::broadcast(StellarMessage const& msg) const
{
mApp.getOverlayManager().broadcastMessage(msg);
}
void
SurveyManager::populatePeerStats(std::vector<Peer::pointer> const& peers,
PeerStatList& results,
VirtualClock::time_point now) const
{
size_t resultSize = std::min<size_t>(peers.size(), results.max_size());
results.reserve(resultSize);
for (size_t i = 0; i < resultSize; ++i)
{
auto& peer = peers[i];
auto& peerMetrics = peer->getPeerMetrics();
PeerStats stats;
stats.id = peer->getPeerID();
stats.versionStr = peer->getRemoteVersion();
stats.messagesRead = peerMetrics.mMessageRead;
stats.messagesWritten = peerMetrics.mMessageWrite;
stats.bytesRead = peerMetrics.mByteRead;
stats.bytesWritten = peerMetrics.mByteWrite;
stats.uniqueFloodBytesRecv = peerMetrics.mUniqueFloodBytesRecv;
stats.duplicateFloodBytesRecv = peerMetrics.mDuplicateFloodBytesRecv;
stats.uniqueFetchBytesRecv = peerMetrics.mUniqueFetchBytesRecv;
stats.duplicateFetchBytesRecv = peerMetrics.mDuplicateFetchBytesRecv;
stats.uniqueFloodMessageRecv = peerMetrics.mUniqueFloodMessageRecv;
stats.duplicateFloodMessageRecv =
peerMetrics.mDuplicateFloodMessageRecv;
stats.uniqueFetchMessageRecv = peerMetrics.mUniqueFetchMessageRecv;
stats.duplicateFetchMessageRecv =
peerMetrics.mDuplicateFetchMessageRecv;
stats.secondsConnected =
std::chrono::duration_cast<std::chrono::seconds>(
now - peerMetrics.mConnectedTime)
.count();
results.emplace_back(stats);
}
}
void
SurveyManager::recordResults(Json::Value& jsonResultList,
PeerStatList const& peerList) const
{
for (auto const& peer : peerList)
{
Json::Value peerInfo;
peerInfo["nodeId"] = KeyUtils::toStrKey(peer.id);
peerInfo["version"] = peer.versionStr;
peerInfo["messagesRead"] = static_cast<Json::UInt64>(peer.messagesRead);
peerInfo["messagesWritten"] =
static_cast<Json::UInt64>(peer.messagesWritten);
peerInfo["bytesRead"] = static_cast<Json::UInt64>(peer.bytesRead);
peerInfo["bytesWritten"] = static_cast<Json::UInt64>(peer.bytesWritten);
peerInfo["secondsConnected"] =
static_cast<Json::UInt64>(peer.secondsConnected);
peerInfo["uniqueFloodBytesRecv"] =
static_cast<Json::UInt64>(peer.uniqueFloodBytesRecv);
peerInfo["duplicateFloodBytesRecv"] =
static_cast<Json::UInt64>(peer.duplicateFloodBytesRecv);
peerInfo["uniqueFetchBytesRecv"] =
static_cast<Json::UInt64>(peer.uniqueFetchBytesRecv);
peerInfo["duplicateFetchBytesRecv"] =
static_cast<Json::UInt64>(peer.duplicateFetchBytesRecv);
peerInfo["uniqueFloodMessageRecv"] =
static_cast<Json::UInt64>(peer.uniqueFloodMessageRecv);
peerInfo["duplicateFloodMessageRecv"] =
static_cast<Json::UInt64>(peer.duplicateFloodMessageRecv);
peerInfo["uniqueFetchMessageRecv"] =
static_cast<Json::UInt64>(peer.uniqueFetchMessageRecv);
peerInfo["duplicateFetchMessageRecv"] =
static_cast<Json::UInt64>(peer.duplicateFetchMessageRecv);
jsonResultList.append(peerInfo);
}
}
void
SurveyManager::clearOldLedgers(uint32_t lastClosedledgerSeq)
{
mMessageLimiter.clearOldLedgers(lastClosedledgerSeq);
}
Json::Value const&
SurveyManager::getJsonResults()
{
mResults["surveyInProgress"] = mRunningSurveyType.has_value();
auto& jsonBacklog = mResults["backlog"];
jsonBacklog.clear();
for (auto const& peer : mPeersToSurvey)
{
jsonBacklog.append(KeyUtils::toStrKey(peer));
}
auto& badResponseNodes = mResults["badResponseNodes"];
badResponseNodes.clear();
for (auto const& peer : mBadResponseNodes)
{
badResponseNodes.append(KeyUtils::toStrKey(peer));
}
return mResults;
}
std::string
SurveyManager::getMsgSummary(StellarMessage const& msg)
{
std::string summary;
SurveyMessageCommandType commandType;
switch (msg.type())
{
case SURVEY_REQUEST:
summary = "SURVEY_REQUEST:";
commandType = msg.signedSurveyRequestMessage().request.commandType;
break;
case SURVEY_RESPONSE:
summary = "SURVEY_RESPONSE:";
commandType = msg.signedSurveyResponseMessage().response.commandType;
break;
default:
throw std::runtime_error(
"invalid call of SurveyManager::getMsgSummary");
}
return summary + commandTypeName(commandType);
}
void
SurveyManager::topOffRequests(SurveyMessageCommandType type)
{
// Only stop the survey if all pending requests have been processed
if (mApp.getClock().now() > mSurveyExpirationTime && mPeersToSurvey.empty())
{
stopSurvey();
return;
}
// we only send up to MAX_REQUEST_LIMIT_PER_LEDGER requests and wait
// mSurveyThrottleTimeoutSec between topoffs as to reduce the
// chance of having more than MAX_REQUEST_LIMIT_PER_LEDGER (which is the
// rate limit) on any node relaying requests on the network (NB: can still
// happen if some connections get congested)
uint32_t requestsSentInSchedule = 0;
while (mRunningSurveyType &&
requestsSentInSchedule < MAX_REQUEST_LIMIT_PER_LEDGER &&
!mPeersToSurvey.empty())
{
if (mPeersToSurveyQueue.empty())
{
throw std::runtime_error("mPeersToSurveyQueue unexpectedly empty");
}
auto key = mPeersToSurveyQueue.front();
mPeersToSurvey.erase(key);
mPeersToSurveyQueue.pop();
sendTopologyRequest(key);
++requestsSentInSchedule;
}
std::weak_ptr<SurveyManager> weak = shared_from_this();
auto handler = [weak, type]() {
auto self = weak.lock();
if (!self)
{
return;
}
self->topOffRequests(type);
};
// schedule next top off
mSurveyThrottleTimer->expires_from_now(SURVEY_THROTTLE_TIMEOUT_SEC);
mSurveyThrottleTimer->async_wait(handler, &VirtualTimer::onFailureNoop);
}
void
SurveyManager::updateSurveyExpiration(std::chrono::seconds surveyDuration)
{
mSurveyExpirationTime = mApp.getClock().now() + surveyDuration;
}
void
SurveyManager::addPeerToBacklog(NodeID const& nodeToSurvey)
{
// filter conditions-
// 1. already queued
// 2. node would survey itself
// This ensures that mPeersToSurveyQueue doesn't contain any duplicates.
if (mPeersToSurvey.count(nodeToSurvey) != 0 ||
nodeToSurvey == mApp.getConfig().NODE_SEED.getPublicKey())
{
return;
}
mBadResponseNodes.erase(nodeToSurvey);
// we clear the results because it's possible to send and receive
// multiple requests and responses for a surveyor-surveyed node pair. We
// expect the user to save any previous results before sending the
// duplicate requests, so we can just overwrite the previous result
mResults["topology"][KeyUtils::toStrKey(nodeToSurvey)].clear();
mPeersToSurvey.emplace(nodeToSurvey);
mPeersToSurveyQueue.emplace(nodeToSurvey);
}
bool
SurveyManager::dropPeerIfSigInvalid(PublicKey const& key,
Signature const& signature,
ByteSlice const& bin, Peer::pointer peer)
{
bool success = PubKeyUtils::verifySig(key, signature, bin);
if (!success && peer)
{
// we drop the connection to keep a bad peer from pegging the CPU with
// signature verification
peer->sendErrorAndDrop(ERR_MISC, "Survey has invalid signature",
Peer::DropMode::IGNORE_WRITE_QUEUE);
}
return success;
}
std::string
SurveyManager::commandTypeName(SurveyMessageCommandType type)
{
return xdr::xdr_traits<SurveyMessageCommandType>::enum_name(type);
}
}