forked from oxen-io/oxen-storage-server
/
service_node.cpp
1717 lines (1347 loc) · 55 KB
/
service_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 "service_node.h"
#include "Database.hpp"
#include "Item.hpp"
#include "http_connection.h"
#include "https_client.h"
#include "loki_common.h"
#include "loki_logger.h"
#include "lokid_key.h"
#include "net_stats.h"
#include "serialization.h"
#include "signature.h"
#include "utils.hpp"
#include "version.h"
#include "dns_text_records.h"
#include <algorithm>
#include <chrono>
#include <fstream>
#include <boost/bind.hpp>
using json = nlohmann::json;
using loki::storage::Item;
using namespace std::chrono_literals;
namespace loki {
using http_server::connection_t;
constexpr std::array<std::chrono::seconds, 8> RETRY_INTERVALS = {
std::chrono::seconds(1), std::chrono::seconds(5),
std::chrono::seconds(10), std::chrono::seconds(20),
std::chrono::seconds(40), std::chrono::seconds(80),
std::chrono::seconds(160), std::chrono::seconds(320)};
constexpr std::chrono::milliseconds RELAY_INTERVAL = 350ms;
static void make_sn_request(boost::asio::io_context& ioc, const sn_record_t& sn,
const std::shared_ptr<request_t>& req,
http_callback_t&& cb) {
// TODO: Return to using snode address instead of ip
return make_https_request(ioc, sn.ip(), sn.port(), sn.pub_key_base32z(),
req, std::move(cb));
}
FailedRequestHandler::FailedRequestHandler(
boost::asio::io_context& ioc, const sn_record_t& sn,
std::shared_ptr<request_t> req,
boost::optional<std::function<void()>>&& give_up_cb)
: ioc_(ioc), retry_timer_(ioc), sn_(sn), request_(std::move(req)),
give_up_callback_(std::move(give_up_cb)) {}
void FailedRequestHandler::retry(std::shared_ptr<FailedRequestHandler>&& self) {
attempt_count_ += 1;
if (attempt_count_ > RETRY_INTERVALS.size()) {
LOKI_LOG(debug, "Gave up after {} attempts", attempt_count_);
if (give_up_callback_)
(*give_up_callback_)();
return;
}
retry_timer_.expires_after(RETRY_INTERVALS[attempt_count_ - 1]);
LOKI_LOG(debug, "Will retry in {} secs",
RETRY_INTERVALS[attempt_count_ - 1].count());
retry_timer_.async_wait(
[self = std::move(self)](const boost::system::error_code& ec) mutable {
/// Save some references before possibly moved out of `self`
const auto& sn = self->sn_;
auto& ioc = self->ioc_;
/// TODO: investigate whether we can get rid of the extra ptr copy
/// here?
const std::shared_ptr<request_t> req = self->request_;
/// Request will be copied here
make_sn_request(
ioc, sn, req,
[self = std::move(self)](sn_response_t&& res) mutable {
if (res.error_code != SNodeError::NO_ERROR) {
LOKI_LOG(debug, "Could not relay one: {} (attempt #{})",
self->sn_, self->attempt_count_);
self->retry(std::move(self));
}
});
});
}
FailedRequestHandler::~FailedRequestHandler() {
LOKI_LOG(trace, "~FailedRequestHandler()");
}
void FailedRequestHandler::init_timer() { retry(shared_from_this()); }
/// TODO: there should be config.h to store constants like these
#ifdef INTEGRATION_TEST
constexpr std::chrono::milliseconds SWARM_UPDATE_INTERVAL = 200ms;
#else
constexpr std::chrono::milliseconds SWARM_UPDATE_INTERVAL = 1000ms;
#endif
constexpr std::chrono::seconds STATS_CLEANUP_INTERVAL = 60min;
constexpr std::chrono::seconds PING_PEERS_INTERVAL = 10s;
constexpr std::chrono::minutes LOKID_PING_INTERVAL = 5min;
constexpr std::chrono::minutes POW_DIFFICULTY_UPDATE_INTERVAL = 10min;
constexpr std::chrono::seconds VERSION_CHECK_INTERVAL = 10min;
constexpr int CLIENT_RETRIEVE_MESSAGE_LIMIT = 10;
static std::shared_ptr<request_t> make_push_all_request(std::string&& data) {
return build_post_request("/swarms/push_batch/v1", std::move(data));
}
static bool verify_message(const message_t& msg,
const std::vector<pow_difficulty_t> history,
const char** error_message = nullptr) {
if (!util::validateTTL(msg.ttl)) {
if (error_message)
*error_message = "Provided TTL is not valid";
return false;
}
if (!util::validateTimestamp(msg.timestamp, msg.ttl)) {
if (error_message)
*error_message = "Provided timestamp is not valid";
return false;
}
std::string hash;
#ifndef DISABLE_POW
const int difficulty =
get_valid_difficulty(std::to_string(msg.timestamp), history);
if (!checkPoW(msg.nonce, std::to_string(msg.timestamp),
std::to_string(msg.ttl), msg.pub_key, msg.data, hash,
difficulty)) {
if (error_message)
*error_message = "Provided PoW nonce is not valid";
return false;
}
#endif
if (hash != msg.hash) {
if (error_message)
*error_message = "Incorrect hash provided";
return false;
}
return true;
}
ServiceNode::ServiceNode(boost::asio::io_context& ioc,
boost::asio::io_context& worker_ioc, uint16_t port,
const lokid_key_pair_t& lokid_key_pair,
const loki::lokid_key_pair_t& key_pair_x25519,
const std::string& db_location,
LokidClient& lokid_client, const bool force_start)
: ioc_(ioc), worker_ioc_(worker_ioc),
db_(std::make_unique<Database>(ioc, db_location)),
swarm_update_timer_(ioc), lokid_ping_timer_(ioc),
stats_cleanup_timer_(ioc), pow_update_timer_(worker_ioc),
check_version_timer_(worker_ioc), peer_ping_timer_(ioc),
relay_timer_(ioc), lokid_key_pair_(lokid_key_pair),
lokid_key_pair_x25519_(key_pair_x25519), lokid_client_(lokid_client),
force_start_(force_start) {
char buf[64] = {0};
if (!util::base32z_encode(lokid_key_pair_.public_key, buf)) {
throw std::runtime_error("Could not encode our public key");
}
const std::string addr = buf;
LOKI_LOG(info, "Our loki address: {}", addr);
const auto pk_hex = util::as_hex(lokid_key_pair_.public_key);
// TODO: get rid of "unused" fields
our_address_ = sn_record_t(port, addr, pk_hex, "unused", "unused", "1.1.1.1");
// TODO: fail hard if we can't encode our public key
LOKI_LOG(info, "Read our snode address: {}", our_address_);
swarm_ = std::make_unique<Swarm>(our_address_);
LOKI_LOG(info, "Requesting initial swarm state");
#ifndef INTEGRATION_TEST
bootstrap_data();
#else
this->syncing_ = false;
#endif
swarm_timer_tick();
lokid_ping_timer_tick();
cleanup_timer_tick();
ping_peers_tick();
worker_thread_ = boost::thread([this]() { worker_ioc_.run(); });
boost::asio::post(worker_ioc_, [this]() {
pow_difficulty_timer_tick(std::bind(
&ServiceNode::set_difficulty_history, this, std::placeholders::_1));
});
boost::asio::post(worker_ioc_,
[this]() { this->check_version_timer_tick(); });
}
static block_update_t
parse_swarm_update(const std::shared_ptr<std::string>& response_body) {
if (!response_body) {
LOKI_LOG(critical, "Bad lokid rpc response: no response body");
throw std::runtime_error("Failed to parse swarm update");
}
const json body = json::parse(*response_body, nullptr, false);
if (body.is_discarded()) {
LOKI_LOG(trace, "Response body: {}", *response_body);
LOKI_LOG(critical, "Bad lokid rpc response: invalid json");
throw std::runtime_error("Failed to parse swarm update");
}
std::map<swarm_id_t, std::vector<sn_record_t>> swarm_map;
block_update_t bu;
try {
const auto& result = body.at("result");
bu.height = result.at("height").get<uint64_t>();
bu.block_hash = result.at("block_hash").get<std::string>();
bu.hardfork = result.at("hardfork").get<int>();
bu.unchanged = result.count("unchanged") && result.at("unchanged").get<bool>();
if (bu.unchanged)
return bu;
const json service_node_states = result.at("service_node_states");
for (const auto& sn_json : service_node_states) {
const auto& pubkey =
sn_json.at("service_node_pubkey").get_ref<const std::string&>();
const swarm_id_t swarm_id =
sn_json.at("swarm_id").get<swarm_id_t>();
std::string snode_address = util::hex_to_base32z(pubkey);
const uint16_t port = sn_json.at("storage_port").get<uint16_t>();
const auto& snode_ip =
sn_json.at("public_ip").get_ref<const std::string&>();
const auto& pubkey_x25519 =
sn_json.at("pubkey_x25519").get_ref<const std::string&>();
const auto& pubkey_ed25519 =
sn_json.at("pubkey_ed25519").get_ref<const std::string&>();
const auto sn =
sn_record_t{port, std::move(snode_address), pubkey,
pubkey_x25519, pubkey_ed25519, snode_ip};
const bool fully_funded = sn_json.at("funded").get<bool>();
/// We want to include (test) decommissioned nodes, but not
/// partially funded ones.
if (!fully_funded) {
continue;
}
/// Storing decommissioned nodes (with dummy swarm id) in
/// a separate data structure as it seems less error prone
if (swarm_id == INVALID_SWARM_ID) {
bu.decommissioned_nodes.push_back(sn);
} else {
swarm_map[swarm_id].push_back(sn);
}
}
} catch (...) {
LOKI_LOG(trace, "swarm repsonse: {}", body.dump(2));
LOKI_LOG(critical, "Bad lokid rpc response: invalid json fields");
throw std::runtime_error("Failed to parse swarm update");
}
for (auto const& swarm : swarm_map) {
bu.swarms.emplace_back(SwarmInfo{swarm.first, swarm.second});
}
return bu;
}
void ServiceNode::bootstrap_data() {
LOKI_LOG(trace, "Bootstrapping peer data");
json params;
json fields;
fields["service_node_pubkey"] = true;
fields["swarm_id"] = true;
fields["storage_port"] = true;
fields["public_ip"] = true;
fields["height"] = true;
fields["block_hash"] = true;
fields["hardfork"] = true;
fields["funded"] = true;
fields["pubkey_x25519"] = true;
fields["pubkey_ed25519"] = true;
params["fields"] = fields;
std::vector<std::pair<std::string, uint16_t>> seed_nodes;
if (loki::is_mainnet()) {
seed_nodes = {{{"public.loki.foundation", 38157},
{"storage.seed1.loki.network", 22023},
{"storage.seed2.loki.network", 38157},
{"imaginary.stream", 38157}}};
} else {
seed_nodes = {{{"public.loki.foundation", 38157},
{"storage.testnetseed1.loki.network", 38157}}};
}
auto req_counter = std::make_shared<int>(0);
for (auto seed_node : seed_nodes) {
lokid_client_.make_custom_lokid_request(
seed_node.first, seed_node.second, "get_n_service_nodes", params,
[this, seed_node, req_counter,
node_count = seed_nodes.size()](const sn_response_t&& res) {
if (res.error_code == SNodeError::NO_ERROR) {
try {
const block_update_t bu = parse_swarm_update(res.body);
// TODO: this should be disabled in the "testnet" mode
// (or changed to point to testnet seeds)
on_bootstrap_update(bu);
} catch (const std::exception& e) {
LOKI_LOG(
error,
"Exception caught while bootstrapping from {}: {}",
seed_node.first, e.what());
}
} else {
LOKI_LOG(error, "Failed to contact bootstrap node {}",
seed_node.first);
}
(*req_counter)++;
if (*req_counter == node_count && this->target_height_ == 0) {
// If target height is still 0 after having contacted
// (successfully or not) all seed nodes, just assume we have
// finished syncing. (Otherwise we will never get a chance
// to update syncing status.)
LOKI_LOG(
warn,
"Could not contact any of the seed nodes to get target "
"height. Going to assume our height is correct.");
this->syncing_ = false;
}
});
}
}
bool ServiceNode::snode_ready(boost::optional<std::string&> reason) {
bool ready = true;
std::string buf;
if (hardfork_ < STORAGE_SERVER_HARDFORK) {
buf += "not yet on hardfork 12; ";
ready = false;
}
if (!swarm_ || !swarm_->is_valid()) {
buf += "not in any swarm; ";
ready = false;
}
if (syncing_) {
buf += "not done syncing; ";
ready = false;
}
if (reason) {
*reason = std::move(buf);
}
return ready || force_start_;
}
ServiceNode::~ServiceNode() {
worker_ioc_.stop();
worker_thread_.join();
};
void ServiceNode::relay_data_reliable(const std::shared_ptr<request_t>& req,
const sn_record_t& sn) const {
LOKI_LOG(trace, "Relaying data to: {}", sn);
// Note: often one of the reason for failure here is that the node has just
// deregistered but our SN hasn't updated its swarm list yet.
make_sn_request(ioc_, sn, req, [this, sn, req](sn_response_t&& res) {
if (res.error_code != SNodeError::NO_ERROR) {
all_stats_.record_request_failed(sn);
if (res.error_code == SNodeError::NO_REACH) {
LOKI_LOG(debug,
"Could not relay data to {} at first attempt: "
"(Unreachable)",
sn);
} else if (res.error_code == SNodeError::ERROR_OTHER) {
LOKI_LOG(debug,
"Could not relay data to {} at first attempt: "
"(Generic error)",
sn);
}
std::function<void()> give_up_cb = [this, sn]() {
LOKI_LOG(debug, "Failed to send a request to: {}", sn);
this->all_stats_.record_push_failed(sn);
};
boost::optional<std::function<void()>> cb = give_up_cb;
std::make_shared<FailedRequestHandler>(ioc_, sn, req, std::move(cb))
->init_timer();
}
});
}
void ServiceNode::register_listener(const std::string& pk,
const std::shared_ptr<connection_t>& c) {
// NOTE: it is the responsibility of connection_t to deregister itself!
pk_to_listeners[pk].push_back(c);
LOKI_LOG(debug, "Register pubkey: {}, total pubkeys: {}", pk,
pk_to_listeners.size());
LOKI_LOG(debug, "Number of connections listening for {}: {}", pk,
pk_to_listeners[pk].size());
}
void ServiceNode::remove_listener(const std::string& pk,
const connection_t* const c) {
const auto it = pk_to_listeners.find(pk);
if (it == pk_to_listeners.end()) {
/// This will sometimes happen because we reset all listeners on
/// push_all
LOKI_LOG(debug, "Trying to remove an unknown pk from the notification "
"map. Operation ignored.");
} else {
LOKI_LOG(trace,
"Deregistering notification for connection {} for pk {}",
c->conn_idx, pk);
auto& cs = it->second;
const auto new_end = std::remove_if(
cs.begin(), cs.end(), [c](const std::shared_ptr<connection_t>& e) {
return e.get() == c;
});
const auto count = std::distance(new_end, cs.end());
cs.erase(new_end, cs.end());
if (count == 0) {
LOKI_LOG(debug, "Connection {} in not registered for pk {}",
c->conn_idx, pk);
} else if (count > 1) {
LOKI_LOG(debug,
"Multiple registrations ({}) for connection {} for pk {}",
count, c->conn_idx, pk);
}
}
}
void ServiceNode::notify_listeners(const std::string& pk,
const message_t& msg) {
auto it = pk_to_listeners.find(pk);
if (it != pk_to_listeners.end()) {
auto& listeners = it->second;
LOKI_LOG(debug, "number of notified listeners: {}", listeners.size());
for (auto& c : listeners) {
c->notify(msg);
}
pk_to_listeners.erase(it);
}
}
void ServiceNode::reset_listeners() {
/// It is probably not worth it to try to
/// determine which connections needn't
/// be reset (most of them will need to be),
/// so we just reset all connections for
/// simplicity
for (auto& entry : pk_to_listeners) {
for (auto& c : entry.second) {
/// notify with no messages
c->notify(boost::none);
}
}
pk_to_listeners.clear();
}
/// do this asynchronously on a different thread? (on the same thread?)
bool ServiceNode::process_store(const message_t& msg) {
/// only accept a message if we are in a swarm
if (!swarm_) {
// This should never be printed now that we have "snode_ready"
LOKI_LOG(error, "error: my swarm in not initialized");
return false;
}
all_stats_.bump_store_requests();
/// store in the database
this->save_if_new(msg);
// Instead of sending the messages immediatly, store them in a buffer
// and periodically send all messages from there as batches
this->relay_buffer_.push_back(msg);
return true;
}
void ServiceNode::process_push(const message_t& msg) {
#ifndef DISABLE_POW
const char* error_msg;
if (!verify_message(msg, pow_history_, &error_msg))
throw std::runtime_error(error_msg);
#endif
save_if_new(msg);
}
void ServiceNode::process_proxy_req(const std::string& req_body,
const std::string& sender_key,
const std::string& target_snode,
http_callback_t&& on_proxy_response) {
auto sn = swarm_->find_node_by_ed25519_pk(target_snode);
if (!sn) {
LOKI_LOG(debug, "Could not find target snode for proxy: {}", target_snode);
on_proxy_response(sn_response_t{SNodeError::ERROR_OTHER, nullptr, boost::none});
return;
}
LOKI_LOG(trace, "Target Snode: {}", target_snode);
auto body_clone = req_body;
auto req = build_post_request("/swarms/proxy_exit", std::move(body_clone));
req->insert(LOKI_SENDER_KEY_HEADER, sender_key);
this->sign_request(req);
make_sn_request(ioc_, *sn, req, std::move(on_proxy_response));
}
void ServiceNode::save_if_new(const message_t& msg) {
if (db_->store(msg.hash, msg.pub_key, msg.data, msg.ttl, msg.timestamp,
msg.nonce)) {
notify_listeners(msg.pub_key, msg);
LOKI_LOG(trace, "saved message: {}", msg.data);
}
}
void ServiceNode::save_bulk(const std::vector<Item>& items) {
if (!db_->bulk_store(items)) {
LOKI_LOG(error, "failed to save batch to the database");
return;
}
LOKI_LOG(trace, "saved messages count: {}", items.size());
// For batches, it is not trivial to get the list of saved (new)
// messages, so we are only going to "notify" clients with no data
// effectively resetting the connection.
reset_listeners();
}
void ServiceNode::on_bootstrap_update(const block_update_t& bu) {
swarm_->apply_swarm_changes(bu.swarms);
target_height_ = std::max(target_height_, bu.height);
}
void ServiceNode::on_swarm_update(const block_update_t& bu) {
hardfork_ = bu.hardfork;
if (syncing_) {
if (target_height_ == 0) {
// If we are here, the probably means we were never able to contact
// any seed, so the bast we can do is to assume we are synced
// (this shouldn't be necessary as we do the same when all requests
// fail, but it won't hurt either)
LOKI_LOG(info, "Target height is 0, assuming we are synced");
syncing_ = false;
} else {
syncing_ = bu.height < target_height_;
}
}
/// We don't have anything to do until we have synced
if (syncing_) {
LOKI_LOG(debug, "Still syncing: {}/{}", bu.height, target_height_);
// Note that because we are still syncing, we won't update our swarm id
return;
}
if (bu.block_hash != block_hash_) {
LOKI_LOG(debug, "new block, height: {}, hash: {}", bu.height,
bu.block_hash);
if (bu.height > block_height_ + 1 && block_height_ != 0) {
LOKI_LOG(warn, "Skipped some block(s), old: {} new: {}",
block_height_, bu.height);
/// TODO: if we skipped a block, should we try to run peer tests for
/// them as well?
} else if (bu.height <= block_height_) {
// TODO: investigate how testing will be affected under reorg
LOKI_LOG(warn,
"new block height is not higher than the current height");
}
block_height_ = bu.height;
block_hash_ = bu.block_hash;
block_hashes_cache_.push_back(std::make_pair(bu.height, bu.block_hash));
} else {
LOKI_LOG(trace, "already seen this block");
return;
}
const SwarmEvents events = swarm_->derive_swarm_events(bu.swarms);
swarm_->set_swarm_id(events.our_swarm_id);
std::string reason;
if (!snode_ready(boost::optional<std::string&>(reason))) {
LOKI_LOG(warn, "Storage server is still not ready: {}", reason);
return;
} else {
static bool active = false;
if (!active) {
LOKI_LOG(info, "Storage server is now active!");
relay_timer_.expires_after(RELAY_INTERVAL);
relay_timer_.async_wait(
boost::bind(&ServiceNode::relay_buffered_messages, this));
active = true;
}
}
swarm_->update_state(bu.swarms, bu.decommissioned_nodes, events);
if (!events.new_snodes.empty()) {
bootstrap_peers(events.new_snodes);
}
if (!events.new_swarms.empty()) {
bootstrap_swarms(events.new_swarms);
}
if (events.dissolved) {
/// Go through all our PK and push them accordingly
salvage_data();
}
initiate_peer_test();
}
void ServiceNode::relay_buffered_messages() {
// Should we wait for the response first?
relay_timer_.expires_after(RELAY_INTERVAL);
relay_timer_.async_wait(
boost::bind(&ServiceNode::relay_buffered_messages, this));
if (relay_buffer_.empty())
return;
LOKI_LOG(debug, "Relaying {} messages from buffer to {} nodes", relay_buffer_.size(), swarm_->other_nodes().size());
this->relay_messages(relay_buffer_, swarm_->other_nodes());
relay_buffer_.clear();
}
void ServiceNode::check_version_timer_tick() {
check_version_timer_.expires_after(VERSION_CHECK_INTERVAL);
check_version_timer_.async_wait(
std::bind(&ServiceNode::check_version_timer_tick, this));
dns::check_latest_version();
}
void ServiceNode::pow_difficulty_timer_tick(const pow_dns_callback_t cb) {
std::error_code ec;
std::vector<pow_difficulty_t> new_history = dns::query_pow_difficulty(ec);
if (!ec) {
boost::asio::post(ioc_, std::bind(cb, new_history));
}
pow_update_timer_.expires_after(POW_DIFFICULTY_UPDATE_INTERVAL);
pow_update_timer_.async_wait(
boost::bind(&ServiceNode::pow_difficulty_timer_tick, this, cb));
}
void ServiceNode::swarm_timer_tick() {
LOKI_LOG(trace, "Swarm timer tick");
json params;
json fields;
fields["service_node_pubkey"] = true;
fields["swarm_id"] = true;
fields["storage_port"] = true;
fields["public_ip"] = true;
fields["height"] = true;
fields["block_hash"] = true;
fields["hardfork"] = true;
fields["funded"] = true;
fields["pubkey_x25519"] = true;
fields["pubkey_ed25519"] = true;
params["fields"] = fields;
params["poll_block_hash"] = block_hash_;
params["active_only"] = false;
lokid_client_.make_lokid_request(
"get_n_service_nodes", params, [this](const sn_response_t&& res) {
if (res.error_code == SNodeError::NO_ERROR) {
try {
const block_update_t bu = parse_swarm_update(res.body);
if (!bu.unchanged)
on_swarm_update(bu);
} catch (const std::exception& e) {
LOKI_LOG(error, "Exception caught on swarm update: {}",
e.what());
}
} else {
LOKI_LOG(critical, "Failed to contact local Lokid");
}
// It would make more sense to wait the difference between the time
// elapsed and SWARM_UPDATE_INTERVAL, but this is good enough:
swarm_update_timer_.expires_after(SWARM_UPDATE_INTERVAL);
swarm_update_timer_.async_wait(
boost::bind(&ServiceNode::swarm_timer_tick, this));
});
}
void ServiceNode::cleanup_timer_tick() {
all_stats_.cleanup();
stats_cleanup_timer_.expires_after(STATS_CLEANUP_INTERVAL);
stats_cleanup_timer_.async_wait(
boost::bind(&ServiceNode::cleanup_timer_tick, this));
}
void ServiceNode::ping_peers_tick() {
this->peer_ping_timer_.expires_after(PING_PEERS_INTERVAL);
this->peer_ping_timer_.async_wait(
std::bind(&ServiceNode::ping_peers_tick, this));
/// TODO: To be safe, let's not even test peers until we
/// have reached the right hardfork height
if (hardfork_ < ENFORCED_REACHABILITY_HARDFORK) {
LOKI_LOG(debug, "Have not reached HF13, skipping reachability tests");
return;
}
/// We always test one node already known to be offline
/// plus one random other node (could even be the same node)
const auto random_node = swarm_->choose_funded_node();
if (random_node) {
if (random_node == our_address_) {
LOKI_LOG(trace, "Would test our own node, skipping");
} else {
LOKI_LOG(trace, "Selected random node for testing: {}",
(*random_node).pub_key_hex());
test_reachability(*random_node);
}
} else {
LOKI_LOG(trace, "No nodes to test for reachability");
}
// TODO: there is an edge case where SS reported some offending
// nodes, but then restarted, so SS won't give priority to those
// nodes. SS will still test them eventually (through random selection) and
// update Lokid, but this scenario could be made more robust.
const auto offline_node = reach_records_.next_to_test();
if (offline_node) {
const boost::optional<sn_record_t> sn =
swarm_->get_node_by_pk(*offline_node);
LOKI_LOG(debug, "No offline nodes to test for reachability yet");
if (sn) {
test_reachability(*sn);
} else {
LOKI_LOG(debug, "Node does not seem to exist anymore: {}",
*offline_node);
// delete its entry from test records as irrelevant
reach_records_.expire(*offline_node);
}
}
}
void ServiceNode::sign_request(std::shared_ptr<request_t> &req) const {
// TODO: investigate why we are not signing headers
const auto hash = hash_data(req->body());
const auto signature = generate_signature(hash, lokid_key_pair_);
attach_signature(req, signature);
}
void ServiceNode::test_reachability(const sn_record_t& sn) {
LOKI_LOG(debug, "Testing node for reachability {}", sn);
auto callback = [this, sn](sn_response_t&& res) {
this->process_reach_test_response(std::move(res), sn.pub_key_base32z());
};
nlohmann::json json_body;
auto req = build_post_request("/swarms/ping_test/v1", json_body.dump());
this->sign_request(req);
make_sn_request(ioc_, sn, req, std::move(callback));
}
void ServiceNode::lokid_ping_timer_tick() {
/// TODO: Note that this is not actually an SN response! (but Lokid)
auto cb = [](const sn_response_t&& res) {
if (res.error_code == SNodeError::NO_ERROR) {
if (!res.body) {
LOKI_LOG(critical, "Empty body on Lokid ping");
return;
}
try {
json res_json = json::parse(*res.body);
const auto status =
res_json.at("result").at("status").get<std::string>();
if (status == "OK") {
LOKI_LOG(info, "Successfully pinged Lokid");
} else {
LOKI_LOG(critical, "Could not ping Lokid. Status: {}",
status);
}
} catch (...) {
LOKI_LOG(critical,
"Could not ping Lokid: bad json in response");
}
} else {
LOKI_LOG(critical, "Could not ping Lokid");
}
};
json params;
params["version_major"] = VERSION_MAJOR;
params["version_minor"] = VERSION_MINOR;
params["version_patch"] = VERSION_PATCH;
lokid_client_.make_lokid_request("storage_server_ping", params,
std::move(cb));
lokid_ping_timer_.expires_after(LOKID_PING_INTERVAL);
lokid_ping_timer_.async_wait(
boost::bind(&ServiceNode::lokid_ping_timer_tick, this));
}
static std::vector<std::shared_ptr<request_t>>
make_batch_requests(std::vector<std::string>&& data) {
std::vector<std::shared_ptr<request_t>> result;
result.reserve(data.size());
std::transform(std::make_move_iterator(data.begin()),
std::make_move_iterator(data.end()),
std::back_inserter(result), make_push_all_request);
return result;
}
void ServiceNode::perform_blockchain_test(
bc_test_params_t test_params,
std::function<void(blockchain_test_answer_t)>&& cb) const {
LOKI_LOG(debug, "Delegating blockchain test to Lokid");
nlohmann::json params;
params["max_height"] = test_params.max_height;
params["seed"] = test_params.seed;
auto on_resp = [cb = std::move(cb)](const sn_response_t& resp) {
if (resp.error_code != SNodeError::NO_ERROR || !resp.body) {
LOKI_LOG(critical, "Could not send blockchain request to Lokid");
return;
}
const json body = json::parse(*resp.body, nullptr, false);
if (body.is_discarded()) {
LOKI_LOG(critical, "Bad Lokid rpc response: invalid json");
return;
}
try {
auto result = body.at("result");
uint64_t height = result.at("res_height").get<uint64_t>();
cb(blockchain_test_answer_t{height});
} catch (...) {
}
};
lokid_client_.make_lokid_request("perform_blockchain_test", params,
std::move(on_resp));
}
void ServiceNode::attach_signature(std::shared_ptr<request_t>& request,
const signature& sig) const {
std::string raw_sig;
raw_sig.reserve(sig.c.size() + sig.r.size());
raw_sig.insert(raw_sig.begin(), sig.c.begin(), sig.c.end());
raw_sig.insert(raw_sig.end(), sig.r.begin(), sig.r.end());
const std::string sig_b64 = util::base64_encode(raw_sig);
request->set(LOKI_SNODE_SIGNATURE_HEADER, sig_b64);
attach_pubkey(request);
}
void ServiceNode::attach_pubkey(std::shared_ptr<request_t>& request) const {
request->set(LOKI_SENDER_SNODE_PUBKEY_HEADER,
our_address_.pub_key_base32z());
}
void abort_if_integration_test() {
#ifdef INTEGRATION_TEST
LOKI_LOG(critical, "ABORT in integration test");
abort();
#endif
}
void ServiceNode::process_storage_test_response(const sn_record_t& testee,
const Item& item,
uint64_t test_height,
sn_response_t&& res) {
if (res.error_code != SNodeError::NO_ERROR) {
// TODO: retry here, otherwise tests sometimes fail (when SN not
// running yet)
this->all_stats_.record_storage_test_result(testee, ResultType::OTHER);
LOKI_LOG(debug, "Failed to send a storage test request to snode: {}",
testee);
return;
}
// If we got here, the response is 200 OK, but we still need to check
// status in response body and check the answer
if (!res.body) {
this->all_stats_.record_storage_test_result(testee, ResultType::OTHER);
LOKI_LOG(debug, "Empty body in storage test response");
return;
}
ResultType result = ResultType::OTHER;
try {
json res_json = json::parse(*res.body);
const auto status = res_json.at("status").get<std::string>();
if (status == "OK") {
const auto value = res_json.at("value").get<std::string>();
if (value == item.data) {
LOKI_LOG(debug,
"Storage test is successful for: {} at height: {}",
testee, test_height);
result = ResultType::OK;
} else {
LOKI_LOG(debug,
"Test answer doesn't match for: {} at height {}",
testee, test_height);