This repository has been archived by the owner on Mar 3, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 36
/
pbft.cpp
1783 lines (1515 loc) · 57.9 KB
/
pbft.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
// Copyright (C) 2018 Bluzelle
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License, version 3,
// as published by the Free Software Foundation.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
#include <pbft/pbft.hpp>
#include <pbft/pbft_memory_operation.hpp>
#include <utils/make_endpoint.hpp>
#include <utils/bytes_to_debug_string.hpp>
#include <google/protobuf/text_format.h>
#include <boost/beast/core/detail/base64.hpp>
#include <boost/format.hpp>
#include <cstdint>
#include <memory>
#include <algorithm>
#include <numeric>
#include <optional>
#include <iterator>
#include <crud/crud_base.hpp>
#include <random>
#include <chrono>
using namespace bzn;
pbft::pbft(
std::shared_ptr<bzn::node_base> node
, std::shared_ptr<bzn::asio::io_context_base> io_context
, const bzn::peers_list_t& peers
, std::shared_ptr<bzn::options_base> options
, std::shared_ptr<pbft_service_base> service
, std::shared_ptr<pbft_failure_detector_base> failure_detector
, std::shared_ptr<bzn::crypto_base> crypto
)
: node(std::move(node))
, uuid(options->get_uuid())
, options(options)
, service(std::move(service))
, failure_detector(std::move(failure_detector))
, io_context(io_context)
, audit_heartbeat_timer(this->io_context->make_unique_steady_timer())
, crypto(std::move(crypto))
{
if (peers.empty())
{
throw std::runtime_error("No peers found!");
}
this->initialize_configuration(peers);
// TODO: stable checkpoint should be read from disk first: KEP-494
this->low_water_mark = this->stable_checkpoint.first;
this->high_water_mark = this->stable_checkpoint.first + std::lround(CHECKPOINT_INTERVAL*HIGH_WATER_INTERVAL_IN_CHECKPOINTS);
this->service->save_service_state_at(((this->next_issued_sequence_number / CHECKPOINT_INTERVAL) + 1) * CHECKPOINT_INTERVAL);
}
void
pbft::start()
{
std::call_once(this->start_once,
[this]()
{
this->node->register_for_message(bzn_envelope::PayloadCase::kPbft,
std::bind(&pbft::handle_bzn_message, shared_from_this(), std::placeholders::_1, std::placeholders::_2));
this->node->register_for_message(bzn_envelope::PayloadCase::kPbftMembership,
std::bind(&pbft::handle_membership_message, shared_from_this(), std::placeholders::_1, std::placeholders::_2));
this->node->register_for_message(bzn_envelope::kDatabaseMsg,
std::bind(&pbft::handle_database_message, shared_from_this(), std::placeholders::_1, std::placeholders::_2));
this->audit_heartbeat_timer->expires_from_now(HEARTBEAT_INTERVAL);
this->audit_heartbeat_timer->async_wait(
std::bind(&pbft::handle_audit_heartbeat_timeout, shared_from_this(), std::placeholders::_1));
this->service->register_execute_handler(
[weak_this = this->weak_from_this(), fd = this->failure_detector]
(std::shared_ptr<pbft_operation> op)
{
fd->request_executed(op->get_request_hash());
if (op->get_sequence() % CHECKPOINT_INTERVAL == 0)
{
auto strong_this = weak_this.lock();
if (strong_this)
{
// tell service to save the next checkpoint after this one
strong_this->service->save_service_state_at(op->get_sequence() + CHECKPOINT_INTERVAL);
strong_this->checkpoint_reached_locally(op->get_sequence());
}
else
{
throw std::runtime_error("pbft_service callback failed because pbft does not exist");
}
}
}
);
this->failure_detector->register_failure_handler(
[weak_this = this->weak_from_this()]()
{
auto strong_this = weak_this.lock();
if (strong_this)
{
strong_this->handle_failure();
}
}
);
this->join_swarm();
});
}
void
pbft::handle_audit_heartbeat_timeout(const boost::system::error_code& ec)
{
if (ec)
{
LOG(error) << "pbft audit heartbeat canceled? " << ec.message();
return;
}
if (this->is_primary() && this->audit_enabled)
{
audit_message msg;
msg.mutable_primary_status()->set_view(this->view);
msg.mutable_primary_status()->set_primary(this->uuid);
this->broadcast(this->wrap_message(msg));
}
this->audit_heartbeat_timer->expires_from_now(HEARTBEAT_INTERVAL);
this->audit_heartbeat_timer->async_wait(std::bind(&pbft::handle_audit_heartbeat_timeout, shared_from_this(), std::placeholders::_1));
}
void
pbft::handle_bzn_message(const bzn_envelope& msg, std::shared_ptr<bzn::session_base> /*session*/)
{
if (msg.payload_case() != bzn_envelope::kPbft)
{
LOG(error) << "Got misdirected message " << msg.DebugString().substr(0, MAX_MESSAGE_SIZE);
}
pbft_msg inner_msg;
if (!inner_msg.ParseFromString(msg.pbft()))
{
LOG(error) << "Failed to parse payload of wrapped message " << msg.DebugString().substr(0, MAX_MESSAGE_SIZE);
return;
}
this->handle_message(inner_msg, msg);
}
void
pbft::handle_membership_message(const bzn_envelope& msg, std::shared_ptr<bzn::session_base> session)
{
LOG(debug) << "Received message: " << msg.ShortDebugString().substr(0, MAX_MESSAGE_SIZE);
pbft_membership_msg inner_msg;
if (!inner_msg.ParseFromString(msg.pbft_membership()))
{
LOG(error) << "Failed to parse payload of wrapped message " << msg.DebugString().substr(0, MAX_MESSAGE_SIZE);
return;
}
switch (inner_msg.type())
{
case PBFT_MMSG_JOIN:
case PBFT_MMSG_LEAVE:
if (!this->is_primary())
{
this->forward_request_to_primary(msg, session);
return;
}
this->handle_join_or_leave(inner_msg, session);
break;
case PBFT_MMSG_GET_STATE:
this->handle_get_state(inner_msg, std::move(session));
break;
case PBFT_MMSG_SET_STATE:
this->handle_set_state(inner_msg);
break;
case PBFT_MMSG_JOIN_RESPONSE:
this->handle_join_response(inner_msg);
break;
default:
LOG(error) << "Invalid membership message received "
<< inner_msg.DebugString().substr(0, MAX_MESSAGE_SIZE);
}
}
void
pbft::handle_message(const pbft_msg& msg, const bzn_envelope& original_msg)
{
LOG(debug) << "Received message: " << msg.ShortDebugString().substr(0, MAX_MESSAGE_SIZE);
if (!this->preliminary_filter_msg(msg))
{
return;
}
std::lock_guard<std::mutex> lock(this->pbft_lock);
switch (msg.type())
{
case PBFT_MSG_PREPREPARE :
this->handle_preprepare(msg, original_msg);
break;
case PBFT_MSG_PREPARE :
this->handle_prepare(msg, original_msg);
break;
case PBFT_MSG_COMMIT :
this->handle_commit(msg, original_msg);
break;
case PBFT_MSG_CHECKPOINT :
this->handle_checkpoint(msg, original_msg);
break;
case PBFT_MSG_VIEWCHANGE :
this->handle_viewchange(msg, original_msg);
break;
case PBFT_MSG_NEWVIEW :
this->handle_newview(msg, original_msg);
break;
default :
throw std::runtime_error("Unsupported message type");
}
}
bool
pbft::preliminary_filter_msg(const pbft_msg& msg)
{
if (!this->is_view_valid() && !(msg.type() == PBFT_MSG_CHECKPOINT || msg.type() == PBFT_MSG_VIEWCHANGE || msg.type() == PBFT_MSG_NEWVIEW))
{
LOG(debug) << "Dropping message because local view is invalid";
return false;
}
if (auto t = msg.type();t == PBFT_MSG_PREPREPARE || t == PBFT_MSG_PREPARE || t == PBFT_MSG_COMMIT)
{
if (msg.view() != this->view)
{
LOG(debug) << "Dropping message because it has the wrong view number";
return false;
}
if (msg.sequence() <= this->low_water_mark)
{
LOG(debug) << "Dropping message because it has an unreasonable sequence number " << msg.sequence();
return false;
}
if (msg.sequence() > this->high_water_mark)
{
LOG(debug) << "Dropping message because it has an unreasonable sequence number " << msg.sequence();
return false;
}
}
return true;
}
std::shared_ptr<pbft_operation>
pbft::setup_request_operation(const bzn_envelope& request_env, const bzn::hash_t& request_hash, const std::shared_ptr<session_base>& session)
{
const uint64_t request_seq = this->next_issued_sequence_number++;
auto op = this->find_operation(this->view, request_seq, request_hash);
op->record_request(request_env);
if (session)
{
op->set_session(session);
}
return op;
}
void
pbft::handle_request(const bzn_envelope& request_env, const std::shared_ptr<session_base>& session)
{
if (!this->is_primary())
{
this->forward_request_to_primary(request_env, session);
return;
}
if (request_env.timestamp() < (this->now() - MAX_REQUEST_AGE_MS) || request_env.timestamp() > (this->now() + MAX_REQUEST_AGE_MS))
{
// TODO: send error message to client
LOG(info) << "Rejecting request because it is outside allowable timestamp range: " << request_env.ShortDebugString();
return;
}
auto hash = this->crypto->hash(request_env);
// keep track of what requests we've seen based on timestamp and only send preprepares once
if (this->already_seen_request(request_env, hash))
{
// TODO: send error message to client
LOG(info) << "Rejecting duplicate request: " << request_env.ShortDebugString();
return;
}
this->saw_request(request_env, hash);
auto op = setup_request_operation(request_env, hash, session);
this->do_preprepare(op);
}
void
pbft::forward_request_to_primary(const bzn_envelope& request_env, const std::shared_ptr<session_base>& session)
{
LOG(info) << "Forwarding request to primary";
this->node->send_message(bzn::make_endpoint(this->get_primary()), std::make_shared<bzn_envelope>(request_env));
const bzn::hash_t req_hash = this->crypto->hash(request_env);
const auto existing_operation = std::find_if(this->operations.begin(), this->operations.end(),
// This search is inefficient for in-memory operations, but the db lookup that will replace it is not
[&](const auto& pair)
{
return std::get<2>(pair.first) == req_hash;
});
// If we already have an operation for this request_hash, attach the session to it
if (existing_operation != this->operations.end())
{
const std::shared_ptr<bzn::pbft_operation>& op = existing_operation->second;
LOG(debug) << "We already had an operation for that request hash; attaching session to it";
if (!op->has_session())
{
op->set_session(session);
}
}
else
{
LOG(debug) << "Saving session because we don't have an operation for this hash: " << bzn::bytes_to_debug_string(req_hash);
this->sessions_waiting_on_forwarded_requests[req_hash] = session;
}
this->failure_detector->request_seen(req_hash);
}
void
pbft::maybe_record_request(const pbft_msg& msg, const std::shared_ptr<pbft_operation>& op)
{
if (msg.has_request() && !op->has_request())
{
if (this->crypto->hash(msg.request()) != msg.request_hash())
{
LOG(info) << "Not recording request because its hash does not match";
return;
}
op->record_request(msg.request());
}
}
void
pbft::handle_preprepare(const pbft_msg& msg, const bzn_envelope& original_msg)
{
// If we've already accepted a preprepare for this view+sequence, and it's not this one, then we should reject this one
// Note that if we get the same preprepare more than once, we can still accept it
const log_key_t log_key(msg.view(), msg.sequence());
if (auto lookup = this->accepted_preprepares.find(log_key);
lookup != this->accepted_preprepares.end()
&& std::get<2>(lookup->second) != msg.request_hash())
{
LOG(debug) << "Rejecting preprepare because I've already accepted a conflicting one \n";
return;
}
else
{
auto op = this->find_operation(msg);
op->record_pbft_msg(msg, original_msg);
this->maybe_record_request(msg, op);
// This assignment will be redundant if we've seen this preprepare before, but that's fine
accepted_preprepares[log_key] = op->get_operation_key();
if (op->has_config_request())
{
this->handle_config_message(msg, op);
}
this->do_preprepared(op);
this->maybe_advance_operation_state(op);
}
}
void
pbft::handle_prepare(const pbft_msg& msg, const bzn_envelope& original_msg)
{
// Prepare messages are never rejected, assuming the sanity checks passed
auto op = this->find_operation(msg);
op->record_pbft_msg(msg, original_msg);
this->maybe_record_request(msg, op);
this->maybe_advance_operation_state(op);
}
void
pbft::handle_commit(const pbft_msg& msg, const bzn_envelope& original_msg)
{
// Commit messages are never rejected, assuming the sanity checks passed
auto op = this->find_operation(msg);
op->record_pbft_msg(msg, original_msg);
this->maybe_record_request(msg, op);
this->maybe_advance_operation_state(op);
}
void
pbft::handle_join_or_leave(const pbft_membership_msg& msg, std::shared_ptr<bzn::session_base> session)
{
if (msg.has_peer_info())
{
// build a peer_address_t from the message
auto const &peer_info = msg.peer_info();
bzn::peer_address_t peer(peer_info.host(), static_cast<uint16_t>(peer_info.port()),
static_cast<uint16_t>(peer_info.http_port()), peer_info.name(), peer_info.uuid());
auto config = std::make_shared<pbft_configuration>(*(this->configurations.current()));
if (msg.type() == PBFT_MMSG_JOIN)
{
// see if we can add this peer
if (!config->add_peer(peer))
{
LOG(debug) << "Can't add new peer due to conflict";
if (session && session->is_open())
{
pbft_membership_msg response;
response.set_type(PBFT_MMSG_JOIN_RESPONSE);
response.set_result(false);
auto env = this->wrap_message(response);
session->send_message(std::make_shared<std::string>(env.SerializeAsString()), true);
}
return;
}
}
else if (msg.type() == PBFT_MMSG_LEAVE)
{
if (!config->remove_peer(peer))
{
// TODO - respond with negative result?
LOG(debug) << "Couldn't remove requested peer";
return;
}
}
this->configurations.add(config);
this->broadcast_new_configuration(config, session);
}
else
{
LOG(debug) << "Malformed join/leave message";
}
}
void
pbft::handle_join_response(const pbft_membership_msg& msg)
{
if (!this->in_swarm)
{
if (msg.result())
{
this->in_swarm = true;
LOG(debug) << "Successfully joined the swarm, waiting for NEW_VIEW message...";
}
else
{
LOG(error) << "Request to join swarm rejected. Aborting...";
throw (std::runtime_error("Request to join swarm rejected."));
}
}
else
{
LOG(error) << "Received JOIN response when not waiting to join swarm";
}
}
void
pbft::handle_get_state(const pbft_membership_msg& msg, std::shared_ptr<bzn::session_base> session) const
{
LOG(debug) << boost::format("Got request for state data for checkpoint: seq: %1%, hash: %2%")
% msg.sequence() % msg.state_hash();
// get stable checkpoint for request
checkpoint_t req_cp(msg.sequence(), msg.state_hash());
if (req_cp == this->latest_stable_checkpoint())
{
auto state = this->get_checkpoint_state(req_cp);
if (!state)
{
LOG(debug) << boost::format("I'm missing data for checkpoint: seq: %1%, hash: %2%")
% msg.sequence() % msg.state_hash();
// TODO: send error response
return;
}
pbft_membership_msg reply;
reply.set_type(PBFT_MMSG_SET_STATE);
reply.set_sequence(req_cp.first);
reply.set_state_hash(req_cp.second);
reply.set_state_data(*state);
auto msg_ptr = std::make_shared<bzn::encoded_message>(this->wrap_message(reply).SerializeAsString());
session->send_datagram(msg_ptr);
}
else
{
LOG(debug) << boost::format("Request for checkpoint that I don't have: seq: %1%, hash: %2%")
% msg.sequence() % msg.state_hash();
// TODO: send error response
}
}
void
pbft::handle_set_state(const pbft_membership_msg& msg)
{
checkpoint_t cp(msg.sequence(), msg.state_hash());
// do we need this checkpoint state?
// make sure we don't have this checkpoint locally, but do know of a stablized one
// based on the messages sent by peers.
if (this->unstable_checkpoint_proofs[cp].size() >= this->quorum_size() &&
this->local_unstable_checkpoints.count(cp) == 0)
{
LOG(info) << boost::format("Adopting checkpoint %1% at seq %2%")
% cp.second % cp.first;
// TODO: validate the state data
this->set_checkpoint_state(cp, msg.state_data());
this->stabilize_checkpoint(cp);
}
else
{
LOG(debug) << boost::format("Sent state for checkpoint that I don't need: seq: %1%, hash: %2%")
% msg.sequence() % msg.state_hash();
}
}
void
pbft::broadcast(const bzn_envelope& msg)
{
auto msg_ptr = std::make_shared<bzn_envelope>(msg);
for (const auto& peer : this->current_peers())
{
this->node->send_message(make_endpoint(peer), msg_ptr);
}
}
void
pbft::maybe_advance_operation_state(const std::shared_ptr<pbft_operation>& op)
{
if (op->get_stage() == pbft_operation_stage::prepare && op->is_prepared())
{
this->do_prepared(op);
}
if (op->get_stage() == pbft_operation_stage::commit && op->is_committed())
{
this->do_committed(op);
}
}
pbft_msg
pbft::common_message_setup(const std::shared_ptr<pbft_operation>& op, pbft_msg_type type)
{
pbft_msg msg;
msg.set_view(op->get_view());
msg.set_sequence(op->get_sequence());
msg.set_request_hash(op->get_request_hash());
msg.set_type(type);
return msg;
}
void
pbft::do_preprepare(const std::shared_ptr<pbft_operation>& op)
{
LOG(debug) << "Doing preprepare for operation " << op->get_sequence();
pbft_msg msg = this->common_message_setup(op, PBFT_MSG_PREPREPARE);
msg.set_allocated_request(new bzn_envelope(op->get_request()));
this->broadcast(this->wrap_message(msg));
}
void
pbft::do_preprepared(const std::shared_ptr<pbft_operation>& op)
{
LOG(debug) << "Entering prepare phase for operation " << op->get_sequence();
pbft_msg msg = this->common_message_setup(op, PBFT_MSG_PREPARE);
this->broadcast(this->wrap_message(msg));
}
void
pbft::do_prepared(const std::shared_ptr<pbft_operation>& op)
{
// accept new configuration if applicable
if (op->has_config_request())
{
pbft_configuration config;
if (config.from_string(op->get_config_request().configuration()))
{
this->configurations.enable(config.get_hash());
}
}
LOG(debug) << "Entering commit phase for operation " << op->get_sequence();
op->advance_operation_stage(pbft_operation_stage::commit);
pbft_msg msg = this->common_message_setup(op, PBFT_MSG_COMMIT);
this->broadcast(this->wrap_message(msg));
}
void
pbft::do_committed(const std::shared_ptr<pbft_operation>& op)
{
LOG(debug) << "Operation " << op->get_sequence() << " is committed-local";
op->advance_operation_stage(pbft_operation_stage::execute);
// commit new configuration if applicable
if (op->has_config_request())
{
pbft_configuration config;
if (config.from_string(op->get_config_request().configuration()))
{
// get rid of all other previous configs, except for currently active one
this->configurations.remove_prior_to(config.get_hash());
}
// send response to new node
auto session = op->session();
if (session && session->is_open())
{
pbft_membership_msg response;
response.set_type(PBFT_MMSG_JOIN_RESPONSE);
response.set_result(true);
auto env = this->wrap_message(response);
session->send_message(std::make_shared<std::string>(env.SerializeAsString()), true);
// TODO: start timer for sending viewchange KEP-825
}
else
{
LOG(debug) << "Unable to send join response, session is not valid";
}
}
if (this->audit_enabled)
{
audit_message msg;
msg.mutable_pbft_commit()->set_operation(op->get_request_hash());
msg.mutable_pbft_commit()->set_sequence_number(op->get_sequence());
msg.mutable_pbft_commit()->set_sender_uuid(this->uuid);
this->broadcast(this->wrap_message(msg));
}
// TODO: this needs to be refactored to be service-agnostic
if (op->has_db_request())
{
this->io_context->post(std::bind(&pbft_service_base::apply_operation, this->service, op));
}
else
{
// the service needs sequentially sequenced operations. post a null request to fill in this hole
auto msg = new database_msg;
msg->set_allocated_nullmsg(new database_nullmsg);
bzn_envelope request;
request.set_database_msg(msg->SerializeAsString());
auto new_op = std::make_shared<pbft_memory_operation>(op->get_view(), op->get_sequence()
, this->crypto->hash(request), nullptr);
new_op->record_request(request);
this->io_context->post(std::bind(&pbft_service_base::apply_operation, this->service, new_op));
}
}
size_t
pbft::outstanding_operations_count() const
{
return operations.size();
}
bool
pbft::is_primary() const
{
return this->get_primary().uuid == this->uuid;
}
const peer_address_t&
pbft::get_primary(std::optional<uint64_t> view) const
{
return this->current_peers()[view.value_or(this->view) % this->current_peers().size()];
}
// Find this node's record of an operation (creating a new record for it if this is the first time we've heard of it)
std::shared_ptr<pbft_operation>
pbft::find_operation(const pbft_msg& msg)
{
return this->find_operation(msg.view(), msg.sequence(), msg.request_hash());
}
std::shared_ptr<pbft_operation>
pbft::find_operation(const std::shared_ptr<pbft_operation>& op)
{
return this->find_operation(op->get_view(), op->get_sequence(), op->get_request_hash());
}
std::shared_ptr<pbft_operation>
pbft::find_operation(uint64_t view, uint64_t sequence, const bzn::hash_t& req_hash)
{
auto key = bzn::operation_key_t(view, sequence, req_hash);
auto lookup = operations.find(key);
if (lookup == operations.end())
{
LOG(debug) << "Creating operation for seq " << sequence << " view " << view << " req " << bytes_to_debug_string(req_hash);
std::shared_ptr<pbft_operation> op = std::make_shared<pbft_memory_operation>(view, sequence, req_hash,
this->current_peers_ptr());
bool added;
std::tie(std::ignore, added) = operations.emplace(std::piecewise_construct, std::forward_as_tuple(std::move(key)), std::forward_as_tuple(op));
assert(added);
auto session_pair = this->sessions_waiting_on_forwarded_requests.find(req_hash);
if (session_pair != this->sessions_waiting_on_forwarded_requests.end())
{
LOG(debug) << "Attaching pending session to new operation";
std::shared_ptr<bzn::session_base> session;
std::tie(std::ignore, session) = *session_pair;
op->set_session(session);
this->sessions_waiting_on_forwarded_requests.erase(req_hash);
}
return op;
}
return lookup->second;
}
bzn_envelope
pbft::wrap_message(const pbft_msg& msg) const
{
bzn_envelope result;
result.set_pbft(msg.SerializeAsString());
result.set_sender(this->uuid);
result.set_timestamp(this->now());
// this->crypto->sign(result);
return result;
}
bzn_envelope
pbft::wrap_message(const pbft_membership_msg& msg) const
{
bzn_envelope result;
result.set_pbft_membership(msg.SerializeAsString());
result.set_sender(this->uuid);
result.set_timestamp(this->now());
// this->crypto->sign(result);
return result;
}
bzn_envelope
pbft::wrap_message(const audit_message& msg) const
{
bzn_envelope result;
result.set_audit(msg.SerializeAsString());
result.set_sender(this->uuid);
result.set_timestamp(this->now());
// this->crypto->sign(result);
return result;
}
const bzn::uuid_t&
pbft::get_uuid() const
{
return this->uuid;
}
void
pbft::set_audit_enabled(bool setting)
{
this->audit_enabled = setting;
}
void
pbft::notify_audit_failure_detected()
{
if (this->audit_enabled)
{
audit_message msg;
msg.mutable_failure_detected()->set_sender_uuid(this->uuid);
this->broadcast(this->wrap_message(msg));
}
}
void
pbft::handle_failure()
{
std::lock_guard<std::mutex> lock(this->pbft_lock);
LOG (error) << "handle_failure - PBFT failure - invalidating current view and sending VIEWCHANGE to view: " << this->view + 1;
this->notify_audit_failure_detected();
this->view_is_valid = false;
pbft_msg view_change{pbft::make_viewchange(this->view + 1, this->latest_stable_checkpoint().first, this->stable_checkpoint_proof, this->prepared_operations_since_last_checkpoint())};
this->broadcast(this->wrap_message(view_change));
}
void
pbft::checkpoint_reached_locally(uint64_t sequence)
{
std::lock_guard<std::mutex> lock(this->pbft_lock);
LOG(info) << "Reached checkpoint " << sequence;
auto cp = this->local_unstable_checkpoints.emplace(sequence, this->service->service_state_hash(sequence)).first;
pbft_msg cp_msg;
cp_msg.set_type(PBFT_MSG_CHECKPOINT);
cp_msg.set_view(this->view);
cp_msg.set_sequence(sequence);
cp_msg.set_state_hash(cp->second);
this->broadcast(this->wrap_message(cp_msg));
this->maybe_stabilize_checkpoint(*cp);
}
void
pbft::handle_checkpoint(const pbft_msg& msg, const bzn_envelope& original_msg)
{
if (msg.sequence() <= stable_checkpoint.first)
{
LOG(debug) << boost::format("Ignoring checkpoint message for seq %1% because I already have a stable checkpoint at seq %2%")
% msg.sequence()
% stable_checkpoint.first;
return;
}
LOG(info) << boost::format("Received checkpoint message for seq %1% from %2%")
% msg.sequence()
% original_msg.sender();
checkpoint_t cp(msg.sequence(), msg.state_hash());
this->unstable_checkpoint_proofs[cp][original_msg.sender()] = original_msg.SerializeAsString();
this->maybe_stabilize_checkpoint(cp);
}
bzn::checkpoint_t
pbft::latest_stable_checkpoint() const
{
return this->stable_checkpoint;
}
bzn::checkpoint_t
pbft::latest_checkpoint() const
{
return this->local_unstable_checkpoints.empty() ? this->stable_checkpoint : *(this->local_unstable_checkpoints.rbegin());
}
size_t
pbft::unstable_checkpoints_count() const
{
return this->local_unstable_checkpoints.size();
}
void
pbft::maybe_stabilize_checkpoint(const checkpoint_t& cp)
{
if (this->unstable_checkpoint_proofs[cp].size() < this->quorum_size())
{
return;
}
if (this->local_unstable_checkpoints.count(cp) != 0)
{
this->stabilize_checkpoint(cp);
}
else
{
// we don't have this checkpoint, so we need to catch up
this->request_checkpoint_state(cp);
}
}
void
pbft::stabilize_checkpoint(const checkpoint_t& cp)
{
this->stable_checkpoint = cp;
this->stable_checkpoint_proof = this->unstable_checkpoint_proofs[cp];
LOG(info) << boost::format("Checkpoint %1% at seq %2% is now stable; clearing old data")
% cp.second % cp.first;
this->clear_local_checkpoints_until(cp);
this->clear_checkpoint_messages_until(cp);
this->clear_operations_until(cp);
this->low_water_mark = std::max(this->low_water_mark, cp.first);
this->high_water_mark = std::max(this->high_water_mark,
cp.first + std::lround(HIGH_WATER_INTERVAL_IN_CHECKPOINTS * CHECKPOINT_INTERVAL));
// remove seen requests older than our time threshold
this->recent_requests.erase(this->recent_requests.begin(),
this->recent_requests.upper_bound(this->now() - MAX_REQUEST_AGE_MS));
}
void
pbft::request_checkpoint_state(const checkpoint_t& cp)
{
pbft_membership_msg msg;
msg.set_type(PBFT_MMSG_GET_STATE);
msg.set_sequence(cp.first);
msg.set_state_hash(cp.second);
auto selected = this->select_peer_for_checkpoint(cp);
LOG(info) << boost::format("Requesting checkpoint state for hash %1% at seq %2% from %3%")
% cp.second % cp.first % selected.uuid;
auto msg_ptr = std::make_shared<bzn_envelope>(this->wrap_message(msg));
this->node->send_message(make_endpoint(selected), msg_ptr);
}
const peer_address_t&
pbft::select_peer_for_checkpoint(const checkpoint_t& cp)
{
// choose one of the peers who vouch for this checkpoint at random
std::random_device rd;
std::mt19937 gen(rd());
std::uniform_int_distribution<uint32_t> dist(0, this->unstable_checkpoint_proofs[cp].size() - 1);
auto it = this->unstable_checkpoint_proofs[cp].begin();
uint32_t selected = dist(gen);
for (size_t i = 0; i < selected; i++)
{
it++;
}
return this->get_peer_by_uuid(it->first);
}
std::shared_ptr<std::string>
pbft::get_checkpoint_state(const checkpoint_t& cp) const
{
// call service to retrieve state at this checkpoint
return this->service->get_service_state(cp.first);
}
void
pbft::set_checkpoint_state(const checkpoint_t& cp, const std::string& data)
{
// set the service state at the given checkpoint sequence
// the service is expected to load the state and discard any pending operations
// prior to the sequence number, then execute any subsequent operations sequentially
this->service->set_service_state(cp.first, data);
}
void
pbft::clear_local_checkpoints_until(const checkpoint_t& cp)
{
const auto local_start = this->local_unstable_checkpoints.begin();
// Iterator to the first unstable checkpoint that's newer than this one. This logic assumes that CHECKPOINT_INTERVAL
// is >= 2, otherwise we would have do do something awkward here
const auto local_end = this->local_unstable_checkpoints.upper_bound(checkpoint_t(cp.first+1, ""));
const size_t local_removed = std::distance(local_start, local_end);
this->local_unstable_checkpoints.erase(local_start, local_end);
LOG(debug) << boost::format("Cleared %1% unstable local checkpoints") % local_removed;
}
void
pbft::clear_checkpoint_messages_until(const checkpoint_t& cp)
{
const auto start = this->unstable_checkpoint_proofs.begin();
const auto end = this->unstable_checkpoint_proofs.upper_bound(checkpoint_t(cp.first+1, ""));
const size_t to_remove = std::distance(start, end);