-
Notifications
You must be signed in to change notification settings - Fork 791
/
node.cpp
3689 lines (3511 loc) · 112 KB
/
node.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
#include <rai/node/node.hpp>
#include <rai/lib/interface.h>
#include <rai/lib/utility.hpp>
#include <rai/node/common.hpp>
#include <rai/node/rpc.hpp>
#include <algorithm>
#include <cstdlib>
#include <future>
#include <sstream>
#include <boost/polymorphic_cast.hpp>
#include <boost/property_tree/json_parser.hpp>
double constexpr rai::node::price_max;
double constexpr rai::node::free_cutoff;
std::chrono::seconds constexpr rai::node::period;
std::chrono::seconds constexpr rai::node::cutoff;
std::chrono::seconds constexpr rai::node::syn_cookie_cutoff;
std::chrono::minutes constexpr rai::node::backup_interval;
std::chrono::seconds constexpr rai::node::search_pending_interval;
int constexpr rai::port_mapping::mapping_timeout;
int constexpr rai::port_mapping::check_timeout;
unsigned constexpr rai::active_transactions::announce_interval_ms;
size_t constexpr rai::active_transactions::max_broadcast_queue;
size_t constexpr rai::block_arrival::arrival_size_min;
std::chrono::seconds constexpr rai::block_arrival::arrival_time_min;
namespace rai
{
extern unsigned char rai_bootstrap_weights[];
extern size_t rai_bootstrap_weights_size;
}
rai::network::network (rai::node & node_a, uint16_t port) :
buffer_container (node_a.stats, rai::network::buffer_size, 4096), // 2Mb receive buffer
socket (node_a.service, rai::endpoint (boost::asio::ip::address_v6::any (), port)),
resolver (node_a.service),
node (node_a),
on (true)
{
boost::thread::attributes attrs;
rai::thread_attributes::set (attrs);
for (size_t i = 0; i < node.config.network_threads; ++i)
{
packet_processing_threads.push_back (boost::thread (attrs, [this]() {
rai::thread_role::set (rai::thread_role::name::packet_processing);
try
{
process_packets ();
}
catch (boost::system::error_code & ec)
{
BOOST_LOG (this->node.log) << FATAL_LOG_PREFIX << ec.message ();
release_assert (false);
}
catch (std::error_code & ec)
{
BOOST_LOG (this->node.log) << FATAL_LOG_PREFIX << ec.message ();
release_assert (false);
}
catch (std::runtime_error & err)
{
BOOST_LOG (this->node.log) << FATAL_LOG_PREFIX << err.what ();
release_assert (false);
}
catch (...)
{
BOOST_LOG (this->node.log) << FATAL_LOG_PREFIX << "Unknown exception";
release_assert (false);
}
if (this->node.config.logging.network_packet_logging ())
{
BOOST_LOG (this->node.log) << "Exiting packet processing thread";
}
}));
}
}
rai::network::~network ()
{
for (auto & thread : packet_processing_threads)
{
thread.join ();
}
}
void rai::network::start ()
{
for (size_t i = 0; i < node.config.io_threads; ++i)
{
receive ();
}
}
void rai::network::receive ()
{
if (node.config.logging.network_packet_logging ())
{
BOOST_LOG (node.log) << "Receiving packet";
}
std::unique_lock<std::mutex> lock (socket_mutex);
auto data (buffer_container.allocate ());
socket.async_receive_from (boost::asio::buffer (data->buffer, rai::network::buffer_size), data->endpoint, [this, data](boost::system::error_code const & error, size_t size_a) {
if (!error && this->on)
{
data->size = size_a;
this->buffer_container.enqueue (data);
this->receive ();
}
else
{
this->buffer_container.release (data);
if (error)
{
if (this->node.config.logging.network_logging ())
{
BOOST_LOG (this->node.log) << boost::str (boost::format ("UDP Receive error: %1%") % error.message ());
}
}
if (this->on)
{
this->node.alarm.add (std::chrono::steady_clock::now () + std::chrono::seconds (5), [this]() { this->receive (); });
}
}
});
}
void rai::network::process_packets ()
{
while (on)
{
auto data (buffer_container.dequeue ());
if (data == nullptr)
{
break;
}
//std::cerr << data->endpoint.address ().to_string ();
receive_action (data);
buffer_container.release (data);
}
}
void rai::network::stop ()
{
on = false;
socket.close ();
resolver.cancel ();
buffer_container.stop ();
}
void rai::network::send_keepalive (rai::endpoint const & endpoint_a)
{
assert (endpoint_a.address ().is_v6 ());
rai::keepalive message;
node.peers.random_fill (message.peers);
auto bytes = message.to_bytes ();
if (node.config.logging.network_keepalive_logging ())
{
BOOST_LOG (node.log) << boost::str (boost::format ("Keepalive req sent to %1%") % endpoint_a);
}
std::weak_ptr<rai::node> node_w (node.shared ());
send_buffer (bytes->data (), bytes->size (), endpoint_a, [bytes, node_w, endpoint_a](boost::system::error_code const & ec, size_t) {
if (auto node_l = node_w.lock ())
{
if (ec && node_l->config.logging.network_keepalive_logging ())
{
BOOST_LOG (node_l->log) << boost::str (boost::format ("Error sending keepalive to %1%: %2%") % endpoint_a % ec.message ());
}
else
{
node_l->stats.inc (rai::stat::type::message, rai::stat::detail::keepalive, rai::stat::dir::out);
}
}
});
}
void rai::node::keepalive (std::string const & address_a, uint16_t port_a)
{
auto node_l (shared_from_this ());
network.resolver.async_resolve (boost::asio::ip::udp::resolver::query (address_a, std::to_string (port_a)), [node_l, address_a, port_a](boost::system::error_code const & ec, boost::asio::ip::udp::resolver::iterator i_a) {
if (!ec)
{
for (auto i (i_a), n (boost::asio::ip::udp::resolver::iterator{}); i != n; ++i)
{
node_l->send_keepalive (rai::map_endpoint_to_v6 (i->endpoint ()));
}
}
else
{
BOOST_LOG (node_l->log) << boost::str (boost::format ("Error resolving address: %1%:%2%: %3%") % address_a % port_a % ec.message ());
}
});
}
void rai::network::send_node_id_handshake (rai::endpoint const & endpoint_a, boost::optional<rai::uint256_union> const & query, boost::optional<rai::uint256_union> const & respond_to)
{
assert (endpoint_a.address ().is_v6 ());
boost::optional<std::pair<rai::account, rai::signature>> response (boost::none);
if (respond_to)
{
response = std::make_pair (node.node_id.pub, rai::sign_message (node.node_id.prv, node.node_id.pub, *respond_to));
assert (!rai::validate_message (response->first, *respond_to, response->second));
}
rai::node_id_handshake message (query, response);
auto bytes = message.to_bytes ();
if (node.config.logging.network_node_id_handshake_logging ())
{
BOOST_LOG (node.log) << boost::str (boost::format ("Node ID handshake sent with node ID %1% to %2%: query %3%, respond_to %4% (signature %5%)") % node.node_id.pub.to_account () % endpoint_a % (query ? query->to_string () : std::string ("[none]")) % (respond_to ? respond_to->to_string () : std::string ("[none]")) % (response ? response->second.to_string () : std::string ("[none]")));
}
node.stats.inc (rai::stat::type::message, rai::stat::detail::node_id_handshake, rai::stat::dir::out);
std::weak_ptr<rai::node> node_w (node.shared ());
send_buffer (bytes->data (), bytes->size (), endpoint_a, [bytes, node_w, endpoint_a](boost::system::error_code const & ec, size_t) {
if (auto node_l = node_w.lock ())
{
if (ec && node_l->config.logging.network_node_id_handshake_logging ())
{
BOOST_LOG (node_l->log) << boost::str (boost::format ("Error sending node ID handshake to %1% %2%") % endpoint_a % ec.message ());
}
}
});
}
void rai::network::republish (rai::block_hash const & hash_a, std::shared_ptr<std::vector<uint8_t>> buffer_a, rai::endpoint endpoint_a)
{
if (node.config.logging.network_publish_logging ())
{
BOOST_LOG (node.log) << boost::str (boost::format ("Publishing %1% to %2%") % hash_a.to_string () % endpoint_a);
}
std::weak_ptr<rai::node> node_w (node.shared ());
send_buffer (buffer_a->data (), buffer_a->size (), endpoint_a, [buffer_a, node_w, endpoint_a](boost::system::error_code const & ec, size_t size) {
if (auto node_l = node_w.lock ())
{
if (ec && node_l->config.logging.network_logging ())
{
BOOST_LOG (node_l->log) << boost::str (boost::format ("Error sending publish to %1%: %2%") % endpoint_a % ec.message ());
}
else
{
node_l->stats.inc (rai::stat::type::message, rai::stat::detail::publish, rai::stat::dir::out);
}
}
});
}
template <typename T>
bool confirm_block (rai::transaction const & transaction_a, rai::node & node_a, T & list_a, std::shared_ptr<rai::block> block_a, bool also_publish)
{
bool result (false);
if (node_a.config.enable_voting)
{
node_a.wallets.foreach_representative (transaction_a, [&result, &block_a, &list_a, &node_a, &transaction_a, also_publish](rai::public_key const & pub_a, rai::raw_key const & prv_a) {
result = true;
auto hash (block_a->hash ());
auto vote (node_a.store.vote_generate (transaction_a, pub_a, prv_a, std::vector<rai::block_hash> (1, hash)));
rai::confirm_ack confirm (vote);
auto vote_bytes = confirm.to_bytes ();
rai::publish publish (block_a);
std::shared_ptr<std::vector<uint8_t>> publish_bytes;
if (also_publish)
{
publish_bytes = publish.to_bytes ();
}
for (auto j (list_a.begin ()), m (list_a.end ()); j != m; ++j)
{
node_a.network.confirm_send (confirm, vote_bytes, *j);
if (also_publish)
{
node_a.network.republish (hash, publish_bytes, *j);
}
}
});
}
return result;
}
bool confirm_block (rai::transaction const & transaction_a, rai::node & node_a, rai::endpoint & peer_a, std::shared_ptr<rai::block> block_a, bool also_publish)
{
std::array<rai::endpoint, 1> endpoints;
endpoints[0] = peer_a;
auto result (confirm_block (transaction_a, node_a, endpoints, std::move (block_a), also_publish));
return result;
}
void rai::network::republish_block (std::shared_ptr<rai::block> block)
{
auto hash (block->hash ());
auto list (node.peers.list_fanout ());
rai::publish message (block);
auto bytes = message.to_bytes ();
for (auto i (list.begin ()), n (list.end ()); i != n; ++i)
{
republish (hash, bytes, *i);
}
if (node.config.logging.network_logging ())
{
BOOST_LOG (node.log) << boost::str (boost::format ("Block %1% was republished to peers") % hash.to_string ());
}
}
void rai::network::republish_block_batch (std::deque<std::shared_ptr<rai::block>> blocks_a, unsigned delay_a)
{
auto block (blocks_a.front ());
blocks_a.pop_front ();
republish_block (block);
if (!blocks_a.empty ())
{
std::weak_ptr<rai::node> node_w (node.shared ());
node.alarm.add (std::chrono::steady_clock::now () + std::chrono::milliseconds (delay_a + std::rand () % delay_a), [node_w, blocks_a, delay_a]() {
if (auto node_l = node_w.lock ())
{
node_l->network.republish_block_batch (blocks_a, delay_a);
}
});
}
}
// In order to rate limit network traffic we republish:
// 1) Only if they are a non-replay vote of a block that's actively settling. Settling blocks are limited by block PoW
// 2) The rep has a weight > Y to prevent creating a lot of small-weight accounts to send out votes
// 3) Only if a vote for this block from this representative hasn't been received in the previous X second.
// This prevents rapid publishing of votes with increasing sequence numbers.
//
// These rules are implemented by the caller, not this function.
void rai::network::republish_vote (std::shared_ptr<rai::vote> vote_a)
{
rai::confirm_ack confirm (vote_a);
auto bytes = confirm.to_bytes ();
auto list (node.peers.list_fanout ());
for (auto j (list.begin ()), m (list.end ()); j != m; ++j)
{
node.network.confirm_send (confirm, bytes, *j);
}
}
void rai::network::broadcast_confirm_req (std::shared_ptr<rai::block> block_a)
{
auto list (std::make_shared<std::vector<rai::peer_information>> (node.peers.representatives (std::numeric_limits<size_t>::max ())));
if (list->empty () || node.peers.total_weight () < node.config.online_weight_minimum.number ())
{
// broadcast request to all peers
list = std::make_shared<std::vector<rai::peer_information>> (node.peers.list_vector (100));
}
/*
* In either case (broadcasting to all representatives, or broadcasting to
* all peers because there are not enough connected representatives),
* limit each instance to a single random up-to-32 selection. The invoker
* of "broadcast_confirm_req" will be responsible for calling it again
* if the votes for a block have not arrived in time.
*/
const size_t max_endpoints = 32;
std::random_shuffle (list->begin (), list->end ());
if (list->size () > max_endpoints)
{
list->erase (list->begin () + max_endpoints, list->end ());
}
broadcast_confirm_req_base (block_a, list, 0);
}
void rai::network::broadcast_confirm_req_base (std::shared_ptr<rai::block> block_a, std::shared_ptr<std::vector<rai::peer_information>> endpoints_a, unsigned delay_a, bool resumption)
{
const size_t max_reps = 10;
if (!resumption && node.config.logging.network_logging ())
{
BOOST_LOG (node.log) << boost::str (boost::format ("Broadcasting confirm req for block %1% to %2% representatives") % block_a->hash ().to_string () % endpoints_a->size ());
}
auto count (0);
while (!endpoints_a->empty () && count < max_reps)
{
send_confirm_req (endpoints_a->back ().endpoint, block_a);
endpoints_a->pop_back ();
count++;
}
if (!endpoints_a->empty ())
{
delay_a += std::rand () % broadcast_interval_ms;
std::weak_ptr<rai::node> node_w (node.shared ());
node.alarm.add (std::chrono::steady_clock::now () + std::chrono::milliseconds (delay_a), [node_w, block_a, endpoints_a, delay_a]() {
if (auto node_l = node_w.lock ())
{
node_l->network.broadcast_confirm_req_base (block_a, endpoints_a, delay_a, true);
}
});
}
}
void rai::network::broadcast_confirm_req_batch (std::deque<std::pair<std::shared_ptr<rai::block>, std::shared_ptr<std::vector<rai::peer_information>>>> deque_a, unsigned delay_a)
{
auto pair (deque_a.front ());
deque_a.pop_front ();
auto block (pair.first);
// confirm_req to representatives
auto endpoints (pair.second);
if (!endpoints->empty ())
{
broadcast_confirm_req_base (block, endpoints, delay_a);
}
/* Continue while blocks remain
Broadcast with random delay between delay_a & 2*delay_a */
if (!deque_a.empty ())
{
std::weak_ptr<rai::node> node_w (node.shared ());
node.alarm.add (std::chrono::steady_clock::now () + std::chrono::milliseconds (delay_a + std::rand () % delay_a), [node_w, deque_a, delay_a]() {
if (auto node_l = node_w.lock ())
{
node_l->network.broadcast_confirm_req_batch (deque_a, delay_a);
}
});
}
}
void rai::network::send_confirm_req (rai::endpoint const & endpoint_a, std::shared_ptr<rai::block> block)
{
rai::confirm_req message (block);
auto bytes = message.to_bytes ();
if (node.config.logging.network_message_logging ())
{
BOOST_LOG (node.log) << boost::str (boost::format ("Sending confirm req to %1%") % endpoint_a);
}
std::weak_ptr<rai::node> node_w (node.shared ());
node.stats.inc (rai::stat::type::message, rai::stat::detail::confirm_req, rai::stat::dir::out);
send_buffer (bytes->data (), bytes->size (), endpoint_a, [bytes, node_w](boost::system::error_code const & ec, size_t size) {
if (auto node_l = node_w.lock ())
{
if (ec && node_l->config.logging.network_logging ())
{
BOOST_LOG (node_l->log) << boost::str (boost::format ("Error sending confirm request: %1%") % ec.message ());
}
}
});
}
template <typename T>
void rep_query (rai::node & node_a, T const & peers_a)
{
auto transaction (node_a.store.tx_begin_read ());
std::shared_ptr<rai::block> block (node_a.store.block_random (transaction));
auto hash (block->hash ());
node_a.rep_crawler.add (hash);
for (auto i (peers_a.begin ()), n (peers_a.end ()); i != n; ++i)
{
node_a.peers.rep_request (*i);
node_a.network.send_confirm_req (*i, block);
}
std::weak_ptr<rai::node> node_w (node_a.shared ());
node_a.alarm.add (std::chrono::steady_clock::now () + std::chrono::seconds (5), [node_w, hash]() {
if (auto node_l = node_w.lock ())
{
node_l->rep_crawler.remove (hash);
}
});
}
void rep_query (rai::node & node_a, rai::endpoint const & peers_a)
{
std::array<rai::endpoint, 1> peers;
peers[0] = peers_a;
rep_query (node_a, peers);
}
namespace
{
class network_message_visitor : public rai::message_visitor
{
public:
network_message_visitor (rai::node & node_a, rai::endpoint const & sender_a) :
node (node_a),
sender (sender_a)
{
}
virtual ~network_message_visitor () = default;
void keepalive (rai::keepalive const & message_a) override
{
if (node.config.logging.network_keepalive_logging ())
{
BOOST_LOG (node.log) << boost::str (boost::format ("Received keepalive message from %1%") % sender);
}
node.stats.inc (rai::stat::type::message, rai::stat::detail::keepalive, rai::stat::dir::in);
if (node.peers.contacted (sender, message_a.header.version_using))
{
auto endpoint_l (rai::map_endpoint_to_v6 (sender));
auto cookie (node.peers.assign_syn_cookie (endpoint_l));
if (cookie)
{
node.network.send_node_id_handshake (endpoint_l, *cookie, boost::none);
}
}
node.network.merge_peers (message_a.peers);
}
void publish (rai::publish const & message_a) override
{
if (node.config.logging.network_message_logging ())
{
BOOST_LOG (node.log) << boost::str (boost::format ("Publish message from %1% for %2%") % sender % message_a.block->hash ().to_string ());
}
node.stats.inc (rai::stat::type::message, rai::stat::detail::publish, rai::stat::dir::in);
node.peers.contacted (sender, message_a.header.version_using);
node.process_active (message_a.block);
node.active.publish (message_a.block);
}
void confirm_req (rai::confirm_req const & message_a) override
{
if (node.config.logging.network_message_logging ())
{
BOOST_LOG (node.log) << boost::str (boost::format ("Confirm_req message from %1% for %2%") % sender % message_a.block->hash ().to_string ());
}
node.stats.inc (rai::stat::type::message, rai::stat::detail::confirm_req, rai::stat::dir::in);
node.peers.contacted (sender, message_a.header.version_using);
// Don't load nodes with disabled voting
if (node.config.enable_voting)
{
auto transaction (node.store.tx_begin_read ());
auto successor (node.ledger.successor (transaction, message_a.block->root ()));
if (successor != nullptr)
{
auto same_block (successor->hash () == message_a.block->hash ());
confirm_block (transaction, node, sender, std::move (successor), !same_block);
}
}
}
void confirm_ack (rai::confirm_ack const & message_a) override
{
if (node.config.logging.network_message_logging ())
{
BOOST_LOG (node.log) << boost::str (boost::format ("Received confirm_ack message from %1% for %2%sequence %3%") % sender % message_a.vote->hashes_string () % std::to_string (message_a.vote->sequence));
}
node.stats.inc (rai::stat::type::message, rai::stat::detail::confirm_ack, rai::stat::dir::in);
node.peers.contacted (sender, message_a.header.version_using);
for (auto & vote_block : message_a.vote->blocks)
{
if (!vote_block.which ())
{
auto block (boost::get<std::shared_ptr<rai::block>> (vote_block));
node.process_active (block);
node.active.publish (block);
}
}
node.vote_processor.vote (message_a.vote, sender);
}
void bulk_pull (rai::bulk_pull const &) override
{
assert (false);
}
void bulk_pull_account (rai::bulk_pull_account const &) override
{
assert (false);
}
void bulk_pull_blocks (rai::bulk_pull_blocks const &) override
{
assert (false);
}
void bulk_push (rai::bulk_push const &) override
{
assert (false);
}
void frontier_req (rai::frontier_req const &) override
{
assert (false);
}
void node_id_handshake (rai::node_id_handshake const & message_a) override
{
if (node.config.logging.network_node_id_handshake_logging ())
{
BOOST_LOG (node.log) << boost::str (boost::format ("Received node_id_handshake message from %1% with query %2% and response account %3%") % sender % (message_a.query ? message_a.query->to_string () : std::string ("[none]")) % (message_a.response ? message_a.response->first.to_account () : std::string ("[none]")));
}
node.stats.inc (rai::stat::type::message, rai::stat::detail::node_id_handshake, rai::stat::dir::in);
auto endpoint_l (rai::map_endpoint_to_v6 (sender));
boost::optional<rai::uint256_union> out_query;
boost::optional<rai::uint256_union> out_respond_to;
if (message_a.query)
{
out_respond_to = message_a.query;
}
auto validated_response (false);
if (message_a.response)
{
if (!node.peers.validate_syn_cookie (endpoint_l, message_a.response->first, message_a.response->second))
{
validated_response = true;
if (message_a.response->first != node.node_id.pub)
{
node.peers.insert (endpoint_l, message_a.header.version_using);
}
}
else if (node.config.logging.network_node_id_handshake_logging ())
{
BOOST_LOG (node.log) << boost::str (boost::format ("Failed to validate syn cookie signature %1% by %2%") % message_a.response->second.to_string () % message_a.response->first.to_account ());
}
}
if (!validated_response && !node.peers.known_peer (endpoint_l))
{
out_query = node.peers.assign_syn_cookie (endpoint_l);
}
if (out_query || out_respond_to)
{
node.network.send_node_id_handshake (sender, out_query, out_respond_to);
}
}
rai::node & node;
rai::endpoint sender;
};
}
void rai::network::receive_action (rai::udp_data * data_a)
{
auto allowed_sender (true);
if (data_a->endpoint == endpoint ())
{
allowed_sender = false;
}
else if (rai::reserved_address (data_a->endpoint, false) && !node.config.allow_local_peers)
{
allowed_sender = false;
}
if (allowed_sender)
{
network_message_visitor visitor (node, data_a->endpoint);
rai::message_parser parser (node.block_uniquer, node.vote_uniquer, visitor, node.work);
parser.deserialize_buffer (data_a->buffer, data_a->size);
if (parser.status != rai::message_parser::parse_status::success)
{
node.stats.inc (rai::stat::type::error);
switch (parser.status)
{
case rai::message_parser::parse_status::insufficient_work:
// We've already increment error count, update detail only
node.stats.inc_detail_only (rai::stat::type::error, rai::stat::detail::insufficient_work);
break;
case rai::message_parser::parse_status::invalid_magic:
node.stats.inc (rai::stat::type::udp, rai::stat::detail::invalid_magic);
break;
case rai::message_parser::parse_status::invalid_network:
node.stats.inc (rai::stat::type::udp, rai::stat::detail::invalid_network);
break;
case rai::message_parser::parse_status::invalid_header:
node.stats.inc (rai::stat::type::udp, rai::stat::detail::invalid_header);
break;
case rai::message_parser::parse_status::invalid_message_type:
node.stats.inc (rai::stat::type::udp, rai::stat::detail::invalid_message_type);
break;
case rai::message_parser::parse_status::invalid_keepalive_message:
node.stats.inc (rai::stat::type::udp, rai::stat::detail::invalid_keepalive_message);
break;
case rai::message_parser::parse_status::invalid_publish_message:
node.stats.inc (rai::stat::type::udp, rai::stat::detail::invalid_publish_message);
break;
case rai::message_parser::parse_status::invalid_confirm_req_message:
node.stats.inc (rai::stat::type::udp, rai::stat::detail::invalid_confirm_req_message);
break;
case rai::message_parser::parse_status::invalid_confirm_ack_message:
node.stats.inc (rai::stat::type::udp, rai::stat::detail::invalid_confirm_ack_message);
break;
case rai::message_parser::parse_status::invalid_node_id_handshake_message:
node.stats.inc (rai::stat::type::udp, rai::stat::detail::invalid_node_id_handshake_message);
break;
case rai::message_parser::parse_status::outdated_version:
node.stats.inc (rai::stat::type::udp, rai::stat::detail::outdated_version);
break;
case rai::message_parser::parse_status::success:
/* Already checked, unreachable */
break;
}
if (node.config.logging.network_logging ())
{
BOOST_LOG (node.log) << "Could not parse message. Error: " << parser.status_string ();
}
}
else
{
node.stats.add (rai::stat::type::traffic, rai::stat::dir::in, data_a->size);
}
}
else
{
if (node.config.logging.network_logging ())
{
BOOST_LOG (node.log) << boost::str (boost::format ("Reserved sender %1%") % data_a->endpoint.address ().to_string ());
}
node.stats.inc_detail_only (rai::stat::type::error, rai::stat::detail::bad_sender);
}
}
// Send keepalives to all the peers we've been notified of
void rai::network::merge_peers (std::array<rai::endpoint, 8> const & peers_a)
{
for (auto i (peers_a.begin ()), j (peers_a.end ()); i != j; ++i)
{
if (!node.peers.reachout (*i))
{
send_keepalive (*i);
}
}
}
bool rai::operation::operator> (rai::operation const & other_a) const
{
return wakeup > other_a.wakeup;
}
rai::alarm::alarm (boost::asio::io_service & service_a) :
service (service_a),
thread ([this]() {
rai::thread_role::set (rai::thread_role::name::alarm);
run ();
})
{
}
rai::alarm::~alarm ()
{
add (std::chrono::steady_clock::now (), nullptr);
thread.join ();
}
void rai::alarm::run ()
{
std::unique_lock<std::mutex> lock (mutex);
auto done (false);
while (!done)
{
if (!operations.empty ())
{
auto & operation (operations.top ());
if (operation.function)
{
if (operation.wakeup <= std::chrono::steady_clock::now ())
{
service.post (operation.function);
operations.pop ();
}
else
{
auto wakeup (operation.wakeup);
condition.wait_until (lock, wakeup);
}
}
else
{
done = true;
}
}
else
{
condition.wait (lock);
}
}
}
void rai::alarm::add (std::chrono::steady_clock::time_point const & wakeup_a, std::function<void()> const & operation)
{
{
std::lock_guard<std::mutex> lock (mutex);
operations.push (rai::operation ({ wakeup_a, operation }));
}
condition.notify_all ();
}
rai::node_init::node_init () :
block_store_init (false),
wallet_init (false)
{
}
bool rai::node_init::error ()
{
return block_store_init || wallet_init;
}
rai::vote_processor::vote_processor (rai::node & node_a) :
node (node_a),
started (false),
stopped (false),
active (false),
thread ([this]() {
rai::thread_role::set (rai::thread_role::name::vote_processing);
process_loop ();
})
{
std::unique_lock<std::mutex> lock (mutex);
while (!started)
{
condition.wait (lock);
}
}
void rai::vote_processor::process_loop ()
{
std::chrono::steady_clock::time_point start_time, end_time;
std::chrono::steady_clock::duration elapsed_time;
std::chrono::milliseconds elapsed_time_ms;
uint64_t elapsed_time_ms_int;
bool log_this_iteration;
std::unique_lock<std::mutex> lock (mutex);
started = true;
lock.unlock ();
condition.notify_all ();
lock.lock ();
while (!stopped)
{
if (!votes.empty ())
{
std::deque<std::pair<std::shared_ptr<rai::vote>, rai::endpoint>> votes_l;
votes_l.swap (votes);
log_this_iteration = false;
if (node.config.logging.network_logging () && votes_l.size () > 50)
{
/*
* Only log the timing information for this iteration if
* there are a sufficient number of items for it to be relevant
*/
log_this_iteration = true;
start_time = std::chrono::steady_clock::now ();
}
active = true;
lock.unlock ();
verify_votes (votes_l);
{
std::unique_lock<std::mutex> active_single_lock (node.active.mutex);
auto transaction (node.store.tx_begin_read ());
uint64_t count (1);
for (auto & i : votes_l)
{
vote_blocking (transaction, i.first, i.second, true);
// Free active_transactions mutex each 100 processed votes
if (count % 100 == 0)
{
active_single_lock.unlock ();
active_single_lock.lock ();
}
count++;
}
}
lock.lock ();
active = false;
lock.unlock ();
condition.notify_all ();
lock.lock ();
if (log_this_iteration)
{
end_time = std::chrono::steady_clock::now ();
elapsed_time = end_time - start_time;
elapsed_time_ms = std::chrono::duration_cast<std::chrono::milliseconds> (elapsed_time);
elapsed_time_ms_int = elapsed_time_ms.count ();
if (elapsed_time_ms_int >= 100)
{
/*
* If the time spent was less than 100ms then
* the results are probably not useful as well,
* so don't spam the logs.
*/
BOOST_LOG (node.log) << boost::str (boost::format ("Processed %1% votes in %2% milliseconds (rate of %3% votes per second)") % votes_l.size () % elapsed_time_ms_int % ((votes_l.size () * 1000ULL) / elapsed_time_ms_int));
}
}
}
else
{
condition.wait (lock);
}
}
}
void rai::vote_processor::vote (std::shared_ptr<rai::vote> vote_a, rai::endpoint endpoint_a)
{
assert (endpoint_a.address ().is_v6 ());
std::unique_lock<std::mutex> lock (mutex);
if (!stopped)
{
bool process (false);
/* Random early delection levels
Always process votes for test network (process = true)
Stop processing with max 144 * 1024 votes */
if (rai::rai_network != rai::rai_networks::rai_test_network)
{
// Level 0 (< 0.1%)
if (votes.size () < 96 * 1024)
{
process = true;
}
// Level 1 (0.1-1%)
else if (votes.size () < 112 * 1024)
{
process = (representatives_1.find (vote_a->account) != representatives_1.end ());
}
// Level 2 (1-5%)
else if (votes.size () < 128 * 1024)
{
process = (representatives_2.find (vote_a->account) != representatives_2.end ());
}
// Level 3 (> 5%)
else if (votes.size () < 144 * 1024)
{
process = (representatives_3.find (vote_a->account) != representatives_3.end ());
}
}
else
{
// Process for test network
process = true;
}
if (process)
{
votes.push_back (std::make_pair (vote_a, endpoint_a));
lock.unlock ();
condition.notify_all ();
lock.lock ();
}
else
{
node.stats.inc (rai::stat::type::vote, rai::stat::detail::vote_overflow);
if (node.config.logging.vote_logging ())
{
BOOST_LOG (node.log) << "Votes overflow";
}
}
}
}
void rai::vote_processor::verify_votes (std::deque<std::pair<std::shared_ptr<rai::vote>, rai::endpoint>> & votes_a)
{
auto size (votes_a.size ());
std::vector<unsigned char const *> messages;
messages.reserve (size);
std::vector<rai::uint256_union> hashes;
hashes.reserve (size);
std::vector<size_t> lengths (size, sizeof (rai::uint256_union));
std::vector<unsigned char const *> pub_keys;
pub_keys.reserve (size);
std::vector<unsigned char const *> signatures;
signatures.reserve (size);
std::vector<int> verifications;
verifications.resize (size);
for (auto & vote : votes_a)
{
hashes.push_back (vote.first->hash ());
messages.push_back (hashes.back ().bytes.data ());
pub_keys.push_back (vote.first->account.bytes.data ());
signatures.push_back (vote.first->signature.bytes.data ());
}
std::promise<void> promise;
rai::signature_check_set check = { size, messages.data (), lengths.data (), pub_keys.data (), signatures.data (), verifications.data (), &promise };
node.checker.add (check);
promise.get_future ().wait ();
std::remove_reference_t<decltype (votes_a)> result;
auto i (0);
for (auto & vote : votes_a)
{
assert (verifications[i] == 1 || verifications[i] == 0);
if (verifications[i] == 1)
{
result.push_back (vote);
}
++i;
}
votes_a.swap (result);
}
// node.active.mutex lock required
rai::vote_code rai::vote_processor::vote_blocking (rai::transaction const & transaction_a, std::shared_ptr<rai::vote> vote_a, rai::endpoint endpoint_a, bool validated)
{
assert (endpoint_a.address ().is_v6 ());
assert (!node.active.mutex.try_lock ());
auto result (rai::vote_code::invalid);
if (validated || !vote_a->validate ())
{
auto max_vote (node.store.vote_max (transaction_a, vote_a));
result = rai::vote_code::replay;
if (!node.active.vote (vote_a, true))
{
result = rai::vote_code::vote;
}
switch (result)
{
case rai::vote_code::vote:
node.observers.vote.notify (transaction_a, vote_a, endpoint_a);
case rai::vote_code::replay:
// This tries to assist rep nodes that have lost track of their highest sequence number by replaying our highest known vote back to them
// Only do this if the sequence number is significantly different to account for network reordering
// Amplify attack considerations: We're sending out a confirm_ack in response to a confirm_ack for no net traffic increase
if (max_vote->sequence > vote_a->sequence + 10000)
{
rai::confirm_ack confirm (max_vote);
node.network.confirm_send (confirm, confirm.to_bytes (), endpoint_a);
}
break;
case rai::vote_code::invalid: