-
Notifications
You must be signed in to change notification settings - Fork 1.5k
/
Copy pathPeerImp.cpp
2986 lines (2594 loc) · 87.5 KB
/
PeerImp.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//------------------------------------------------------------------------------
/*
This file is part of rippled: https://github.com/ripple/rippled
Copyright (c) 2012, 2013 Ripple Labs Inc.
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
//==============================================================================
#include <ripple/app/consensus/RCLValidations.h>
#include <ripple/app/ledger/InboundLedgers.h>
#include <ripple/app/ledger/InboundTransactions.h>
#include <ripple/app/ledger/LedgerMaster.h>
#include <ripple/app/misc/HashRouter.h>
#include <ripple/app/misc/LoadFeeTrack.h>
#include <ripple/app/misc/NetworkOPs.h>
#include <ripple/app/misc/Transaction.h>
#include <ripple/app/misc/ValidatorList.h>
#include <ripple/app/tx/apply.h>
#include <ripple/basics/UptimeClock.h>
#include <ripple/basics/base64.h>
#include <ripple/basics/random.h>
#include <ripple/basics/safe_cast.h>
#include <ripple/beast/core/LexicalCast.h>
#include <ripple/beast/core/SemanticVersion.h>
#include <ripple/nodestore/DatabaseShard.h>
#include <ripple/overlay/Cluster.h>
#include <ripple/overlay/impl/PeerImp.h>
#include <ripple/overlay/impl/Tuning.h>
#include <ripple/overlay/predicates.h>
#include <ripple/protocol/digest.h>
#include <boost/algorithm/clamp.hpp>
#include <boost/algorithm/string.hpp>
#include <boost/algorithm/string/predicate.hpp>
#include <boost/beast/core/ostream.hpp>
#include <algorithm>
#include <memory>
#include <numeric>
#include <sstream>
using namespace std::chrono_literals;
namespace ripple {
PeerImp::PeerImp(
Application& app,
id_t id,
std::shared_ptr<PeerFinder::Slot> const& slot,
http_request_type&& request,
PublicKey const& publicKey,
ProtocolVersion protocol,
Resource::Consumer consumer,
std::unique_ptr<stream_type>&& stream_ptr,
OverlayImpl& overlay)
: Child(overlay)
, app_(app)
, id_(id)
, sink_(app_.journal("Peer"), makePrefix(id))
, p_sink_(app_.journal("Protocol"), makePrefix(id))
, journal_(sink_)
, p_journal_(p_sink_)
, stream_ptr_(std::move(stream_ptr))
, socket_(stream_ptr_->next_layer().socket())
, stream_(*stream_ptr_)
, strand_(socket_.get_executor())
, timer_(waitable_timer{socket_.get_executor()})
, remote_address_(slot->remote_endpoint())
, overlay_(overlay)
, m_inbound(true)
, protocol_(protocol)
, state_(State::active)
, sanity_(Sanity::unknown)
, insaneTime_(clock_type::now())
, publicKey_(publicKey)
, creationTime_(clock_type::now())
, usage_(consumer)
, fee_(Resource::feeLightPeer)
, slot_(slot)
, request_(std::move(request))
, headers_(request_)
, compressionEnabled_(
headers_["X-Offer-Compression"] == "lz4" ? Compressed::On
: Compressed::Off)
{
}
PeerImp::~PeerImp()
{
const bool inCluster{cluster()};
if (state_ == State::active)
overlay_.onPeerDeactivate(id_);
overlay_.peerFinder().on_closed(slot_);
overlay_.remove(slot_);
if (inCluster)
{
JLOG(journal_.warn()) << getName() << " left cluster";
}
}
// Helper function to check for valid uint256 values in protobuf buffers
static bool
stringIsUint256Sized(std::string const& pBuffStr)
{
return pBuffStr.size() == uint256::size();
}
void
PeerImp::run()
{
if (!strand_.running_in_this_thread())
return post(strand_, std::bind(&PeerImp::run, shared_from_this()));
// We need to decipher
auto parseLedgerHash =
[](std::string const& value) -> boost::optional<uint256> {
uint256 ret;
if (ret.SetHexExact(value))
return {ret};
auto const s = base64_decode(value);
if (s.size() != uint256::size())
return boost::none;
return uint256{s};
};
boost::optional<uint256> closed;
boost::optional<uint256> previous;
if (auto const iter = headers_.find("Closed-Ledger");
iter != headers_.end())
{
closed = parseLedgerHash(iter->value().to_string());
if (!closed)
fail("Malformed handshake data (1)");
}
if (auto const iter = headers_.find("Previous-Ledger");
iter != headers_.end())
{
previous = parseLedgerHash(iter->value().to_string());
if (!previous)
fail("Malformed handshake data (2)");
}
if (previous && !closed)
fail("Malformed handshake data (3)");
{
std::lock_guard<std::mutex> sl(recentLock_);
if (closed)
closedLedgerHash_ = *closed;
if (previous)
previousLedgerHash_ = *previous;
}
if (m_inbound)
{
doAccept();
}
else
{
assert(state_ == State::active);
// XXX Set timer: connection is in grace period to be useful.
// XXX Set timer: connection idle (idle may vary depending on connection
// type.)
doProtocolStart();
}
// Request shard info from peer
protocol::TMGetPeerShardInfo tmGPS;
tmGPS.set_hops(0);
send(std::make_shared<Message>(tmGPS, protocol::mtGET_PEER_SHARD_INFO));
setTimer();
}
void
PeerImp::stop()
{
if (!strand_.running_in_this_thread())
return post(strand_, std::bind(&PeerImp::stop, shared_from_this()));
if (socket_.is_open())
{
// The rationale for using different severity levels is that
// outbound connections are under our control and may be logged
// at a higher level, but inbound connections are more numerous and
// uncontrolled so to prevent log flooding the severity is reduced.
//
if (m_inbound)
{
JLOG(journal_.debug()) << "Stop";
}
else
{
JLOG(journal_.info()) << "Stop";
}
}
close();
}
//------------------------------------------------------------------------------
void
PeerImp::send(std::shared_ptr<Message> const& m)
{
if (!strand_.running_in_this_thread())
return post(strand_, std::bind(&PeerImp::send, shared_from_this(), m));
if (gracefulClose_)
return;
if (detaching_)
return;
overlay_.reportTraffic(
safe_cast<TrafficCount::category>(m->getCategory()),
false,
static_cast<int>(m->getBuffer(compressionEnabled_).size()));
auto sendq_size = send_queue_.size();
if (sendq_size < Tuning::targetSendQueue)
{
// To detect a peer that does not read from their
// side of the connection, we expect a peer to have
// a small senq periodically
large_sendq_ = 0;
}
else if (
journal_.active(beast::severities::kDebug) &&
(sendq_size % Tuning::sendQueueLogFreq) == 0)
{
std::string const name{getName()};
JLOG(journal_.debug())
<< (name.empty() ? remote_address_.to_string() : name)
<< " sendq: " << sendq_size;
}
send_queue_.push(m);
if (sendq_size != 0)
return;
boost::asio::async_write(
stream_,
boost::asio::buffer(
send_queue_.front()->getBuffer(compressionEnabled_)),
bind_executor(
strand_,
std::bind(
&PeerImp::onWriteMessage,
shared_from_this(),
std::placeholders::_1,
std::placeholders::_2)));
}
void
PeerImp::charge(Resource::Charge const& fee)
{
if ((usage_.charge(fee) == Resource::drop) && usage_.disconnect() &&
strand_.running_in_this_thread())
{
// Sever the connection
overlay_.incPeerDisconnectCharges();
fail("charge: Resources");
}
}
//------------------------------------------------------------------------------
bool
PeerImp::crawl() const
{
auto const iter = headers_.find("Crawl");
if (iter == headers_.end())
return false;
return boost::iequals(iter->value(), "public");
}
bool
PeerImp::cluster() const
{
return static_cast<bool>(app_.cluster().member(publicKey_));
}
std::string
PeerImp::getVersion() const
{
if (m_inbound)
return headers_["User-Agent"].to_string();
return headers_["Server"].to_string();
}
Json::Value
PeerImp::json()
{
Json::Value ret(Json::objectValue);
ret[jss::public_key] = toBase58(TokenType::NodePublic, publicKey_);
ret[jss::address] = remote_address_.to_string();
if (m_inbound)
ret[jss::inbound] = true;
if (cluster())
{
ret[jss::cluster] = true;
std::string name{getName()};
if (!name.empty())
// Could move here if Json::Value supported moving from a string
ret[jss::name] = name;
}
ret[jss::load] = usage_.balance();
{
auto const version = getVersion();
if (!version.empty())
ret[jss::version] = version;
}
ret[jss::protocol] = to_string(protocol_);
{
std::lock_guard sl(recentLock_);
if (latency_)
ret[jss::latency] = static_cast<Json::UInt>(latency_->count());
}
ret[jss::uptime] = static_cast<Json::UInt>(
std::chrono::duration_cast<std::chrono::seconds>(uptime()).count());
std::uint32_t minSeq, maxSeq;
ledgerRange(minSeq, maxSeq);
if ((minSeq != 0) || (maxSeq != 0))
ret[jss::complete_ledgers] =
std::to_string(minSeq) + " - " + std::to_string(maxSeq);
switch (sanity_.load())
{
case Sanity::insane:
ret[jss::sanity] = "insane";
break;
case Sanity::unknown:
ret[jss::sanity] = "unknown";
break;
case Sanity::sane:
// Nothing to do here
break;
}
uint256 closedLedgerHash;
protocol::TMStatusChange last_status;
{
std::lock_guard sl(recentLock_);
closedLedgerHash = closedLedgerHash_;
last_status = last_status_;
}
if (closedLedgerHash != beast::zero)
ret[jss::ledger] = to_string(closedLedgerHash);
if (last_status.has_newstatus())
{
switch (last_status.newstatus())
{
case protocol::nsCONNECTING:
ret[jss::status] = "connecting";
break;
case protocol::nsCONNECTED:
ret[jss::status] = "connected";
break;
case protocol::nsMONITORING:
ret[jss::status] = "monitoring";
break;
case protocol::nsVALIDATING:
ret[jss::status] = "validating";
break;
case protocol::nsSHUTTING:
ret[jss::status] = "shutting";
break;
default:
JLOG(p_journal_.warn())
<< "Unknown status: " << last_status.newstatus();
}
}
ret[jss::metrics] = Json::Value(Json::objectValue);
ret[jss::metrics][jss::total_bytes_recv] =
std::to_string(metrics_.recv.total_bytes());
ret[jss::metrics][jss::total_bytes_sent] =
std::to_string(metrics_.sent.total_bytes());
ret[jss::metrics][jss::avg_bps_recv] =
std::to_string(metrics_.recv.average_bytes());
ret[jss::metrics][jss::avg_bps_sent] =
std::to_string(metrics_.sent.average_bytes());
return ret;
}
bool
PeerImp::supportsFeature(ProtocolFeature f) const
{
switch (f)
{
case ProtocolFeature::ValidatorListPropagation:
return protocol_ >= make_protocol(2, 1);
}
return false;
}
//------------------------------------------------------------------------------
bool
PeerImp::hasLedger(uint256 const& hash, std::uint32_t seq) const
{
{
std::lock_guard sl(recentLock_);
if ((seq != 0) && (seq >= minLedger_) && (seq <= maxLedger_) &&
(sanity_.load() == Sanity::sane))
return true;
if (std::find(recentLedgers_.begin(), recentLedgers_.end(), hash) !=
recentLedgers_.end())
return true;
}
return seq >= app_.getNodeStore().earliestLedgerSeq() &&
hasShard(NodeStore::seqToShardIndex(seq));
}
void
PeerImp::ledgerRange(std::uint32_t& minSeq, std::uint32_t& maxSeq) const
{
std::lock_guard sl(recentLock_);
minSeq = minLedger_;
maxSeq = maxLedger_;
}
bool
PeerImp::hasShard(std::uint32_t shardIndex) const
{
std::lock_guard l{shardInfoMutex_};
auto const it{shardInfo_.find(publicKey_)};
if (it != shardInfo_.end())
return boost::icl::contains(it->second.shardIndexes, shardIndex);
return false;
}
bool
PeerImp::hasTxSet(uint256 const& hash) const
{
std::lock_guard sl(recentLock_);
return std::find(recentTxSets_.begin(), recentTxSets_.end(), hash) !=
recentTxSets_.end();
}
void
PeerImp::cycleStatus()
{
// Operations on closedLedgerHash_ and previousLedgerHash_ must be
// guarded by recentLock_.
std::lock_guard sl(recentLock_);
previousLedgerHash_ = closedLedgerHash_;
closedLedgerHash_.zero();
}
bool
PeerImp::hasRange(std::uint32_t uMin, std::uint32_t uMax)
{
std::lock_guard sl(recentLock_);
return (sanity_ != Sanity::insane) && (uMin >= minLedger_) &&
(uMax <= maxLedger_);
}
//------------------------------------------------------------------------------
void
PeerImp::close()
{
assert(strand_.running_in_this_thread());
if (socket_.is_open())
{
detaching_ = true; // DEPRECATED
error_code ec;
timer_.cancel(ec);
socket_.close(ec);
overlay_.incPeerDisconnect();
if (m_inbound)
{
JLOG(journal_.debug()) << "Closed";
}
else
{
JLOG(journal_.info()) << "Closed";
}
}
}
void
PeerImp::fail(std::string const& reason)
{
if (!strand_.running_in_this_thread())
return post(
strand_,
std::bind(
(void (Peer::*)(std::string const&)) & PeerImp::fail,
shared_from_this(),
reason));
if (journal_.active(beast::severities::kWarning) && socket_.is_open())
{
std::string const name{getName()};
JLOG(journal_.warn())
<< (name.empty() ? remote_address_.to_string() : name)
<< " failed: " << reason;
}
close();
}
void
PeerImp::fail(std::string const& name, error_code ec)
{
assert(strand_.running_in_this_thread());
if (socket_.is_open())
{
JLOG(journal_.warn())
<< name << " from " << toBase58(TokenType::NodePublic, publicKey_)
<< " at " << remote_address_.to_string() << ": " << ec.message();
}
close();
}
boost::optional<RangeSet<std::uint32_t>>
PeerImp::getShardIndexes() const
{
std::lock_guard l{shardInfoMutex_};
auto it{shardInfo_.find(publicKey_)};
if (it != shardInfo_.end())
return it->second.shardIndexes;
return boost::none;
}
boost::optional<hash_map<PublicKey, PeerImp::ShardInfo>>
PeerImp::getPeerShardInfo() const
{
std::lock_guard l{shardInfoMutex_};
if (!shardInfo_.empty())
return shardInfo_;
return boost::none;
}
void
PeerImp::gracefulClose()
{
assert(strand_.running_in_this_thread());
assert(socket_.is_open());
assert(!gracefulClose_);
gracefulClose_ = true;
#if 0
// Flush messages
while(send_queue_.size() > 1)
send_queue_.pop_back();
#endif
if (send_queue_.size() > 0)
return;
setTimer();
stream_.async_shutdown(bind_executor(
strand_,
std::bind(
&PeerImp::onShutdown, shared_from_this(), std::placeholders::_1)));
}
void
PeerImp::setTimer()
{
error_code ec;
timer_.expires_from_now(std::chrono::seconds(Tuning::timerSeconds), ec);
if (ec)
{
JLOG(journal_.error()) << "setTimer: " << ec.message();
return;
}
timer_.async_wait(bind_executor(
strand_,
std::bind(
&PeerImp::onTimer, shared_from_this(), std::placeholders::_1)));
}
// convenience for ignoring the error code
void
PeerImp::cancelTimer()
{
error_code ec;
timer_.cancel(ec);
}
//------------------------------------------------------------------------------
std::string
PeerImp::makePrefix(id_t id)
{
std::stringstream ss;
ss << "[" << std::setfill('0') << std::setw(3) << id << "] ";
return ss.str();
}
void
PeerImp::onTimer(error_code const& ec)
{
if (!socket_.is_open())
return;
if (ec == boost::asio::error::operation_aborted)
return;
if (ec)
{
// This should never happen
JLOG(journal_.error()) << "onTimer: " << ec.message();
return close();
}
if (large_sendq_++ >= Tuning::sendqIntervals)
{
fail("Large send queue");
return;
}
bool failedNoPing{false};
boost::optional<std::uint32_t> pingSeq;
// Operations on lastPingSeq_, lastPingTime_, no_ping_, and latency_
// must be guarded by recentLock_.
{
std::lock_guard sl(recentLock_);
if (no_ping_++ >= Tuning::noPing)
{
failedNoPing = true;
}
else if (!lastPingSeq_)
{
// Make the sequence unpredictable enough to prevent guessing
lastPingSeq_ = rand_int<std::uint32_t>();
lastPingTime_ = clock_type::now();
pingSeq = lastPingSeq_;
}
else
{
// We have an outstanding ping, raise latency
auto const minLatency =
std::chrono::duration_cast<std::chrono::milliseconds>(
clock_type::now() - lastPingTime_);
if (latency_ < minLatency)
latency_ = minLatency;
}
}
if (failedNoPing)
{
fail("No ping reply received");
return;
}
if (pingSeq)
{
protocol::TMPing message;
message.set_type(protocol::TMPing::ptPING);
message.set_seq(*pingSeq);
send(std::make_shared<Message>(message, protocol::mtPING));
}
setTimer();
}
void
PeerImp::onShutdown(error_code ec)
{
cancelTimer();
// If we don't get eof then something went wrong
if (!ec)
{
JLOG(journal_.error()) << "onShutdown: expected error condition";
return close();
}
if (ec != boost::asio::error::eof)
return fail("onShutdown", ec);
close();
}
//------------------------------------------------------------------------------
void
PeerImp::doAccept()
{
assert(read_buffer_.size() == 0);
JLOG(journal_.debug()) << "doAccept: " << remote_address_;
auto const sharedValue = makeSharedValue(*stream_ptr_, journal_);
// This shouldn't fail since we already computed
// the shared value successfully in OverlayImpl
if (!sharedValue)
return fail("makeSharedValue: Unexpected failure");
// TODO Apply headers to connection state.
boost::beast::ostream(write_buffer_) << makeResponse(
!overlay_.peerFinder().config().peerPrivate,
request_,
remote_address_.address(),
*sharedValue);
JLOG(journal_.info()) << "Protocol: " << to_string(protocol_);
JLOG(journal_.info()) << "Public Key: "
<< toBase58(TokenType::NodePublic, publicKey_);
if (auto member = app_.cluster().member(publicKey_))
{
{
std::unique_lock<std::shared_timed_mutex> lock{nameMutex_};
name_ = *member;
}
JLOG(journal_.info()) << "Cluster name: " << *member;
}
overlay_.activate(shared_from_this());
// XXX Set timer: connection is in grace period to be useful.
// XXX Set timer: connection idle (idle may vary depending on connection
// type.)
onWriteResponse(error_code(), 0);
}
http_response_type
PeerImp::makeResponse(
bool crawl,
http_request_type const& req,
beast::IP::Address remote_ip,
uint256 const& sharedValue)
{
http_response_type resp;
resp.result(boost::beast::http::status::switching_protocols);
resp.version(req.version());
resp.insert("Connection", "Upgrade");
resp.insert("Upgrade", to_string(protocol_));
resp.insert("Connect-As", "Peer");
resp.insert("Server", BuildInfo::getFullVersionString());
resp.insert("Crawl", crawl ? "public" : "private");
if (req["X-Offer-Compression"] == "lz4" && app_.config().COMPRESSION)
resp.insert("X-Offer-Compression", "lz4");
buildHandshake(
resp,
sharedValue,
overlay_.setup().networkID,
overlay_.setup().public_ip,
remote_ip,
app_);
return resp;
}
// Called repeatedly to send the bytes in the response
void
PeerImp::onWriteResponse(error_code ec, std::size_t bytes_transferred)
{
if (!socket_.is_open())
return;
if (ec == boost::asio::error::operation_aborted)
return;
if (ec)
return fail("onWriteResponse", ec);
if (auto stream = journal_.trace())
{
if (bytes_transferred > 0)
stream << "onWriteResponse: " << bytes_transferred << " bytes";
else
stream << "onWriteResponse";
}
write_buffer_.consume(bytes_transferred);
if (write_buffer_.size() == 0)
return doProtocolStart();
stream_.async_write_some(
write_buffer_.data(),
bind_executor(
strand_,
std::bind(
&PeerImp::onWriteResponse,
shared_from_this(),
std::placeholders::_1,
std::placeholders::_2)));
}
std::string
PeerImp::getName() const
{
std::shared_lock<std::shared_timed_mutex> read_lock{nameMutex_};
return name_;
}
//------------------------------------------------------------------------------
// Protocol logic
void
PeerImp::doProtocolStart()
{
onReadMessage(error_code(), 0);
// Send all the validator lists that have been loaded
if (supportsFeature(ProtocolFeature::ValidatorListPropagation))
{
app_.validators().for_each_available([&](std::string const& manifest,
std::string const& blob,
std::string const& signature,
std::uint32_t version,
PublicKey const& pubKey,
std::size_t sequence,
uint256 const& hash) {
protocol::TMValidatorList vl;
vl.set_manifest(manifest);
vl.set_blob(blob);
vl.set_signature(signature);
vl.set_version(version);
JLOG(p_journal_.debug())
<< "Sending validator list for " << strHex(pubKey)
<< " with sequence " << sequence << " to "
<< remote_address_.to_string() << " (" << id_ << ")";
auto m = std::make_shared<Message>(vl, protocol::mtVALIDATORLIST);
send(m);
// Don't send it next time.
app_.getHashRouter().addSuppressionPeer(hash, id_);
setPublisherListSequence(pubKey, sequence);
});
}
protocol::TMManifests tm;
app_.validatorManifests().for_each_manifest(
[&tm](std::size_t s) { tm.mutable_list()->Reserve(s); },
[&tm, &hr = app_.getHashRouter()](Manifest const& manifest) {
auto const& s = manifest.serialized;
auto& tm_e = *tm.add_list();
tm_e.set_stobject(s.data(), s.size());
hr.addSuppression(manifest.hash());
});
if (tm.list_size() > 0)
{
auto m = std::make_shared<Message>(tm, protocol::mtMANIFESTS);
send(m);
}
}
// Called repeatedly with protocol message data
void
PeerImp::onReadMessage(error_code ec, std::size_t bytes_transferred)
{
if (!socket_.is_open())
return;
if (ec == boost::asio::error::operation_aborted)
return;
if (ec == boost::asio::error::eof)
{
JLOG(journal_.info()) << "EOF";
return gracefulClose();
}
if (ec)
return fail("onReadMessage", ec);
if (auto stream = journal_.trace())
{
if (bytes_transferred > 0)
stream << "onReadMessage: " << bytes_transferred << " bytes";
else
stream << "onReadMessage";
}
metrics_.recv.add_message(bytes_transferred);
read_buffer_.commit(bytes_transferred);
while (read_buffer_.size() > 0)
{
std::size_t bytes_consumed;
std::tie(bytes_consumed, ec) =
invokeProtocolMessage(read_buffer_.data(), *this);
if (ec)
return fail("onReadMessage", ec);
if (!socket_.is_open())
return;
if (gracefulClose_)
return;
if (bytes_consumed == 0)
break;
read_buffer_.consume(bytes_consumed);
}
// Timeout on writes only
stream_.async_read_some(
read_buffer_.prepare(Tuning::readBufferBytes),
bind_executor(
strand_,
std::bind(
&PeerImp::onReadMessage,
shared_from_this(),
std::placeholders::_1,
std::placeholders::_2)));
}
void
PeerImp::onWriteMessage(error_code ec, std::size_t bytes_transferred)
{
if (!socket_.is_open())
return;
if (ec == boost::asio::error::operation_aborted)
return;
if (ec)
return fail("onWriteMessage", ec);
if (auto stream = journal_.trace())
{
if (bytes_transferred > 0)
stream << "onWriteMessage: " << bytes_transferred << " bytes";
else
stream << "onWriteMessage";
}
metrics_.sent.add_message(bytes_transferred);
assert(!send_queue_.empty());
send_queue_.pop();
if (!send_queue_.empty())
{
// Timeout on writes only
return boost::asio::async_write(
stream_,
boost::asio::buffer(
send_queue_.front()->getBuffer(compressionEnabled_)),
bind_executor(
strand_,
std::bind(
&PeerImp::onWriteMessage,
shared_from_this(),
std::placeholders::_1,
std::placeholders::_2)));
}
if (gracefulClose_)
{
return stream_.async_shutdown(bind_executor(
strand_,
std::bind(
&PeerImp::onShutdown,
shared_from_this(),
std::placeholders::_1)));
}
}
//------------------------------------------------------------------------------
//
// ProtocolHandler
//
//------------------------------------------------------------------------------
void
PeerImp::onMessageUnknown(std::uint16_t type)
{
// TODO
}
void